summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.qmake.conf2
-rw-r--r--config_help.txt3
-rw-r--r--examples/widgets/widgets/imageviewer/imageviewer.cpp2
-rw-r--r--qmake/qmake.pro13
-rw-r--r--src/corelib/configure.json19
-rw-r--r--src/corelib/corelib.pro2
-rw-r--r--src/corelib/eval.pri4
-rw-r--r--src/corelib/global/qhooks.cpp2
-rw-r--r--src/corelib/global/qlibraryinfo.cpp5
-rw-r--r--src/corelib/global/qtrace_p.h2
-rw-r--r--src/corelib/kernel/kernel.pri2
-rw-r--r--src/corelib/kernel/qcoreapplication.cpp14
-rw-r--r--src/corelib/kernel/qmetaobject_p.h4
-rw-r--r--src/corelib/kernel/qobject.cpp630
-rw-r--r--src/corelib/kernel/qobject_p.h123
-rw-r--r--src/corelib/kernel/qtcore_eval.cpp560
-rw-r--r--src/corelib/serialization/qdatastream.cpp1
-rw-r--r--src/corelib/serialization/qdatastream.h5
-rw-r--r--src/corelib/thread/qorderedmutexlocker_p.h62
-rw-r--r--src/gui/configure.json26
-rw-r--r--src/gui/image/qimage.cpp134
-rw-r--r--src/gui/image/qimage.h10
-rw-r--r--src/gui/image/qimage_conversions.cpp4
-rw-r--r--src/gui/image/qimage_p.h4
-rw-r--r--src/gui/image/qpnghandler.cpp72
-rw-r--r--src/gui/kernel/kernel.pri2
-rw-r--r--src/gui/kernel/qguiapplication.cpp30
-rw-r--r--src/gui/kernel/qguiapplication_p.h11
-rw-r--r--src/gui/opengl/qopengltexture.cpp234
-rw-r--r--src/gui/opengl/qopengltexture.h26
-rw-r--r--src/gui/opengl/qopengltexture_p.h4
-rw-r--r--src/gui/painting/painting.pri16
-rw-r--r--src/gui/painting/qcolormatrix_p.h214
-rw-r--r--src/gui/painting/qcolorspace.cpp633
-rw-r--r--src/gui/painting/qcolorspace.h136
-rw-r--r--src/gui/painting/qcolorspace_p.h (renamed from src/plugins/platforms/mirclient/qmirclientclipboard.h)86
-rw-r--r--src/gui/painting/qcolortransferfunction_p.h207
-rw-r--r--src/gui/painting/qcolortransfertable_p.h245
-rw-r--r--src/gui/painting/qcolortransform.cpp679
-rw-r--r--src/gui/painting/qcolortransform.h (renamed from src/plugins/platforms/mirclient/qmirclientscreenobserver.h)71
-rw-r--r--src/gui/painting/qcolortransform_p.h (renamed from src/plugins/platforms/mirclient/qmirclientbackingstore.h)67
-rw-r--r--src/gui/painting/qcolortrc_p.h129
-rw-r--r--src/gui/painting/qcolortrclut.cpp (renamed from src/gui/painting/qcolorprofile.cpp)41
-rw-r--r--src/gui/painting/qcolortrclut_p.h (renamed from src/gui/painting/qcolorprofile_p.h)72
-rw-r--r--src/gui/painting/qdrawhelper.cpp22
-rw-r--r--src/gui/painting/qicc.cpp669
-rw-r--r--src/gui/painting/qicc_p.h (renamed from src/plugins/platforms/mirclient/qmirclientdebugextension.h)43
-rw-r--r--src/gui/painting/qpaintengine_raster.cpp76
-rw-r--r--src/gui/painting/qpaintengine_raster_p.h20
-rw-r--r--src/gui/painting/qpainter_p.h2
-rw-r--r--src/gui/painting/qpdfwriter.cpp10
-rw-r--r--src/gui/painting/qpdfwriter.h6
-rw-r--r--src/gui/text/qfont.cpp99
-rw-r--r--src/gui/text/qfont.h6
-rw-r--r--src/network/access/qhttpnetworkconnection.cpp13
-rw-r--r--src/network/access/qhttpnetworkreply.cpp3
-rw-r--r--src/network/configure.json26
-rw-r--r--src/network/kernel/kernel.pri2
-rw-r--r--src/network/kernel/qauthenticator.cpp406
-rw-r--r--src/network/kernel/qauthenticator_p.h17
-rw-r--r--src/network/socket/qhttpsocketengine.cpp2
-rw-r--r--src/network/ssl/qsslsocket_openssl.cpp3
-rw-r--r--src/platformsupport/eglconvenience/qeglstreamconvenience_p.h11
-rw-r--r--src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp324
-rw-r--r--src/platformsupport/themes/genericunix/qgenericunixthemes.cpp12
-rw-r--r--src/plugins/imageformats/jpeg/qjpeghandler.cpp14
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp50
-rw-r--r--src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h2
-rw-r--r--src/plugins/platforms/mirclient/mirclient.json3
-rw-r--r--src/plugins/platforms/mirclient/mirclient.pro61
-rw-r--r--src/plugins/platforms/mirclient/qmirclientappstatecontroller.cpp102
-rw-r--r--src/plugins/platforms/mirclient/qmirclientappstatecontroller.h62
-rw-r--r--src/plugins/platforms/mirclient/qmirclientbackingstore.cpp157
-rw-r--r--src/plugins/platforms/mirclient/qmirclientclipboard.cpp181
-rw-r--r--src/plugins/platforms/mirclient/qmirclientcursor.cpp209
-rw-r--r--src/plugins/platforms/mirclient/qmirclientcursor.h64
-rw-r--r--src/plugins/platforms/mirclient/qmirclientdebugextension.cpp79
-rw-r--r--src/plugins/platforms/mirclient/qmirclientdesktopwindow.cpp50
-rw-r--r--src/plugins/platforms/mirclient/qmirclientdesktopwindow.h53
-rw-r--r--src/plugins/platforms/mirclient/qmirclientglcontext.cpp132
-rw-r--r--src/plugins/platforms/mirclient/qmirclientglcontext.h63
-rw-r--r--src/plugins/platforms/mirclient/qmirclientinput.cpp708
-rw-r--r--src/plugins/platforms/mirclient/qmirclientinput.h86
-rw-r--r--src/plugins/platforms/mirclient/qmirclientintegration.cpp411
-rw-r--r--src/plugins/platforms/mirclient/qmirclientintegration.h131
-rw-r--r--src/plugins/platforms/mirclient/qmirclientlogging.h55
-rw-r--r--src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp217
-rw-r--r--src/plugins/platforms/mirclient/qmirclientnativeinterface.h83
-rw-r--r--src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h61
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplatformservices.cpp75
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplatformservices.h57
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplugin.cpp56
-rw-r--r--src/plugins/platforms/mirclient/qmirclientplugin.h56
-rw-r--r--src/plugins/platforms/mirclient/qmirclientscreen.cpp262
-rw-r--r--src/plugins/platforms/mirclient/qmirclientscreen.h106
-rw-r--r--src/plugins/platforms/mirclient/qmirclientscreenobserver.cpp161
-rw-r--r--src/plugins/platforms/mirclient/qmirclienttheme.cpp67
-rw-r--r--src/plugins/platforms/mirclient/qmirclienttheme.h57
-rw-r--r--src/plugins/platforms/mirclient/qmirclientwindow.cpp968
-rw-r--r--src/plugins/platforms/mirclient/qmirclientwindow.h118
-rw-r--r--src/plugins/platforms/platforms.pro2
-rw-r--r--src/printsupport/dialogs/qpagesetupdialog_unix.cpp26
-rw-r--r--src/printsupport/dialogs/qprintpreviewdialog.cpp12
-rw-r--r--src/testlib/qsignaldumper.cpp5
-rw-r--r--src/tools/bootstrap/bootstrap.pro2
-rw-r--r--src/tools/moc/moc.cpp33
-rw-r--r--src/tools/moc/moc.h1
-rw-r--r--src/widgets/doc/snippets/timeline/main.cpp4
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.cpp33
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.h5
-rw-r--r--src/widgets/kernel/qapplication.cpp4
-rw-r--r--src/widgets/kernel/qformlayout.cpp2
-rw-r--r--src/widgets/kernel/qwidget.cpp11
-rw-r--r--src/widgets/kernel/qwidgetbackingstore.cpp6
-rw-r--r--src/widgets/kernel/qwidgetbackingstore_p.h1
-rw-r--r--src/widgets/styles/qstylesheetstyle.cpp5
-rw-r--r--src/widgets/widgets.pro2
-rw-r--r--src/widgets/widgets/qcombobox.cpp6
-rw-r--r--src/widgets/widgets/qcombobox.h12
-rw-r--r--src/widgets/widgets/qlineedit.cpp12
-rw-r--r--src/widgets/widgets/qlineedit_p.cpp7
-rw-r--r--src/widgets/widgets/qlineedit_p.h4
-rw-r--r--src/widgets/widgets/qmdiarea.cpp4
-rw-r--r--tests/auto/corelib/kernel/qobject/tst_qobject.cpp165
-rw-r--r--tests/auto/gui/painting/painting.pro1
-rw-r--r--tests/auto/gui/painting/qcolor/tst_qcolor.cpp5
-rw-r--r--tests/auto/gui/painting/qcolorspace/qcolorspace.pro9
-rw-r--r--tests/auto/gui/painting/qcolorspace/resources/ProPhoto.jpgbin0 -> 30900 bytes
-rw-r--r--tests/auto/gui/painting/qcolorspace/resources/sRGB2014.iccbin0 -> 3024 bytes
-rw-r--r--tests/auto/gui/painting/qcolorspace/tst_qcolorspace.cpp238
-rw-r--r--tests/auto/network-settings.h72
-rw-r--r--tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro2
-rw-r--r--tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp7
-rw-r--r--tests/auto/network/access/qhttpnetworkconnection/qhttpnetworkconnection.pro4
-rw-r--r--tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp76
-rw-r--r--tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp8
-rw-r--r--tests/auto/network/socket/qsocks5socketengine/qsocks5socketengine.pro6
-rw-r--r--tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp42
-rw-r--r--tests/auto/network/socket/qtcpserver/test/test.pro6
-rw-r--r--tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp43
-rw-r--r--tests/auto/network/socket/qtcpsocket/test/test.pro6
-rw-r--r--tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp174
-rw-r--r--tests/auto/other/toolsupport/tst_toolsupport.cpp4
-rw-r--r--tests/auto/testlib/selftests/blacklisted/tst_blacklisted.cpp21
-rw-r--r--tests/auto/testlib/selftests/expected_crashes_5.txt5
-rw-r--r--tests/auto/testlib/selftests/silent/tst_silent.cpp21
-rw-r--r--tests/auto/testserver.pri4
-rw-r--r--tests/auto/tools/moc/tst_moc.cpp13
-rw-r--r--tests/auto/widgets/graphicsview/qgraphicsitemanimation/tst_qgraphicsitemanimation.cpp6
-rw-r--r--tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp8
-rw-r--r--tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp10
-rw-r--r--tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp1
-rwxr-xr-xtests/testserver/apache2/apache2.sh3
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol-expire.cgi7
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol.cgi13
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol200.cgi9
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag200.cgi5
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag304.cgi11
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires200.cgi5
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires304.cgi11
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified200.cgi5
-rwxr-xr-xtests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified304.cgi11
-rw-r--r--tests/testserver/apache2/testdata/www/htdocs/rfcs/.gitattributes1
-rw-r--r--tests/testserver/apache2/testdata/www/htdocs/rfcs/rfc2616.html8380
-rwxr-xr-xtests/testserver/cyrus/cyrus.sh34
-rw-r--r--tests/testserver/docker-compose.yml29
-rwxr-xr-xtests/testserver/iptables/iptables.sh34
167 files changed, 14160 insertions, 6951 deletions
diff --git a/.qmake.conf b/.qmake.conf
index c92e38c48f..08e1a4723c 100644
--- a/.qmake.conf
+++ b/.qmake.conf
@@ -4,4 +4,4 @@ CONFIG += warning_clean
QT_SOURCE_TREE = $$PWD
QT_BUILD_TREE = $$shadowed($$PWD)
-MODULE_VERSION = 5.13.0
+MODULE_VERSION = 5.14.0
diff --git a/config_help.txt b/config_help.txt
index 8eea64e03a..77a333c89a 100644
--- a/config_help.txt
+++ b/config_help.txt
@@ -241,7 +241,7 @@ Core options:
-inotify ............. Enable inotify support
-iconv ............... Enable iconv(3) support [posix/sun/gnu/no] (Unix only)
-icu ................. Enable ICU support [auto]
- -pcre ................ Select used libpcre2 [system/qt]
+ -pcre ................ Select used libpcre2 [system/qt/no]
-pps ................. Enable PPS support [auto] (QNX only)
-zlib ................ Select used zlib [system/qt]
@@ -296,7 +296,6 @@ Gui, printing, widget options:
-gbm ............... Enable backends for GBM [auto] (Linux only)
-kms ............... Enable backends for KMS [auto] (Linux only)
-linuxfb ........... Enable Linux Framebuffer support [auto] (Linux only)
- -mirclient ......... Enable Mir client support [no] (Linux only)
-xcb ............... Enable X11 support. Select used xcb-* libraries [system/qt/no]
(-qt-xcb still uses system version of libxcb itself)
diff --git a/examples/widgets/widgets/imageviewer/imageviewer.cpp b/examples/widgets/widgets/imageviewer/imageviewer.cpp
index fed551dade..2fc8ff63de 100644
--- a/examples/widgets/widgets/imageviewer/imageviewer.cpp
+++ b/examples/widgets/widgets/imageviewer/imageviewer.cpp
@@ -106,6 +106,8 @@ bool ImageViewer::loadFile(const QString &fileName)
void ImageViewer::setImage(const QImage &newImage)
{
image = newImage;
+ if (image.colorSpace().isValid())
+ image.convertToColorSpace(QColorSpace::SRgb);
imageLabel->setPixmap(QPixmap::fromImage(image));
//! [4]
scaleFactor = 1.0;
diff --git a/qmake/qmake.pro b/qmake/qmake.pro
index 5399e8c298..6a6116c8db 100644
--- a/qmake/qmake.pro
+++ b/qmake/qmake.pro
@@ -96,7 +96,7 @@ HEADERS += \
bp = $$shadowed(..)
INCLUDEPATH += \
$$bp/include $$bp/include/QtCore \
- $$bp/include/QtCore/$$QT_VERSION $$bp/include/QtCore/$$QT_VERSION/QtCore
+ $$bp/include/QtCore/$$QT_VERSION $$bp/include/QtCore/$$QT_VERSION/QtCore \
$$bp/src/corelib/global
VPATH += \
@@ -182,18 +182,17 @@ HEADERS += \
qglobal.h \
qhash.h \
qiodevice.h \
- qjson.h \
+ qjson_p.h \
qjsonarray.h \
qjsondocument.h \
qjsonobject.h \
- qjsonparser.h \
+ qjsonparser_p.h \
qjsonvalue.h \
- qjsonwriter.h \
+ qjsonwriter_p.h \
qlinkedlist.h \
qlist.h \
qlocale.h \
qlocale_tools_p.h \
- qmalloc.h \
qmap.h \
qmetatype.h \
qnumeric.h \
@@ -204,12 +203,12 @@ HEADERS += \
qsystemerror_p.h \
qtemporaryfile.h \
qtextstream.h \
- qutfcodec.h \
+ qutfcodec_p.h \
quuid.h \
qvector.h \
qversionnumber.h \
qxmlstream.h \
- qxmlutils.h
+ qxmlutils_p.h
unix {
SOURCES += \
diff --git a/src/corelib/configure.json b/src/corelib/configure.json
index 948aa0829b..81768507f6 100644
--- a/src/corelib/configure.json
+++ b/src/corelib/configure.json
@@ -11,7 +11,7 @@
"icu": "boolean",
"inotify": "boolean",
"journald": "boolean",
- "pcre": { "type": "enum", "values": [ "qt", "system" ] },
+ "pcre": { "type": "enum", "values": [ "no", "qt", "system" ] },
"posix-ipc": { "type": "boolean", "name": "ipc_posix" },
"pps": { "type": "boolean", "name": "qqnx_pps" },
"slog2": "boolean",
@@ -662,15 +662,18 @@
"condition": "features.textcodec",
"output": [ "publicFeature", "feature" ]
},
+ "pcre2": {
+ "label": "PCRE2",
+ "disable": "input.pcre == 'no' || input.pcre == 'system'",
+ "enable": "input.pcre == 'qt'",
+ "output": [ "privateConfig" ]
+ },
"system-pcre2": {
- "label": "Using system PCRE2",
- "disable": "input.pcre == 'qt'",
+ "label": " Using system PCRE2",
+ "disable": "input.pcre == 'no' || input.pcre == 'qt'",
"enable": "input.pcre == 'system'",
"condition": "libs.pcre2",
- "output": [
- "privateFeature",
- { "type": "privateConfig", "negative": true, "name": "pcre2" }
- ]
+ "output": [ "privateFeature" ]
},
"poll_ppoll": {
"label": "Native ppoll()",
@@ -749,6 +752,7 @@
"label": "QRegularExpression",
"purpose": "Provides an API to Perl-compatible regular expressions.",
"section": "Kernel",
+ "condition": "features.system-pcre2 || features.pcre2",
"output": [ "publicFeature", "feature" ]
},
"sharedmemory": {
@@ -1048,6 +1052,7 @@ Please apply the patch corresponding to your Standard Library vendor, found in
"args": "qqnx_pps",
"condition": "config.qnx"
},
+ "pcre2",
"system-pcre2"
]
}
diff --git a/src/corelib/corelib.pro b/src/corelib/corelib.pro
index 4b758532e6..dc43e56836 100644
--- a/src/corelib/corelib.pro
+++ b/src/corelib/corelib.pro
@@ -68,8 +68,6 @@ integrity {
QMAKE_DYNAMIC_LIST_FILE = $$PWD/QtCore.dynlist
-contains(DEFINES,QT_EVAL):include(eval.pri)
-
HOST_BINS = $$[QT_HOST_BINS]
host_bins.name = host_bins
host_bins.variable = HOST_BINS
diff --git a/src/corelib/eval.pri b/src/corelib/eval.pri
deleted file mode 100644
index efda56b16a..0000000000
--- a/src/corelib/eval.pri
+++ /dev/null
@@ -1,4 +0,0 @@
-SOURCES += \
- $$QT_SOURCE_TREE/src/corelib/kernel/qtcore_eval.cpp
-INCLUDEPATH += \
- $$QT_BUILD_TREE/src/corelib/global
diff --git a/src/corelib/global/qhooks.cpp b/src/corelib/global/qhooks.cpp
index bbddb1cbf1..020dee3710 100644
--- a/src/corelib/global/qhooks.cpp
+++ b/src/corelib/global/qhooks.cpp
@@ -67,7 +67,7 @@ quintptr Q_CORE_EXPORT qtHookData[] = {
// The required sizes and offsets are tested in tests/auto/other/toolsupport.
// When this fails and the change was intentional, adjust the test and
// adjust this value here.
- 16
+ 17
};
Q_STATIC_ASSERT(QHooks::LastHookIndex == sizeof(qtHookData) / sizeof(qtHookData[0]));
diff --git a/src/corelib/global/qlibraryinfo.cpp b/src/corelib/global/qlibraryinfo.cpp
index 4119012d85..88cc5b0b01 100644
--- a/src/corelib/global/qlibraryinfo.cpp
+++ b/src/corelib/global/qlibraryinfo.cpp
@@ -717,11 +717,6 @@ void qt_core_boilerplate()
QT_PREPEND_NAMESPACE(qDumpCPUFeatures)();
-#ifdef QT_EVAL
- extern void qt_core_eval_init(QCoreApplicationPrivate::Type);
- qt_core_eval_init(QCoreApplicationPrivate::Tty);
-#endif
-
exit(0);
}
diff --git a/src/corelib/global/qtrace_p.h b/src/corelib/global/qtrace_p.h
index 3d04a7311d..56d1f9a318 100644
--- a/src/corelib/global/qtrace_p.h
+++ b/src/corelib/global/qtrace_p.h
@@ -114,10 +114,12 @@
QT_BEGIN_NAMESPACE
#if defined(Q_TRACEPOINT) && !defined(QT_BOOTSTRAPPED)
+# define Q_HAS_TRACEPOINTS 1
# define Q_TRACE(x, ...) QtPrivate::trace_ ## x(__VA_ARGS__)
# define Q_UNCONDITIONAL_TRACE(x, ...) QtPrivate::do_trace_ ## x(__VA_ARGS__)
# define Q_TRACE_ENABLED(x) QtPrivate::trace_ ## x ## _enabled()
#else
+# define Q_HAS_TRACEPOINTS 0
# define Q_TRACE(x, ...)
# define Q_UNCONDITIONAL_TRACE(x, ...)
# define Q_TRACE_ENABLED(x) false
diff --git a/src/corelib/kernel/kernel.pri b/src/corelib/kernel/kernel.pri
index 3f7bf3cd47..789bcb7927 100644
--- a/src/corelib/kernel/kernel.pri
+++ b/src/corelib/kernel/kernel.pri
@@ -7,7 +7,7 @@ HEADERS += \
kernel/qdeadlinetimer.h \
kernel/qdeadlinetimer_p.h \
kernel/qelapsedtimer.h \
- kernel/qeventloop.h\
+ kernel/qeventloop.h \
kernel/qpointer.h \
kernel/qcorecmdlineargs_p.h \
kernel/qcoreapplication.h \
diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp
index c06af79cc7..5da33a5aae 100644
--- a/src/corelib/kernel/qcoreapplication.cpp
+++ b/src/corelib/kernel/qcoreapplication.cpp
@@ -256,15 +256,6 @@ void QCoreApplicationPrivate::processCommandLineArguments()
// Support for introspection
-#ifndef QT_NO_QOBJECT
-QSignalSpyCallbackSet Q_CORE_EXPORT qt_signal_spy_callback_set = { 0, 0, 0, 0 };
-
-void qt_register_signal_spy_callbacks(const QSignalSpyCallbackSet &callback_set)
-{
- qt_signal_spy_callback_set = callback_set;
-}
-#endif
-
extern "C" void Q_CORE_EXPORT qt_startup_hook()
{
}
@@ -866,11 +857,6 @@ void QCoreApplicationPrivate::init()
eventDispatcherReady();
#endif
-#ifdef QT_EVAL
- extern void qt_core_eval_init(QCoreApplicationPrivate::Type);
- qt_core_eval_init(application_type);
-#endif
-
processCommandLineArguments();
qt_call_pre_routines();
diff --git a/src/corelib/kernel/qmetaobject_p.h b/src/corelib/kernel/qmetaobject_p.h
index 522bd78e42..5b412b5140 100644
--- a/src/corelib/kernel/qmetaobject_p.h
+++ b/src/corelib/kernel/qmetaobject_p.h
@@ -54,6 +54,7 @@
#include <QtCore/qglobal.h>
#include <QtCore/qobjectdefs.h>
+#include <QtCore/qmutex.h>
#ifndef QT_NO_QOBJECT
#include <private/qobject_p.h> // For QObjectPrivate::Connection
#endif
@@ -168,7 +169,6 @@ Q_DECLARE_TYPEINFO(QArgumentType, Q_MOVABLE_TYPE);
typedef QVarLengthArray<QArgumentType, 10> QArgumentTypeArray;
class QMetaMethodPrivate;
-class QMutex;
struct QMetaObjectPrivate
{
@@ -234,7 +234,7 @@ struct QMetaObjectPrivate
DisconnectType = DisconnectAll);
static inline bool disconnectHelper(QObjectPrivate::Connection *c,
const QObject *receiver, int method_index, void **slot,
- QMutex *senderMutex, DisconnectType = DisconnectAll);
+ QBasicMutex *senderMutex, DisconnectType = DisconnectAll);
#endif
};
diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp
index 3a3eb726fa..25e205b812 100644
--- a/src/corelib/kernel/qobject.cpp
+++ b/src/corelib/kernel/qobject.cpp
@@ -77,6 +77,12 @@ QT_BEGIN_NAMESPACE
static int DIRECT_CONNECTION_ONLY = 0;
+Q_CORE_EXPORT QBasicAtomicPointer<QSignalSpyCallbackSet> qt_signal_spy_callback_set = Q_BASIC_ATOMIC_INITIALIZER(nullptr);
+
+void qt_register_signal_spy_callbacks(QSignalSpyCallbackSet *callback_set)
+{
+ qt_signal_spy_callback_set.store(callback_set);
+}
QDynamicMetaObjectData::~QDynamicMetaObjectData()
{
@@ -146,10 +152,9 @@ static QBasicMutex _q_ObjectMutexPool[131];
* \internal
* mutex to be locked when accessing the connectionlists or the senders list
*/
-static inline QMutex *signalSlotLock(const QObject *o)
+static inline QBasicMutex *signalSlotLock(const QObject *o)
{
- return static_cast<QMutex *>(&_q_ObjectMutexPool[
- uint(quintptr(o)) % sizeof(_q_ObjectMutexPool)/sizeof(QBasicMutex)]);
+ return &_q_ObjectMutexPool[uint(quintptr(o)) % sizeof(_q_ObjectMutexPool)/sizeof(QBasicMutex)];
}
#if QT_VERSION < 0x60000
@@ -160,39 +165,6 @@ extern "C" Q_CORE_EXPORT void qt_removeObject(QObject *)
{}
#endif
-struct QConnectionSenderSwitcher {
- QObject *receiver;
- QObjectPrivate::Sender *previousSender;
- QObjectPrivate::Sender currentSender;
- bool switched;
-
- inline QConnectionSenderSwitcher() : switched(false) {}
-
- inline QConnectionSenderSwitcher(QObject *receiver, QObject *sender, int signal_absolute_id)
- {
- switchSender(receiver, sender, signal_absolute_id);
- }
-
- inline void switchSender(QObject *receiver, QObject *sender, int signal_absolute_id)
- {
- this->receiver = receiver;
- currentSender.sender = sender;
- currentSender.signal = signal_absolute_id;
- currentSender.ref = 1;
- previousSender = QObjectPrivate::setCurrentSender(receiver, &currentSender);
- switched = true;
- }
-
- inline ~QConnectionSenderSwitcher()
- {
- if (switched)
- QObjectPrivate::resetCurrentSender(receiver, &currentSender, previousSender);
- }
-private:
- Q_DISABLE_COPY(QConnectionSenderSwitcher)
-};
-
-
void (*QAbstractDeclarativeData::destroyed)(QAbstractDeclarativeData *, QObject *) = 0;
void (*QAbstractDeclarativeData::destroyed_qml1)(QAbstractDeclarativeData *, QObject *) = 0;
void (*QAbstractDeclarativeData::parentChanged)(QAbstractDeclarativeData *, QObject *, QObject *) = 0;
@@ -209,7 +181,7 @@ QMetaObject *QObjectData::dynamicMetaObject() const
}
QObjectPrivate::QObjectPrivate(int version)
- : threadData(0), connectionLists(0), senders(0), currentSender(0), currentChildBeingDeleted(0)
+ : threadData(0), currentChildBeingDeleted(0)
{
#ifdef QT_BUILD_INTERNAL
// Don't check the version parameter in internal builds.
@@ -232,7 +204,6 @@ QObjectPrivate::QObjectPrivate(int version)
receiveChildEvents = true;
postedEvents = 0;
extraData = 0;
- connectedSignals[0] = connectedSignals[1] = 0;
metaObject = 0;
isWindow = false;
deleteLaterCalled = false;
@@ -285,59 +256,22 @@ static void computeOffsets(const QMetaObject *metaobject, int *signalOffset, int
}
}
-/*
- This vector contains the all connections from an object.
-
- Each object may have one vector containing the lists of
- connections for a given signal. The index in the vector correspond
- to the signal index. The signal index is the one returned by
- QObjectPrivate::signalIndex (not QMetaObject::indexOfSignal).
- Negative index means connections to all signals.
-
- This vector is protected by the object mutex (signalSlotMutexes())
-
- Each Connection is also part of a 'senders' linked list. The mutex
- of the receiver must be locked when touching the pointers of this
- linked list.
-*/
-class QObjectConnectionListVector : public QVector<QObjectPrivate::ConnectionList>
-{
-public:
- bool orphaned; //the QObject owner of this vector has been destroyed while the vector was inUse
- bool dirty; //some Connection have been disconnected (their receiver is 0) but not removed from the list yet
- int inUse; //number of functions that are currently accessing this object or its connections
- QObjectPrivate::ConnectionList allsignals;
-
- QObjectConnectionListVector()
- : QVector<QObjectPrivate::ConnectionList>(), orphaned(false), dirty(false), inUse(0)
- { }
-
- QObjectPrivate::ConnectionList &operator[](int at)
- {
- if (at < 0)
- return allsignals;
- return QVector<QObjectPrivate::ConnectionList>::operator[](at);
- }
-};
-
// Used by QAccessibleWidget
bool QObjectPrivate::isSender(const QObject *receiver, const char *signal) const
{
Q_Q(const QObject);
int signal_index = signalIndex(signal);
- if (signal_index < 0)
+ ConnectionData *cd = connections.load();
+ if (signal_index < 0 || !cd)
return false;
- QMutexLocker locker(signalSlotLock(q));
- if (connectionLists) {
- if (signal_index < connectionLists->count()) {
- const QObjectPrivate::Connection *c =
- connectionLists->at(signal_index).first;
-
- while (c) {
- if (c->receiver == receiver)
- return true;
- c = c->nextConnectionList;
- }
+ QBasicMutexLocker locker(signalSlotLock(q));
+ if (signal_index < cd->signalVector.count()) {
+ const QObjectPrivate::Connection *c = cd->signalVector.at(signal_index).first;
+
+ while (c) {
+ if (c->receiver == receiver)
+ return true;
+ c = c->nextConnectionList;
}
}
return false;
@@ -349,18 +283,17 @@ QObjectList QObjectPrivate::receiverList(const char *signal) const
Q_Q(const QObject);
QObjectList returnValue;
int signal_index = signalIndex(signal);
- if (signal_index < 0)
+ ConnectionData *cd = connections.load();
+ if (signal_index < 0 || !cd)
return returnValue;
- QMutexLocker locker(signalSlotLock(q));
- if (connectionLists) {
- if (signal_index < connectionLists->count()) {
- const QObjectPrivate::Connection *c = connectionLists->at(signal_index).first;
-
- while (c) {
- if (c->receiver)
- returnValue << c->receiver;
- c = c->nextConnectionList;
- }
+ QBasicMutexLocker locker(signalSlotLock(q));
+ if (signal_index < cd->signalVector.count()) {
+ const QObjectPrivate::Connection *c = cd->signalVector.at(signal_index).first;
+
+ while (c) {
+ if (c->receiver)
+ returnValue << c->receiver;
+ c = c->nextConnectionList;
}
}
return returnValue;
@@ -370,9 +303,12 @@ QObjectList QObjectPrivate::receiverList(const char *signal) const
QObjectList QObjectPrivate::senderList() const
{
QObjectList returnValue;
- QMutexLocker locker(signalSlotLock(q_func()));
- for (Connection *c = senders; c; c = c->next)
- returnValue << c->sender;
+ ConnectionData *cd = connections.load();
+ if (cd) {
+ QBasicMutexLocker locker(signalSlotLock(q_func()));
+ for (Connection *c = cd->senders; c; c = c->next)
+ returnValue << c->sender;
+ }
return returnValue;
}
@@ -389,12 +325,12 @@ QObjectList QObjectPrivate::senderList() const
void QObjectPrivate::addConnection(int signal, Connection *c)
{
Q_ASSERT(c->sender == q_ptr);
- if (!connectionLists)
- connectionLists = new QObjectConnectionListVector();
- if (signal >= connectionLists->count())
- connectionLists->resize(signal + 1);
+ ensureConnectionData();
+ ConnectionData *cd = connections.load();
+ if (signal >= cd->signalVector.count())
+ cd->signalVector.resize(signal + 1);
- ConnectionList &connectionList = (*connectionLists)[signal];
+ ConnectionList &connectionList = cd->connectionsForSignal(signal);
if (connectionList.last) {
connectionList.last->nextConnectionList = c;
} else {
@@ -404,27 +340,23 @@ void QObjectPrivate::addConnection(int signal, Connection *c)
cleanConnectionLists();
- c->prev = &(QObjectPrivate::get(c->receiver)->senders);
+ QObjectPrivate *rd = QObjectPrivate::get(c->receiver);
+ rd->ensureConnectionData();
+
+ c->prev = &(rd->connections.load()->senders);
c->next = *c->prev;
*c->prev = c;
if (c->next)
c->next->prev = &c->next;
-
- if (signal < 0) {
- connectedSignals[0] = connectedSignals[1] = ~0;
- } else if (signal < (int)sizeof(connectedSignals) * 8) {
- connectedSignals[signal >> 5] |= (1 << (signal & 0x1f));
- }
}
void QObjectPrivate::cleanConnectionLists()
{
- if (connectionLists->dirty && !connectionLists->inUse) {
+ ConnectionData *cd = connections.load();
+ if (cd->dirty && cd->ref == 1) {
// remove broken connections
- bool allConnected = false;
- for (int signal = -1; signal < connectionLists->count(); ++signal) {
- QObjectPrivate::ConnectionList &connectionList =
- (*connectionLists)[signal];
+ for (int signal = -1; signal < cd->signalVector.count(); ++signal) {
+ ConnectionList &connectionList = cd->connectionsForSignal(signal);
// Set to the last entry in the connection list that was *not*
// deleted. This is needed to update the list's last pointer
@@ -433,13 +365,11 @@ void QObjectPrivate::cleanConnectionLists()
QObjectPrivate::Connection **prev = &connectionList.first;
QObjectPrivate::Connection *c = *prev;
- bool connected = false; // whether the signal is still connected somewhere
while (c) {
if (c->receiver) {
last = c;
prev = &c->nextConnectionList;
c = *prev;
- connected = true;
} else {
QObjectPrivate::Connection *next = c->nextConnectionList;
*prev = next;
@@ -451,19 +381,41 @@ void QObjectPrivate::cleanConnectionLists()
// Correct the connection list's last pointer.
// As conectionList.last could equal last, this could be a noop
connectionList.last = last;
+ }
+ cd->dirty = false;
+ }
+}
- if (!allConnected && !connected && signal >= 0
- && size_t(signal) < sizeof(connectedSignals) * 8) {
- // This signal is no longer connected
- connectedSignals[signal >> 5] &= ~(1 << (signal & 0x1f));
- } else if (signal == -1) {
- allConnected = connected;
- }
+/*! \internal
+
+ Returns \c true if the signal with index \a signal_index from object \a sender is connected.
+
+ \a signal_index must be the index returned by QObjectPrivate::signalIndex;
+*/
+bool QObjectPrivate::isSignalConnected(uint signalIndex, bool checkDeclarative) const
+{
+ if (checkDeclarative && isDeclarativeSignalConnected(signalIndex))
+ return true;
+
+ ConnectionData *cd = connections.load();
+ if (!cd)
+ return false;
+
+ if (cd->allsignals.first)
+ return true;
+
+ if (signalIndex < uint(cd->signalVector.count())) {
+ const QObjectPrivate::Connection *c = cd->signalVector.at(signalIndex).first;
+ while (c) {
+ if (c->receiver)
+ return true;
+ c = c->nextConnectionList;
}
- connectionLists->dirty = false;
}
+ return false;
}
+
/*!
\internal
*/
@@ -921,60 +873,50 @@ QObject::~QObject()
}
}
- // set ref to zero to indicate that this object has been deleted
- if (d->currentSender != 0)
- d->currentSender->ref = 0;
- d->currentSender = 0;
+ QObjectPrivate::ConnectionData *cd = d->connections.load();
+ if (cd) {
+ if (cd->currentSender) {
+ cd->currentSender->receiverDeleted();
+ cd->currentSender = nullptr;
+ }
- if (d->connectionLists || d->senders) {
- QMutex *signalSlotMutex = signalSlotLock(this);
- QMutexLocker locker(signalSlotMutex);
+ QBasicMutex *signalSlotMutex = signalSlotLock(this);
+ QBasicMutexLocker locker(signalSlotMutex);
// disconnect all receivers
- if (d->connectionLists) {
- ++d->connectionLists->inUse;
- int connectionListsCount = d->connectionLists->count();
- for (int signal = -1; signal < connectionListsCount; ++signal) {
- QObjectPrivate::ConnectionList &connectionList =
- (*d->connectionLists)[signal];
-
- while (QObjectPrivate::Connection *c = connectionList.first) {
- if (!c->receiver) {
- connectionList.first = c->nextConnectionList;
- c->deref();
- continue;
- }
-
- QMutex *m = signalSlotLock(c->receiver);
- bool needToUnlock = QOrderedMutexLocker::relock(signalSlotMutex, m);
-
- if (c->receiver) {
- *c->prev = c->next;
- if (c->next) c->next->prev = c->prev;
- }
- c->receiver = 0;
- if (needToUnlock)
- m->unlock();
+ int receiverCount = cd->signalVector.count();
+ for (int signal = -1; signal < receiverCount; ++signal) {
+ QObjectPrivate::ConnectionList &connectionList = cd->connectionsForSignal(signal);
+ while (QObjectPrivate::Connection *c = connectionList.first) {
+ if (!c->receiver) {
connectionList.first = c->nextConnectionList;
-
- // The destroy operation must happen outside the lock
- if (c->isSlotObject) {
- c->isSlotObject = false;
- locker.unlock();
- c->slotObj->destroyIfLastRef();
- locker.relock();
- }
c->deref();
+ continue;
}
- }
- if (!--d->connectionLists->inUse) {
- delete d->connectionLists;
- } else {
- d->connectionLists->orphaned = true;
+ QBasicMutex *m = signalSlotLock(c->receiver);
+ bool needToUnlock = QOrderedMutexLocker::relock(signalSlotMutex, m);
+
+ if (c->receiver) {
+ *c->prev = c->next;
+ if (c->next) c->next->prev = c->prev;
+ }
+ c->receiver = 0;
+ if (needToUnlock)
+ m->unlock();
+
+ connectionList.first = c->nextConnectionList;
+
+ // The destroy operation must happen outside the lock
+ if (c->isSlotObject) {
+ c->isSlotObject = false;
+ locker.unlock();
+ c->slotObj->destroyIfLastRef();
+ locker.relock();
+ }
+ c->deref();
}
- d->connectionLists = 0;
}
/* Disconnect all senders:
@@ -986,14 +928,15 @@ QObject::~QObject()
* thread. That's why we set node->prev to &node, that way, if node is destroyed, node will
* be updated.
*/
- QObjectPrivate::Connection *node = d->senders;
+ QObjectPrivate::Connection *node = cd->senders;
while (node) {
+ Q_ASSERT(node->receiver);
QObject *sender = node->sender;
// Send disconnectNotify before removing the connection from sender's connection list.
// This ensures any eventual destructor of sender will block on getting receiver's lock
// and not finish until we release it.
sender->disconnectNotify(QMetaObjectPrivate::signal(sender->metaObject(), node->signal_index));
- QMutex *m = signalSlotLock(sender);
+ QBasicMutex *m = signalSlotLock(sender);
node->prev = &node;
bool needToUnlock = QOrderedMutexLocker::relock(signalSlotMutex, m);
//the node has maybe been removed while the mutex was unlocked in relock?
@@ -1004,9 +947,9 @@ QObject::~QObject()
continue;
}
node->receiver = 0;
- QObjectConnectionListVector *senderLists = sender->d_func()->connectionLists;
- if (senderLists)
- senderLists->dirty = true;
+ QObjectPrivate::ConnectionData *senderData = sender->d_func()->connections.load();
+ if (senderData)
+ senderData->dirty = true;
QtPrivate::QSlotObjectBase *slotObj = nullptr;
if (node->isSlotObject) {
@@ -1026,7 +969,12 @@ QObject::~QObject()
locker.relock();
}
}
+
+ cd->objectDeleted = true;
}
+ if (cd && !cd->ref.deref())
+ delete cd;
+ d->connections.store(nullptr);
if (!d->children.isEmpty())
d->deleteChildren();
@@ -1255,7 +1203,11 @@ bool QObject::event(QEvent *e)
{
QMetaCallEvent *mce = static_cast<QMetaCallEvent*>(e);
- QConnectionSenderSwitcher sw(this, const_cast<QObject*>(mce->sender()), mce->signalId());
+ if (!d_func()->connections.load()) {
+ QBasicMutexLocker locker(signalSlotLock(this));
+ d_func()->ensureConnectionData();
+ }
+ QObjectPrivate::Sender sender(this, const_cast<QObject*>(mce->sender()), mce->signalId());
mce->placeMetaCall(this);
break;
@@ -1559,9 +1511,11 @@ void QObjectPrivate::setThreadData_helper(QThreadData *currentData, QThreadData
}
// the current emitting thread shouldn't restore currentSender after calling moveToThread()
- if (currentSender)
- currentSender->ref = 0;
- currentSender = 0;
+ ConnectionData *cd = connections.load();
+ if (cd && cd->currentSender) {
+ cd->currentSender->receiverDeleted();
+ cd->currentSender = nullptr;
+ }
// set new thread data
targetData->ref();
@@ -2370,13 +2324,14 @@ QObject *QObject::sender() const
{
Q_D(const QObject);
- QMutexLocker locker(signalSlotLock(this));
- if (!d->currentSender)
- return 0;
+ QBasicMutexLocker locker(signalSlotLock(this));
+ QObjectPrivate::ConnectionData *cd = d->connections.load();
+ if (!cd || !cd->currentSender)
+ return nullptr;
- for (QObjectPrivate::Connection *c = d->senders; c; c = c->next) {
- if (c->sender == d->currentSender->sender)
- return d->currentSender->sender;
+ for (QObjectPrivate::Connection *c = cd->senders; c; c = c->next) {
+ if (c->sender == cd->currentSender->sender)
+ return cd->currentSender->sender;
}
return 0;
@@ -2411,14 +2366,15 @@ int QObject::senderSignalIndex() const
{
Q_D(const QObject);
- QMutexLocker locker(signalSlotLock(this));
- if (!d->currentSender)
+ QBasicMutexLocker locker(signalSlotLock(this));
+ QObjectPrivate::ConnectionData *cd = d->connections.load();
+ if (!cd || !cd->currentSender)
return -1;
- for (QObjectPrivate::Connection *c = d->senders; c; c = c->next) {
- if (c->sender == d->currentSender->sender) {
+ for (QObjectPrivate::Connection *c = cd->senders; c; c = c->next) {
+ if (c->sender == cd->currentSender->sender) {
// Convert from signal range to method range
- return QMetaObjectPrivate::signal(c->sender->metaObject(), d->currentSender->signal).methodIndex();
+ return QMetaObjectPrivate::signal(c->sender->metaObject(), cd->currentSender->signal).methodIndex();
}
}
@@ -2474,15 +2430,14 @@ int QObject::receivers(const char *signal) const
signal_index);
}
- QMutexLocker locker(signalSlotLock(this));
- if (d->connectionLists) {
- if (signal_index < d->connectionLists->count()) {
- const QObjectPrivate::Connection *c =
- d->connectionLists->at(signal_index).first;
- while (c) {
- receivers += c->receiver ? 1 : 0;
- c = c->nextConnectionList;
- }
+ QObjectPrivate::ConnectionData *cd = d->connections.load();
+ QBasicMutexLocker locker(signalSlotLock(this));
+ if (cd && signal_index < cd->signalVector.count()) {
+ const QObjectPrivate::Connection *c =
+ cd->signalVector.at(signal_index).first;
+ while (c) {
+ receivers += c->receiver ? 1 : 0;
+ c = c->nextConnectionList;
}
}
}
@@ -2522,22 +2477,8 @@ bool QObject::isSignalConnected(const QMetaMethod &signal) const
signalIndex += QMetaObjectPrivate::signalOffset(signal.mobj);
- QMutexLocker locker(signalSlotLock(this));
- if (d->connectionLists) {
- if (signalIndex < sizeof(d->connectedSignals) * 8 && !d->connectionLists->dirty)
- return d->isSignalConnected(signalIndex);
-
- if (signalIndex < uint(d->connectionLists->count())) {
- const QObjectPrivate::Connection *c =
- d->connectionLists->at(signalIndex).first;
- while (c) {
- if (c->receiver)
- return true;
- c = c->nextConnectionList;
- }
- }
- }
- return d->isDeclarativeSignalConnected(signalIndex);
+ QBasicMutexLocker locker(signalSlotLock(this));
+ return d->isSignalConnected(signalIndex, true);
}
/*!
@@ -3300,23 +3241,21 @@ QObjectPrivate::Connection *QMetaObjectPrivate::connect(const QObject *sender,
int method_offset = rmeta ? rmeta->methodOffset() : 0;
Q_ASSERT(!rmeta || QMetaObjectPrivate::get(rmeta)->revision >= 6);
- QObjectPrivate::StaticMetaCallFunction callFunction =
- rmeta ? rmeta->d.static_metacall : 0;
+ QObjectPrivate::StaticMetaCallFunction callFunction = rmeta ? rmeta->d.static_metacall : nullptr;
QOrderedMutexLocker locker(signalSlotLock(sender),
signalSlotLock(receiver));
- if (type & Qt::UniqueConnection) {
- QObjectConnectionListVector *connectionLists = QObjectPrivate::get(s)->connectionLists;
- if (connectionLists && connectionLists->count() > signal_index) {
- const QObjectPrivate::Connection *c2 =
- (*connectionLists)[signal_index].first;
+ QObjectPrivate::ConnectionData *scd = QObjectPrivate::get(s)->connections.load();
+ if (type & Qt::UniqueConnection && scd) {
+ if (scd->signalVector.count() > signal_index) {
+ const QObjectPrivate::Connection *c2 = scd->signalVector.at(signal_index).first;
int method_index_absolute = method_index + method_offset;
while (c2) {
if (!c2->isSlotObject && c2->receiver == receiver && c2->method() == method_index_absolute)
- return 0;
+ return nullptr;
c2 = c2->nextConnectionList;
}
}
@@ -3380,7 +3319,7 @@ bool QMetaObject::disconnectOne(const QObject *sender, int signal_index,
*/
bool QMetaObjectPrivate::disconnectHelper(QObjectPrivate::Connection *c,
const QObject *receiver, int method_index, void **slot,
- QMutex *senderMutex, DisconnectType disconnectType)
+ QBasicMutex *senderMutex, DisconnectType disconnectType)
{
bool success = false;
while (c) {
@@ -3389,7 +3328,7 @@ bool QMetaObjectPrivate::disconnectHelper(QObjectPrivate::Connection *c,
&& (method_index < 0 || (!c->isSlotObject && c->method() == method_index))
&& (slot == 0 || (c->isSlotObject && c->slotObj->compare(slot)))))) {
bool needToUnlock = false;
- QMutex *receiverMutex = 0;
+ QBasicMutex *receiverMutex = nullptr;
if (c->receiver) {
receiverMutex = signalSlotLock(c->receiver);
// need to relock this receiver and sender in the correct order
@@ -3437,41 +3376,36 @@ bool QMetaObjectPrivate::disconnect(const QObject *sender,
QObject *s = const_cast<QObject *>(sender);
- QMutex *senderMutex = signalSlotLock(sender);
- QMutexLocker locker(senderMutex);
+ QBasicMutex *senderMutex = signalSlotLock(sender);
+ QBasicMutexLocker locker(senderMutex);
- QObjectConnectionListVector *connectionLists = QObjectPrivate::get(s)->connectionLists;
- if (!connectionLists)
+ QObjectPrivate::ConnectionData *scd = QObjectPrivate::get(s)->connections.load();
+ if (!scd)
return false;
- // prevent incoming connections changing the connectionLists while unlocked
- ++connectionLists->inUse;
-
bool success = false;
- if (signal_index < 0) {
- // remove from all connection lists
- for (int sig_index = -1; sig_index < connectionLists->count(); ++sig_index) {
- QObjectPrivate::Connection *c =
- (*connectionLists)[sig_index].first;
+ {
+ // prevent incoming connections changing the connections->receivers while unlocked
+ QObjectPrivate::ConnectionDataPointer connections(scd);
+
+ if (signal_index < 0) {
+ // remove from all connection lists
+ for (int sig_index = -1; sig_index < scd->signalVector.count(); ++sig_index) {
+ QObjectPrivate::Connection *c = scd->connectionsForSignal(sig_index).first;
+ if (disconnectHelper(c, receiver, method_index, slot, senderMutex, disconnectType)) {
+ success = true;
+ scd->dirty = true;
+ }
+ }
+ } else if (signal_index < scd->signalVector.count()) {
+ QObjectPrivate::Connection *c = scd->signalVector.at(signal_index).first;
if (disconnectHelper(c, receiver, method_index, slot, senderMutex, disconnectType)) {
success = true;
- connectionLists->dirty = true;
+ scd->dirty = true;
}
}
- } else if (signal_index < connectionLists->count()) {
- QObjectPrivate::Connection *c =
- (*connectionLists)[signal_index].first;
- if (disconnectHelper(c, receiver, method_index, slot, senderMutex, disconnectType)) {
- success = true;
- connectionLists->dirty = true;
- }
}
- --connectionLists->inUse;
- Q_ASSERT(connectionLists->inUse >= 0);
- if (connectionLists->orphaned && !connectionLists->inUse)
- delete connectionLists;
-
locker.unlock();
if (success) {
QMetaMethod smethod = QMetaObjectPrivate::signal(smeta, signal_index);
@@ -3590,7 +3524,7 @@ void QMetaObject::connectSlotsByName(QObject *o)
\a signal must be in the signal index range (see QObjectPrivate::signalIndex()).
*/
static void queued_activate(QObject *sender, int signal, QObjectPrivate::Connection *c, void **argv,
- QMutexLocker &locker)
+ QBasicMutexLocker &locker)
{
const int *argumentTypes = c->argumentTypes.load();
if (!argumentTypes) {
@@ -3643,89 +3577,53 @@ static void queued_activate(QObject *sender, int signal, QObjectPrivate::Connect
QCoreApplication::postEvent(c->receiver, ev);
}
-/*!
- \internal
- */
-void QMetaObject::activate(QObject *sender, const QMetaObject *m, int local_signal_index,
- void **argv)
+template <bool callbacks_enabled>
+void doActivate(QObject *sender, int signal_index, void **argv)
{
- activate(sender, QMetaObjectPrivate::signalOffset(m), local_signal_index, argv);
-}
-
-/*!
- \internal
- */
-void QMetaObject::activate(QObject *sender, int signalOffset, int local_signal_index, void **argv)
-{
- int signal_index = signalOffset + local_signal_index;
+ QObjectPrivate *sp = QObjectPrivate::get(sender);
- if (sender->d_func()->blockSig)
+ if (sp->blockSig)
return;
- if (sender->d_func()->isDeclarativeSignalConnected(signal_index)
+ if (sp->isDeclarativeSignalConnected(signal_index)
&& QAbstractDeclarativeData::signalEmitted) {
Q_TRACE(QMetaObject_activate_begin_declarative_signal, sender, signal_index);
- QAbstractDeclarativeData::signalEmitted(sender->d_func()->declarativeData, sender,
+ QAbstractDeclarativeData::signalEmitted(sp->declarativeData, sender,
signal_index, argv);
Q_TRACE(QMetaObject_activate_end_declarative_signal, sender, signal_index);
}
- if (!sender->d_func()->isSignalConnected(signal_index, /*checkDeclarative =*/ false)
- && !qt_signal_spy_callback_set.signal_begin_callback
- && !qt_signal_spy_callback_set.signal_end_callback
- && !Q_TRACE_ENABLED(QMetaObject_activate_begin_signal)
- && !Q_TRACE_ENABLED(QMetaObject_activate_end_signal)) {
- // The possible declarative connection is done, and nothing else is connected, so:
- return;
- }
+ const QSignalSpyCallbackSet *signal_spy_set = callbacks_enabled ? qt_signal_spy_callback_set.load() : nullptr;
void *empty_argv[] = { nullptr };
if (!argv)
argv = empty_argv;
- if (qt_signal_spy_callback_set.signal_begin_callback != 0) {
- qt_signal_spy_callback_set.signal_begin_callback(sender, signal_index, argv);
+ if (!sp->isSignalConnected(signal_index, false)) {
+ // The possible declarative connection is done, and nothing else is connected
+ if (callbacks_enabled && signal_spy_set->signal_begin_callback != nullptr)
+ signal_spy_set->signal_begin_callback(sender, signal_index, argv);
+ Q_TRACE(QMetaObject_activate_begin_signal, sender, signal_index);
+ Q_TRACE(QMetaObject_activate_end_signal, sender, signal_index);
+ if (callbacks_enabled && signal_spy_set->signal_end_callback != nullptr)
+ signal_spy_set->signal_end_callback(sender, signal_index);
+ return;
}
+
+ if (callbacks_enabled && signal_spy_set->signal_begin_callback != nullptr)
+ signal_spy_set->signal_begin_callback(sender, signal_index, argv);
Q_TRACE(QMetaObject_activate_begin_signal, sender, signal_index);
{
- QMutexLocker locker(signalSlotLock(sender));
- struct ConnectionListsRef {
- QObjectConnectionListVector *connectionLists;
- ConnectionListsRef(QObjectConnectionListVector *connectionLists) : connectionLists(connectionLists)
- {
- if (connectionLists)
- ++connectionLists->inUse;
- }
- ~ConnectionListsRef()
- {
- if (!connectionLists)
- return;
-
- --connectionLists->inUse;
- Q_ASSERT(connectionLists->inUse >= 0);
- if (connectionLists->orphaned) {
- if (!connectionLists->inUse)
- delete connectionLists;
- }
- }
-
- QObjectConnectionListVector *operator->() const { return connectionLists; }
- };
- ConnectionListsRef connectionLists = sender->d_func()->connectionLists;
- if (!connectionLists.connectionLists) {
- locker.unlock();
- if (qt_signal_spy_callback_set.signal_end_callback != 0)
- qt_signal_spy_callback_set.signal_end_callback(sender, signal_index);
- Q_TRACE(QMetaObject_activate_end_signal, sender, signal_index);
- return;
- }
+ QBasicMutexLocker locker(signalSlotLock(sender));
+ Q_ASSERT(sp->connections);
+ QObjectPrivate::ConnectionDataPointer connections(sp->connections.load());
const QObjectPrivate::ConnectionList *list;
- if (signal_index < connectionLists->count())
- list = &connectionLists->at(signal_index);
+ if (signal_index < connections->signalVector.count())
+ list = &connections->signalVector.at(signal_index);
else
- list = &connectionLists->allsignals;
+ list = &connections->allsignals;
Qt::HANDLE currentThreadId = QThread::currentThreadId();
@@ -3741,7 +3639,7 @@ void QMetaObject::activate(QObject *sender, int signalOffset, int local_signal_i
continue;
QObject * const receiver = c->receiver;
- const bool receiverInSameThread = currentThreadId == receiver->d_func()->threadData->threadId.load();
+ const bool receiverInSameThread = currentThreadId == QObjectPrivate::get(receiver)->threadData->threadId.load();
// determine if this connection should be sent immediately or
// put into the event queue
@@ -3769,11 +3667,8 @@ void QMetaObject::activate(QObject *sender, int signalOffset, int local_signal_i
#endif
}
- QConnectionSenderSwitcher sw;
+ QObjectPrivate::Sender senderData(receiverInSameThread ? receiver : nullptr, sender, signal_index);
- if (receiverInSameThread) {
- sw.switchSender(receiver, sender, signal_index);
- }
if (c->isSlotObject) {
c->slotObj->ref();
QScopedPointer<QtPrivate::QSlotObjectBase, QSlotObjectBaseDeleter> obj(c->slotObj);
@@ -3790,57 +3685,85 @@ void QMetaObject::activate(QObject *sender, int signalOffset, int local_signal_i
locker.relock();
} else if (c->callFunction && c->method_offset <= receiver->metaObject()->methodOffset()) {
//we compare the vtable to make sure we are not in the destructor of the object.
- const int methodIndex = c->method();
const int method_relative = c->method_relative;
const auto callFunction = c->callFunction;
locker.unlock();
- if (qt_signal_spy_callback_set.slot_begin_callback != 0)
- qt_signal_spy_callback_set.slot_begin_callback(receiver, methodIndex, argv);
+ const int methodIndex = (Q_HAS_TRACEPOINTS || callbacks_enabled) ? c->method() : 0;
+ if (callbacks_enabled && signal_spy_set->slot_begin_callback != nullptr)
+ signal_spy_set->slot_begin_callback(receiver, methodIndex, argv);
Q_TRACE(QMetaObject_activate_begin_slot, receiver, methodIndex);
callFunction(receiver, QMetaObject::InvokeMetaMethod, method_relative, argv);
Q_TRACE(QMetaObject_activate_end_slot, receiver, methodIndex);
- if (qt_signal_spy_callback_set.slot_end_callback != 0)
- qt_signal_spy_callback_set.slot_end_callback(receiver, methodIndex);
+ if (callbacks_enabled && signal_spy_set->slot_end_callback != nullptr)
+ signal_spy_set->slot_end_callback(receiver, methodIndex);
locker.relock();
} else {
const int method = c->method_relative + c->method_offset;
locker.unlock();
- if (qt_signal_spy_callback_set.slot_begin_callback != 0) {
- qt_signal_spy_callback_set.slot_begin_callback(receiver, method, argv);
+ if (callbacks_enabled && signal_spy_set->slot_begin_callback != nullptr) {
+ signal_spy_set->slot_begin_callback(receiver, method, argv);
}
Q_TRACE(QMetaObject_activate_begin_slot, receiver, method);
- metacall(receiver, QMetaObject::InvokeMetaMethod, method, argv);
+ QMetaObject::metacall(receiver, QMetaObject::InvokeMetaMethod, method, argv);
Q_TRACE(QMetaObject_activate_end_slot, receiver, method);
- if (qt_signal_spy_callback_set.slot_end_callback != 0)
- qt_signal_spy_callback_set.slot_end_callback(receiver, method);
+ if (callbacks_enabled && signal_spy_set->slot_end_callback != nullptr)
+ signal_spy_set->slot_end_callback(receiver, method);
locker.relock();
}
- if (connectionLists->orphaned)
+ if (connections->objectDeleted)
break;
} while (c != last && (c = c->nextConnectionList) != 0);
- if (connectionLists->orphaned)
+ if (connections->objectDeleted)
break;
- } while (list != &connectionLists->allsignals &&
+ } while (list != &connections->allsignals &&
//start over for all signals;
- ((list = &connectionLists->allsignals), true));
+ ((list = &connections->allsignals), true));
}
- if (qt_signal_spy_callback_set.signal_end_callback != 0)
- qt_signal_spy_callback_set.signal_end_callback(sender, signal_index);
+ if (callbacks_enabled && signal_spy_set->signal_end_callback != nullptr)
+ signal_spy_set->signal_end_callback(sender, signal_index);
Q_TRACE(QMetaObject_activate_end_signal, sender, signal_index);
+
}
/*!
\internal
+ */
+void QMetaObject::activate(QObject *sender, const QMetaObject *m, int local_signal_index,
+ void **argv)
+{
+ int signal_index = local_signal_index + QMetaObjectPrivate::signalOffset(m);
+
+ if (Q_UNLIKELY(qt_signal_spy_callback_set.load()))
+ doActivate<true>(sender, signal_index, argv);
+ else
+ doActivate<false>(sender, signal_index, argv);
+}
+
+/*!
+ \internal
+ */
+void QMetaObject::activate(QObject *sender, int signalOffset, int local_signal_index, void **argv)
+{
+ int signal_index = signalOffset + local_signal_index;
+
+ if (Q_UNLIKELY(qt_signal_spy_callback_set.load()))
+ doActivate<true>(sender, signal_index, argv);
+ else
+ doActivate<false>(sender, signal_index, argv);
+ }
+
+/*!
+ \internal
signal_index comes from indexOfMethod()
*/
void QMetaObject::activate(QObject *sender, int signal_index, void **argv)
@@ -3853,7 +3776,7 @@ void QMetaObject::activate(QObject *sender, int signal_index, void **argv)
/*!
\internal
- Returns the signal index used in the internal connectionLists vector.
+ Returns the signal index used in the internal connections->receivers vector.
It is different from QMetaObject::indexOfSignal(): indexOfSignal is the same as indexOfMethod
while QObjectPrivate::signalIndex is smaller because it doesn't give index to slots.
@@ -4093,19 +4016,19 @@ void QObject::dumpObjectInfo() const
objectName().isEmpty() ? "unnamed" : objectName().toLocal8Bit().data());
Q_D(const QObject);
- QMutexLocker locker(signalSlotLock(this));
+ QBasicMutexLocker locker(signalSlotLock(this));
// first, look for connections where this object is the sender
qDebug(" SIGNALS OUT");
- if (d->connectionLists) {
- for (int signal_index = 0; signal_index < d->connectionLists->count(); ++signal_index) {
+ QObjectPrivate::ConnectionData *cd = d->connections.load();
+ if (cd && cd->signalVector.count()) {
+ for (int signal_index = 0; signal_index < cd->signalVector.count(); ++signal_index) {
const QMetaMethod signal = QMetaObjectPrivate::signal(metaObject(), signal_index);
qDebug(" signal: %s", signal.methodSignature().constData());
// receivers
- const QObjectPrivate::Connection *c =
- d->connectionLists->at(signal_index).first;
+ const QObjectPrivate::Connection *c = cd->signalVector.at(signal_index).first;
while (c) {
if (!c->receiver) {
qDebug(" <Disconnected receiver>");
@@ -4133,8 +4056,8 @@ void QObject::dumpObjectInfo() const
// now look for connections where this object is the receiver
qDebug(" SIGNALS IN");
- if (d->senders) {
- for (QObjectPrivate::Connection *s = d->senders; s; s = s->next) {
+ if (cd && cd->senders) {
+ for (QObjectPrivate::Connection *s = cd->senders; s; s = s->next) {
QByteArray slotName = QByteArrayLiteral("<unknown>");
if (!s->isSlotObject) {
const QMetaMethod slot = metaObject()->method(s->method());
@@ -4869,11 +4792,10 @@ QMetaObject::Connection QObjectPrivate::connectImpl(const QObject *sender, int s
QOrderedMutexLocker locker(signalSlotLock(sender),
signalSlotLock(receiver));
- if (type & Qt::UniqueConnection && slot) {
- QObjectConnectionListVector *connectionLists = QObjectPrivate::get(s)->connectionLists;
- if (connectionLists && connectionLists->count() > signal_index) {
- const QObjectPrivate::Connection *c2 =
- (*connectionLists)[signal_index].first;
+ if (type & Qt::UniqueConnection && slot && QObjectPrivate::get(s)->connections.load()) {
+ QObjectPrivate::ConnectionData *connections = QObjectPrivate::get(s)->connections.load();
+ if (connections->signalVector.count() > signal_index) {
+ const QObjectPrivate::Connection *c2 = connections->signalVector.at(signal_index).first;
while (c2) {
if (c2->receiver == receiver && c2->isSlotObject && c2->slotObj->compare(slot)) {
@@ -4924,20 +4846,20 @@ bool QObject::disconnect(const QMetaObject::Connection &connection)
if (!c || !c->receiver)
return false;
- QMutex *senderMutex = signalSlotLock(c->sender);
- QMutex *receiverMutex = signalSlotLock(c->receiver);
+ QBasicMutex *senderMutex = signalSlotLock(c->sender);
+ QBasicMutex *receiverMutex = signalSlotLock(c->receiver);
{
QOrderedMutexLocker locker(senderMutex, receiverMutex);
- QObjectConnectionListVector *connectionLists = QObjectPrivate::get(c->sender)->connectionLists;
- Q_ASSERT(connectionLists);
- connectionLists->dirty = true;
+ QObjectPrivate::ConnectionData *connections = QObjectPrivate::get(c->sender)->connections.load();
+ Q_ASSERT(connections);
+ connections->dirty = true;
*c->prev = c->next;
if (c->next)
c->next->prev = c->prev;
- c->receiver = 0;
+ c->receiver = nullptr;
}
// destroy the QSlotObject, if possible
@@ -4949,7 +4871,7 @@ bool QObject::disconnect(const QMetaObject::Connection &connection)
c->sender->disconnectNotify(QMetaObjectPrivate::signal(c->sender->metaObject(),
c->signal_index));
- const_cast<QMetaObject::Connection &>(connection).d_ptr = 0;
+ const_cast<QMetaObject::Connection &>(connection).d_ptr = nullptr;
c->deref(); // has been removed from the QMetaObject::Connection object
return true;
diff --git a/src/corelib/kernel/qobject_p.h b/src/corelib/kernel/qobject_p.h
index a762e6f529..823c7a195a 100644
--- a/src/corelib/kernel/qobject_p.h
+++ b/src/corelib/kernel/qobject_p.h
@@ -79,9 +79,9 @@ struct QSignalSpyCallbackSet
EndCallback signal_end_callback,
slot_end_callback;
};
-void Q_CORE_EXPORT qt_register_signal_spy_callbacks(const QSignalSpyCallbackSet &callback_set);
+void Q_CORE_EXPORT qt_register_signal_spy_callbacks(QSignalSpyCallbackSet *callback_set);
-extern QSignalSpyCallbackSet Q_CORE_EXPORT qt_signal_spy_callback_set;
+extern Q_CORE_EXPORT QBasicAtomicPointer<QSignalSpyCallbackSet> qt_signal_spy_callback_set;
enum { QObjectPrivateVersion = QT_VERSION };
@@ -167,11 +167,69 @@ public:
struct Sender
{
+ Sender(QObject *receiver, QObject *sender, int signal)
+ : receiver(receiver), sender(sender), signal(signal)
+ {
+ if (receiver) {
+ ConnectionData *cd = receiver->d_func()->connections.load();
+ previous = cd->currentSender;
+ cd->currentSender = this;
+ }
+ }
+ ~Sender()
+ {
+ if (receiver)
+ receiver->d_func()->connections.load()->currentSender = previous;
+ }
+ void receiverDeleted()
+ {
+ Sender *s = this;
+ while (s) {
+ s->receiver = nullptr;
+ s = s->previous;
+ }
+ }
+ Sender *previous;
+ QObject *receiver;
QObject *sender;
int signal;
- int ref;
};
+ /*
+ This contains the all connections from and to an object.
+
+ The signalVector contains the lists of connections for a given signal. The index in the vector correspond
+ to the signal index. The signal index is the one returned by QObjectPrivate::signalIndex (not
+ QMetaObject::indexOfSignal). allsignals contains a list of special connections that will get invoked on
+ any signal emission. This is done by connecting to signal index -1.
+
+ This vector is protected by the object mutex (signalSlotLock())
+
+ Each Connection is also part of a 'senders' linked list. This one contains all connections connected
+ to a slot in this object. The mutex of the receiver must be locked when touching the pointers of this
+ linked list.
+ */
+ struct ConnectionData {
+ bool objectDeleted = false; //the QObject owner of this vector has been destroyed while the vector was inUse
+ struct Ref {
+ int _ref = 0;
+ void ref() { ++_ref; }
+ int deref() { return --_ref; }
+ operator int() const { return _ref; }
+ };
+
+ Ref ref;
+ bool dirty = false; //some Connection have been disconnected (their receiver is 0) but not removed from the list yet
+ ConnectionList allsignals;
+ QVector<ConnectionList> signalVector;
+ Connection *senders = nullptr;
+ Sender *currentSender = nullptr; // object currently activating the object
+
+ ConnectionList &connectionsForSignal(int signal)
+ {
+ return signal < 0 ? allsignals : signalVector[signal];
+ }
+ };
QObjectPrivate(int version = QObjectPrivateVersion);
virtual ~QObjectPrivate();
@@ -189,19 +247,13 @@ public:
void addConnection(int signal, Connection *c);
void cleanConnectionLists();
- static inline Sender *setCurrentSender(QObject *receiver,
- Sender *sender);
- static inline void resetCurrentSender(QObject *receiver,
- Sender *currentSender,
- Sender *previousSender);
-
static QObjectPrivate *get(QObject *o) {
return o->d_func();
}
static const QObjectPrivate *get(const QObject *o) { return o->d_func(); }
int signalIndex(const char *signalName, const QMetaObject **meta = nullptr) const;
- inline bool isSignalConnected(uint signalIdx, bool checkDeclarative = true) const;
+ bool isSignalConnected(uint signalIdx, bool checkDeclarative = true) const;
inline bool isDeclarativeSignalConnected(uint signalIdx) const;
// To allow abitrary objects to call connectNotify()/disconnectNotify() without making
@@ -224,15 +276,21 @@ public:
const int *types, const QMetaObject *senderMetaObject);
static QMetaObject::Connection connect(const QObject *sender, int signal_index, QtPrivate::QSlotObjectBase *slotObj, Qt::ConnectionType type);
static bool disconnect(const QObject *sender, int signal_index, void **slot);
+
+ void ensureConnectionData()
+ {
+ if (connections.load())
+ return;
+ ConnectionData *cd = new ConnectionData;
+ cd->ref.ref();
+ connections.store(cd);
+ }
public:
ExtraData *extraData; // extra data set by the user
QThreadData *threadData; // id of the thread that owns the object
- QObjectConnectionListVector *connectionLists;
-
- Connection *senders; // linked list of connections connected to this object
- Sender *currentSender; // object currently activating the object
- mutable quint32 connectedSignals[2];
+ using ConnectionDataPointer = QExplicitlySharedDataPointer<ConnectionData>;
+ QAtomicPointer<ConnectionData> connections;
union {
QObject *currentChildBeingDeleted; // should only be used when QObjectData::isDeletingChildren is set
@@ -246,47 +304,12 @@ public:
Q_DECLARE_TYPEINFO(QObjectPrivate::ConnectionList, Q_MOVABLE_TYPE);
-/*! \internal
-
- Returns \c true if the signal with index \a signal_index from object \a sender is connected.
- Signals with indices above a certain range are always considered connected (see connectedSignals
- in QObjectPrivate).
-
- \a signal_index must be the index returned by QObjectPrivate::signalIndex;
-*/
-inline bool QObjectPrivate::isSignalConnected(uint signal_index, bool checkDeclarative) const
-{
- return signal_index >= sizeof(connectedSignals) * 8
- || (connectedSignals[signal_index >> 5] & (1 << (signal_index & 0x1f))
- || (checkDeclarative && isDeclarativeSignalConnected(signal_index)));
-}
-
inline bool QObjectPrivate::isDeclarativeSignalConnected(uint signal_index) const
{
return declarativeData && QAbstractDeclarativeData::isSignalConnected
&& QAbstractDeclarativeData::isSignalConnected(declarativeData, q_func(), signal_index);
}
-inline QObjectPrivate::Sender *QObjectPrivate::setCurrentSender(QObject *receiver,
- Sender *sender)
-{
- Sender *previousSender = receiver->d_func()->currentSender;
- receiver->d_func()->currentSender = sender;
- return previousSender;
-}
-
-inline void QObjectPrivate::resetCurrentSender(QObject *receiver,
- Sender *currentSender,
- Sender *previousSender)
-{
- // ref is set to zero when this object is deleted during the metacall
- if (currentSender->ref == 1)
- receiver->d_func()->currentSender = previousSender;
- // if we've recursed, we need to tell the caller about the objects deletion
- if (previousSender)
- previousSender->ref = currentSender->ref;
-}
-
inline void QObjectPrivate::connectNotify(const QMetaMethod &signal)
{
q_ptr->connectNotify(signal);
diff --git a/src/corelib/kernel/qtcore_eval.cpp b/src/corelib/kernel/qtcore_eval.cpp
deleted file mode 100644
index 5437210699..0000000000
--- a/src/corelib/kernel/qtcore_eval.cpp
+++ /dev/null
@@ -1,560 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtCore module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qcoreevent.h>
-#include <qdatetime.h>
-#include <qlibraryinfo.h>
-#include <qobject.h>
-#include <qcoreapplication.h>
-#include <private/qcoreapplication_p.h>
-
-#include "stdio.h"
-#include "stdlib.h"
-
-QT_BEGIN_NAMESPACE
-
-#include "qconfig_eval.cpp"
-
-static const char boilerplate_supported_but_time_limited[] =
- "\nQt %1 Evaluation License\n"
- "Copyright (C) 2016 The Qt Company Ltd.\n"
- "This trial version may only be used for evaluation purposes\n"
- "and will shut down after 120 minutes.\n"
- "Registered to:\n"
- " Licensee: %2\n\n"
- "The evaluation expires in %4 days\n\n"
- "Contact http://www.qt.io/contact-us for pricing and purchasing information.\n";
-
-static const char boilerplate_supported[] =
- "\nQt %1 Evaluation License\n"
- "Copyright (C) 2016 The Qt Company Ltd.\n"
- "This trial version may only be used for evaluation purposes\n"
- "Registered to:\n"
- " Licensee: %2\n\n"
- "The evaluation expires in %4 days\n\n"
- "Contact http://www.qt.io/contact-us for pricing and purchasing information.\n";
-
-static const char boilerplate_expired[] =
- "This software is using the trial version of the Qt GUI toolkit.\n"
- "The trial period has expired. If you need more time to\n"
- "evaluate Qt, or if you have any questions about Qt, contact us\n"
- "at: http://www.qt.io/contact-us.\n\n";
-
-static const char will_shutdown_1min[] =
- "\nThe evaluation of Qt will SHUT DOWN in 1 minute.\n"
- "Contact http://www.qt.io/contact-us for pricing and purchasing information.\n";
-
-static const char will_shutdown_now[] =
- "\nThe evaluation of Qt has now reached its automatic\n"
- "timeout and will shut down.\n"
- "Contact http://www.qt.io/contact-us for pricing and purchasing information.\n";
-
-enum EvaluationStatus {
- EvaluationNotSupported = 0,
- EvaluationSupportedButTimeLimited,
- EvaluationSupported
-};
-
-static EvaluationStatus qt_eval_is_supported()
-{
- const volatile char *const license_key = qt_eval_key_data + 12;
-
- // fast fail
- if (!qt_eval_key_data[0] || !*license_key)
- return EvaluationNotSupported;
-
- // is this an unsupported evaluation?
- const volatile char *typecode = license_key;
- int field = 2;
- for ( ; field && *typecode; ++typecode)
- if (*typecode == '-')
- --field;
-
- if (!field && typecode[1] == '4' && typecode[2] == 'M') {
- if (typecode[0] == 'Q')
- return EvaluationSupportedButTimeLimited;
- else if (typecode[0] == 'R' || typecode[0] == 'Z')
- return EvaluationSupported;
- }
- return EvaluationNotSupported;
-}
-
-static int qt_eval_days_left()
-{
- const volatile char *const expiry_date = qt_eval_expiry_date + 12;
-
- QDate today = QDate::currentDate();
- QDate lastday = QDate::fromString(
- QString::fromLatin1(const_cast<const char*>(expiry_date)), Qt::ISODate);
- return today.daysTo(lastday);
-}
-
-static bool qt_eval_is_expired()
-{
- return qt_eval_days_left() < 0;
-}
-
-static QString qt_eval_string()
-{
- const char *msg;
- switch (qt_eval_is_supported()) {
- case EvaluationSupportedButTimeLimited:
- msg = boilerplate_supported_but_time_limited;
- break;
- case EvaluationSupported:
- msg = boilerplate_supported;
- break;
- default:
- return QString();
- }
-
- return QString::fromLatin1(msg)
- .arg(QLatin1String(QT_VERSION_STR))
- .arg(QLibraryInfo::licensee())
- .arg(qt_eval_days_left());
-}
-
-#define WARN_TIMEOUT 60 * 1000 * 119
-#define KILL_DELAY 60 * 1000 * 1
-
-class QCoreFuriCuri : public QObject
-{
-public:
-
- int warn;
- int kill;
-
- QCoreFuriCuri() : QObject(), warn(-1), kill(-1)
- {
- if (qt_eval_is_supported() == EvaluationSupportedButTimeLimited) {
- warn = startTimer(WARN_TIMEOUT);
- kill = 0;
- }
- }
-
- void timerEvent(QTimerEvent *e) override {
- if (e->timerId() == warn) {
- killTimer(warn);
- fprintf(stderr, "%s\n", will_shutdown_1min);
- kill = startTimer(KILL_DELAY);
- } else if (e->timerId() == kill) {
- fprintf(stderr, "%s\n", will_shutdown_now);
- QCoreApplication::instance()->quit();
- }
- }
-};
-
-#if defined(QT_BUILD_CORE_LIB) || defined (QT_BOOTSTRAPPED)
-
-void qt_core_eval_init(QCoreApplicationPrivate::Type type)
-{
- if (type != QCoreApplicationPrivate::Tty)
- return;
-
- if (!qt_eval_is_supported())
- return;
-
- if (qt_eval_is_expired()) {
- fprintf(stderr, "%s\n", boilerplate_expired);
- exit(0);
- } else {
- fprintf(stderr, "%s\n", qPrintable(qt_eval_string()));
- Q_UNUSED(new QCoreFuriCuri());
- }
-}
-#endif
-
-#ifdef QT_BUILD_WIDGETS_LIB
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qdialog.h>
-#include <qlabel.h>
-#include <qlayout.h>
-#include <qmessagebox.h>
-#if QT_CONFIG(pushbutton)
-#include <qpushbutton.h>
-#endif
-#include <qtimer.h>
-#include <qapplication.h>
-QT_END_INCLUDE_NAMESPACE
-
-
-static const char * const qtlogo_eval_xpm[] = {
-/* columns rows colors chars-per-pixel */
-"46 55 174 2",
-" c #002E02",
-". c #00370D",
-"X c #003A0E",
-"o c #003710",
-"O c #013C13",
-"+ c #043E1A",
-"@ c #084F0A",
-"# c #0B520C",
-"$ c #054413",
-"% c #0C4C17",
-"& c #07421D",
-"* c #09451D",
-"= c #0D491E",
-"- c #125515",
-"; c #13541A",
-": c #17591B",
-"> c #1B5C1D",
-", c #1F611F",
-"< c #20621E",
-"1 c #337B1E",
-"2 c #0B4521",
-"3 c #0F4923",
-"4 c #114B24",
-"5 c #154D2A",
-"6 c #175323",
-"7 c #1C5924",
-"8 c #1C532F",
-"9 c #1E5432",
-"0 c #245936",
-"q c #265938",
-"w c #295C3B",
-"e c #246324",
-"r c #266823",
-"t c #2A6C24",
-"y c #276628",
-"u c #2D7026",
-"i c #327427",
-"p c #367927",
-"a c #37782A",
-"s c #397C2A",
-"d c #2E613E",
-"f c #336C37",
-"g c #2F6040",
-"h c #356545",
-"j c #3C6B4E",
-"k c #3F6C51",
-"l c #406E4F",
-"z c #406D52",
-"x c #477457",
-"c c #497557",
-"v c #4B7857",
-"b c #517B5E",
-"n c #3C8423",
-"m c #3E812C",
-"M c #53A61D",
-"N c #41862C",
-"B c #458A2D",
-"V c #498F2D",
-"C c #479324",
-"Z c #489226",
-"A c #4D952C",
-"S c #478B30",
-"D c #488C30",
-"F c #4D9232",
-"G c #509632",
-"H c #549A33",
-"J c #589F35",
-"K c #56A526",
-"L c #57A821",
-"P c #5BAA27",
-"I c #57A32A",
-"U c #5CA72E",
-"Y c #5DAB2A",
-"T c #5CA336",
-"R c #60AD2E",
-"E c #63B12D",
-"W c #65AF35",
-"Q c #62A53F",
-"! c #65AE39",
-"~ c #66B036",
-"^ c #6AB437",
-"/ c #67B138",
-"( c #6AB339",
-") c #6DB838",
-"_ c #70BA3C",
-"` c #4D8545",
-"' c #4E8942",
-"] c #548851",
-"[ c #6FAF4A",
-"{ c #6DB243",
-"} c #71B546",
-"| c #70B840",
-" . c #73B648",
-".. c #79BA4E",
-"X. c #7CBB53",
-"o. c #598266",
-"O. c #62886D",
-"+. c #6A8F75",
-"@. c #6B9173",
-"#. c #70937A",
-"$. c #799F79",
-"%. c #7BAF66",
-"&. c #81BD5B",
-"*. c #85BF60",
-"=. c #85AC7F",
-"-. c #8DBA7B",
-";. c #87C061",
-":. c #8AC364",
-">. c #8DC46A",
-",. c #90C56E",
-"<. c #93C771",
-"1. c #96CA73",
-"2. c #9ACB7C",
-"3. c #9FD07D",
-"4. c #779981",
-"5. c #7F9F89",
-"6. c #809F88",
-"7. c #82A18B",
-"8. c #86A192",
-"9. c #8DA994",
-"0. c #8FA998",
-"q. c #94AF9B",
-"w. c #97B991",
-"e. c #97B19E",
-"r. c #9DB6A3",
-"t. c #A3BCA7",
-"y. c #A6BCAB",
-"u. c #A9BEB1",
-"i. c #9ECD81",
-"p. c #A2CF85",
-"a. c #A5D284",
-"s. c #A6D189",
-"d. c #A9D28E",
-"f. c #ABD491",
-"g. c #B1D797",
-"h. c #B1D699",
-"j. c #B5D89E",
-"k. c #ADC5AC",
-"l. c #B1CAAE",
-"z. c #B9DAA3",
-"x. c #BDDDA8",
-"c. c #ADC1B4",
-"v. c #B2C6B6",
-"b. c #B5C6BC",
-"n. c #B6C9BA",
-"m. c #BCD1BA",
-"M. c #C6E1B4",
-"N. c #CDE5BD",
-"B. c #C2D2C6",
-"V. c #CADEC2",
-"C. c #C6D3CC",
-"Z. c #C8D7CB",
-"A. c #CEDAD2",
-"S. c #D2DDD4",
-"D. c #D3E9C6",
-"F. c #D7EBC9",
-"G. c #D9EBCD",
-"H. c #DEEED4",
-"J. c #D6E0D9",
-"K. c #DAE4DC",
-"L. c #E0EFD7",
-"P. c #E5F2DD",
-"I. c #DFE8E0",
-"U. c #E4EBE5",
-"Y. c #E9EFEA",
-"T. c #EDF4EB",
-"R. c #F0FAE6",
-"E. c #F1F8EC",
-"W. c #EDF0F0",
-"Q. c #F4F7F3",
-"!. c #F6F9F4",
-"~. c #F8FAF7",
-"^. c #FEFEFE",
-"/. c None",
-/* pixels */
-"/././././.c h ' Q / W _ &.p././././././././././././././././././././././././././././././././.",
-"/././.4 O % Z ~ ~ W ~ W R U R R ( X.>.p././././././././././././././././././././././././././.",
-"/./.. * = J _ ~ ~ ~ ~ ~ / / / / W W U P P U W .;.2././././././././././././././././././././.",
-"/.= = & a ) W ~ ~ ~ ~ ~ / W / ~ ~ ~ ^ ( ( ^ ~ R R U P Y ~ .;.2././././././././././././././.",
-"O.O = = T ^ W ~ ~ ~ ~ ~ ~ W W / W ~ ~ ~ ~ ~ ~ ~ ( ( ( ( ~ W Y Y Y Y W { &.1././././././././.",
-"0 = * 7 ~ ~ ~ ~ ~ ~ ~ ~ ~ / / W ~ ~ ~ ~ ~ ~ ~ ~ W W W ~ ~ ~ ~ ( ( ( W W R U P U W { X.1.f./.",
-"= = & e ^ W ~ ~ ~ ~ ~ ~ ~ ~ / / ~ ~ ~ ~ ~ ~ ~ ~ W ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ^ ( ( / ~ W R U U Y ",
-"= = & e ^ W ~ ~ ~ ~ ~ ~ ~ ~ W W ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W ( W ~ ~ ~ ^ ^ ( ",
-"= = * e ^ W ~ ~ ~ ~ ~ ~ / W / W ! ( / ~ W ^ ( ( ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W ~ W W ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ ! ~ ~ ~ ~ ~ ~ W W ^ _ ~ K Y W W R P Y W ( ~ ~ ~ ~ ~ ~ ~ W / ~ ~ ~ ^ W ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ ~ ~ ~ ~ W ) W 1 ` w.V.L.H.D.z.,.~ Y ^ ~ ~ ~ ~ ~ W ~ ~ ~ ( ~ W W ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ ~ ~ ~ W ) V = 8.~.^.^.^.^.^.^.^.U.<.Y ~ ~ ~ ~ ~ W W ! ~ Y W ^ W ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ ~ ~ W ^ B O u.^.~.^.^.^.^.~.~.^.^.^.h.Y ^ ~ ~ ^ F $ k.R.G.1.Y / ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ ~ ~ ~ / W ( J X 7.^.~.^.^.^.^.^.^.^.^.^.^.^.s.Y / W ) a 2 U.^.^.d.U ( ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W / ~ ~ ~ ^ > w ~.^.^.^.^.^.F.%.v c.^.^.^.^.~.X.W ~ ^ > h ^.^.^.d.P ( ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ W ^ H o e.^.^.^.^.^.G.Y E n . y.^.^.^.^.M.Y ( ! $ @.^.~.^.f.U ( / ~ ~ W ~ ~ ",
-"= = & e ^ W ~ W ! ) t 4 U.^.^.^.^.^.>.U ( _ , 9 ~.^.^.^.~...^ A y.^.~.^.s.M W Y ~ ~ ~ ~ ~ ",
-"= 3 & e ^ W ~ ( ^ ( $ c ^.^.^.^.^.E.) ~ ~ ^ S o n.^.^.^.^.=.- l.v.Y.^.^.^.M.:.:.X.~ ~ ~ ~ ~ ",
-"= = & e ^ ! W W ( J X 7.^.^.^.^.^.F.Y ( W ^ T X 6.^.^.~.^.c.. J.^.^.^.^.^.^.^.^.P.~ ~ ~ ~ ~ ",
-"= = & r ^ W / W ) B o v.^.~.^.^.^.M.U / ~ ~ ! $ o.^.^.^.^.K.* S.^.^.^.^.^.^.^.^.P.~ ~ ~ ~ ~ ",
-"= = & e ^ ! ~ W ) a + S.^.^.^.^.^.z.P ( W ~ ( % z ^.^.^.^.~.f t.U.^.^.^.^.~.^.^.P.~ ~ ~ ~ ~ ",
-"* = & e ^ W ~ W ) t 3 Y.^.^.^.^.^.f.P ( ~ ~ ^ ; h ^.^.^.^.^.:.@ j ^.^.^.^.h.{ X.&.~ ~ ~ ~ ~ ",
-"3 = & e ^ W ~ ~ ^ e 8 Q.^.^.^.^.^.s.P ~ ~ W ^ > 0 ~.^.^.^.^.1.# z ^.^.^.^.d.L W R ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ ^ > q ~.^.^.^.^.^.p.U ^ ~ W ) e 9 ~.^.^.^.^.3.# k ^.^.^.^.f.Y ( / ~ ~ ~ ~ ~ ",
-"= = & e ^ W / W ^ > w ~.^.^.^.^.^.i.Y / ~ W ^ e 8 Q.^.^.^.^.a.# z ^.^.^.^.f.Y / ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W / W ^ > w ^.^.^.^.^.^.2.Y / ~ ~ ) e 8 Q.^.^.^.^.s.# z ^.^.^.^.d.P ( ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W W W ^ > q ^.^.^.^.^.^.p.Y / ~ ~ ^ e 9 Q.^.^.^.^.a.@ z ^.^.^.^.f.U / ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W / W ) 7 9 Q.^.^.^.^.^.a.P / ~ W ) , 9 Q.^.^.^.^.3.# z ^.^.~.^.f.P ^ ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W / W ) r 5 T.^.^.^.^.^.d.Y / ~ W ) > q ~.^.^.^.^.1.# k ^.^.^.^.f.Y ( ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ / / W ) i 2 I.^.^.^.^.^.h.P ( ~ W ( > g ^.^.^.^.^.:.# z ^.^.^.^.f.P / ~ ~ ~ ~ ~ ~ ",
-"= = & e ( W / W ) m O Z.^.^.^.^.^.x.P / ~ ~ ( ; j ^.^.^.^.~.&.- k ^.^.~.^.f.P / ~ ~ ~ ~ ~ ~ ",
-"= = & e ( W / W ) F o y.^.~.^.^.^.N.U ( ~ ~ W $ b ^.^.^.^.R._ - k ^.^.^.^.f.Y ( ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ ^ J X 4.^.^.^.^.^.L.~ ~ W ^ T X #.^.^.^.^.F.~ ; j ^.^.^.^.f.U ( ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ ~ ~ ~ / ^ % l ^.^.^.^.^.!. .R ^ ^ G . r.^.~.^.^.j.E : j ^.^.^.^.f.P ) ( ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ W ) u = U.^.^.^.^.^.1.Y ! ) a & K.^.^.^.^.;.~ : j ^.^.~.^.z.M I I / ~ ~ W ~ ",
-"= = & e ( W ~ ~ W ( G . q.^.^.^.^.^.D.U ^ ! X o.^.^.^.^.P.~ ^ > g ^.^.^.^.E.-.$.m.X.W ~ ~ ~ ",
-"= = & e ^ / ~ ~ ^ ! ( > w ~.^.^.^.^.^.h.T > j T.^.^.~.^.a.Y _ i 3 U.^.^.^.^.^.^.^.X.R ~ ~ ~ ",
-"= = & e ^ / ~ ~ W W ^ H . 9.^.~.^.^.^.^.K.C.~.^.^.^.^.H.W W ^ T . q.^.~.^.^.^.^.^.X.R ~ ~ ~ ",
-"= = + e ^ W / ~ W W W ) m + B.^.~.^.^.^.^.^.^.^.^.^.E.X.Y ( W ^ B 6 y.^.^.^.E.D.2.( ~ ~ ~ ~ ",
-"= = * e ^ ! / ! W ^ W W ) a 4 b.^.^.^.^.^.^.^.^.^.P...Y ( ! W ! ^ W Z [ *.X.{ Y U ~ ~ ~ ~ ~ ",
-"= = & e ( W ~ ~ W / W / W ) A < +.A.~.^.^.^.^.!.p.W R ~ ~ ~ ~ ~ W / ) E U W W / ^ ~ ~ ~ ~ ~ ",
-"= = & e ^ W ~ ~ / W / / / W ( _ Z X 6.^.^.^.^.E.W ~ ^ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ / ~ ~ ~ ~ ~ ~ ~ ~ ",
-"= = & e ^ ~ ~ ~ W W / W ~ ~ ~ ~ ) ; h ^.^.^.^.^.d.M U ~ / ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W ",
-"= = & e ^ W ~ ~ ^ W W / ~ ~ ~ W ) p + S.^.^.^.^.~.M.f. .W ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ .",
-"= = & e ^ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W ( T O +.^.~.^.^.^.^.^.&.Y ( ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W ( Y 2.",
-"= = & e ( W ~ ~ ~ ~ ~ ~ ~ ~ ~ / W ) N + b.^.^.^.^.^.^.&.R ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W /.",
-"= = & e ^ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W ^ N 7 r.W.^.^.^.!.X.W ~ ~ W ~ W ~ ~ ~ ~ ~ ~ / ( ( K p./.",
-"= = & e ( W ~ ~ W ~ ~ ~ ~ ~ ~ ~ ~ ~ W ( W C Q &.:.X.| ~ ~ ~ ~ W ~ / ~ ( / ( ~ W E U P 1././.",
-"= = + e ^ / / / ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W / ) ^ R Y W W ~ ~ ( / ( / W R Y Y U R ( X.,././././.",
-"= = * e ( / ~ / ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ W W W ! ( ( ( W W E U P Y W ( X.,.d./././././././././.",
-"= = * e ( W ~ ~ ~ ~ W ! ~ W ~ W ~ ( ( / ^ W W U Y P W ( X.,.d./././././././././././././././.",
-"8 $ * e ( W ~ ~ ~ ! ( ( ( / ( W R Y Y Y R ( X.>.d./././././././././././././././././././././.",
-"/.d . y ^ / / / ( W Y Y P P W ( X.>.d./././././././././././././././././././././././././././.",
-"/./.h : ^ R R R W ( X.<.f./././././././././././././././././././././././././././././././././.",
-"/././.] _ *.3./././././././././././././././././././././././././././././././././././././././."
-};
-
-class EvalMessageBox : public QDialog
-{
-public:
- EvalMessageBox(bool expired)
- {
- setWindowTitle(QLatin1String(" "));
-
- QString str = expired ? QLatin1String(boilerplate_expired) : qt_eval_string();
- str = str.trimmed();
-
- QFrame *border = new QFrame(this);
-
- QLabel *pixmap_label = new QLabel(border);
- pixmap_label->setPixmap(QPixmap(qtlogo_eval_xpm));
- pixmap_label->setAlignment(Qt::AlignTop);
-
- QLabel *text_label = new QLabel(str, border);
-
- QHBoxLayout *pm_and_text_layout = new QHBoxLayout();
- pm_and_text_layout->addWidget(pixmap_label);
- pm_and_text_layout->addWidget(text_label);
-
- QVBoxLayout *master_layout = new QVBoxLayout(border);
- master_layout->addLayout(pm_and_text_layout);
-
- QVBoxLayout *border_layout = new QVBoxLayout(this);
- border_layout->setMargin(0);
- border_layout->addWidget(border);
-
- if (expired) {
- QPushButton *cmd = new QPushButton(QLatin1String("OK"), border);
- cmd->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- cmd->setDefault(true);
-
- QHBoxLayout *button_layout = new QHBoxLayout();
- master_layout->addLayout(button_layout);
- button_layout->addWidget(cmd);
-
- connect(cmd, SIGNAL(clicked()), this, SLOT(close()));
- } else {
- border->setFrameShape(QFrame::WinPanel);
- border->setFrameShadow(QFrame::Raised);
- setParent(parentWidget(), Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
- QTimer::singleShot(7000, this, SLOT(close()));
- setAttribute(Qt::WA_DeleteOnClose);
- setAttribute(Qt::WA_QuitOnClose, false);
- }
-
- setFixedSize(sizeHint());
- }
-};
-
-class QGuiFuriCuri : public QCoreFuriCuri
-{
-public:
- void timerEvent(QTimerEvent *e) {
- if (e->timerId() == warn) {
- killTimer(warn);
- QMessageBox::information(0, QLatin1String("Automatic Timeout"), QLatin1String(will_shutdown_1min));
- kill = startTimer(KILL_DELAY);
- } else if (e->timerId() == kill) {
- killTimer(kill);
- QMessageBox::information(0, QLatin1String("Automatic Timeout"), QLatin1String(will_shutdown_now));
- qApp->quit();
- }
- }
-};
-
-
-void qt_gui_eval_init(QCoreApplicationPrivate::Type type)
-{
- Q_UNUSED(type);
-
- if (!qt_eval_is_supported())
- return;
-
- if (qt_eval_is_expired()) {
- EvalMessageBox box(true);
- box.exec();
- ::exit(0);
- } else {
- Q_UNUSED(new QGuiFuriCuri());
- }
-}
-
-static QString qt_eval_title_prefix()
-{
- return QLatin1String("[Qt Evaluation] ");
-}
-
-QString qt_eval_adapt_window_title(const QString &title)
-{
- if (!qt_eval_is_supported())
- return title;
- return qt_eval_title_prefix() + title;
-}
-
-void qt_eval_init_widget(QWidget *w)
-{
- if (!qt_eval_is_supported())
- return;
- if (w->isTopLevel() && w->windowTitle().isEmpty() && w->windowType() != Qt::Desktop ) {
- w->setWindowTitle(QLatin1String(" "));
- }
-}
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/corelib/serialization/qdatastream.cpp b/src/corelib/serialization/qdatastream.cpp
index ead6ed5083..3ea518907b 100644
--- a/src/corelib/serialization/qdatastream.cpp
+++ b/src/corelib/serialization/qdatastream.cpp
@@ -561,6 +561,7 @@ void QDataStream::setByteOrder(ByteOrder bo)
\value Qt_5_11 Same as Qt_5_6
\value Qt_5_12 Version 18 (Qt 5.12)
\value Qt_5_13 Version 19 (Qt 5.13)
+ \value Qt_5_14 Same as Qt_5_13
\omitvalue Qt_DefaultCompiledVersion
\sa setVersion(), version()
diff --git a/src/corelib/serialization/qdatastream.h b/src/corelib/serialization/qdatastream.h
index 81134f74b0..6e358df02e 100644
--- a/src/corelib/serialization/qdatastream.h
+++ b/src/corelib/serialization/qdatastream.h
@@ -100,10 +100,11 @@ public:
Qt_5_11 = Qt_5_10,
Qt_5_12 = 18,
Qt_5_13 = 19,
-#if QT_VERSION >= 0x050e00
+ Qt_5_14 = Qt_5_13,
+#if QT_VERSION >= 0x050f00
#error Add the datastream version for this Qt version and update Qt_DefaultCompiledVersion
#endif
- Qt_DefaultCompiledVersion = Qt_5_13
+ Qt_DefaultCompiledVersion = Qt_5_14
};
enum ByteOrder {
diff --git a/src/corelib/thread/qorderedmutexlocker_p.h b/src/corelib/thread/qorderedmutexlocker_p.h
index ded102d32d..5b2c7ab112 100644
--- a/src/corelib/thread/qorderedmutexlocker_p.h
+++ b/src/corelib/thread/qorderedmutexlocker_p.h
@@ -58,6 +58,8 @@
QT_BEGIN_NAMESPACE
+#if QT_CONFIG(thread)
+
/*
Locks 2 mutexes in a defined order, avoiding a recursive lock if
we're trying to lock the same mutex twice.
@@ -65,9 +67,9 @@ QT_BEGIN_NAMESPACE
class QOrderedMutexLocker
{
public:
- QOrderedMutexLocker(QMutex *m1, QMutex *m2)
- : mtx1((m1 == m2) ? m1 : (std::less<QMutex *>()(m1, m2) ? m1 : m2)),
- mtx2((m1 == m2) ? 0 : (std::less<QMutex *>()(m1, m2) ? m2 : m1)),
+ QOrderedMutexLocker(QBasicMutex *m1, QBasicMutex *m2)
+ : mtx1((m1 == m2) ? m1 : (std::less<QBasicMutex *>()(m1, m2) ? m1 : m2)),
+ mtx2((m1 == m2) ? 0 : (std::less<QBasicMutex *>()(m1, m2) ? m2 : m1)),
locked(false)
{
relock();
@@ -95,12 +97,12 @@ public:
}
}
- static bool relock(QMutex *mtx1, QMutex *mtx2)
+ static bool relock(QBasicMutex *mtx1, QBasicMutex *mtx2)
{
// mtx1 is already locked, mtx2 not... do we need to unlock and relock?
if (mtx1 == mtx2)
return false;
- if (std::less<QMutex *>()(mtx1, mtx2)) {
+ if (std::less<QBasicMutex *>()(mtx1, mtx2)) {
mtx2->lock();
return true;
}
@@ -113,10 +115,58 @@ public:
}
private:
- QMutex *mtx1, *mtx2;
+ QBasicMutex *mtx1, *mtx2;
bool locked;
};
+class QBasicMutexLocker
+{
+public:
+ inline explicit QBasicMutexLocker(QBasicMutex *m) QT_MUTEX_LOCK_NOEXCEPT
+ : m(m), isLocked(true)
+ {
+ m->lock();
+ }
+ inline ~QBasicMutexLocker() { if (isLocked) unlock(); }
+
+ inline void unlock() Q_DECL_NOTHROW
+ {
+ isLocked = false;
+ m->unlock();
+ }
+
+ inline void relock() QT_MUTEX_LOCK_NOEXCEPT
+ {
+ isLocked = true;
+ m->lock();
+ }
+
+private:
+ Q_DISABLE_COPY(QBasicMutexLocker)
+
+ QBasicMutex *m;
+ bool isLocked;
+};
+
+#else
+
+class QOrderedMutexLocker
+{
+public:
+ QOrderedMutexLocker(QBasicMutex *, QBasicMutex *) {}
+ ~QOrderedMutexLocker() {}
+
+ void relock() {}
+ void unlock() {}
+
+ static bool relock(QBasicMutex *, QBasicMutex *) {}
+};
+
+using QBasicMutexLocker = QMutexLocker;
+
+#endif
+
+
QT_END_NAMESPACE
#endif
diff --git a/src/gui/configure.json b/src/gui/configure.json
index 59c06af97f..2ac06173a8 100644
--- a/src/gui/configure.json
+++ b/src/gui/configure.json
@@ -30,7 +30,6 @@
"libjpeg": { "type": "enum", "values": [ "no", "qt", "system" ] },
"libpng": { "type": "enum", "values": [ "no", "qt", "system" ] },
"linuxfb": "boolean",
- "mirclient": "boolean",
"mtdev": "boolean",
"opengl": { "type": "optionalString", "values": [ "no", "yes", "desktop", "es2", "dynamic" ] },
"opengl-es-2": { "type": "void", "name": "opengl", "value": "es2" },
@@ -395,20 +394,6 @@
{ "lib": "zlib", "condition": "features.system-zlib" }
]
},
- "mirclient": {
- "label": "Mir client libraries",
- "test": {
- "tail": "static void surfaceCreateCallback(MirSurface*, void*) {}",
- "main": [
- "u_application_lifecycle_delegate_new();",
- "mir_surface_create(0, surfaceCreateCallback, 0);"
- ]
- },
- "headers": [ "mir_toolkit/mir_client_library.h", "ubuntu/application/lifecycle_delegate.h", "EGL/egl.h" ],
- "sources": [
- { "type": "pkgConfig", "args": "egl mirclient ubuntu-platform-api libcontent-hub >= 0.2.0" }
- ]
- },
"mtdev": {
"label": "mtdev",
"test": {
@@ -1295,13 +1280,6 @@
],
"output": [ "privateFeature" ]
},
- "mirclient": {
- "label": "Mir client",
- "section": "Platform plugins",
- "autoDetect": false,
- "condition": "libs.mirclient && features.xkbcommon",
- "output": [ "privateFeature" ]
- },
"mtdev": {
"label": "mtdev",
"condition": "libs.mtdev",
@@ -1828,7 +1806,7 @@ or may depend on your system and XQuartz setup."
},
{
"type": "warning",
- "condition": "features.gui && config.linux && !config.android && !features.xcb && !features.eglfs && !features.directfb && !features.linuxfb && !features.mirclient",
+ "condition": "features.gui && config.linux && !config.android && !features.xcb && !features.eglfs && !features.directfb && !features.linuxfb",
"message": "No QPA platform plugin enabled! This will
produce a Qt that cannot run GUI applications.
See \"Platform backends\" in the output of --help."
@@ -1936,7 +1914,7 @@ QMAKE_LIBDIR_OPENGL[_ES2] and QMAKE_LIBS_OPENGL[_ES2] in the mkspec for your pla
"eglfs_openwfd", "eglfs_viv", "eglfs_viv_wl", "eglfs_rcar", "eglfs_egldevice", "eglfs_gbm", "eglfs_vsp2", "eglfs_mali", "eglfs_brcm", "eglfs_x11"
]
},
- "linuxfb", "vnc", "mirclient",
+ "linuxfb", "vnc",
{
"type": "feature",
"condition": "config.integrity",
diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp
index 97123bfec2..e508cc9413 100644
--- a/src/gui/image/qimage.cpp
+++ b/src/gui/image/qimage.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
@@ -38,8 +38,10 @@
****************************************************************************/
#include "qimage.h"
-#include "qdatastream.h"
+
#include "qbuffer.h"
+#include "qdatastream.h"
+#include "qcolortransform.h"
#include "qmap.h"
#include "qmatrix.h"
#include "qtransform.h"
@@ -54,6 +56,7 @@
#include <stdlib.h>
#include <limits.h>
#include <qpa/qplatformpixmap.h>
+#include <private/qcolortransform_p.h>
#include <private/qdrawhelper_p.h>
#include <private/qmemrotate_p.h>
#include <private/qimagescale_p.h>
@@ -1098,6 +1101,7 @@ static void copyMetadata(QImageData *dst, const QImageData *src)
dst->dpmy = src->dpmy;
dst->devicePixelRatio = src->devicePixelRatio;
dst->text = src->text;
+ dst->colorSpace = src->colorSpace;
}
/*!
@@ -4922,6 +4926,132 @@ QTransform QImage::trueMatrix(const QTransform &matrix, int w, int h)
return matrix * QTransform().translate(-delta.x(), -delta.y());
}
+/*!
+ \since 5.14
+
+ Sets the image color space to \a colorSpace without performing any conversions on image data.
+
+ \sa colorSpace()
+*/
+void QImage::setColorSpace(const QColorSpace &colorSpace)
+{
+ if (!d)
+ return;
+ if (d->colorSpace == colorSpace)
+ return;
+ if (!isDetached()) // Detach only if shared, not for read-only data.
+ detach();
+ d->colorSpace = colorSpace;
+}
+
+/*!
+ \since 5.14
+
+ Converts the image to \a colorSpace.
+
+ If the image has no valid color space, the method does nothing.
+
+ \sa convertedToColorSpace(), setColorSpace()
+*/
+void QImage::convertToColorSpace(const QColorSpace &colorSpace)
+{
+ if (!d)
+ return;
+ if (!d->colorSpace.isValid())
+ return;
+ if (!colorSpace.isValid()) {
+ qWarning() << "QImage::convertToColorSpace: Output colorspace is not valid";
+ return;
+ }
+ detach();
+ applyColorTransform(d->colorSpace.transformationToColorSpace(colorSpace));
+ d->colorSpace = colorSpace;
+}
+
+/*!
+ \since 5.14
+
+ Returns the image converted to \a colorSpace.
+
+ If the image has no valid color space, a null QImage is returned.
+
+ \sa convertToColorSpace()
+*/
+QImage QImage::convertedToColorSpace(const QColorSpace &colorSpace) const
+{
+ if (!d || !d->colorSpace.isValid() || !colorSpace.isValid())
+ return QImage();
+ QImage image = copy();
+ image.convertToColorSpace(colorSpace);
+ return image;
+}
+
+/*!
+ \since 5.14
+
+ Returns the color space of the image if a color space is defined.
+*/
+QColorSpace QImage::colorSpace() const
+{
+ if (!d)
+ return QColorSpace::Undefined;
+ return d->colorSpace;
+}
+
+/*!
+ \since 5.14
+
+ Applies the color transformation \a transform to all pixels in the image.
+*/
+void QImage::applyColorTransform(const QColorTransform &transform)
+{
+ QImage::Format oldFormat = format();
+ if (depth() > 32) {
+ if (format() != QImage::Format_RGBX64 && format() != QImage::Format_RGBA64
+ && format() != QImage::Format_RGBA64_Premultiplied)
+ *this = std::move(*this).convertToFormat(QImage::Format_RGBA64);
+ } else if (format() != QImage::Format_ARGB32 && format() != QImage::Format_RGB32
+ && format() != QImage::Format_ARGB32_Premultiplied) {
+ if (hasAlphaChannel())
+ *this = std::move(*this).convertToFormat(QImage::Format_ARGB32);
+ else
+ *this = std::move(*this).convertToFormat(QImage::Format_RGB32);
+ }
+
+ QColorTransformPrivate::TransformFlags flags = QColorTransformPrivate::Unpremultiplied;
+ switch (format()) {
+ case Format_ARGB32_Premultiplied:
+ case Format_RGBA64_Premultiplied:
+ flags = QColorTransformPrivate::Premultiplied;
+ break;
+ case Format_RGB32:
+ case Format_RGBX64:
+ flags = QColorTransformPrivate::InputOpaque;
+ break;
+ case Format_ARGB32:
+ case Format_RGBA64:
+ break;
+ default:
+ Q_UNREACHABLE();
+ }
+
+ if (depth() > 32) {
+ for (int i = 0; i < height(); ++i) {
+ QRgba64 *scanline = reinterpret_cast<QRgba64 *>(scanLine(i));
+ transform.d_func()->apply(scanline, scanline, width(), flags);
+ }
+ } else {
+ for (int i = 0; i < height(); ++i) {
+ QRgb *scanline = reinterpret_cast<QRgb *>(scanLine(i));
+ transform.d_func()->apply(scanline, scanline, width(), flags);
+ }
+ }
+
+ if (oldFormat != format())
+ *this = std::move(*this).convertToFormat(oldFormat);
+}
+
+
bool QImageData::convertInPlace(QImage::Format newFormat, Qt::ImageConversionFlags flags)
{
if (format == newFormat)
diff --git a/src/gui/image/qimage.h b/src/gui/image/qimage.h
index 45f571807c..b09e69c839 100644
--- a/src/gui/image/qimage.h
+++ b/src/gui/image/qimage.h
@@ -61,9 +61,11 @@ Q_FORWARD_DECLARE_MUTABLE_CG_TYPE(CGImage);
QT_BEGIN_NAMESPACE
+class QColorSpace;
+class QColorTransform;
class QIODevice;
-class QStringList;
class QMatrix;
+class QStringList;
class QTransform;
class QVariant;
template <class T> class QList;
@@ -296,6 +298,12 @@ public:
#endif
void invertPixels(InvertMode = InvertRgb);
+ QColorSpace colorSpace() const;
+ QImage convertedToColorSpace(const QColorSpace &) const;
+ void convertToColorSpace(const QColorSpace &);
+ void setColorSpace(const QColorSpace &);
+
+ void applyColorTransform(const QColorTransform &transform);
bool load(QIODevice *device, const char* format);
bool load(const QString &fileName, const char *format = nullptr);
diff --git a/src/gui/image/qimage_conversions.cpp b/src/gui/image/qimage_conversions.cpp
index 82ffb8af8b..837ac88470 100644
--- a/src/gui/image/qimage_conversions.cpp
+++ b/src/gui/image/qimage_conversions.cpp
@@ -39,7 +39,7 @@
#include <private/qdrawhelper_p.h>
#include <private/qguiapplication_p.h>
-#include <private/qcolorprofile_p.h>
+#include <private/qcolortrclut_p.h>
#include <private/qendian_p.h>
#include <private/qsimd_p.h>
#include <private/qimage_p.h>
@@ -100,7 +100,7 @@ const uchar *qt_get_bitflip_array()
void qGamma_correct_back_to_linear_cs(QImage *image)
{
- const QColorProfile *cp = QGuiApplicationPrivate::instance()->colorProfileForA32Text();
+ const QColorTrcLut *cp = QGuiApplicationPrivate::instance()->colorProfileForA32Text();
if (!cp)
return;
// gamma correct the pixels back to linear color space...
diff --git a/src/gui/image/qimage_p.h b/src/gui/image/qimage_p.h
index de12a313e8..a599fc17c9 100644
--- a/src/gui/image/qimage_p.h
+++ b/src/gui/image/qimage_p.h
@@ -51,7 +51,9 @@
// We mean it.
//
+#include <QtGui/qcolorspace.h>
#include <QtGui/private/qtguiglobal_p.h>
+#include <QtGui/qimage.h>
#include <QtCore/private/qnumeric_p.h>
#include <QMap>
@@ -106,6 +108,8 @@ struct Q_GUI_EXPORT QImageData { // internal image data
QPaintEngine *paintEngine;
+ QColorSpace colorSpace;
+
struct ImageSizeParameters {
qsizetype bytesPerLine;
qsizetype totalSize;
diff --git a/src/gui/image/qpnghandler.cpp b/src/gui/image/qpnghandler.cpp
index 140196004b..93635a051d 100644
--- a/src/gui/image/qpnghandler.cpp
+++ b/src/gui/image/qpnghandler.cpp
@@ -42,6 +42,7 @@
#ifndef QT_NO_IMAGEFORMAT_PNG
#include <qcoreapplication.h>
+#include <qdebug.h>
#include <qiodevice.h>
#include <qimage.h>
#include <qlist.h>
@@ -50,6 +51,10 @@
#include <private/qimage_p.h> // for qt_getImageText
+#include <qcolorspace.h>
+#include <private/qcolorspace_p.h>
+#include <private/qicc_p.h>
+
#include <png.h>
#include <pngconf.h>
@@ -96,9 +101,16 @@ public:
ReadingEnd,
Error
};
+ // Defines the order of how the various ways of setting colorspace overrides eachother:
+ enum ColorSpaceState {
+ Undefined = 0,
+ GammaChrm = 1, // gAMA+cHRM chunks
+ Srgb = 2, // sRGB chunk
+ Icc = 3 // iCCP chunk
+ };
QPngHandlerPrivate(QPngHandler *qq)
- : gamma(0.0), fileGamma(0.0), quality(50), compression(50), png_ptr(0), info_ptr(0), end_info(0), state(Ready), q(qq)
+ : gamma(0.0), fileGamma(0.0), quality(50), compression(50), colorSpaceState(Undefined), png_ptr(0), info_ptr(0), end_info(0), state(Ready), q(qq)
{ }
float gamma;
@@ -108,6 +120,8 @@ public:
QString description;
QSize scaledSize;
QStringList readTexts;
+ QColorSpace colorSpace;
+ ColorSpaceState colorSpaceState;
png_struct *png_ptr;
png_info *info_ptr;
@@ -226,11 +240,8 @@ void qpiw_flush_fn(png_structp /* png_ptr */)
}
static
-void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, QSize scaledSize, bool *doScaledRead, float screen_gamma=0.0, float file_gamma=0.0)
+void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, QSize scaledSize, bool *doScaledRead)
{
- if (screen_gamma != 0.0 && file_gamma != 0.0)
- png_set_gamma(png_ptr, 1.0f / screen_gamma, file_gamma);
-
png_uint_32 width;
png_uint_32 height;
int bit_depth = 0;
@@ -585,10 +596,45 @@ bool QPngHandlerPrivate::readPngHeader()
readPngTexts(info_ptr);
+#ifdef PNG_iCCP_SUPPORTED
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP)) {
+ png_charp name = nullptr;
+ int compressionType = 0;
+#if (PNG_LIBPNG_VER < 10500)
+ png_charp profileData = nullptr;
+#else
+ png_bytep profileData = nullptr;
+#endif
+ png_uint_32 profLen;
+ png_get_iCCP(png_ptr, info_ptr, &name, &compressionType, &profileData, &profLen);
+ if (!QIcc::fromIccProfile(QByteArray::fromRawData((const char *)profileData, profLen), &colorSpace)) {
+ qWarning() << "QPngHandler: Failed to parse ICC profile";
+ } else {
+ colorSpaceState = Icc;
+ }
+ }
+#endif
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
+ int rendering_intent = -1;
+ png_get_sRGB(png_ptr, info_ptr, &rendering_intent);
+ // We don't actually care about the rendering_intent, just that it is valid
+ if (rendering_intent >= 0 && rendering_intent <= 3 && colorSpaceState <= Srgb) {
+ colorSpace = QColorSpace::SRgb;
+ colorSpaceState = Srgb;
+ }
+ }
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
double file_gamma = 0.0;
png_get_gAMA(png_ptr, info_ptr, &file_gamma);
fileGamma = file_gamma;
+ if (fileGamma > 0.0f && colorSpaceState <= GammaChrm) {
+ QColorSpacePrivate *csPrivate = colorSpace.d_func();
+ csPrivate->gamut = QColorSpace::Gamut::SRgb;
+ csPrivate->transferFunction = QColorSpace::TransferFunction::Gamma;
+ csPrivate->gamma = fileGamma;
+ csPrivate->initialize();
+ colorSpaceState = GammaChrm;
+ }
}
state = ReadHeader;
@@ -613,8 +659,19 @@ bool QPngHandlerPrivate::readPngImage(QImage *outImage)
return false;
}
+ if (gamma != 0.0 && fileGamma != 0.0) {
+ // This configuration forces gamma correction and
+ // thus changes the output colorspace
+ png_set_gamma(png_ptr, 1.0f / gamma, fileGamma);
+ QColorSpacePrivate *csPrivate = colorSpace.d_func();
+ csPrivate->transferFunction = QColorSpace::TransferFunction::Gamma;
+ csPrivate->gamma = gamma;
+ csPrivate->initialize();
+ colorSpaceState = GammaChrm;
+ }
+
bool doScaledRead = false;
- setup_qt(*outImage, png_ptr, info_ptr, scaledSize, &doScaledRead, gamma, fileGamma);
+ setup_qt(*outImage, png_ptr, info_ptr, scaledSize, &doScaledRead);
if (outImage->isNull()) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
@@ -683,6 +740,9 @@ bool QPngHandlerPrivate::readPngImage(QImage *outImage)
if (scaledSize.isValid() && outImage->size() != scaledSize)
*outImage = outImage->scaled(scaledSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
+ if (colorSpaceState > Undefined && colorSpace.isValid())
+ outImage->setColorSpace(colorSpace);
+
return true;
}
diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri
index 1f137fc46f..9c80f1e2cc 100644
--- a/src/gui/kernel/kernel.pri
+++ b/src/gui/kernel/kernel.pri
@@ -21,7 +21,7 @@ HEADERS += \
kernel/qplatforminputcontextplugin_p.h \
kernel/qplatformintegrationfactory_p.h \
kernel/qplatformintegrationplugin.h \
- kernel/qplatformtheme.h\
+ kernel/qplatformtheme.h \
kernel/qplatformtheme_p.h \
kernel/qplatformthemefactory_p.h \
kernel/qplatformthemeplugin.h \
diff --git a/src/gui/kernel/qguiapplication.cpp b/src/gui/kernel/qguiapplication.cpp
index 4e0c45d8ae..7218e55627 100644
--- a/src/gui/kernel/qguiapplication.cpp
+++ b/src/gui/kernel/qguiapplication.cpp
@@ -68,7 +68,7 @@
#include <qpalette.h>
#include <qscreen.h>
#include "qsessionmanager.h"
-#include <private/qcolorprofile_p.h>
+#include <private/qcolortrclut_p.h>
#include <private/qscreen_p.h>
#include <QtGui/qgenericpluginfactory.h>
@@ -1643,8 +1643,6 @@ QGuiApplicationPrivate::~QGuiApplicationPrivate()
platform_theme = 0;
delete platform_integration;
platform_integration = 0;
- delete m_a8ColorProfile.load();
- delete m_a32ColorProfile.load();
window_list.clear();
screen_list.clear();
@@ -3984,32 +3982,26 @@ void QGuiApplicationPrivate::notifyDragStarted(const QDrag *drag)
}
#endif
-const QColorProfile *QGuiApplicationPrivate::colorProfileForA8Text()
+const QColorTrcLut *QGuiApplicationPrivate::colorProfileForA8Text()
{
#ifdef Q_OS_WIN
- QColorProfile *result = m_a8ColorProfile.load();
- if (!result){
- QColorProfile *cs = QColorProfile::fromGamma(2.31); // This is a hard-coded thing for Windows text rendering
- if (!m_a8ColorProfile.testAndSetRelease(0, cs))
- delete cs;
- result = m_a8ColorProfile.load();
+ if (!m_a8ColorProfile){
+ QColorTrcLut *cs = QColorTrcLut::fromGamma(2.31); // This is a hard-coded thing for Windows text rendering
+ m_a8ColorProfile.reset(cs);
}
- return result;
+ return m_a8ColorProfile.get();
#else
return colorProfileForA32Text();
#endif
}
-const QColorProfile *QGuiApplicationPrivate::colorProfileForA32Text()
+const QColorTrcLut *QGuiApplicationPrivate::colorProfileForA32Text()
{
- QColorProfile *result = m_a32ColorProfile.load();
- if (!result){
- QColorProfile *cs = QColorProfile::fromGamma(fontSmoothingGamma);
- if (!m_a32ColorProfile.testAndSetRelease(0, cs))
- delete cs;
- result = m_a32ColorProfile.load();
+ if (!m_a32ColorProfile) {
+ QColorTrcLut *cs = QColorTrcLut::fromGamma(fontSmoothingGamma);
+ m_a32ColorProfile.reset(cs);
}
- return result;
+ return m_a32ColorProfile.get();
}
void QGuiApplicationPrivate::_q_updateFocusObject(QObject *object)
diff --git a/src/gui/kernel/qguiapplication_p.h b/src/gui/kernel/qguiapplication_p.h
index 63646dcd50..61d9661286 100644
--- a/src/gui/kernel/qguiapplication_p.h
+++ b/src/gui/kernel/qguiapplication_p.h
@@ -55,6 +55,7 @@
#include <QtGui/qguiapplication.h>
#include <QtCore/QPointF>
+#include <QtCore/QSharedPointer>
#include <QtCore/private/qcoreapplication_p.h>
#include <QtCore/private/qthread_p.h>
@@ -66,7 +67,7 @@
QT_BEGIN_NAMESPACE
-class QColorProfile;
+class QColorTrcLut;
class QPlatformIntegration;
class QPlatformTheme;
class QPlatformDragQtResponse;
@@ -299,8 +300,8 @@ public:
static QInputDeviceManager *inputDeviceManager();
- const QColorProfile *colorProfileForA8Text();
- const QColorProfile *colorProfileForA32Text();
+ const QColorTrcLut *colorProfileForA8Text();
+ const QColorTrcLut *colorProfileForA32Text();
// hook reimplemented in QApplication to apply the QStyle function on the QIcon
virtual QPixmap applyQIconStyleHelper(QIcon::Mode, const QPixmap &basePixmap) const { return basePixmap; }
@@ -327,8 +328,8 @@ private:
static QGuiApplicationPrivate *self;
static QTouchDevice *m_fakeTouchDevice;
static int m_fakeMouseSourcePointId;
- QAtomicPointer<QColorProfile> m_a8ColorProfile;
- QAtomicPointer<QColorProfile> m_a32ColorProfile;
+ QSharedPointer<QColorTrcLut> m_a8ColorProfile;
+ QSharedPointer<QColorTrcLut> m_a32ColorProfile;
bool ownGlobalShareContext;
diff --git a/src/gui/opengl/qopengltexture.cpp b/src/gui/opengl/qopengltexture.cpp
index 5b7956d31e..f25988585e 100644
--- a/src/gui/opengl/qopengltexture.cpp
+++ b/src/gui/opengl/qopengltexture.cpp
@@ -1467,6 +1467,122 @@ void QOpenGLTexturePrivate::setData(int mipLevel, int layer, int layerCount, QOp
}
}
+void QOpenGLTexturePrivate::setData(int xOffset, int yOffset, int zOffset, int width, int height, int depth,
+ int mipLevel, int layer, int layerCount, QOpenGLTexture::CubeMapFace cubeFace,
+ QOpenGLTexture::PixelFormat sourceFormat, QOpenGLTexture::PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options)
+{
+ switch (target) {
+ case QOpenGLTexture::Target1D:
+ Q_UNUSED(layer);
+ Q_UNUSED(cubeFace);
+ Q_UNUSED(layerCount);
+ Q_UNUSED(yOffset);
+ Q_UNUSED(zOffset);
+ Q_UNUSED(height);
+ Q_UNUSED(depth);
+ texFuncs->glTextureSubImage1D(textureId, target, bindingTarget, mipLevel,
+ xOffset, width,
+ sourceFormat, sourceType, data, options);
+ break;
+
+ case QOpenGLTexture::Target1DArray:
+ Q_UNUSED(cubeFace);
+ Q_UNUSED(yOffset);
+ Q_UNUSED(zOffset);
+ Q_UNUSED(height);
+ Q_UNUSED(depth);
+ texFuncs->glTextureSubImage2D(textureId, target, bindingTarget, mipLevel,
+ xOffset, layer,
+ width,
+ layerCount,
+ sourceFormat, sourceType, data, options);
+ break;
+
+ case QOpenGLTexture::Target2D:
+ Q_UNUSED(layer);
+ Q_UNUSED(cubeFace);
+ Q_UNUSED(layerCount);
+ Q_UNUSED(zOffset);
+ Q_UNUSED(depth);
+ texFuncs->glTextureSubImage2D(textureId, target, bindingTarget, mipLevel,
+ xOffset, yOffset,
+ width, height,
+ sourceFormat, sourceType, data, options);
+ break;
+
+ case QOpenGLTexture::Target2DArray:
+ Q_UNUSED(cubeFace);
+ Q_UNUSED(zOffset);
+ Q_UNUSED(depth);
+ texFuncs->glTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
+ xOffset, yOffset, layer,
+ width, height, layerCount,
+ sourceFormat, sourceType, data, options);
+ break;
+
+ case QOpenGLTexture::Target3D:
+ Q_UNUSED(cubeFace);
+ Q_UNUSED(layerCount);
+ texFuncs->glTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
+ xOffset, yOffset, zOffset,
+ width, height, depth,
+ sourceFormat, sourceType, data, options);
+ break;
+
+ case QOpenGLTexture::TargetCubeMap:
+ Q_UNUSED(layer);
+ Q_UNUSED(layerCount);
+ Q_UNUSED(zOffset);
+ Q_UNUSED(depth);
+ texFuncs->glTextureSubImage2D(textureId, cubeFace, bindingTarget, mipLevel,
+ xOffset, yOffset,
+ width, height,
+ sourceFormat, sourceType, data, options);
+ break;
+
+ case QOpenGLTexture::TargetCubeMapArray: {
+ Q_UNUSED(zOffset);
+ Q_UNUSED(depth);
+ int faceIndex = cubeFace - QOpenGLTexture::CubeMapPositiveX;
+ int layerFace = 6 * layer + faceIndex;
+ texFuncs->glTextureSubImage3D(textureId, target, bindingTarget, mipLevel,
+ xOffset, yOffset, layerFace,
+ width, height,
+ layerCount,
+ sourceFormat, sourceType, data, options);
+ break;
+ }
+
+ case QOpenGLTexture::TargetRectangle:
+ Q_UNUSED(mipLevel);
+ Q_UNUSED(layer);
+ Q_UNUSED(cubeFace);
+ Q_UNUSED(layerCount);
+ Q_UNUSED(zOffset);
+ Q_UNUSED(depth);
+ texFuncs->glTextureSubImage2D(textureId, target, bindingTarget, 0,
+ xOffset, yOffset,
+ width, height,
+ sourceFormat, sourceType, data, options);
+ break;
+
+ case QOpenGLTexture::Target2DMultisample:
+ case QOpenGLTexture::Target2DMultisampleArray:
+ case QOpenGLTexture::TargetBuffer:
+ // We don't upload pixel data for these targets
+ qWarning("QOpenGLTexture::setData(): Texture target does not support pixel data upload");
+ break;
+ }
+
+ // If requested perform automatic mip map generation
+ if (mipLevel == 0 && autoGenerateMipMaps && mipLevels > 1) {
+ Q_Q(QOpenGLTexture);
+ q->generateMipMaps();
+ }
+}
+
+
void QOpenGLTexturePrivate::setCompressedData(int mipLevel, int layer, int layerCount,
QOpenGLTexture::CubeMapFace cubeFace,
int dataSize, const void *data,
@@ -3380,6 +3496,124 @@ void QOpenGLTexture::setData(PixelFormat sourceFormat, PixelType sourceType,
d->setData(0, 0, 1, QOpenGLTexture::CubeMapPositiveX, sourceFormat, sourceType, data, options);
}
+/*!
+ \since 5.14
+ \overload
+
+ This overload is to be used to update a part of the texture. Parameters \a
+ xOffset, \a yOffset, \a zOffset specify the texel offsets within the
+ texture. Parameters \a width, \a height and \a depth specify the dimensions
+ of the sub image.
+
+ The structure of the pixel data pointed to by \a data is specified by \a
+ sourceFormat and \a sourceType. The pixel data upload can optionally be
+ controlled by \a options.
+*/
+void QOpenGLTexture::setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options)
+{
+ Q_D(QOpenGLTexture);
+ Q_ASSERT(d->textureId);
+ d->setData(xOffset, yOffset, zOffset,
+ width, height, depth,
+ 0, 0, 1,
+ QOpenGLTexture::CubeMapPositiveX, sourceFormat,
+ sourceType, data, options);
+}
+
+/*!
+ \since 5.14
+ \overload
+
+ This overload is to be used to update a part of the texture. Parameters \a
+ xOffset, \a yOffset, \a zOffset specify the texel offsets within the
+ texture. Parameters \a width, \a height and \a depth specify the dimensions
+ of the sub image. The mip map level and layerof the sub image we want to
+ update are specified with \a mipLevel and \a layer.
+
+ The structure of the pixel data pointed to by \a data is specified by \a
+ sourceFormat and \a sourceType. The pixel data upload can optionally be
+ controlled by \a options.
+*/
+void QOpenGLTexture::setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ int mipLevel, int layer,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options)
+{
+ Q_D(QOpenGLTexture);
+ Q_ASSERT(d->textureId);
+ d->setData(xOffset, yOffset, zOffset,
+ width, height, depth,
+ mipLevel, layer, 1,
+ QOpenGLTexture::CubeMapPositiveX, sourceFormat,
+ sourceType, data, options);
+}
+
+/*!
+ \since 5.14
+ \overload
+
+ This overload is to be used to update a part of the texture. Parameters \a
+ xOffset, \a yOffset, \a zOffset specify the texel offsets within the
+ texture. Parameters \a width, \a height and \a depth specify the dimensions
+ of the sub image.The mip map level, layer and cube map face of the sub
+ image we want to update are specified with \a mipLevel, \a layer and \a
+ face.
+
+ The structure of the pixel data pointed to by \a data is specified by \a
+ sourceFormat and \a sourceType. The pixel data upload can optionally be
+ controlled by \a options.
+*/
+void QOpenGLTexture::setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ int mipLevel, int layer,
+ CubeMapFace face,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options)
+{
+ Q_D(QOpenGLTexture);
+ Q_ASSERT(d->textureId);
+ d->setData(xOffset, yOffset, zOffset,
+ width, height, depth,
+ mipLevel, layer, 1,
+ face, sourceFormat,
+ sourceType, data, options);
+}
+
+/*!
+ \since 5.14
+ \overload
+
+ This overload is to be used to update a part of the texture. Parameters \a
+ xOffset, \a yOffset, \a zOffset specify the texel offsets within the
+ texture. Parameters \a width, \a height and \a depth specify the dimensions
+ of the sub image.The mip map level, starting layer, cube map face and
+ number of layers of the sub image we want to update are specified with \a
+ mipLevel, \a layer, \a face and \a layerCount.
+
+ The structure of the pixel data pointed to by \a data is specified by \a
+ sourceFormat and \a sourceType. The pixel data upload can optionally be
+ controlled by \a options.
+*/
+void QOpenGLTexture::setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ int mipLevel, int layer,
+ CubeMapFace face, int layerCount,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options)
+{
+ Q_D(QOpenGLTexture);
+ Q_ASSERT(d->textureId);
+ d->setData(xOffset, yOffset, zOffset,
+ width, height, depth,
+ mipLevel, layer, layerCount,
+ face, sourceFormat,
+ sourceType, data, options);
+}
+
#if QT_DEPRECATED_SINCE(5, 3)
/*!
\obsolete
diff --git a/src/gui/opengl/qopengltexture.h b/src/gui/opengl/qopengltexture.h
index c0c5283374..7d984babc8 100644
--- a/src/gui/opengl/qopengltexture.h
+++ b/src/gui/opengl/qopengltexture.h
@@ -485,6 +485,32 @@ public:
void setData(PixelFormat sourceFormat, PixelType sourceType,
const void *data, const QOpenGLPixelTransferOptions * const options = nullptr);
+ void setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options = nullptr);
+ void setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth, int mipLevel,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options = nullptr);
+ void setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ int mipLevel, int layer,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options = nullptr);
+ void setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ int mipLevel, int layer,
+ CubeMapFace cubeFace,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options = nullptr);
+ void setData(int xOffset, int yOffset, int zOffset,
+ int width, int height, int depth,
+ int mipLevel, int layer,
+ CubeMapFace cubeFace, int layerCount,
+ PixelFormat sourceFormat, PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options = nullptr);
+
// Compressed data upload
// ### Qt 6: remove the non-const void * overloads
#if QT_DEPRECATED_SINCE(5, 3)
diff --git a/src/gui/opengl/qopengltexture_p.h b/src/gui/opengl/qopengltexture_p.h
index f7694f77bc..9f3457ad0a 100644
--- a/src/gui/opengl/qopengltexture_p.h
+++ b/src/gui/opengl/qopengltexture_p.h
@@ -101,6 +101,10 @@ public:
void setData(int mipLevel, int layer, int layerCount, QOpenGLTexture::CubeMapFace cubeFace,
QOpenGLTexture::PixelFormat sourceFormat, QOpenGLTexture::PixelType sourceType,
const void *data, const QOpenGLPixelTransferOptions * const options);
+ void setData(int xOffset, int yOffset, int zOffset, int width, int height, int depth,
+ int mipLevel, int layer, int layerCount, QOpenGLTexture::CubeMapFace cubeFace,
+ QOpenGLTexture::PixelFormat sourceFormat, QOpenGLTexture::PixelType sourceType,
+ const void *data, const QOpenGLPixelTransferOptions * const options);
void setCompressedData(int mipLevel, int layer, int layerCount, QOpenGLTexture::CubeMapFace cubeFace,
int dataSize, const void *data,
const QOpenGLPixelTransferOptions * const options);
diff --git a/src/gui/painting/painting.pri b/src/gui/painting/painting.pri
index c3585a4647..0e2dfed9ab 100644
--- a/src/gui/painting/painting.pri
+++ b/src/gui/painting/painting.pri
@@ -8,7 +8,15 @@ HEADERS += \
painting/qbrush.h \
painting/qcolor.h \
painting/qcolor_p.h \
- painting/qcolorprofile_p.h \
+ painting/qcolormatrix_p.h \
+ painting/qcolorspace.h \
+ painting/qcolorspace_p.h \
+ painting/qcolortransferfunction_p.h \
+ painting/qcolortransfertable_p.h \
+ painting/qcolortransform.h \
+ painting/qcolortransform_p.h \
+ painting/qcolortrc_p.h \
+ painting/qcolortrclut_p.h \
painting/qcosmeticstroker_p.h \
painting/qdatabuffer_p.h \
painting/qdrawhelper_p.h \
@@ -17,6 +25,7 @@ HEADERS += \
painting/qemulationpaintengine_p.h \
painting/qfixed_p.h \
painting/qgrayraster_p.h \
+ painting/qicc_p.h \
painting/qmatrix.h \
painting/qmemrotate_p.h \
painting/qoutlinemapper_p.h \
@@ -64,12 +73,15 @@ SOURCES += \
painting/qblittable.cpp \
painting/qbrush.cpp \
painting/qcolor.cpp \
- painting/qcolorprofile.cpp \
+ painting/qcolorspace.cpp \
+ painting/qcolortransform.cpp \
+ painting/qcolortrclut.cpp \
painting/qcompositionfunctions.cpp \
painting/qcosmeticstroker.cpp \
painting/qdrawhelper.cpp \
painting/qemulationpaintengine.cpp \
painting/qgrayraster.c \
+ painting/qicc.cpp \
painting/qimagescale.cpp \
painting/qmatrix.cpp \
painting/qmemrotate.cpp \
diff --git a/src/gui/painting/qcolormatrix_p.h b/src/gui/painting/qcolormatrix_p.h
new file mode 100644
index 0000000000..3d1dca6222
--- /dev/null
+++ b/src/gui/painting/qcolormatrix_p.h
@@ -0,0 +1,214 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QCOLORMATRIX_H
+#define QCOLORMATRIX_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtGui/qtguiglobal.h>
+#include <cmath>
+
+QT_BEGIN_NAMESPACE
+
+// An abstract 3 value color
+class QColorVector
+{
+public:
+ QColorVector() = default;
+ constexpr QColorVector(float x, float y, float z) : x(x), y(y), z(z), _unused(0.0f) { }
+ float x; // X, x or red
+ float y; // Y, y or green
+ float z; // Z, Y or blue
+ float _unused;
+
+ friend inline bool operator==(const QColorVector &v1, const QColorVector &v2);
+ friend inline bool operator!=(const QColorVector &v1, const QColorVector &v2);
+
+ static constexpr QColorVector null() { return QColorVector(0.0f, 0.0f, 0.0f); }
+ // Common whitepoints on normalized XYZ form:
+ static constexpr QColorVector D50() { return QColorVector(0.96421f, 1.0f, 0.82519f); }
+ static constexpr QColorVector D65() { return QColorVector(0.95043f, 1.0f, 1.08890f); }
+};
+
+inline bool operator==(const QColorVector &v1, const QColorVector &v2)
+{
+ return (std::abs(v1.x - v2.x) < (1.0f / 2048.0f))
+ && (std::abs(v1.y - v2.y) < (1.0f / 2048.0f))
+ && (std::abs(v1.z - v2.z) < (1.0f / 2048.0f));
+}
+
+inline bool operator!=(const QColorVector &v1, const QColorVector &v2)
+{
+ return !(v1 == v2);
+}
+
+
+// A matrix mapping 3 value colors.
+// Not using QMatrix because only floats are needed and performance is critical.
+class QColorMatrix
+{
+public:
+ // We are storing the matrix transposed as that is more convenient:
+ QColorVector r;
+ QColorVector g;
+ QColorVector b;
+
+ friend inline bool operator==(const QColorMatrix &m1, const QColorMatrix &m2);
+ friend inline bool operator!=(const QColorMatrix &m1, const QColorMatrix &m2);
+
+ bool isValid() const
+ {
+ // A color matrix must be invertible
+ float det = r.x * (b.z * g.y - g.z * b.y) -
+ r.y * (b.z * g.x - g.z * b.x) +
+ r.z * (b.y * g.x - g.y * b.x);
+ return !qFuzzyIsNull(det);
+ }
+
+ QColorMatrix inverted() const
+ {
+ float det = r.x * (b.z * g.y - g.z * b.y) -
+ r.y * (b.z * g.x - g.z * b.x) +
+ r.z * (b.y * g.x - g.y * b.x);
+ det = 1.0f / det;
+ QColorMatrix inv;
+ inv.r.x = (g.y * b.z - b.y * g.z) * det;
+ inv.r.y = (b.y * r.z - r.y * b.z) * det;
+ inv.r.z = (r.y * g.z - g.y * r.z) * det;
+ inv.g.x = (b.x * g.z - g.x * b.z) * det;
+ inv.g.y = (r.x * b.z - b.x * r.z) * det;
+ inv.g.z = (g.x * r.z - r.x * g.z) * det;
+ inv.b.x = (g.x * b.y - b.x * g.y) * det;
+ inv.b.y = (b.x * r.y - r.x * b.y) * det;
+ inv.b.z = (r.x * g.y - g.x * r.y) * det;
+ return inv;
+ }
+ QColorMatrix operator*(const QColorMatrix &o) const
+ {
+ QColorMatrix comb;
+ comb.r.x = r.x * o.r.x + g.x * o.r.y + b.x * o.r.z;
+ comb.g.x = r.x * o.g.x + g.x * o.g.y + b.x * o.g.z;
+ comb.b.x = r.x * o.b.x + g.x * o.b.y + b.x * o.b.z;
+
+ comb.r.y = r.y * o.r.x + g.y * o.r.y + b.y * o.r.z;
+ comb.g.y = r.y * o.g.x + g.y * o.g.y + b.y * o.g.z;
+ comb.b.y = r.y * o.b.x + g.y * o.b.y + b.y * o.b.z;
+
+ comb.r.z = r.z * o.r.x + g.z * o.r.y + b.z * o.r.z;
+ comb.g.z = r.z * o.g.x + g.z * o.g.y + b.z * o.g.z;
+ comb.b.z = r.z * o.b.x + g.z * o.b.y + b.z * o.b.z;
+ return comb;
+
+ }
+ QColorVector map(const QColorVector &c) const
+ {
+ return QColorVector { c.x * r.x + c.y * g.x + c.z * b.x,
+ c.x * r.y + c.y * g.y + c.z * b.y,
+ c.x * r.z + c.y * g.z + c.z * b.z };
+ }
+ QColorMatrix transposed() const
+ {
+ return QColorMatrix { { r.x, g.x, b.x },
+ { r.y, g.y, b.y },
+ { r.z, g.z, b.z } };
+ }
+
+ static QColorMatrix null()
+ {
+ return { QColorVector::null(), QColorVector::null(), QColorVector::null() };
+ }
+ static QColorMatrix identity()
+ {
+ return { { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } };
+ }
+ static QColorMatrix toXyzFromSRgb()
+ {
+ return QColorMatrix { { 0.4360217452f, 0.2224751115f, 0.0139281144f },
+ { 0.3851087987f, 0.7169067264f, 0.0971015394f },
+ { 0.1430812478f, 0.0606181994f, 0.7141585946f } };
+ }
+ static QColorMatrix toXyzFromAdobeRgb()
+ {
+ return QColorMatrix { { 0.6097189188f, 0.3111021519f, 0.0194766335f },
+ { 0.2052682191f, 0.6256770492f, 0.0608891509f },
+ { 0.1492247432f, 0.0632209629f, 0.7448224425f } };
+ }
+ static QColorMatrix toXyzFromDciP3D65()
+ {
+ return QColorMatrix { { 0.5150973201f, 0.2411795557f, -0.0010491034f },
+ { 0.2919696569f, 0.6922441125f, 0.0418830328f },
+ { 0.1571449190f, 0.0665764511f, 0.7843542695f } };
+ }
+ static QColorMatrix toXyzFromProPhotoRgb()
+ {
+ return QColorMatrix { { 0.7976672649f, 0.2880374491f, 0.0000000000f },
+ { 0.1351922452f, 0.7118769884f, 0.0000000000f },
+ { 0.0313525312f, 0.0000856627f, 0.8251883388f } };
+ }
+ static QColorMatrix toXyzFromBt2020()
+ {
+ return QColorMatrix { { 0.6506130099f, 0.2695676684f, -0.0018652577f },
+ { 0.1865101457f, 0.6840794086f, 0.0172256753f },
+ { 0.1270887405f, 0.0463530831f, 0.8098278046f } };
+ }
+};
+
+inline bool operator==(const QColorMatrix &m1, const QColorMatrix &m2)
+{
+ return (m1.r == m2.r) && (m1.g == m2.g) && (m1.b == m2.b);
+}
+
+inline bool operator!=(const QColorMatrix &m1, const QColorMatrix &m2)
+{
+ return !(m1 == m2);
+}
+
+QT_END_NAMESPACE
+
+#endif // QCOLORMATRIX_P_H
diff --git a/src/gui/painting/qcolorspace.cpp b/src/gui/painting/qcolorspace.cpp
new file mode 100644
index 0000000000..24785f7b61
--- /dev/null
+++ b/src/gui/painting/qcolorspace.cpp
@@ -0,0 +1,633 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qcolorspace.h"
+#include "qcolorspace_p.h"
+
+#include "qcolortransform.h"
+#include "qcolormatrix_p.h"
+#include "qcolortransferfunction_p.h"
+#include "qcolortransform_p.h"
+#include "qicc_p.h"
+
+#include <qmath.h>
+#include <qtransform.h>
+
+#include <qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+QColorSpacePrivate::QColorSpacePrivate()
+ : id(QColorSpace::Unknown)
+ , gamut(QColorSpace::Gamut::Custom)
+ , transferFunction(QColorSpace::TransferFunction::Custom)
+ , gamma(0.0f)
+ , whitePoint(QColorVector::null())
+ , toXyz(QColorMatrix::null())
+{
+}
+
+QColorSpacePrivate::QColorSpacePrivate(QColorSpace::ColorSpaceId colorSpaceId)
+ : id(colorSpaceId)
+{
+ switch (colorSpaceId) {
+ case QColorSpace::Undefined:
+ gamut = QColorSpace::Gamut::Custom;
+ transferFunction = QColorSpace::TransferFunction::Custom;
+ gamma = 0.0f;
+ description = QStringLiteral("Undefined");
+ break;
+ case QColorSpace::SRgb:
+ gamut = QColorSpace::Gamut::SRgb;
+ transferFunction = QColorSpace::TransferFunction::SRgb;
+ gamma = 2.31f; // ?
+ description = QStringLiteral("sRGB");
+ break;
+ case QColorSpace::SRgbLinear:
+ gamut = QColorSpace::Gamut::SRgb;
+ transferFunction = QColorSpace::TransferFunction::Linear;
+ gamma = 1.0f;
+ description = QStringLiteral("Linear sRGB");
+ break;
+ case QColorSpace::AdobeRgb:
+ gamut = QColorSpace::Gamut::AdobeRgb;
+ transferFunction = QColorSpace::TransferFunction::Gamma;
+ gamma = 2.19921875f; // Not quite 2.2, see https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
+ description = QStringLiteral("Adobe RGB");
+ break;
+ case QColorSpace::DisplayP3:
+ gamut = QColorSpace::Gamut::DciP3D65;
+ transferFunction = QColorSpace::TransferFunction::SRgb;
+ gamma = 2.31f; // ?
+ description = QStringLiteral("Display P3");
+ break;
+ case QColorSpace::ProPhotoRgb:
+ gamut = QColorSpace::Gamut::ProPhotoRgb;
+ transferFunction = QColorSpace::TransferFunction::ProPhotoRgb;
+ gamma = 1.8f;
+ description = QStringLiteral("ProPhoto RGB");
+ break;
+ case QColorSpace::Bt2020:
+ gamut = QColorSpace::Gamut::Bt2020;
+ transferFunction = QColorSpace::TransferFunction::Bt2020;
+ gamma = 2.1f; // ?
+ description = QStringLiteral("BT.2020");
+ break;
+ case QColorSpace::Unknown:
+ qWarning("Can not create an unknown color space");
+ Q_FALLTHROUGH();
+ default:
+ Q_UNREACHABLE();
+ }
+ initialize();
+}
+
+QColorSpacePrivate::QColorSpacePrivate(QColorSpace::Gamut gamut, QColorSpace::TransferFunction fun, float gamma)
+ : gamut(gamut)
+ , transferFunction(fun)
+ , gamma(gamma)
+{
+ if (!identifyColorSpace())
+ id = QColorSpace::Unknown;
+ initialize();
+}
+
+bool QColorSpacePrivate::identifyColorSpace()
+{
+ switch (gamut) {
+ case QColorSpace::Gamut::SRgb:
+ if (transferFunction == QColorSpace::TransferFunction::SRgb) {
+ id = QColorSpace::SRgb;
+ description = QStringLiteral("sRGB");
+ return true;
+ }
+ if (transferFunction == QColorSpace::TransferFunction::Linear) {
+ id = QColorSpace::SRgbLinear;
+ description = QStringLiteral("Linear sRGB");
+ return true;
+ }
+ break;
+ case QColorSpace::Gamut::AdobeRgb:
+ if (transferFunction == QColorSpace::TransferFunction::Gamma) {
+ if (qAbs(gamma - 2.19921875f) < (1/1024.0f)) {
+ id = QColorSpace::AdobeRgb;
+ description = QStringLiteral("Adobe RGB");
+ return true;
+ }
+ }
+ break;
+ case QColorSpace::Gamut::DciP3D65:
+ if (transferFunction == QColorSpace::TransferFunction::SRgb) {
+ id = QColorSpace::DisplayP3;
+ description = QStringLiteral("Display P3");
+ return true;
+ }
+ break;
+ case QColorSpace::Gamut::ProPhotoRgb:
+ if (transferFunction == QColorSpace::TransferFunction::ProPhotoRgb) {
+ id = QColorSpace::ProPhotoRgb;
+ description = QStringLiteral("ProPhoto RGB");
+ return true;
+ }
+ if (transferFunction == QColorSpace::TransferFunction::Gamma) {
+ // ProPhoto RGB's curve is effectively gamma 1.8 for 8bit precision.
+ if (qAbs(gamma - 1.8f) < (1/1024.0f)) {
+ id = QColorSpace::ProPhotoRgb;
+ description = QStringLiteral("ProPhoto RGB");
+ return true;
+ }
+ }
+ break;
+ case QColorSpace::Gamut::Bt2020:
+ if (transferFunction == QColorSpace::TransferFunction::Bt2020) {
+ id = QColorSpace::Bt2020;
+ description = QStringLiteral("BT.2020");
+ return true;
+ }
+ break;
+ default:
+ break;
+ }
+ return false;
+}
+
+void QColorSpacePrivate::initialize()
+{
+ setToXyzMatrix();
+ setTransferFunction();
+}
+
+void QColorSpacePrivate::setToXyzMatrix()
+{
+ switch (gamut) {
+ case QColorSpace::Gamut::SRgb:
+ toXyz = QColorMatrix::toXyzFromSRgb();
+ whitePoint = QColorVector::D65();
+ return;
+ case QColorSpace::Gamut::AdobeRgb:
+ toXyz = QColorMatrix::toXyzFromAdobeRgb();
+ whitePoint = QColorVector::D65();
+ return;
+ case QColorSpace::Gamut::DciP3D65:
+ toXyz = QColorMatrix::toXyzFromDciP3D65();
+ whitePoint = QColorVector::D65();
+ return;
+ case QColorSpace::Gamut::ProPhotoRgb:
+ toXyz = QColorMatrix::toXyzFromProPhotoRgb();
+ whitePoint = QColorVector::D50();
+ return;
+ case QColorSpace::Gamut::Bt2020:
+ toXyz = QColorMatrix::toXyzFromBt2020();
+ whitePoint = QColorVector::D65();
+ return;
+ case QColorSpace::Gamut::Custom:
+ toXyz = QColorMatrix::null();
+ whitePoint = QColorVector::D50();
+ return;
+ }
+ Q_UNREACHABLE();
+}
+
+void QColorSpacePrivate::setTransferFunction()
+{
+ switch (transferFunction) {
+ case QColorSpace::TransferFunction::Linear:
+ trc[0].m_type = QColorTrc::Type::Function;
+ trc[0].m_fun = QColorTransferFunction();
+ break;
+ case QColorSpace::TransferFunction::Gamma:
+ trc[0].m_type = QColorTrc::Type::Function;
+ trc[0].m_fun = QColorTransferFunction::fromGamma(gamma);
+ break;
+ case QColorSpace::TransferFunction::SRgb:
+ trc[0].m_type = QColorTrc::Type::Function;
+ trc[0].m_fun = QColorTransferFunction::fromSRgb();
+ break;
+ case QColorSpace::TransferFunction::ProPhotoRgb:
+ trc[0].m_type = QColorTrc::Type::Function;
+ trc[0].m_fun = QColorTransferFunction::fromProPhotoRgb();
+ break;
+ case QColorSpace::TransferFunction::Bt2020:
+ trc[0].m_type = QColorTrc::Type::Function;
+ trc[0].m_fun = QColorTransferFunction::fromBt2020();
+ break;
+ case QColorSpace::TransferFunction::Custom:
+ break;
+ default:
+ Q_UNREACHABLE();
+ break;
+ }
+ trc[1] = trc[0];
+ trc[2] = trc[0];
+}
+
+QColorTransform QColorSpacePrivate::transformationToColorSpace(const QColorSpacePrivate *out) const
+{
+ Q_ASSERT(out);
+ QColorTransform combined;
+ combined.d_ptr.reset(new QColorTransformPrivate);
+ combined.d_ptr->colorSpaceIn = this;
+ combined.d_ptr->colorSpaceOut = out;
+ combined.d_ptr->colorMatrix = out->toXyz.inverted() * toXyz;
+ return combined;
+}
+
+/*!
+ \class QColorSpace
+ \brief The QColorSpace class provides a color space abstraction.
+ \since 5.14
+
+ \ingroup painting
+ \ingroup appearance
+ \inmodule QtGui
+
+ Color values can be interpreted in different ways, and based on the interpretation
+ can live in different spaces. We call this \e {color spaces}.
+
+ QColorSpace provides access to creating several predefined color spaces and
+ can generate QColorTransforms for converting colors from one color space to
+ another.
+
+ QColorSpace can also represent color spaces defined by ICC profiles or embedded
+ in images, that do not otherwise fit the predefined color spaces.
+
+ A color space can generally speaking be conceived as a combination of a transfer
+ function and a gamut. The gamut defines which colors the color space can represent.
+ A color space that can represent a wider range of colors is also known as a
+ wide-gamut color space. The gamut is defined by three primary colors that represent
+ exactly how red, green, and blue look in this particular color space, and a white
+ color that represents where and how bright pure white is.
+
+ The transfer function or gamma curve determines how each component in the
+ color space is encoded. These are used because human perception does not operate
+ linearly, and the transfer functions try to ensure that colors will seem evenly
+ spaced to human eyes.
+*/
+
+
+/*!
+ \enum QColorSpace::ColorSpaceId
+
+ Predefined color spaces.
+
+ \value Undefined An empty, invalid or unsupported color space.
+ \value Unknown A valid color space that doesn't match any of the predefined color spaces.
+ \value SRgb The sRGB color space, which Qt operates in by default. It is a close approximation
+ of how most classic monitors operate, and a mode most software and hardware support.
+ \l{http://www.color.org/chardata/rgb/srgb.xalter}{ICC registration of sRGB}.
+ \value SRgbLinear The sRGB color space with linear gamma. Useful for gamma-corrected blending.
+ \value AdobeRgb The Adobe RGB color space is a classic wide-gamut color space, using a gamma of 2.2.
+ \l{http://www.color.org/chardata/rgb/adobergb.xalter}{ICC registration of Adobe RGB (1998)}
+ \value DisplayP3 A color-space using the primaries of DCI-P3, but with the whitepoint and transfer
+ function of sRGB. Common in modern wide-gamut screens.
+ \l{http://www.color.org/chardata/rgb/DCIP3.xalter}{ICC registration of DCI-P3}
+ \value ProPhotoRgb The Pro Photo RGB color space, also known as ROMM RGB is a very wide gamut color space.
+ \l{http://www.color.org/chardata/rgb/rommrgb.xalter}{ICC registration of ROMM RGB}
+ \value Bt2020 BT.2020 also known as Rec.2020 is the color space of HDR TVs.
+ \l{http://www.color.org/chardata/rgb/BT2020.xalter}{ICC registration of BT.2020}
+*/
+
+/*!
+ \enum QColorSpace::Gamut
+
+ Predefined gamuts, or sets of primary colors.
+
+ \value Custom The gamut is undefined or does not match any predefined sets.
+ \value SRgb The sRGB gamut
+ \value AdobeRgb The Adobe RGB gamut
+ \value DciP3D65 The DCI-P3 gamut with the D65 whitepoint
+ \value ProPhotoRgb The ProPhoto RGB gamut with the D50 whitepoint
+ \value Bt2020 The BT.2020 gamut
+*/
+
+/*!
+ \enum QColorSpace::TransferFunction
+
+ Predefined transfer functions or gamma curves.
+
+ \value Custom The custom or null transfer function
+ \value Linear The linear transfer functions
+ \value Gamma A transfer function that is a real gamma curve based on the value of gamma()
+ \value SRgb The sRGB transfer function, composed of linear and gamma parts
+ \value ProPhotoRgb The ProPhoto RGB transfer function, composed of linear and gamma parts
+ \value Bt2020 The BT.2020 transfer function, composed of linear and gamma parts
+*/
+
+/*!
+ Creates a new colorspace object that represents \a colorSpaceId.
+ */
+QColorSpace::QColorSpace(QColorSpace::ColorSpaceId colorSpaceId)
+{
+ static QExplicitlySharedDataPointer<QColorSpacePrivate> predefinedColorspacePrivates[QColorSpace::Bt2020];
+ if (colorSpaceId <= QColorSpace::Unknown) {
+ if (!predefinedColorspacePrivates[0])
+ predefinedColorspacePrivates[0] = new QColorSpacePrivate(QColorSpace::Undefined);
+ d_ptr = predefinedColorspacePrivates[0]; // unknown and undefined both returns the static undefined colorspace.
+ } else {
+ if (!predefinedColorspacePrivates[colorSpaceId - 1])
+ predefinedColorspacePrivates[colorSpaceId - 1] = new QColorSpacePrivate(colorSpaceId);
+ d_ptr = predefinedColorspacePrivates[colorSpaceId - 1];
+ }
+
+ Q_ASSERT(colorSpaceId == QColorSpace::Undefined || isValid());
+}
+
+/*!
+ Creates a custom color space with the gamut \a gamut, using the transfer function \a fun and
+ optionally \a gamma.
+ */
+QColorSpace::QColorSpace(QColorSpace::Gamut gamut, QColorSpace::TransferFunction fun, float gamma)
+ : d_ptr(new QColorSpacePrivate(gamut, fun, gamma))
+{
+}
+
+/*!
+ Creates a custom color space with the gamut \a gamut, using a gamma transfer function of
+ \a gamma.
+ */
+QColorSpace::QColorSpace(QColorSpace::Gamut gamut, float gamma)
+ : d_ptr(new QColorSpacePrivate(gamut, TransferFunction::Gamma, gamma))
+{
+}
+
+QColorSpace::~QColorSpace()
+{
+}
+
+QColorSpace::QColorSpace(QColorSpace &&colorSpace)
+ : d_ptr(std::move(colorSpace.d_ptr))
+{
+}
+
+QColorSpace::QColorSpace(const QColorSpace &colorSpace)
+ : d_ptr(colorSpace.d_ptr)
+{
+}
+
+QColorSpace &QColorSpace::operator=(QColorSpace &&colorSpace)
+{
+ d_ptr = std::move(colorSpace.d_ptr);
+ return *this;
+}
+
+QColorSpace &QColorSpace::operator=(const QColorSpace &colorSpace)
+{
+ d_ptr = colorSpace.d_ptr;
+ return *this;
+}
+
+/*!
+ Returns the id of the predefined color space this object
+ represents or \c Unknown if it doesn't match any of them.
+*/
+QColorSpace::ColorSpaceId QColorSpace::colorSpaceId() const noexcept
+{
+ return d_ptr->id;
+}
+
+/*!
+ Returns the predefined gamut of the color space
+ or \c Gamut::Custom if it doesn't match any of them.
+*/
+QColorSpace::Gamut QColorSpace::gamut() const noexcept
+{
+ return d_ptr->gamut;
+}
+
+/*!
+ Returns the predefined transfer function of the color space
+ or \c TransferFunction::Custom if it doesn't match any of them.
+
+ \sa gamma()
+*/
+QColorSpace::TransferFunction QColorSpace::transferFunction() const noexcept
+{
+ return d_ptr->transferFunction;
+}
+
+/*!
+ Returns the gamma value of color spaces with \c TransferFunction::Gamma,
+ an approximate gamma value for other predefined color spaces, or
+ 0.0 if no approximate gamma is known.
+
+ \sa transferFunction()
+*/
+float QColorSpace::gamma() const noexcept
+{
+ return d_ptr->gamma;
+}
+
+/*!
+ Returns an ICC profile representing the color space.
+
+ If the color space was generated from an ICC profile, that profile
+ is returned, otherwise one is generated.
+
+ \note Even invalid color spaces may return the ICC profile if they
+ were generated from one, to allow applications to implement wider
+ support themselves.
+
+ \sa fromIccProfile()
+*/
+QByteArray QColorSpace::iccProfile() const
+{
+ if (!d_ptr->iccProfile.isEmpty())
+ return d_ptr->iccProfile;
+ if (!isValid())
+ return QByteArray();
+ return QIcc::toIccProfile(*this);
+}
+
+/*!
+ Creates a QColorSpace from ICC profile \a iccProfile.
+
+ \note Not all ICC profiles are supported. QColorSpace only supports
+ RGB-XYZ ICC profiles that are three-component matrix-based.
+
+ If the ICC profile is not supported an invalid QColorSpace is returned
+ where you can still read the original ICC profile using iccProfile().
+
+ \sa iccProfile()
+*/
+QColorSpace QColorSpace::fromIccProfile(const QByteArray &iccProfile)
+{
+ QColorSpace colorSpace;
+ if (QIcc::fromIccProfile(iccProfile, &colorSpace))
+ return colorSpace;
+ colorSpace.d_ptr->id = QColorSpace::Undefined;
+ colorSpace.d_ptr->iccProfile = iccProfile;
+ return colorSpace;
+}
+
+/*!
+ Returns \c true if the color space is valid.
+*/
+bool QColorSpace::isValid() const noexcept
+{
+ return d_ptr->id != QColorSpace::Undefined && d_ptr->toXyz.isValid()
+ && d_ptr->trc[0].isValid() && d_ptr->trc[1].isValid() && d_ptr->trc[2].isValid();
+}
+
+/*!
+ \relates QColorSpace
+ Returns \c true if colorspace \a colorSpace1 is equal to colorspace \a colorSpace2;
+ otherwise returns \c false
+*/
+bool operator==(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2)
+{
+ if (colorSpace1.d_ptr == colorSpace2.d_ptr)
+ return true;
+
+ if (colorSpace1.colorSpaceId() == QColorSpace::Undefined && colorSpace2.colorSpaceId() == QColorSpace::Undefined)
+ return colorSpace1.d_ptr->iccProfile == colorSpace2.d_ptr->iccProfile;
+
+ if (colorSpace1.colorSpaceId() != QColorSpace::Unknown && colorSpace2.colorSpaceId() != QColorSpace::Unknown)
+ return colorSpace1.colorSpaceId() == colorSpace2.colorSpaceId();
+
+ if (colorSpace1.gamut() != QColorSpace::Gamut::Custom && colorSpace2.gamut() != QColorSpace::Gamut::Custom) {
+ if (colorSpace1.gamut() != colorSpace2.gamut())
+ return false;
+ } else {
+ if (colorSpace1.d_ptr->toXyz != colorSpace2.d_ptr->toXyz)
+ return false;
+ }
+
+ if (colorSpace1.transferFunction() != QColorSpace::TransferFunction::Custom &&
+ colorSpace2.transferFunction() != QColorSpace::TransferFunction::Custom) {
+ if (colorSpace1.transferFunction() != colorSpace2.transferFunction())
+ return false;
+ if (colorSpace1.transferFunction() == QColorSpace::TransferFunction::Gamma)
+ return colorSpace1.gamma() == colorSpace2.gamma();
+ return true;
+ }
+
+ if (colorSpace1.d_ptr->trc[0] != colorSpace2.d_ptr->trc[0] ||
+ colorSpace1.d_ptr->trc[1] != colorSpace2.d_ptr->trc[1] ||
+ colorSpace1.d_ptr->trc[2] != colorSpace2.d_ptr->trc[2])
+ return false;
+
+ return true;
+}
+
+/*!
+ \fn bool operator!=(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2)
+ \relates QColorSpace
+
+ Returns \c true if colorspace \a colorspace1 is not equal to colorspace \a colorspace2;
+ otherwise returns \c false
+*/
+
+/*!
+ Generates and returns a color space transformation from this color space to
+ \a colorspace.
+*/
+QColorTransform QColorSpace::transformationToColorSpace(const QColorSpace &colorspace) const
+{
+ if (!isValid() || !colorspace.isValid())
+ return QColorTransform();
+
+ return d_ptr->transformationToColorSpace(colorspace.d_ptr.constData());
+}
+
+/*!
+ \internal
+*/
+QColorSpacePrivate *QColorSpace::d_func()
+{
+ d_ptr.detach();
+ return d_ptr.data();
+}
+
+/*!
+ \fn const QColorSpacePrivate* QColorSpacePrivate::d_func() const
+ \internal
+*/
+
+/*****************************************************************************
+ QColorSpace stream functions
+ *****************************************************************************/
+#if !defined(QT_NO_DATASTREAM)
+/*!
+ \fn QDataStream &operator<<(QDataStream &stream, const QColorSpace &colorSpace)
+ \relates QColorSpace
+
+ Writes the given \a colorSpace to the given \a stream as an ICC profile.
+
+ \sa QColorSpace::iccProfile(), {Serializing Qt Data Types}
+*/
+
+QDataStream &operator<<(QDataStream &s, const QColorSpace &image)
+{
+ s << image.iccProfile();
+ return s;
+}
+
+/*!
+ \fn QDataStream &operator>>(QDataStream &stream, QColorSpace &colorSpace)
+ \relates QColorSpace
+
+ Reads a color space from the given \a stream and stores it in the given
+ \a colorSpace.
+
+ \sa QColorSpace::fromIccProfile(), {Serializing Qt Data Types}
+*/
+
+QDataStream &operator>>(QDataStream &s, QColorSpace &colorSpace)
+{
+ QByteArray iccProfile;
+ s >> iccProfile;
+ colorSpace = QColorSpace::fromIccProfile(iccProfile);
+ return s;
+}
+#endif // QT_NO_DATASTREAM
+
+#ifndef QT_NO_DEBUG_STREAM
+QDebug operator<<(QDebug dbg, const QColorSpace &colorSpace)
+{
+ QDebugStateSaver saver(dbg);
+ dbg.nospace();
+ dbg << "QColorSpace(";
+ dbg << colorSpace.colorSpaceId() << ", " << colorSpace.gamut() << ", " << colorSpace.transferFunction();
+ dbg << ", gamma=" << colorSpace.gamma();
+ dbg << ')';
+ return dbg;
+}
+#endif
+
+QT_END_NAMESPACE
diff --git a/src/gui/painting/qcolorspace.h b/src/gui/painting/qcolorspace.h
new file mode 100644
index 0000000000..923546ec6f
--- /dev/null
+++ b/src/gui/painting/qcolorspace.h
@@ -0,0 +1,136 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QCOLORSPACE_H
+#define QCOLORSPACE_H
+
+#include <QtGui/qtguiglobal.h>
+#include <QtGui/qcolortransform.h>
+#include <QtCore/qshareddata.h>
+
+QT_BEGIN_NAMESPACE
+
+class QColorSpacePrivate;
+
+class Q_GUI_EXPORT QColorSpace
+{
+ Q_GADGET
+public:
+ enum ColorSpaceId {
+ Undefined = 0,
+ Unknown = 1,
+ SRgb,
+ SRgbLinear,
+ AdobeRgb,
+ DisplayP3,
+ ProPhotoRgb,
+ Bt2020,
+ };
+ Q_ENUM(ColorSpaceId)
+ enum class Gamut {
+ Custom = 0,
+ SRgb,
+ AdobeRgb,
+ DciP3D65,
+ ProPhotoRgb,
+ Bt2020,
+ };
+ Q_ENUM(Gamut)
+ enum class TransferFunction {
+ Custom = 0,
+ Linear,
+ Gamma,
+ SRgb,
+ ProPhotoRgb,
+ Bt2020,
+ };
+ Q_ENUM(TransferFunction)
+
+ QColorSpace(ColorSpaceId colorSpaceId = Undefined);
+ QColorSpace(Gamut gamut, TransferFunction fun, float gamma = 0.0f);
+ QColorSpace(Gamut gamut, float gamma);
+ ~QColorSpace();
+
+ QColorSpace(QColorSpace &&colorSpace);
+ QColorSpace(const QColorSpace &colorSpace);
+ QColorSpace &operator=(QColorSpace &&colorSpace);
+ QColorSpace &operator=(const QColorSpace &colorSpace);
+
+ ColorSpaceId colorSpaceId() const noexcept;
+ Gamut gamut() const noexcept;
+ TransferFunction transferFunction() const noexcept;
+ float gamma() const noexcept;
+
+ bool isValid() const noexcept;
+
+ friend Q_GUI_EXPORT bool operator==(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2);
+ friend inline bool operator!=(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2);
+
+ static QColorSpace fromIccProfile(const QByteArray &iccProfile);
+ QByteArray iccProfile() const;
+
+ QColorTransform transformationToColorSpace(const QColorSpace &colorspace) const;
+
+ QColorSpacePrivate *d_func();
+ inline const QColorSpacePrivate *d_func() const { return d_ptr.constData(); }
+
+private:
+ friend class QColorSpacePrivate;
+ QExplicitlySharedDataPointer<QColorSpacePrivate> d_ptr;
+};
+
+bool Q_GUI_EXPORT operator==(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2);
+inline bool operator!=(const QColorSpace &colorSpace1, const QColorSpace &colorSpace2)
+{
+ return !(colorSpace1 == colorSpace2);
+}
+
+// QColorSpace stream functions
+#if !defined(QT_NO_DATASTREAM)
+Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QColorSpace &);
+Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QColorSpace &);
+#endif
+
+#ifndef QT_NO_DEBUG_STREAM
+Q_GUI_EXPORT QDebug operator<<(QDebug, const QColorSpace &);
+#endif
+
+QT_END_NAMESPACE
+
+#endif // QCOLORSPACE_P_H
diff --git a/src/plugins/platforms/mirclient/qmirclientclipboard.h b/src/gui/painting/qcolorspace_p.h
index 09e9bcdf38..91107a9a89 100644
--- a/src/plugins/platforms/mirclient/qmirclientclipboard.h
+++ b/src/gui/painting/qcolorspace_p.h
@@ -1,9 +1,9 @@
/****************************************************************************
**
-** Copyright (C) 2016 Canonical, Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,56 +37,60 @@
**
****************************************************************************/
+#ifndef QCOLORSPACE_P_H
+#define QCOLORSPACE_P_H
-#ifndef QMIRCLIENTCLIPBOARD_H
-#define QMIRCLIENTCLIPBOARD_H
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
-#include <qpa/qplatformclipboard.h>
+#include "qcolorspace.h"
+#include "qcolormatrix_p.h"
+#include "qcolortrc_p.h"
+#include "qcolortrclut_p.h"
-#include <QMimeData>
-#include <QPointer>
+#include <QtCore/qshareddata.h>
-namespace com {
- namespace ubuntu {
- namespace content {
- class Hub;
- }
- }
-}
+QT_BEGIN_NAMESPACE
-class QDBusPendingCallWatcher;
-
-class QMirClientClipboard : public QObject, public QPlatformClipboard
+class QColorSpacePrivate : public QSharedData
{
- Q_OBJECT
public:
- QMirClientClipboard();
- virtual ~QMirClientClipboard();
-
- // QPlatformClipboard methods.
- QMimeData* mimeData(QClipboard::Mode mode = QClipboard::Clipboard) override;
- void setMimeData(QMimeData* data, QClipboard::Mode mode = QClipboard::Clipboard) override;
- bool supportsMode(QClipboard::Mode mode) const override;
- bool ownsMode(QClipboard::Mode mode) const override;
+ QColorSpacePrivate();
+ QColorSpacePrivate(QColorSpace::ColorSpaceId colorSpaceId);
+ QColorSpacePrivate(QColorSpace::Gamut gamut, QColorSpace::TransferFunction fun, float gamma);
+ QColorSpacePrivate(const QColorSpacePrivate &other) = default;
+ QColorSpacePrivate &operator=(const QColorSpacePrivate &other) = default;
-private Q_SLOTS:
- void onApplicationStateChanged(Qt::ApplicationState state);
+ void initialize();
+ void setToXyzMatrix();
+ void setTransferFunction();
+ bool identifyColorSpace();
+ QColorTransform transformationToColorSpace(const QColorSpacePrivate *out) const;
-private:
- void updateMimeData();
- void requestMimeData();
+ QColorSpace::ColorSpaceId id;
+ QColorSpace::Gamut gamut;
+ QColorSpace::TransferFunction transferFunction;
+ float gamma;
+ QColorVector whitePoint;
- QMimeData *mMimeData;
+ QColorTrc trc[3];
+ QColorMatrix toXyz;
- enum {
- OutdatedClipboard, // Our mimeData is outdated, need to fetch latest from ContentHub
- SyncingClipboard, // Our mimeData is outdated and we are waiting for ContentHub to reply with the latest paste
- SyncedClipboard // Our mimeData is in sync with what ContentHub has
- } mClipboardState{OutdatedClipboard};
+ QString description;
+ QByteArray iccProfile;
- com::ubuntu::content::Hub *mContentHub;
-
- QDBusPendingCallWatcher *mPasteReply{nullptr};
+ mutable QSharedPointer<QColorTrcLut> lut[3];
+ mutable QAtomicInt lutsGenerated;
};
-#endif // QMIRCLIENTCLIPBOARD_H
+QT_END_NAMESPACE
+
+#endif // QCOLORSPACE_P_H
diff --git a/src/gui/painting/qcolortransferfunction_p.h b/src/gui/painting/qcolortransferfunction_p.h
new file mode 100644
index 0000000000..fd7cfa2b2b
--- /dev/null
+++ b/src/gui/painting/qcolortransferfunction_p.h
@@ -0,0 +1,207 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QCOLORTRANSFERFUNCTION_P_H
+#define QCOLORTRANSFERFUNCTION_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtGui/private/qtguiglobal_p.h>
+
+#include <cmath>
+
+QT_BEGIN_NAMESPACE
+
+// Defines a ICC parametric curve type 4
+class Q_GUI_EXPORT QColorTransferFunction
+{
+public:
+ QColorTransferFunction() noexcept
+ : m_a(1.0f), m_b(0.0f), m_c(1.0f), m_d(0.0f), m_e(0.0f), m_f(0.0f), m_g(1.0f), m_flags(0)
+ { }
+ QColorTransferFunction(float a, float b, float c, float d, float e, float f, float g) noexcept
+ : m_a(a), m_b(b), m_c(c), m_d(d), m_e(e), m_f(f), m_g(g), m_flags(0)
+ { }
+
+ bool isGamma() const
+ {
+ updateHints();
+ return m_flags & quint32(Hints::IsGamma);
+ }
+ bool isLinear() const
+ {
+ updateHints();
+ return m_flags & quint32(Hints::IsLinear);
+ }
+ bool isSRgb() const
+ {
+ updateHints();
+ return m_flags & quint32(Hints::IsSRgb);
+ }
+
+ float apply(float x) const
+ {
+ if (x < m_d)
+ return m_c * x + m_f;
+ else
+ return std::pow(m_a * x + m_b, m_g) + m_e;
+ }
+
+ QColorTransferFunction inverted() const
+ {
+ float a, b, c, d, e, f, g;
+
+ d = m_c * m_d + m_f;
+
+ if (!qFuzzyIsNull(m_c)) {
+ c = 1.0f / m_c;
+ f = -m_f / m_c;
+ } else {
+ c = 0.0f;
+ f = 0.0f;
+ }
+
+ if (!qFuzzyIsNull(m_a) && !qFuzzyIsNull(m_g)) {
+ a = std::pow(1.0f / m_a, m_g);
+ b = -a * m_e;
+ e = -m_b / m_a;
+ g = 1.0f / m_g;
+ } else {
+ a = 0.0f;
+ b = 0.0f;
+ e = 1.0f;
+ g = 1.0f;
+ }
+
+ return QColorTransferFunction(a, b, c, d, e, f, g);
+ }
+
+ // A few predefined curves:
+ static QColorTransferFunction fromGamma(float gamma)
+ {
+ return QColorTransferFunction(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, gamma);
+ }
+ static QColorTransferFunction fromSRgb()
+ {
+ return QColorTransferFunction(1.0f / 1.055f, 0.055f / 1.055f, 1.0f / 12.92f, 0.04045f, 0.0f, 0.0f, 2.4f);
+ }
+ static QColorTransferFunction fromBt2020()
+ {
+ return QColorTransferFunction(1.0f / 1.0993f, 0.0993f / 1.0993f, 1.0f / 4.5f, 0.08145f, 0.0f, 0.0f, 2.2f);
+ }
+ static QColorTransferFunction fromProPhotoRgb()
+ {
+ return QColorTransferFunction(1.0f, 0.0f, 1.0f / 16.0f, 16.0f / 512.0f, 0.0f, 0.0f, 1.8f);
+ }
+ bool matches(const QColorTransferFunction &o) const
+ {
+ return paramCompare(m_a, o.m_a) && paramCompare(m_b, o.m_b)
+ && paramCompare(m_c, o.m_c) && paramCompare(m_d, o.m_d)
+ && paramCompare(m_e, o.m_e) && paramCompare(m_f, o.m_f)
+ && paramCompare(m_g, o.m_g);
+ }
+ friend inline bool operator==(const QColorTransferFunction &f1, const QColorTransferFunction &f2);
+ friend inline bool operator!=(const QColorTransferFunction &f1, const QColorTransferFunction &f2);
+
+ float m_a;
+ float m_b;
+ float m_c;
+ float m_d;
+ float m_e;
+ float m_f;
+ float m_g;
+
+private:
+ static inline bool paramCompare(float p1, float p2)
+ {
+ // Much fuzzier than fuzzy compare.
+ // It tries match parameters that has been passed through a 8.8
+ // fixed point form.
+ return (qAbs(p1 - p2) <= (1.0f / 512.0f));
+ }
+
+ void updateHints() const
+ {
+ if (m_flags & quint32(Hints::Calculated))
+ return;
+ // We do not consider the case with m_d = 1.0f linear or simple,
+ // since it wouldn't be linear for applyExtended().
+ bool simple = paramCompare(m_a, 1.0f) && paramCompare(m_b, 0.0f)
+ && paramCompare(m_d, 0.0f)
+ && paramCompare(m_e, 0.0f);
+ if (simple) {
+ m_flags |= quint32(Hints::IsGamma);
+ if (qFuzzyCompare(m_g, 1.0f))
+ m_flags |= quint32(Hints::IsLinear);
+ } else {
+ if (*this == fromSRgb())
+ m_flags |= quint32(Hints::IsSRgb);
+ }
+ m_flags |= quint32(Hints::Calculated);
+ }
+ enum class Hints : quint32 {
+ Calculated = 1,
+ IsGamma = 2,
+ IsLinear = 4,
+ IsSRgb = 8
+ };
+ mutable quint32 m_flags;
+};
+
+inline bool operator==(const QColorTransferFunction &f1, const QColorTransferFunction &f2)
+{
+ return f1.matches(f2);
+}
+inline bool operator!=(const QColorTransferFunction &f1, const QColorTransferFunction &f2)
+{
+ return !f1.matches(f2);
+}
+
+QT_END_NAMESPACE
+
+#endif // QCOLORTRANSFERFUNCTION_P_H
diff --git a/src/gui/painting/qcolortransfertable_p.h b/src/gui/painting/qcolortransfertable_p.h
new file mode 100644
index 0000000000..c8b2f7bd92
--- /dev/null
+++ b/src/gui/painting/qcolortransfertable_p.h
@@ -0,0 +1,245 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QCOLORTRANSFERTABLE_P_H
+#define QCOLORTRANSFERTABLE_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtGui/private/qtguiglobal_p.h>
+#include "qcolortransferfunction_p.h"
+
+#include <QVector>
+#include <cmath>
+
+QT_BEGIN_NAMESPACE
+
+// Defines either an ICC TRC 'curve' or a lut8/lut16 A or B table
+class Q_GUI_EXPORT QColorTransferTable
+{
+public:
+ QColorTransferTable() noexcept
+ : m_tableSize(0)
+ { }
+ QColorTransferTable(uint32_t size, const QVector<uint8_t> &table) noexcept
+ : m_tableSize(size)
+ , m_table8(table)
+ { }
+ QColorTransferTable(uint32_t size, const QVector<uint16_t> &table) noexcept
+ : m_tableSize(size)
+ , m_table16(table)
+ { }
+
+ bool isValid() const
+ {
+ if (m_tableSize < 2)
+ return false;
+
+#if !defined(QT_NO_DEBUG)
+ // The table must describe an injective curve:
+ if (!m_table8.isEmpty()) {
+ uint8_t val = 0;
+ for (uint i = 0; i < m_tableSize; ++i) {
+ Q_ASSERT(m_table8[i] >= val);
+ val = m_table8[i];
+ }
+ }
+ if (!m_table16.isEmpty()) {
+ uint16_t val = 0;
+ for (uint i = 0; i < m_tableSize; ++i) {
+ Q_ASSERT(m_table16[i] >= val);
+ val = m_table16[i];
+ }
+ }
+#endif
+ return !m_table8.isEmpty() || !m_table16.isEmpty();
+ }
+
+ float apply(float x) const
+ {
+ x = std::min(std::max(x, 0.0f), 1.0f);
+ x *= m_tableSize - 1;
+ uint32_t lo = (int)std::floor(x);
+ uint32_t hi = std::min(lo + 1, m_tableSize);
+ float frac = x - lo;
+ if (!m_table16.isEmpty())
+ return (m_table16[lo] * (1.0f - frac) + m_table16[hi] * frac) * (1.0f/65535.0f);
+ if (!m_table8.isEmpty())
+ return (m_table8[lo] * (1.0f - frac) + m_table8[hi] * frac) * (1.0f/255.0f);
+ return x;
+ }
+
+ // Apply inverse, optimized by giving a previous result a value < x.
+ float applyInverse(float x, float resultLargerThan = 0.0f) const
+ {
+ Q_ASSERT(resultLargerThan >= 0.0f && resultLargerThan <= 1.0f);
+ if (x <= 0.0f)
+ return 0.0f;
+ if (x >= 1.0f)
+ return 1.0f;
+ if (!m_table16.isEmpty()) {
+ float v = x * 65535.0f;
+ uint i = std::floor(resultLargerThan * (m_tableSize - 1)) + 1;
+ for ( ; i < m_tableSize; ++i) {
+ if (m_table16[i] > v)
+ break;
+ }
+ if (i >= m_tableSize - 1)
+ return 1.0f;
+ float y1 = m_table16[i - 1];
+ float y2 = m_table16[i];
+ Q_ASSERT(x >= y1 && x < y2);
+ float fr = (v - y1) / (y2 - y1);
+ return (i + fr) * (1.0f / (m_tableSize - 1));
+
+ }
+ if (!m_table8.isEmpty()) {
+ float v = x * 255.0f;
+ uint i = std::floor(resultLargerThan * (m_tableSize - 1)) + 1;
+ for ( ; i < m_tableSize; ++i) {
+ if (m_table8[i] > v)
+ break;
+ }
+ if (i >= m_tableSize - 1)
+ return 1.0f;
+ float y1 = m_table8[i - 1];
+ float y2 = m_table8[i];
+ Q_ASSERT(x >= y1 && x < y2);
+ float fr = (v - y1) / (y2 - y1);
+ return (i + fr) * (1.0f / (m_tableSize - 1));
+ }
+ return x;
+ }
+
+ bool asColorTransferFunction(QColorTransferFunction *transferFn)
+ {
+ Q_ASSERT(isValid());
+ Q_ASSERT(transferFn);
+ if (!m_table8.isEmpty() && (m_table8[0] != 0 || m_table8[m_tableSize - 1] != 255))
+ return false;
+ if (!m_table16.isEmpty() && (m_table16[0] != 0 || m_table16[m_tableSize - 1] != 65535))
+ return false;
+ if (m_tableSize == 2) {
+ *transferFn = QColorTransferFunction(); // Linear
+ return true;
+ }
+ // The following heuristics are based on those from Skia:
+ if (m_tableSize == 26 && !m_table16.isEmpty()) {
+ // code.facebook.com/posts/411525055626587/under-the-hood-improving-facebook-photos
+ if (m_table16[6] != 3062)
+ return false;
+ if (m_table16[12] != 12824)
+ return false;
+ if (m_table16[18] != 31237)
+ return false;
+ *transferFn = QColorTransferFunction::fromSRgb();
+ return true;
+ }
+ if (m_tableSize == 1024 && !m_table16.isEmpty()) {
+ // HP and Canon sRGB gamma tables:
+ if (m_table16[257] != 3366)
+ return false;
+ if (m_table16[513] != 14116)
+ return false;
+ if (m_table16[768] != 34318)
+ return false;
+ *transferFn = QColorTransferFunction::fromSRgb();
+ return true;
+ }
+ if (m_tableSize == 4096 && !m_table16.isEmpty()) {
+ // Nikon, Epson, and lcms2 sRGB gamma tables:
+ if (m_table16[515] != 960)
+ return false;
+ if (m_table16[1025] != 3342)
+ return false;
+ if (m_table16[2051] != 14079)
+ return false;
+ *transferFn = QColorTransferFunction::fromSRgb();
+ return true;
+ }
+ return false;
+ }
+ friend inline bool operator!=(const QColorTransferTable &t1, const QColorTransferTable &t2);
+ friend inline bool operator==(const QColorTransferTable &t1, const QColorTransferTable &t2);
+
+ uint32_t m_tableSize;
+ QVector<uint8_t> m_table8;
+ QVector<uint16_t> m_table16;
+};
+
+inline bool operator!=(const QColorTransferTable &t1, const QColorTransferTable &t2)
+{
+ if (t1.m_tableSize != t2.m_tableSize)
+ return true;
+ if (t1.m_table8.isEmpty() != t2.m_table8.isEmpty())
+ return true;
+ if (t1.m_table16.isEmpty() != t2.m_table16.isEmpty())
+ return true;
+ if (!t1.m_table8.isEmpty()) {
+ for (quint32 i = 0; i < t1.m_tableSize; ++i) {
+ if (t1.m_table8[i] != t2.m_table8[i])
+ return true;
+ }
+ }
+ if (!t1.m_table16.isEmpty()) {
+ for (quint32 i = 0; i < t1.m_tableSize; ++i) {
+ if (t1.m_table16[i] != t2.m_table16[i])
+ return true;
+ }
+ }
+ return false;
+}
+
+inline bool operator==(const QColorTransferTable &t1, const QColorTransferTable &t2)
+{
+ return !(t1 != t2);
+}
+
+QT_END_NAMESPACE
+
+#endif // QCOLORTRANSFERTABLE_P_H
diff --git a/src/gui/painting/qcolortransform.cpp b/src/gui/painting/qcolortransform.cpp
new file mode 100644
index 0000000000..b677c4b36b
--- /dev/null
+++ b/src/gui/painting/qcolortransform.cpp
@@ -0,0 +1,679 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qcolortransform.h"
+#include "qcolortransform_p.h"
+
+#include "qcolormatrix_p.h"
+#include "qcolorspace_p.h"
+#include "qcolortrc_p.h"
+#include "qcolortrclut_p.h"
+
+#include <QtCore/qatomic.h>
+#include <QtCore/qmath.h>
+#include <QtGui/qcolor.h>
+#include <QtGui/qtransform.h>
+#include <QtCore/private/qsimd_p.h>
+
+#include <qdebug.h>
+
+QT_BEGIN_NAMESPACE
+
+QColorTrcLut *lutFromTrc(const QColorTrc &trc)
+{
+ if (trc.m_type == QColorTrc::Type::Table)
+ return QColorTrcLut::fromTransferTable(trc.m_table);
+ if (trc.m_type == QColorTrc::Type::Function)
+ return QColorTrcLut::fromTransferFunction(trc.m_fun);
+ qWarning() << "TRC uninitialized";
+ return nullptr;
+}
+
+void QColorTransformPrivate::updateLutsIn() const
+{
+ if (colorSpaceIn->lutsGenerated.loadAcquire())
+ return;
+ for (int i = 0; i < 3; ++i) {
+ if (!colorSpaceIn->trc[i].isValid())
+ return;
+ }
+
+ if (colorSpaceIn->trc[0] == colorSpaceIn->trc[1] && colorSpaceIn->trc[0] == colorSpaceIn->trc[2]) {
+ colorSpaceIn->lut[0].reset(lutFromTrc(colorSpaceIn->trc[0]));
+ colorSpaceIn->lut[1] = colorSpaceIn->lut[0];
+ colorSpaceIn->lut[2] = colorSpaceIn->lut[0];
+ } else {
+ for (int i = 0; i < 3; ++i)
+ colorSpaceIn->lut[i].reset(lutFromTrc(colorSpaceIn->trc[i]));
+ }
+
+ colorSpaceIn->lutsGenerated.storeRelease(1);
+}
+
+void QColorTransformPrivate::updateLutsOut() const
+{
+ if (colorSpaceOut->lutsGenerated.loadAcquire())
+ return;
+ for (int i = 0; i < 3; ++i) {
+ if (!colorSpaceOut->trc[i].isValid())
+ return;
+ }
+
+ if (colorSpaceOut->trc[0] == colorSpaceOut->trc[1] && colorSpaceOut->trc[0] == colorSpaceOut->trc[2]) {
+ colorSpaceOut->lut[0].reset(lutFromTrc(colorSpaceOut->trc[0]));
+ colorSpaceOut->lut[1] = colorSpaceOut->lut[0];
+ colorSpaceOut->lut[2] = colorSpaceOut->lut[0];
+ } else {
+ for (int i = 0; i < 3; ++i)
+ colorSpaceOut->lut[i].reset(lutFromTrc(colorSpaceOut->trc[i]));
+ }
+
+ colorSpaceOut->lutsGenerated.storeRelease(1);
+}
+
+/*!
+ \class QColorTransform
+ \brief The QColorTransform class is a transformation between color spaces.
+ \since 5.14
+
+ \ingroup painting
+ \ingroup appearance
+ \inmodule QtGui
+
+ QColorTransform is an instantiation of a transformation between color spaces.
+ It can be applied on color and pixels to convert them from one color space to
+ another.
+
+ Setting up a QColorTransform takes some preprocessing, so keeping around
+ QColorTransforms that you need often is recommended, instead of generating
+ them on the fly.
+*/
+
+
+QColorTransform::~QColorTransform() noexcept
+{
+}
+
+/*!
+ Applies the color transformation on the QRgb value \a argb.
+
+ The input should be opaque or unpremultiplied.
+*/
+QRgb QColorTransform::map(const QRgb &argb) const
+{
+ if (!d_ptr)
+ return argb;
+ Q_D(const QColorTransform);
+ constexpr float f = 1.0f / 255.0f;
+ QColorVector c = { qRed(argb) * f, qGreen(argb) * f, qBlue(argb) * f };
+ c.x = d->colorSpaceIn->trc[0].apply(c.x);
+ c.y = d->colorSpaceIn->trc[1].apply(c.y);
+ c.z = d->colorSpaceIn->trc[2].apply(c.z);
+ c = d->colorMatrix.map(c);
+ c.x = std::max(0.0f, std::min(1.0f, c.x));
+ c.y = std::max(0.0f, std::min(1.0f, c.y));
+ c.z = std::max(0.0f, std::min(1.0f, c.z));
+ if (d->colorSpaceOut->lutsGenerated.loadAcquire()) {
+ c.x = d->colorSpaceOut->lut[0]->fromLinear(c.x);
+ c.y = d->colorSpaceOut->lut[1]->fromLinear(c.y);
+ c.z = d->colorSpaceOut->lut[2]->fromLinear(c.z);
+ } else {
+ c.x = d->colorSpaceOut->trc[0].applyInverse(c.x);
+ c.y = d->colorSpaceOut->trc[1].applyInverse(c.y);
+ c.z = d->colorSpaceOut->trc[2].applyInverse(c.z);
+ }
+
+ return qRgba(c.x * 255 + 0.5f, c.y * 255 + 0.5f, c.z * 255 + 0.5f, qAlpha(argb));
+}
+
+/*!
+ Applies the color transformation on the QRgba64 value \a rgba64.
+
+ The input should be opaque or unpremultiplied.
+*/
+QRgba64 QColorTransform::map(const QRgba64 &rgba64) const
+{
+ if (!d_ptr)
+ return rgba64;
+ Q_D(const QColorTransform);
+ constexpr float f = 1.0f / 65535.0f;
+ QColorVector c = { rgba64.red() * f, rgba64.green() * f, rgba64.blue() * f };
+ c.x = d->colorSpaceIn->trc[0].apply(c.x);
+ c.y = d->colorSpaceIn->trc[1].apply(c.y);
+ c.z = d->colorSpaceIn->trc[2].apply(c.z);
+ c = d->colorMatrix.map(c);
+ c.x = std::max(0.0f, std::min(1.0f, c.x));
+ c.y = std::max(0.0f, std::min(1.0f, c.y));
+ c.z = std::max(0.0f, std::min(1.0f, c.z));
+ if (d->colorSpaceOut->lutsGenerated.loadAcquire()) {
+ c.x = d->colorSpaceOut->lut[0]->fromLinear(c.x);
+ c.y = d->colorSpaceOut->lut[1]->fromLinear(c.y);
+ c.z = d->colorSpaceOut->lut[2]->fromLinear(c.z);
+ } else {
+ c.x = d->colorSpaceOut->trc[0].applyInverse(c.x);
+ c.y = d->colorSpaceOut->trc[1].applyInverse(c.y);
+ c.z = d->colorSpaceOut->trc[2].applyInverse(c.z);
+ }
+
+ return QRgba64::fromRgba64(c.x * 65535, c.y * 65535, c.z * 65535, rgba64.alpha());
+}
+
+/*!
+ Applies the color transformation on the QColor value \a color.
+
+*/
+QColor QColorTransform::map(const QColor &color) const
+{
+ if (!d_ptr)
+ return color;
+ Q_D(const QColorTransform);
+ QColorVector c = { (float)color.redF(), (float)color.greenF(), (float)color.blueF() };
+ c.x = d->colorSpaceIn->trc[0].apply(c.x);
+ c.y = d->colorSpaceIn->trc[1].apply(c.y);
+ c.z = d->colorSpaceIn->trc[2].apply(c.z);
+ c = d->colorMatrix.map(c);
+ if (d_ptr->colorSpaceOut->lutsGenerated.loadAcquire()) {
+ c.x = d->colorSpaceOut->lut[0]->fromLinear(c.x);
+ c.y = d->colorSpaceOut->lut[1]->fromLinear(c.y);
+ c.z = d->colorSpaceOut->lut[2]->fromLinear(c.z);
+ } else {
+ c.x = d->colorSpaceOut->trc[0].applyInverse(c.x);
+ c.y = d->colorSpaceOut->trc[1].applyInverse(c.y);
+ c.z = d->colorSpaceOut->trc[2].applyInverse(c.z);
+ }
+ QColor out;
+ out.setRgbF(c.x, c.y, c.z, color.alphaF());
+ return out;
+}
+
+// Optimized sub-routines for fast block based conversion:
+
+static void applyMatrix(QColorVector *buffer, const qsizetype len, const QColorMatrix &colorMatrix)
+{
+#if defined(__SSE2__)
+ const __m128 minV = _mm_set1_ps(0.0f);
+ const __m128 maxV = _mm_set1_ps(1.0f);
+ const __m128 xMat = _mm_loadu_ps(&colorMatrix.r.x);
+ const __m128 yMat = _mm_loadu_ps(&colorMatrix.g.x);
+ const __m128 zMat = _mm_loadu_ps(&colorMatrix.b.x);
+ for (qsizetype j = 0; j < len; ++j) {
+ __m128 c = _mm_loadu_ps(&buffer[j].x);
+ __m128 cx = _mm_shuffle_ps(c, c, _MM_SHUFFLE(0, 0, 0, 0));
+ __m128 cy = _mm_shuffle_ps(c, c, _MM_SHUFFLE(1, 1, 1, 1));
+ __m128 cz = _mm_shuffle_ps(c, c, _MM_SHUFFLE(2, 2, 2, 2));
+ cx = _mm_mul_ps(cx, xMat);
+ cy = _mm_mul_ps(cy, yMat);
+ cz = _mm_mul_ps(cz, zMat);
+ cx = _mm_add_ps(cx, cy);
+ cx = _mm_add_ps(cx, cz);
+ // Clamp:
+ cx = _mm_min_ps(cx, maxV);
+ cx = _mm_max_ps(cx, minV);
+ _mm_storeu_ps(&buffer[j].x, cx);
+ }
+#else
+ for (int j = 0; j < len; ++j) {
+ const QColorVector cv = colorMatrix.map(buffer[j]);
+ buffer[j].x = std::max(0.0f, std::min(1.0f, cv.x));
+ buffer[j].y = std::max(0.0f, std::min(1.0f, cv.y));
+ buffer[j].z = std::max(0.0f, std::min(1.0f, cv.z));
+ }
+#endif
+}
+
+template<typename T>
+static void loadPremultiplied(QColorVector *buffer, const T *src, const qsizetype len, const QColorTransformPrivate *d_ptr);
+template<typename T>
+static void loadUnpremultiplied(QColorVector *buffer, const T *src, const qsizetype len, const QColorTransformPrivate *d_ptr);
+
+#if defined(__SSE2__)
+// Load to [0-alpha] in 4x32 SIMD
+template<typename T>
+static inline void loadP(const T &p, __m128i &v);
+
+template<>
+inline void loadP<QRgb>(const QRgb &p, __m128i &v)
+{
+ v = _mm_cvtsi32_si128(p);
+#if defined(__SSE4_1__)
+ v = _mm_cvtepu8_epi32(v);
+#else
+ v = _mm_unpacklo_epi8(v, _mm_setzero_si128());
+ v = _mm_unpacklo_epi16(v, _mm_setzero_si128());
+#endif
+}
+
+template<>
+inline void loadP<QRgba64>(const QRgba64 &p, __m128i &v)
+{
+ v = _mm_loadl_epi64((const __m128i *)&p);
+#if defined(__SSE4_1__)
+ v = _mm_cvtepu16_epi32(v);
+#else
+ v = _mm_unpacklo_epi16(v, _mm_setzero_si128());
+#endif
+ // Shuffle to ARGB as the template below expects it
+ v = _mm_shuffle_epi32(v, _MM_SHUFFLE(3, 0, 1, 2));
+}
+
+template<typename T>
+static void loadPremultiplied(QColorVector *buffer, const T *src, const qsizetype len, const QColorTransformPrivate *d_ptr)
+{
+ const __m128 v4080 = _mm_set1_ps(4080.f);
+ const __m128 iFF00 = _mm_set1_ps(1.0f / (255 * 256));
+ for (qsizetype i = 0; i < len; ++i) {
+ __m128i v;
+ loadP<T>(src[i], v);
+ __m128 vf = _mm_cvtepi32_ps(v);
+ // Approximate 1/a:
+ __m128 va = _mm_shuffle_ps(vf, vf, _MM_SHUFFLE(3, 3, 3, 3));
+ __m128 via = _mm_rcp_ps(va);
+ via = _mm_sub_ps(_mm_add_ps(via, via), _mm_mul_ps(via, _mm_mul_ps(via, va)));
+ // v * (1/a)
+ vf = _mm_mul_ps(vf, via);
+
+ // Handle zero alpha
+ __m128 vAlphaMask = _mm_cmpeq_ps(va, _mm_set1_ps(0.0f));
+ vf = _mm_andnot_ps(vAlphaMask, vf);
+
+ // LUT
+ v = _mm_cvtps_epi32(_mm_mul_ps(vf, v4080));
+ const int ridx = _mm_extract_epi16(v, 4);
+ const int gidx = _mm_extract_epi16(v, 2);
+ const int bidx = _mm_extract_epi16(v, 0);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceIn->lut[0]->m_toLinear[ridx], 0);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceIn->lut[1]->m_toLinear[gidx], 2);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceIn->lut[2]->m_toLinear[bidx], 4);
+ vf = _mm_mul_ps(_mm_cvtepi32_ps(v), iFF00);
+
+ _mm_storeu_ps(&buffer[i].x, vf);
+ }
+}
+
+// Load to [0-4080] in 4x32 SIMD
+template<typename T>
+static inline void loadPU(const T &p, __m128i &v);
+
+template<>
+inline void loadPU<QRgb>(const QRgb &p, __m128i &v)
+{
+ v = _mm_cvtsi32_si128(p);
+#if defined(__SSE4_1__)
+ v = _mm_cvtepu8_epi32(v);
+#else
+ v = _mm_unpacklo_epi8(v, _mm_setzero_si128());
+ v = _mm_unpacklo_epi16(v, _mm_setzero_si128());
+#endif
+ v = _mm_slli_epi32(v, 4);
+}
+
+template<>
+inline void loadPU<QRgba64>(const QRgba64 &p, __m128i &v)
+{
+ v = _mm_loadl_epi64((const __m128i *)&p);
+ v = _mm_sub_epi16(v, _mm_srli_epi16(v, 8));
+#if defined(__SSE4_1__)
+ v = _mm_cvtepu16_epi32(v);
+#else
+ v = _mm_unpacklo_epi16(v, _mm_setzero_si128());
+#endif
+ v = _mm_srli_epi32(v, 4);
+ // Shuffle to ARGB as the template below expects it
+ v = _mm_shuffle_epi32(v, _MM_SHUFFLE(3, 0, 1, 2));
+}
+
+template<typename T>
+void loadUnpremultiplied(QColorVector *buffer, const T *src, const qsizetype len, const QColorTransformPrivate *d_ptr)
+{
+ const __m128 iFF00 = _mm_set1_ps(1.0f / (255 * 256));
+ for (qsizetype i = 0; i < len; ++i) {
+ __m128i v;
+ loadPU<T>(src[i], v);
+ const int ridx = _mm_extract_epi16(v, 4);
+ const int gidx = _mm_extract_epi16(v, 2);
+ const int bidx = _mm_extract_epi16(v, 0);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceIn->lut[0]->m_toLinear[ridx], 0);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceIn->lut[1]->m_toLinear[gidx], 2);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceIn->lut[2]->m_toLinear[bidx], 4);
+ __m128 vf = _mm_mul_ps(_mm_cvtepi32_ps(v), iFF00);
+ _mm_storeu_ps(&buffer[i].x, vf);
+ }
+}
+
+#else
+template<>
+void loadPremultiplied<QRgb>(QColorVector *buffer, const QRgb *src, const qsizetype len, const QColorTransformPrivate *d_ptr)
+{
+ for (qsizetype i = 0; i < len; ++i) {
+ const uint p = src[i];
+ const int a = qAlpha(p);
+ if (a) {
+ const float ia = 4080.0f / a;
+ const int ridx = int(qRed(p) * ia + 0.5f);
+ const int gidx = int(qGreen(p) * ia + 0.5f);
+ const int bidx = int(qBlue(p) * ia + 0.5f);
+ buffer[i].x = d_ptr->colorSpaceIn->lut[0]->m_toLinear[ridx] * (1.0f / (255 * 256));
+ buffer[i].y = d_ptr->colorSpaceIn->lut[1]->m_toLinear[gidx] * (1.0f / (255 * 256));
+ buffer[i].z = d_ptr->colorSpaceIn->lut[2]->m_toLinear[bidx] * (1.0f / (255 * 256));
+ } else {
+ buffer[i].x = buffer[i].y = buffer[i].z = 0.0f;
+ }
+ }
+}
+
+template<>
+void loadPremultiplied<QRgba64>(QColorVector *buffer, const QRgba64 *src, const qsizetype len, const QColorTransformPrivate *d_ptr)
+{
+ for (qsizetype i = 0; i < len; ++i) {
+ const QRgba64 &p = src[i];
+ const int a = p.alpha();
+ if (a) {
+ const float ia = 4080.0f / a;
+ const int ridx = int(p.red() * ia + 0.5f);
+ const int gidx = int(p.green() * ia + 0.5f);
+ const int bidx = int(p.blue() * ia + 0.5f);
+ buffer[i].x = d_ptr->colorSpaceIn->lut[0]->m_toLinear[ridx] * (1.0f / (255 * 256));
+ buffer[i].y = d_ptr->colorSpaceIn->lut[1]->m_toLinear[gidx] * (1.0f / (255 * 256));
+ buffer[i].z = d_ptr->colorSpaceIn->lut[2]->m_toLinear[bidx] * (1.0f / (255 * 256));
+ } else {
+ buffer[i].x = buffer[i].y = buffer[i].z = 0.0f;
+ }
+ }
+}
+
+template<>
+void loadUnpremultiplied<QRgb>(QColorVector *buffer, const QRgb *src, const qsizetype len, const QColorTransformPrivate *d_ptr)
+{
+ for (qsizetype i = 0; i < len; ++i) {
+ const uint p = src[i];
+ buffer[i].x = d_ptr->colorSpaceIn->lut[0]->u8ToLinearF32(qRed(p));
+ buffer[i].y = d_ptr->colorSpaceIn->lut[1]->u8ToLinearF32(qGreen(p));
+ buffer[i].z = d_ptr->colorSpaceIn->lut[2]->u8ToLinearF32(qBlue(p));
+ }
+}
+
+template<>
+void loadUnpremultiplied<QRgba64>(QColorVector *buffer, const QRgba64 *src, const qsizetype len, const QColorTransformPrivate *d_ptr)
+{
+ for (qsizetype i = 0; i < len; ++i) {
+ const QRgba64 &p = src[i];
+ buffer[i].x = d_ptr->colorSpaceIn->lut[0]->u16ToLinearF32(p.red());
+ buffer[i].y = d_ptr->colorSpaceIn->lut[1]->u16ToLinearF32(p.green());
+ buffer[i].z = d_ptr->colorSpaceIn->lut[2]->u16ToLinearF32(p.blue());
+ }
+}
+#endif
+
+static void storePremultiplied(QRgb *dst, const QRgb *src, const QColorVector *buffer, const qsizetype len,
+ const QColorTransformPrivate *d_ptr)
+{
+#if defined(__SSE2__)
+ const __m128 v4080 = _mm_set1_ps(4080.f);
+ const __m128 iFF00 = _mm_set1_ps(1.0f / (255 * 256));
+ for (qsizetype i = 0; i < len; ++i) {
+ const int a = qAlpha(src[i]);
+ __m128 vf = _mm_loadu_ps(&buffer[i].x);
+ __m128i v = _mm_cvtps_epi32(_mm_mul_ps(vf, v4080));
+ __m128 va = _mm_set1_ps(a);
+ va = _mm_mul_ps(va, iFF00);
+ const int ridx = _mm_extract_epi16(v, 0);
+ const int gidx = _mm_extract_epi16(v, 2);
+ const int bidx = _mm_extract_epi16(v, 4);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[0]->m_fromLinear[ridx], 4);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[1]->m_fromLinear[gidx], 2);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[2]->m_fromLinear[bidx], 0);
+ vf = _mm_cvtepi32_ps(v);
+ vf = _mm_mul_ps(vf, va);
+ v = _mm_cvtps_epi32(vf);
+ v = _mm_packs_epi32(v, v);
+ v = _mm_insert_epi16(v, a, 3);
+ v = _mm_packus_epi16(v, v);
+ dst[i] = _mm_cvtsi128_si32(v);
+ }
+#else
+ for (qsizetype i = 0; i < len; ++i) {
+ const int a = qAlpha(src[i]);
+ const float fa = a / (255.0f * 256.0f);
+ const float r = d_ptr->colorSpaceOut->lut[0]->m_fromLinear[int(buffer[i].x * 4080.0f + 0.5f)];
+ const float g = d_ptr->colorSpaceOut->lut[1]->m_fromLinear[int(buffer[i].y * 4080.0f + 0.5f)];
+ const float b = d_ptr->colorSpaceOut->lut[2]->m_fromLinear[int(buffer[i].z * 4080.0f + 0.5f)];
+ dst[i] = qRgba(r * fa + 0.5f, g * fa + 0.5f, b * fa + 0.5f, a);
+ }
+#endif
+}
+
+static void storeUnpremultiplied(QRgb *dst, const QRgb *src, const QColorVector *buffer, const qsizetype len,
+ const QColorTransformPrivate *d_ptr)
+{
+#if defined(__SSE2__)
+ const __m128 v4080 = _mm_set1_ps(4080.f);
+ for (qsizetype i = 0; i < len; ++i) {
+ const int a = qAlpha(src[i]);
+ __m128 vf = _mm_loadu_ps(&buffer[i].x);
+ __m128i v = _mm_cvtps_epi32(_mm_mul_ps(vf, v4080));
+ const int ridx = _mm_extract_epi16(v, 0);
+ const int gidx = _mm_extract_epi16(v, 2);
+ const int bidx = _mm_extract_epi16(v, 4);
+ v = _mm_setzero_si128();
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[0]->m_fromLinear[ridx], 2);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[1]->m_fromLinear[gidx], 1);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[2]->m_fromLinear[bidx], 0);
+ v = _mm_add_epi16(v, _mm_set1_epi16(0x80));
+ v = _mm_srli_epi16(v, 8);
+ v = _mm_insert_epi16(v, a, 3);
+ v = _mm_packus_epi16(v, v);
+ dst[i] = _mm_cvtsi128_si32(v);
+ }
+#else
+ for (qsizetype i = 0; i < len; ++i) {
+ const int r = d_ptr->colorSpaceOut->lut[0]->u8FromLinearF32(buffer[i].x);
+ const int g = d_ptr->colorSpaceOut->lut[1]->u8FromLinearF32(buffer[i].y);
+ const int b = d_ptr->colorSpaceOut->lut[2]->u8FromLinearF32(buffer[i].z);
+ dst[i] = (src[i] & 0xff000000) | (r << 16) | (g << 8) | (b << 0);
+ }
+#endif
+}
+
+static void storeOpaque(QRgb *dst, const QRgb *src, const QColorVector *buffer, const qsizetype len,
+ const QColorTransformPrivate *d_ptr)
+{
+ Q_UNUSED(src);
+#if defined(__SSE2__)
+ const __m128 v4080 = _mm_set1_ps(4080.f);
+ for (qsizetype i = 0; i < len; ++i) {
+ __m128 vf = _mm_loadu_ps(&buffer[i].x);
+ __m128i v = _mm_cvtps_epi32(_mm_mul_ps(vf, v4080));
+ const int ridx = _mm_extract_epi16(v, 0);
+ const int gidx = _mm_extract_epi16(v, 2);
+ const int bidx = _mm_extract_epi16(v, 4);
+ v = _mm_setzero_si128();
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[0]->m_fromLinear[ridx], 2);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[1]->m_fromLinear[gidx], 1);
+ v = _mm_insert_epi16(v, d_ptr->colorSpaceOut->lut[2]->m_fromLinear[bidx], 0);
+ v = _mm_add_epi16(v, _mm_set1_epi16(0x80));
+ v = _mm_srli_epi16(v, 8);
+ v = _mm_insert_epi16(v, 255, 3);
+ v = _mm_packus_epi16(v, v);
+ dst[i] = _mm_cvtsi128_si32(v);
+ }
+#else
+ for (qsizetype i = 0; i < len; ++i) {
+ const int r = d_ptr->colorSpaceOut->lut[0]->u8FromLinearF32(buffer[i].x);
+ const int g = d_ptr->colorSpaceOut->lut[1]->u8FromLinearF32(buffer[i].y);
+ const int b = d_ptr->colorSpaceOut->lut[2]->u8FromLinearF32(buffer[i].z);
+ dst[i] = 0xff000000 | (r << 16) | (g << 8) | (b << 0);
+ }
+#endif
+}
+
+static void storePremultiplied(QRgba64 *dst, const QRgba64 *src, const QColorVector *buffer, const qsizetype len,
+ const QColorTransformPrivate *d_ptr)
+{
+ for (qsizetype i = 0; i < len; ++i) {
+ const int a = src[i].alpha();
+ const float fa = a / (255.0f * 256.0f);
+ const float r = d_ptr->colorSpaceOut->lut[0]->m_fromLinear[int(buffer[i].x * 4080.0f + 0.5f)];
+ const float g = d_ptr->colorSpaceOut->lut[1]->m_fromLinear[int(buffer[i].y * 4080.0f + 0.5f)];
+ const float b = d_ptr->colorSpaceOut->lut[2]->m_fromLinear[int(buffer[i].z * 4080.0f + 0.5f)];
+ dst[i] = qRgba64(r * fa + 0.5f, g * fa + 0.5f, b * fa + 0.5f, a);
+ }
+}
+
+static void storeUnpremultiplied(QRgba64 *dst, const QRgba64 *src, const QColorVector *buffer, const qsizetype len,
+ const QColorTransformPrivate *d_ptr)
+{
+ for (qsizetype i = 0; i < len; ++i) {
+ const int r = d_ptr->colorSpaceOut->lut[0]->u16FromLinearF32(buffer[i].x);
+ const int g = d_ptr->colorSpaceOut->lut[1]->u16FromLinearF32(buffer[i].y);
+ const int b = d_ptr->colorSpaceOut->lut[2]->u16FromLinearF32(buffer[i].z);
+ dst[i] = qRgba64(r, g, b, src[i].alpha());
+ }
+}
+
+static void storeOpaque(QRgba64 *dst, const QRgba64 *src, const QColorVector *buffer, const qsizetype len,
+ const QColorTransformPrivate *d_ptr)
+{
+ Q_UNUSED(src);
+ for (qsizetype i = 0; i < len; ++i) {
+ const int r = d_ptr->colorSpaceOut->lut[0]->u16FromLinearF32(buffer[i].x);
+ const int g = d_ptr->colorSpaceOut->lut[1]->u16FromLinearF32(buffer[i].y);
+ const int b = d_ptr->colorSpaceOut->lut[2]->u16FromLinearF32(buffer[i].z);
+ dst[i] = qRgba64(r, g, b, 0xFFFF);
+ }
+}
+
+static constexpr qsizetype WorkBlockSize = 256;
+
+template<typename T>
+void QColorTransformPrivate::apply(T *dst, const T *src, qsizetype count, TransformFlags flags) const
+{
+ if (!colorMatrix.isValid())
+ return;
+
+ updateLutsIn();
+ updateLutsOut();
+
+ bool doApplyMatrix = (colorMatrix != QColorMatrix::identity());
+
+ QColorVector buffer[WorkBlockSize];
+ qsizetype i = 0;
+ while (i < count) {
+ const qsizetype len = qMin(count - i, WorkBlockSize);
+ if (flags & InputPremultiplied)
+ loadPremultiplied(buffer, src + i, len, this);
+ else
+ loadUnpremultiplied(buffer, src + i, len, this);
+
+ if (doApplyMatrix)
+ applyMatrix(buffer, len, colorMatrix);
+
+ if (flags & InputOpaque)
+ storeOpaque(dst + i, src + i, buffer, len, this);
+ else if (flags & OutputPremultiplied)
+ storePremultiplied(dst + i, src + i, buffer, len, this);
+ else
+ storeUnpremultiplied(dst + i, src + i, buffer, len, this);
+
+ i += len;
+ }
+}
+
+/*!
+ \internal
+ \enum QColorTransformPrivate::TransformFlag
+
+ Defines how the transform is to be applied.
+
+ \value Unpremultiplied The input and output should both be unpremultiplied.
+ \value InputOpaque The input is guaranteed to be opaque.
+ \value InputPremultiplied The input is premultiplied.
+ \value OutputPremultiplied The output should be premultiplied.
+ \value Premultiplied Both input and output should both be premultiplied.
+*/
+
+/*!
+ \internal
+ Prepares a color transformation for fast application. You do not need to
+ call this explicitly as it will be called implicitly on the first transforms, but
+ if you want predictable performance on the first transforms, you can perform it
+ in advance.
+
+ \sa QColorTransform::map(), apply()
+*/
+void QColorTransformPrivate::prepare()
+{
+ updateLutsIn();
+ updateLutsOut();
+}
+
+/*!
+ \internal
+ Applies the color transformation on \a count QRgb pixels starting from
+ \a src and stores the result in \a dst.
+
+ Thread-safe if prepare() has been called first.
+
+ Assumes unpremultiplied data by default. Set \a flags to change defaults.
+
+ \sa prepare()
+*/
+void QColorTransformPrivate::apply(QRgb *dst, const QRgb *src, qsizetype count, TransformFlags flags) const
+{
+ apply<QRgb>(dst, src, count, flags);
+}
+
+/*!
+ \internal
+ Applies the color transformation on \a count QRgba64 pixels starting from
+ \a src and stores the result in \a dst.
+
+ Thread-safe if prepare() has been called first.
+
+ Assumes unpremultiplied data by default. Set \a flags to change defaults.
+
+ \sa prepare()
+*/
+void QColorTransformPrivate::apply(QRgba64 *dst, const QRgba64 *src, qsizetype count, TransformFlags flags) const
+{
+ apply<QRgba64>(dst, src, count, flags);
+}
+
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/mirclient/qmirclientscreenobserver.h b/src/gui/painting/qcolortransform.h
index ad927319c1..9274387b97 100644
--- a/src/plugins/platforms/mirclient/qmirclientscreenobserver.h
+++ b/src/gui/painting/qcolortransform.h
@@ -1,9 +1,9 @@
/****************************************************************************
**
-** Copyright (C) 2016 Canonical, Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,42 +37,57 @@
**
****************************************************************************/
+#ifndef QCOLORTRANSFORM_H
+#define QCOLORTRANSFORM_H
-#ifndef QMIRCLIENTSCREENOBSERVER_H
-#define QMIRCLIENTSCREENOBSERVER_H
+#include <QtGui/qtguiglobal.h>
+#include <QtCore/qsharedpointer.h>
+#include <QtGui/qrgb.h>
-#include <QObject>
+QT_BEGIN_NAMESPACE
-#include <mir_toolkit/mir_connection.h>
+class QColor;
+class QRgba64;
+class QColorSpacePrivate;
+class QColorTransformPrivate;
-class QMirClientScreen;
-
-class QMirClientScreenObserver : public QObject
+class Q_GUI_EXPORT QColorTransform
{
- Q_OBJECT
-
public:
- QMirClientScreenObserver(MirConnection *connection);
-
- QList<QMirClientScreen*> screens() const { return mScreenList; }
- QMirClientScreen *findScreenWithId(int id);
+ QColorTransform() noexcept : d_ptr(nullptr) { }
+ ~QColorTransform() noexcept;
+ QColorTransform(const QColorTransform &colorTransform) noexcept
+ : d_ptr(colorTransform.d_ptr)
+ { }
+ QColorTransform(QColorTransform &&colorTransform) noexcept
+ : d_ptr(std::move(colorTransform.d_ptr))
+ { }
+ QColorTransform &operator=(const QColorTransform &other) noexcept
+ {
+ d_ptr = other.d_ptr;
+ return *this;
+ }
+ QColorTransform &operator=(QColorTransform &&other) noexcept
+ {
+ d_ptr = std::move(other.d_ptr);
+ return *this;
+ }
- void handleScreenPropertiesChange(QMirClientScreen *screen, int dpi,
- MirFormFactor formFactor, float scale);
+ bool isNull() const { return d_ptr.isNull(); }
-Q_SIGNALS:
- void screenAdded(QMirClientScreen *screen);
- void screenRemoved(QMirClientScreen *screen);
-
-private Q_SLOTS:
- void update();
+ QRgb map(const QRgb &argb) const;
+ QRgba64 map(const QRgba64 &rgba64) const;
+ QColor map(const QColor &color) const;
private:
- QMirClientScreen *findScreenWithId(const QList<QMirClientScreen *> &list, int id);
- void removeScreen(QMirClientScreen *screen);
+ friend class QColorSpace;
+ friend class QColorSpacePrivate;
+ friend class QImage;
- MirConnection *mMirConnection;
- QList<QMirClientScreen*> mScreenList;
+ Q_DECLARE_PRIVATE(QColorTransform)
+ QSharedPointer<QColorTransformPrivate> d_ptr;
};
-#endif // QMIRCLIENTSCREENOBSERVER_H
+QT_END_NAMESPACE
+
+#endif // QCOLORTRANSFORM_H
diff --git a/src/plugins/platforms/mirclient/qmirclientbackingstore.h b/src/gui/painting/qcolortransform_p.h
index 7644c77df2..74a1e7fe0a 100644
--- a/src/plugins/platforms/mirclient/qmirclientbackingstore.h
+++ b/src/gui/painting/qcolortransform_p.h
@@ -1,9 +1,9 @@
/****************************************************************************
**
-** Copyright (C) 2016 Canonical, Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,38 +37,53 @@
**
****************************************************************************/
+#ifndef QCOLORTRANSFORM_P_H
+#define QCOLORTRANSFORM_P_H
-#ifndef QMIRCLIENTBACKINGSTORE_H
-#define QMIRCLIENTBACKINGSTORE_H
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
-#include <qpa/qplatformbackingstore.h>
+#include "qcolormatrix_p.h"
+#include "qcolorspace_p.h"
-class QOpenGLContext;
-class QOpenGLTexture;
-class QOpenGLTextureBlitter;
+QT_BEGIN_NAMESPACE
-class QMirClientBackingStore : public QPlatformBackingStore
+class QColorTransformPrivate
{
public:
- QMirClientBackingStore(QWindow* window);
- virtual ~QMirClientBackingStore();
+ QColorMatrix colorMatrix;
+ QExplicitlySharedDataPointer<const QColorSpacePrivate> colorSpaceIn;
+ QExplicitlySharedDataPointer<const QColorSpacePrivate> colorSpaceOut;
- // QPlatformBackingStore methods.
- void beginPaint(const QRegion&) override;
- void flush(QWindow* window, const QRegion& region, const QPoint& offset) override;
- void resize(const QSize& size, const QRegion& staticContents) override;
- QPaintDevice* paintDevice() override;
- QImage toImage() const override;
+ void updateLutsIn() const;
+ void updateLutsOut() const;
+ bool simpleGammaCorrection() const;
-protected:
- void updateTexture();
+ void prepare();
+ enum TransformFlag {
+ Unpremultiplied = 0,
+ InputOpaque = 1,
+ InputPremultiplied = 2,
+ OutputPremultiplied = 4,
+ Premultiplied = (InputPremultiplied | OutputPremultiplied)
+ };
+ Q_DECLARE_FLAGS(TransformFlags, TransformFlag)
-private:
- QScopedPointer<QOpenGLContext> mContext;
- QScopedPointer<QOpenGLTexture> mTexture;
- QScopedPointer<QOpenGLTextureBlitter> mBlitter;
- QImage mImage;
- QRegion mDirty;
+ void apply(QRgb *dst, const QRgb *src, qsizetype count, TransformFlags flags = Unpremultiplied) const;
+ void apply(QRgba64 *dst, const QRgba64 *src, qsizetype count, TransformFlags flags = Unpremultiplied) const;
+
+ template<typename T>
+ void apply(T *dst, const T *src, qsizetype count, TransformFlags flags) const;
};
-#endif // QMIRCLIENTBACKINGSTORE_H
+QT_END_NAMESPACE
+
+#endif // QCOLORTRANSFORM_P_H
diff --git a/src/gui/painting/qcolortrc_p.h b/src/gui/painting/qcolortrc_p.h
new file mode 100644
index 0000000000..3a649f3756
--- /dev/null
+++ b/src/gui/painting/qcolortrc_p.h
@@ -0,0 +1,129 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QCOLORTRC_P_H
+#define QCOLORTRC_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtGui/private/qtguiglobal_p.h>
+#include "qcolortransferfunction_p.h"
+#include "qcolortransfertable_p.h"
+
+QT_BEGIN_NAMESPACE
+
+
+// Defines an ICC TRC (Tone Reproduction Curve)
+class Q_GUI_EXPORT QColorTrc
+{
+public:
+ QColorTrc() noexcept : m_type(Type::Uninitialized)
+ { }
+ QColorTrc(const QColorTransferFunction &fun) : m_type(Type::Function), m_fun(fun)
+ { }
+ QColorTrc(const QColorTransferTable &table) : m_type(Type::Table), m_table(table)
+ { }
+
+ enum class Type {
+ Uninitialized,
+ Function,
+ Table
+ };
+
+ bool isLinear() const
+ {
+ return m_type == Type::Uninitialized || (m_type == Type::Function && m_fun.isLinear());
+ }
+ bool isValid() const
+ {
+ return m_type != Type::Uninitialized;
+ }
+ float apply(float x) const
+ {
+ if (m_type == Type::Table)
+ return m_table.apply(x);
+ if (m_type == Type::Function)
+ return m_fun.apply(x);
+ return x;
+ }
+
+ float applyInverse(float x) const
+ {
+ if (m_type == Type::Table)
+ return m_table.applyInverse(x);
+ if (m_type == Type::Function)
+ return m_fun.inverted().apply(x);
+ return x;
+ }
+
+ friend inline bool operator!=(const QColorTrc &o1, const QColorTrc &o2);
+ friend inline bool operator==(const QColorTrc &o1, const QColorTrc &o2);
+
+ Type m_type;
+ QColorTransferFunction m_fun;
+ QColorTransferTable m_table;
+};
+
+inline bool operator!=(const QColorTrc &o1, const QColorTrc &o2)
+{
+ if (o1.m_type != o2.m_type)
+ return true;
+ if (o1.m_type == QColorTrc::Type::Function)
+ return o1.m_fun != o2.m_fun;
+ if (o1.m_type == QColorTrc::Type::Table)
+ return o1.m_table != o2.m_table;
+ return false;
+}
+inline bool operator==(const QColorTrc &o1, const QColorTrc &o2)
+{
+ return !(o1 != o2);
+}
+
+QT_END_NAMESPACE
+
+#endif // QCOLORTRC
diff --git a/src/gui/painting/qcolorprofile.cpp b/src/gui/painting/qcolortrclut.cpp
index 3b7b0a248b..268d7252b4 100644
--- a/src/gui/painting/qcolorprofile.cpp
+++ b/src/gui/painting/qcolortrclut.cpp
@@ -37,14 +37,16 @@
**
****************************************************************************/
-#include "qcolorprofile_p.h"
+#include "qcolortrclut_p.h"
+#include "qcolortransferfunction_p.h"
+#include "qcolortransfertable_p.h"
#include <qmath.h>
QT_BEGIN_NAMESPACE
-QColorProfile *QColorProfile::fromGamma(qreal gamma)
+QColorTrcLut *QColorTrcLut::fromGamma(qreal gamma)
{
- QColorProfile *cp = new QColorProfile;
+ QColorTrcLut *cp = new QColorTrcLut;
for (int i = 0; i <= (255 * 16); ++i) {
cp->m_toLinear[i] = ushort(qRound(qPow(i / qreal(255 * 16), gamma) * (255 * 256)));
@@ -54,31 +56,28 @@ QColorProfile *QColorProfile::fromGamma(qreal gamma)
return cp;
}
-static qreal srgbToLinear(qreal v)
+QColorTrcLut *QColorTrcLut::fromTransferFunction(const QColorTransferFunction &fun)
{
- const qreal a = 0.055;
- if (v <= qreal(0.04045))
- return v / qreal(12.92);
- else
- return qPow((v + a) / (qreal(1) + a), qreal(2.4));
-}
+ QColorTrcLut *cp = new QColorTrcLut;
+ QColorTransferFunction inv = fun.inverted();
-static qreal linearToSrgb(qreal v)
-{
- const qreal a = 0.055;
- if (v <= qreal(0.0031308))
- return v * qreal(12.92);
- else
- return (qreal(1) + a) * qPow(v, qreal(1.0 / 2.4)) - a;
+ for (int i = 0; i <= (255 * 16); ++i) {
+ cp->m_toLinear[i] = ushort(qRound(fun.apply(i / qreal(255 * 16)) * (255 * 256)));
+ cp->m_fromLinear[i] = ushort(qRound(inv.apply(i / qreal(255 * 16)) * (255 * 256)));
+ }
+
+ return cp;
}
-QColorProfile *QColorProfile::fromSRgb()
+QColorTrcLut *QColorTrcLut::fromTransferTable(const QColorTransferTable &table)
{
- QColorProfile *cp = new QColorProfile;
+ QColorTrcLut *cp = new QColorTrcLut;
+ float minInverse = 0.0f;
for (int i = 0; i <= (255 * 16); ++i) {
- cp->m_toLinear[i] = ushort(qRound(srgbToLinear(i / qreal(255 * 16)) * (255 * 256)));
- cp->m_fromLinear[i] = ushort(qRound(linearToSrgb(i / qreal(255 * 16)) * (255 * 256)));
+ cp->m_toLinear[i] = ushort(qBound(0, qRound(table.apply(i / qreal(255 * 16)) * (255 * 256)), 65280));
+ minInverse = table.applyInverse(i / qreal(255 * 16), minInverse);
+ cp->m_fromLinear[i] = ushort(qBound(0, qRound(minInverse * (255 * 256)), 65280));
}
return cp;
diff --git a/src/gui/painting/qcolorprofile_p.h b/src/gui/painting/qcolortrclut_p.h
index 425e9abace..76a6a60803 100644
--- a/src/gui/painting/qcolorprofile_p.h
+++ b/src/gui/painting/qcolortrclut_p.h
@@ -37,8 +37,8 @@
**
****************************************************************************/
-#ifndef QCOLORPROFILE_P_H
-#define QCOLORPROFILE_P_H
+#ifndef QCOLORTRCLUT_P_H
+#define QCOLORTRCLUT_P_H
//
// W A R N I N G
@@ -52,21 +52,29 @@
//
#include <QtGui/private/qtguiglobal_p.h>
+#include <QtCore/qsharedpointer.h>
#include <QtGui/qrgb.h>
#include <QtGui/qrgba64.h>
+#include <cmath>
+
#if defined(__SSE2__)
#include <emmintrin.h>
#elif defined(__ARM_NEON__) || defined(__ARM_NEON)
#include <arm_neon.h>
#endif
+
QT_BEGIN_NAMESPACE
-class Q_GUI_EXPORT QColorProfile
+class QColorTransferFunction;
+class QColorTransferTable;
+
+class Q_GUI_EXPORT QColorTrcLut : public QEnableSharedFromThis<QColorTrcLut>
{
public:
- static QColorProfile *fromGamma(qreal gamma);
- static QColorProfile *fromSRgb();
+ static QColorTrcLut *fromGamma(qreal gamma);
+ static QColorTrcLut *fromTransferFunction(const QColorTransferFunction &transfn);
+ static QColorTrcLut *fromTransferTable(const QColorTransferTable &transTable);
// The following methods all convert opaque or unpremultiplied colors:
@@ -121,6 +129,25 @@ public:
return convertWithTable(rgb64, m_toLinear);
}
+ float u8ToLinearF32(int c) const
+ {
+ ushort v = m_toLinear[c << 4];
+ return v * (1.0f / (255*256));
+ }
+
+ float u16ToLinearF32(int c) const
+ {
+ c -= (c >> 8);
+ ushort v = m_toLinear[c >> 4];
+ return v * (1.0f / (255*256));
+ }
+
+ float toLinear(float f) const
+ {
+ ushort v = m_toLinear[(int)(f * (255 * 16) + 0.5f)];
+ return v * (1.0f / (255*256));
+ }
+
QRgb fromLinear64(QRgba64 rgb64) const
{
#if defined(__SSE2__)
@@ -176,8 +203,31 @@ public:
return convertWithTable(rgb64, m_fromLinear);
}
+ int u8FromLinearF32(float f) const
+ {
+ ushort v = m_fromLinear[(int)(f * (255 * 16) + 0.5f)];
+ return (v + 0x80) >> 8;
+ }
+ int u16FromLinearF32(float f) const
+ {
+ ushort v = m_fromLinear[(int)(f * (255 * 16) + 0.5f)];
+ return v + (v >> 8);
+ }
+ float fromLinear(float f) const
+ {
+ ushort v = m_fromLinear[(int)(f * (255 * 16) + 0.5f)];
+ return v * (1.0f / (255*256));
+ }
+
+ // We translate to 0-65280 (255*256) instead to 0-65535 to make simple
+ // shifting an accurate conversion.
+ // We translate from 0-4080 (255*16) for the same speed up, and to keep
+ // the tables small enough to fit in most inner caches.
+ ushort m_toLinear[(255 * 16) + 1]; // [0-4080] -> [0-65280]
+ ushort m_fromLinear[(255 * 16) + 1]; // [0-4080] -> [0-65280]
+
private:
- QColorProfile() { }
+ QColorTrcLut() { }
Q_ALWAYS_INLINE static QRgb convertWithTable(QRgb rgb32, const ushort *table)
{
@@ -230,16 +280,8 @@ private:
return QRgba64::fromRgba64(r, g, b, rgb64.alpha());
#endif
}
-
- // We translate to 0-65280 (255*256) instead to 0-65535 to make simple
- // shifting an accurate conversion.
- // We translate from 0-4080 (255*16) for the same speed up, and to keep
- // the tables small enough to fit in most inner caches.
- ushort m_toLinear[(255 * 16) + 1]; // [0-4080] -> [0-65280]
- ushort m_fromLinear[(255 * 16) + 1]; // [0-4080] -> [0-65280]
-
};
QT_END_NAMESPACE
-#endif // QCOLORPROFILE_P_H
+#endif // QCOLORTRCLUT_P_H
diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp
index 2dd18f6dfc..1ed51d26a2 100644
--- a/src/gui/painting/qdrawhelper.cpp
+++ b/src/gui/painting/qdrawhelper.cpp
@@ -43,7 +43,7 @@
#include <qstylehints.h>
#include <qguiapplication.h>
#include <qatomic.h>
-#include <private/qcolorprofile_p.h>
+#include <private/qcolortrclut_p.h>
#include <private/qdrawhelper_p.h>
#include <private/qpaintengine_raster_p.h>
#include <private/qpainter_p.h>
@@ -5523,7 +5523,7 @@ inline static void qt_bitmapblit_quint16(QRasterBuffer *rasterBuffer,
map, mapWidth, mapHeight, mapStride);
}
-static inline void alphamapblend_generic(int coverage, QRgba64 *dest, int x, const QRgba64 &srcLinear, const QRgba64 &src, const QColorProfile *colorProfile)
+static inline void alphamapblend_generic(int coverage, QRgba64 *dest, int x, const QRgba64 &srcLinear, const QRgba64 &src, const QColorTrcLut *colorProfile)
{
if (coverage == 0) {
// nothing
@@ -5558,7 +5558,7 @@ static void qt_alphamapblit_generic(QRasterBuffer *rasterBuffer,
if (color.isTransparent())
return;
- const QColorProfile *colorProfile = nullptr;
+ const QColorTrcLut *colorProfile = nullptr;
if (useGammaCorrection)
colorProfile = QGuiApplicationPrivate::instance()->colorProfileForA8Text();
@@ -5684,7 +5684,7 @@ void qt_alphamapblit_quint16(QRasterBuffer *rasterBuffer,
}
}
-static inline void rgbBlendPixel(quint32 *dst, int coverage, QRgba64 slinear, const QColorProfile *colorProfile)
+static inline void rgbBlendPixel(quint32 *dst, int coverage, QRgba64 slinear, const QColorTrcLut *colorProfile)
{
// Do a gammacorrected RGB alphablend...
const QRgba64 dlinear = colorProfile ? colorProfile->toLinear64(*dst) : QRgba64::fromArgb32(*dst);
@@ -5694,7 +5694,7 @@ static inline void rgbBlendPixel(quint32 *dst, int coverage, QRgba64 slinear, co
*dst = colorProfile ? colorProfile->fromLinear64(blend) : toArgb32(blend);
}
-static inline void grayBlendPixel(quint32 *dst, int coverage, QRgba64 srcLinear, const QColorProfile *colorProfile)
+static inline void grayBlendPixel(quint32 *dst, int coverage, QRgba64 srcLinear, const QColorTrcLut *colorProfile)
{
// Do a gammacorrected gray alphablend...
const QRgba64 dstLinear = colorProfile ? colorProfile->toLinear64(*dst) : QRgba64::fromArgb32(*dst);
@@ -5704,7 +5704,7 @@ static inline void grayBlendPixel(quint32 *dst, int coverage, QRgba64 srcLinear,
*dst = colorProfile ? colorProfile->fromLinear64(blend) : toArgb32(blend);
}
-static inline void alphamapblend_argb32(quint32 *dst, int coverage, QRgba64 srcLinear, quint32 src, const QColorProfile *colorProfile)
+static inline void alphamapblend_argb32(quint32 *dst, int coverage, QRgba64 srcLinear, quint32 src, const QColorTrcLut *colorProfile)
{
if (coverage == 0) {
// nothing
@@ -5734,7 +5734,7 @@ static void qt_alphamapblit_argb32(QRasterBuffer *rasterBuffer,
if (color.isTransparent())
return;
- const QColorProfile *colorProfile = nullptr;
+ const QColorTrcLut *colorProfile = nullptr;
if (useGammaCorrection)
colorProfile = QGuiApplicationPrivate::instance()->colorProfileForA8Text();
@@ -5830,7 +5830,7 @@ static inline QRgb rgbBlend(QRgb d, QRgb s, uint rgbAlpha)
#endif
}
-static inline void alphargbblend_generic(uint coverage, QRgba64 *dest, int x, const QRgba64 &srcLinear, const QRgba64 &src, const QColorProfile *colorProfile)
+static inline void alphargbblend_generic(uint coverage, QRgba64 *dest, int x, const QRgba64 &srcLinear, const QRgba64 &src, const QColorTrcLut *colorProfile)
{
if (coverage == 0xff000000) {
// nothing
@@ -5852,7 +5852,7 @@ static inline void alphargbblend_generic(uint coverage, QRgba64 *dest, int x, co
}
}
-static inline void alphargbblend_argb32(quint32 *dst, uint coverage, const QRgba64 &srcLinear, quint32 src, const QColorProfile *colorProfile)
+static inline void alphargbblend_argb32(quint32 *dst, uint coverage, const QRgba64 &srcLinear, quint32 src, const QColorTrcLut *colorProfile)
{
if (coverage == 0xff000000) {
// nothing
@@ -5877,7 +5877,7 @@ static void qt_alphargbblit_generic(QRasterBuffer *rasterBuffer,
if (color.isTransparent())
return;
- const QColorProfile *colorProfile = nullptr;
+ const QColorTrcLut *colorProfile = nullptr;
if (useGammaCorrection)
colorProfile = QGuiApplicationPrivate::instance()->colorProfileForA32Text();
@@ -5954,7 +5954,7 @@ static void qt_alphargbblit_argb32(QRasterBuffer *rasterBuffer,
const quint32 c = color.toArgb32();
- const QColorProfile *colorProfile = nullptr;
+ const QColorTrcLut *colorProfile = nullptr;
if (useGammaCorrection)
colorProfile = QGuiApplicationPrivate::instance()->colorProfileForA32Text();
diff --git a/src/gui/painting/qicc.cpp b/src/gui/painting/qicc.cpp
new file mode 100644
index 0000000000..d88b005782
--- /dev/null
+++ b/src/gui/painting/qicc.cpp
@@ -0,0 +1,669 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qicc_p.h"
+
+#include <qbuffer.h>
+#include <qbytearray.h>
+#include <qdatastream.h>
+#include <qloggingcategory.h>
+#include <qendian.h>
+
+#include "qcolorspace_p.h"
+#include "qcolortrc_p.h"
+
+QT_BEGIN_NAMESPACE
+Q_LOGGING_CATEGORY(lcIcc, "qt.gui.icc")
+
+struct ICCProfileHeader
+{
+ quint32_be profileSize;
+
+ quint32_be preferredCmmType;
+
+ quint32_be profileVersion;
+ quint32_be profileClass;
+ quint32_be inputColorSpace;
+ quint32_be pcs;
+ quint32_be datetime[3];
+ quint32_be signature;
+ quint32_be platformSignature;
+ quint32_be flags;
+ quint32_be deviceManufacturer;
+ quint32_be deviceModel;
+ quint32_be deviceAttributes[2];
+
+ quint32_be renderingIntent;
+ qint32_be illuminantXyz[3];
+
+ quint32_be creatorSignature;
+ quint32_be profileId[4];
+
+ quint32_be reserved[7];
+
+// Technically after the header, but easier to include here:
+ quint32_be tagCount;
+};
+
+constexpr quint32 IccTag(uchar a, uchar b, uchar c, uchar d)
+{
+ return (a << 24) | (b << 16) | (c << 8) | d;
+}
+
+enum class ProfileClass : quint32 {
+ Input = IccTag('s', 'c', 'r', 'n'),
+ Display = IccTag('m', 'n', 't', 'r'),
+ // Not supported:
+ Output = IccTag('p', 'r', 't', 'r'),
+ ColorSpace = IccTag('s', 'p', 'a', 'c'),
+};
+
+enum class Tag : quint32 {
+ acsp = IccTag('a', 'c', 's', 'p'),
+ RGB_ = IccTag('R', 'G', 'B', ' '),
+ XYZ_ = IccTag('X', 'Y', 'Z', ' '),
+ rXYZ = IccTag('r', 'X', 'Y', 'Z'),
+ gXYZ = IccTag('g', 'X', 'Y', 'Z'),
+ bXYZ = IccTag('b', 'X', 'Y', 'Z'),
+ rTRC = IccTag('r', 'T', 'R', 'C'),
+ gTRC = IccTag('g', 'T', 'R', 'C'),
+ bTRC = IccTag('b', 'T', 'R', 'C'),
+ A2B0 = IccTag('A', '2', 'B', '0'),
+ A2B1 = IccTag('A', '2', 'B', '1'),
+ B2A0 = IccTag('B', '2', 'A', '0'),
+ B2A1 = IccTag('B', '2', 'A', '1'),
+ desc = IccTag('d', 'e', 's', 'c'),
+ text = IccTag('t', 'e', 'x', 't'),
+ cprt = IccTag('c', 'p', 'r', 't'),
+ curv = IccTag('c', 'u', 'r', 'v'),
+ para = IccTag('p', 'a', 'r', 'a'),
+ wtpt = IccTag('w', 't', 'p', 't'),
+ bkpt = IccTag('b', 'k', 'p', 't'),
+ mft1 = IccTag('m', 'f', 't', '1'),
+ mft2 = IccTag('m', 'f', 't', '2'),
+ mAB_ = IccTag('m', 'A', 'B', ' '),
+ mBA_ = IccTag('m', 'B', 'A', ' '),
+ chad = IccTag('c', 'h', 'a', 'd'),
+ sf32 = IccTag('s', 'f', '3', '2'),
+
+ // Apple extensions for ICCv2:
+ aarg = IccTag('a', 'a', 'r', 'g'),
+ aagg = IccTag('a', 'a', 'g', 'g'),
+ aabg = IccTag('a', 'a', 'b', 'g'),
+};
+
+inline uint qHash(const Tag &key, uint seed = 0)
+{
+ return qHash(quint32(key), seed);
+}
+
+namespace QIcc {
+
+struct TagTableEntry
+{
+ quint32_be signature;
+ quint32_be offset;
+ quint32_be size;
+};
+
+struct GenericTagData {
+ quint32_be type;
+ quint32_be null;
+};
+
+struct XYZTagData : GenericTagData {
+ qint32_be fixedX;
+ qint32_be fixedY;
+ qint32_be fixedZ;
+};
+
+struct CurvTagData : GenericTagData {
+ quint32_be valueCount;
+ quint16_be value[1];
+};
+
+struct ParaTagData : GenericTagData {
+ quint16_be curveType;
+ quint16_be null2;
+ quint32_be parameter[1];
+};
+
+// For both mAB and mBA
+struct mABTagData : GenericTagData {
+ quint8 inputChannels;
+ quint8 outputChannels;
+ quint8 padding[2];
+ quint32_be bCurvesOffset;
+ quint32_be matrixOffset;
+ quint32_be mCurvesOffset;
+ quint32_be clutOffset;
+ quint32_be aCurvesOffset;
+};
+
+struct Sf32TagData : GenericTagData {
+ quint32_be value[1];
+};
+
+static int toFixedS1516(float x)
+{
+ return int(x * 65536.0f + 0.5f);
+}
+
+static float fromFixedS1516(int x)
+{
+ return x * (1.0f / 65536.0f);
+}
+
+QColorVector fromXyzData(const XYZTagData *xyz)
+{
+ const float x = fromFixedS1516(xyz->fixedX);
+ const float y = fromFixedS1516(xyz->fixedY);
+ const float z = fromFixedS1516(xyz->fixedZ);
+ qCDebug(lcIcc) << "XYZ_ " << x << y << z;
+
+ return QColorVector(x, y, z);
+}
+
+static bool isValidIccProfile(const ICCProfileHeader &header)
+{
+ if (header.signature != uint(Tag::acsp)) {
+ qCWarning(lcIcc, "Failed ICC signature test");
+ return false;
+ }
+ if (header.profileSize < (sizeof(ICCProfileHeader) + header.tagCount * sizeof(TagTableEntry))) {
+ qCWarning(lcIcc, "Failed basic size sanity");
+ return false;
+ }
+
+ if (header.profileClass != uint(ProfileClass::Input)
+ && header.profileClass != uint(ProfileClass::Display)) {
+ qCWarning(lcIcc, "Unsupported ICC profile class %x", quint32(header.profileClass));
+ return false;
+ }
+ if (header.inputColorSpace != 0x52474220 /* 'RGB '*/) {
+ qCWarning(lcIcc, "Unsupported ICC input color space %x", quint32(header.inputColorSpace));
+ return false;
+ }
+ if (header.pcs != 0x58595a20 /* 'XYZ '*/) {
+ // ### support PCSLAB
+ qCWarning(lcIcc, "Unsupported ICC profile connection space %x", quint32(header.pcs));
+ return false;
+ }
+
+ QColorVector illuminant;
+ illuminant.x = fromFixedS1516(header.illuminantXyz[0]);
+ illuminant.y = fromFixedS1516(header.illuminantXyz[1]);
+ illuminant.z = fromFixedS1516(header.illuminantXyz[2]);
+ if (illuminant != QColorVector::D50()) {
+ qCWarning(lcIcc, "Invalid ICC illuminant");
+ return false;
+ }
+
+ return true;
+}
+
+static int writeColorTrc(QDataStream &stream, const QColorTrc &trc)
+{
+ if (trc.isLinear()) {
+ stream << uint(Tag::curv) << uint(0);
+ stream << uint(0);
+ return 12;
+ }
+
+ if (trc.m_type == QColorTrc::Type::Function) {
+ const QColorTransferFunction &fun = trc.m_fun;
+ stream << uint(Tag::para) << uint(0);
+ if (fun.isGamma()) {
+ stream << ushort(0) << ushort(0);
+ stream << toFixedS1516(fun.m_g);
+ return 12 + 4;
+ }
+ bool type3 = qFuzzyIsNull(fun.m_e) && qFuzzyIsNull(fun.m_f);
+ stream << ushort(type3 ? 3 : 4) << ushort(0);
+ stream << toFixedS1516(fun.m_g);
+ stream << toFixedS1516(fun.m_a);
+ stream << toFixedS1516(fun.m_b);
+ stream << toFixedS1516(fun.m_c);
+ stream << toFixedS1516(fun.m_d);
+ if (type3)
+ return 12 + 5 * 4;
+ stream << toFixedS1516(fun.m_e);
+ stream << toFixedS1516(fun.m_f);
+ return 12 + 7 * 4;
+ }
+
+ Q_ASSERT(trc.m_type == QColorTrc::Type::Table);
+ stream << uint(Tag::curv) << uint(0);
+ stream << uint(trc.m_table.m_tableSize);
+ if (!trc.m_table.m_table16.isEmpty()) {
+ for (uint i = 0; i < trc.m_table.m_tableSize; ++i) {
+ stream << ushort(trc.m_table.m_table16[i]);
+ }
+ } else {
+ for (uint i = 0; i < trc.m_table.m_tableSize; ++i) {
+ stream << ushort(trc.m_table.m_table8[i] * 257U);
+ }
+ }
+ return 12 + 2 * trc.m_table.m_tableSize;
+}
+
+QByteArray toIccProfile(const QColorSpace &space)
+{
+ if (!space.isValid())
+ return QByteArray();
+
+ const QColorSpacePrivate *spaceDPtr = space.d_func();
+
+ constexpr int tagCount = 9;
+ constexpr uint profileDataOffset = 128 + 4 + 12 * tagCount;
+ constexpr uint variableTagTableOffsets = 128 + 4 + 12 * 5;
+ uint currentOffset = 0;
+ uint rTrcOffset, gTrcOffset, bTrcOffset;
+ uint rTrcSize, gTrcSize, bTrcSize;
+ uint descOffset, descSize;
+
+ QBuffer buffer;
+ buffer.open(QIODevice::WriteOnly);
+ QDataStream stream(&buffer);
+
+ // Profile header:
+ stream << uint(0); // Size, we will update this later
+ stream << uint(0);
+ stream << uint(0x02400000); // Version 2.4 (note we use 'para' from version 4)
+ stream << uint(ProfileClass::Display);
+ stream << uint(Tag::RGB_);
+ stream << uint(Tag::XYZ_);
+ stream << uint(0) << uint(0) << uint(0);
+ stream << uint(Tag::acsp);
+ stream << uint(0) << uint(0) << uint(0);
+ stream << uint(0) << uint(0) << uint(0);
+ stream << uint(1); // Rendering intent
+ stream << uint(0x0000f6d6); // D50 X
+ stream << uint(0x00010000); // D50 Y
+ stream << uint(0x0000d32d); // D50 Z
+ stream << IccTag('Q','t', QT_VERSION_MAJOR, QT_VERSION_MINOR);
+ stream << uint(0) << uint(0) << uint(0) << uint(0);
+ stream << uint(0) << uint(0) << uint(0) << uint(0) << uint(0) << uint(0) << uint(0);
+
+ // Tag table:
+ stream << uint(tagCount);
+ stream << uint(Tag::rXYZ) << uint(profileDataOffset + 00) << uint(20);
+ stream << uint(Tag::gXYZ) << uint(profileDataOffset + 20) << uint(20);
+ stream << uint(Tag::bXYZ) << uint(profileDataOffset + 40) << uint(20);
+ stream << uint(Tag::wtpt) << uint(profileDataOffset + 60) << uint(20);
+ stream << uint(Tag::cprt) << uint(profileDataOffset + 80) << uint(12);
+ // From here the offset and size will be updated later:
+ stream << uint(Tag::rTRC) << uint(0) << uint(0);
+ stream << uint(Tag::gTRC) << uint(0) << uint(0);
+ stream << uint(Tag::bTRC) << uint(0) << uint(0);
+ stream << uint(Tag::desc) << uint(0) << uint(0);
+ // TODO: consider adding 'chad' tag (required in ICC >=4 when we have non-D50 whitepoint)
+ currentOffset = profileDataOffset;
+
+ // Tag data:
+ stream << uint(Tag::XYZ_) << uint(0);
+ stream << toFixedS1516(spaceDPtr->toXyz.r.x);
+ stream << toFixedS1516(spaceDPtr->toXyz.r.y);
+ stream << toFixedS1516(spaceDPtr->toXyz.r.z);
+ stream << uint(Tag::XYZ_) << uint(0);
+ stream << toFixedS1516(spaceDPtr->toXyz.g.x);
+ stream << toFixedS1516(spaceDPtr->toXyz.g.y);
+ stream << toFixedS1516(spaceDPtr->toXyz.g.z);
+ stream << uint(Tag::XYZ_) << uint(0);
+ stream << toFixedS1516(spaceDPtr->toXyz.b.x);
+ stream << toFixedS1516(spaceDPtr->toXyz.b.y);
+ stream << toFixedS1516(spaceDPtr->toXyz.b.z);
+ stream << uint(Tag::XYZ_) << uint(0);
+ stream << toFixedS1516(spaceDPtr->whitePoint.x);
+ stream << toFixedS1516(spaceDPtr->whitePoint.y);
+ stream << toFixedS1516(spaceDPtr->whitePoint.z);
+ stream << uint(Tag::text) << uint(0);
+ stream << uint(IccTag('N', '/', 'A', '\0'));
+ currentOffset += 92;
+
+ // From now on the data is variable sized:
+ rTrcOffset = currentOffset;
+ rTrcSize = writeColorTrc(stream, spaceDPtr->trc[0]);
+ currentOffset += rTrcSize;
+ if (spaceDPtr->trc[0] == spaceDPtr->trc[1]) {
+ gTrcOffset = rTrcOffset;
+ gTrcSize = rTrcSize;
+ } else {
+ gTrcOffset = currentOffset;
+ gTrcSize = writeColorTrc(stream, spaceDPtr->trc[1]);
+ currentOffset += gTrcSize;
+ }
+ if (spaceDPtr->trc[0] == spaceDPtr->trc[2]) {
+ bTrcOffset = rTrcOffset;
+ bTrcSize = rTrcSize;
+ } else {
+ bTrcOffset = currentOffset;
+ bTrcSize = writeColorTrc(stream, spaceDPtr->trc[2]);
+ currentOffset += bTrcSize;
+ }
+
+ descOffset = currentOffset;
+ QByteArray description = spaceDPtr->description.toUtf8();
+ stream << uint(Tag::desc) << uint(0);
+ stream << uint(description.size() + 1);
+ stream.writeRawData(description.constData(), description.size() + 1);
+ stream << uint(0) << uint(0);
+ stream << ushort(0) << uchar(0);
+ QByteArray macdesc(67, '\0');
+ stream.writeRawData(macdesc.constData(), 67);
+ descSize = 90 + description.size() + 1;
+ currentOffset += descSize;
+
+ buffer.close();
+ QByteArray iccProfile = buffer.buffer();
+ // Now write final size
+ *(quint32_be *)iccProfile.data() = iccProfile.size();
+ // And the final indices and sizes of variable size tags:
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 4) = rTrcOffset;
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 8) = rTrcSize;
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 12 + 4) = gTrcOffset;
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 12 + 8) = gTrcSize;
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 2 * 12 + 4) = bTrcOffset;
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 2 * 12 + 8) = bTrcSize;
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 3 * 12 + 4) = descOffset;
+ *(quint32_be *)(iccProfile.data() + variableTagTableOffsets + 3 * 12 + 8) = descSize;
+
+#if !defined(QT_NO_DEBUG) || defined(QT_FORCE_ASSERTS)
+ const ICCProfileHeader *iccHeader = (const ICCProfileHeader *)iccProfile.constData();
+ Q_ASSERT(qsizetype(iccHeader->profileSize) == qsizetype(iccProfile.size()));
+ Q_ASSERT(isValidIccProfile(*iccHeader));
+#endif
+
+ return iccProfile;
+}
+
+bool parseTRC(const GenericTagData *trcData, QColorTrc &gamma)
+{
+ if (trcData->type == quint32(Tag::curv)) {
+ const CurvTagData *curv = reinterpret_cast<const CurvTagData *>(trcData);
+ qCDebug(lcIcc) << "curv" << uint(curv->valueCount);
+ if (curv->valueCount == 0) {
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = QColorTransferFunction(); // Linear
+ } else if (curv->valueCount == 1) {
+ float g = curv->value[0] * (1.0f / 256.0f);
+ qCDebug(lcIcc) << g;
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = QColorTransferFunction::fromGamma(g);
+ } else {
+ QVector<quint16> tabl;
+ tabl.resize(curv->valueCount);
+ for (uint i = 0; i < curv->valueCount; ++i)
+ tabl[i] = curv->value[i];
+ QColorTransferTable table = QColorTransferTable(curv->valueCount, std::move(tabl));
+ QColorTransferFunction curve;
+ if (!table.asColorTransferFunction(&curve)) {
+ gamma.m_type = QColorTrc::Type::Table;
+ gamma.m_table = table;
+ } else {
+ qCDebug(lcIcc) << "Detected curv table as function";
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = curve;
+ }
+ }
+ return true;
+ }
+ if (trcData->type == quint32(Tag::para)) {
+ const ParaTagData *para = reinterpret_cast<const ParaTagData *>(trcData);
+ qCDebug(lcIcc) << "para" << uint(para->curveType);
+ switch (para->curveType) {
+ case 0: {
+ float g = fromFixedS1516(para->parameter[0]);
+ qCDebug(lcIcc) << g;
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = QColorTransferFunction::fromGamma(g);
+ break;
+ }
+ case 1: {
+ float g = fromFixedS1516(para->parameter[0]);
+ float a = fromFixedS1516(para->parameter[1]);
+ float b = fromFixedS1516(para->parameter[2]);
+ float d = -b / a;
+ qCDebug(lcIcc) << g << a << b;
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = QColorTransferFunction(a, b, 0.0f, d, 0.0f, 0.0f, g);
+ break;
+ }
+ case 2: {
+ float g = fromFixedS1516(para->parameter[0]);
+ float a = fromFixedS1516(para->parameter[1]);
+ float b = fromFixedS1516(para->parameter[2]);
+ float c = fromFixedS1516(para->parameter[3]);
+ float d = -b / a;
+ qCDebug(lcIcc) << g << a << b << c;
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = QColorTransferFunction(a, b, 0.0f, d, c, c, g);
+ break;
+ }
+ case 3: {
+ float g = fromFixedS1516(para->parameter[0]);
+ float a = fromFixedS1516(para->parameter[1]);
+ float b = fromFixedS1516(para->parameter[2]);
+ float c = fromFixedS1516(para->parameter[3]);
+ float d = fromFixedS1516(para->parameter[4]);
+ qCDebug(lcIcc) << g << a << b << c << d;
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = QColorTransferFunction(a, b, c, d, 0.0f, 0.0f, g);
+ break;
+ }
+ case 4: {
+ float g = fromFixedS1516(para->parameter[0]);
+ float a = fromFixedS1516(para->parameter[1]);
+ float b = fromFixedS1516(para->parameter[2]);
+ float c = fromFixedS1516(para->parameter[3]);
+ float d = fromFixedS1516(para->parameter[4]);
+ float e = fromFixedS1516(para->parameter[5]);
+ float f = fromFixedS1516(para->parameter[6]);
+ qCDebug(lcIcc) << g << a << b << c << d << e << f;
+ gamma.m_type = QColorTrc::Type::Function;
+ gamma.m_fun = QColorTransferFunction(a, b, c, d, e, f, g);
+ break;
+ }
+ default:
+ qCWarning(lcIcc) << "Unknown para type" << uint(para->curveType);
+ return false;
+ }
+ return true;
+ }
+ qCWarning(lcIcc) << "Invalid TRC data type";
+ return false;
+}
+
+bool fromIccProfile(const QByteArray &data, QColorSpace *colorSpace)
+{
+ if (data.size() < qsizetype(sizeof(ICCProfileHeader))) {
+ qCWarning(lcIcc) << "fromIccProfile: failed size sanity 1";
+ return false;
+ }
+ const ICCProfileHeader *header = (const ICCProfileHeader *)data.constData();
+ if (!isValidIccProfile(*header)) {
+ qCWarning(lcIcc) << "fromIccProfile: failed general sanity check";
+ return false;
+ }
+ if (qsizetype(header->profileSize) > data.size()) {
+ qCWarning(lcIcc) << "fromIccProfile: failed size sanity 2";
+ return false;
+ }
+
+ // Read tag index
+ const TagTableEntry *tagTable = (const TagTableEntry *)(data.constData() + sizeof(ICCProfileHeader));
+ const qsizetype offsetToData = sizeof(ICCProfileHeader) + header->tagCount * sizeof(TagTableEntry);
+
+ QHash<Tag, quint32> tagIndex;
+ for (uint i = 0; i < header->tagCount; ++i) {
+ // Sanity check tag sizes and offsets:
+ if (qsizetype(tagTable[i].offset) < offsetToData) {
+ qCWarning(lcIcc) << "fromIccProfile: failed tag offset sanity 1";
+ return false;
+ }
+ // Checked separately from (+ size) to handle overflow.
+ if (tagTable[i].offset > header->profileSize) {
+ qCWarning(lcIcc) << "fromIccProfile: failed tag offset sanity 2";
+ return false;
+ }
+ if ((tagTable[i].offset + tagTable[i].size) > header->profileSize) {
+ qCWarning(lcIcc) << "fromIccProfile: failed tag offset + size sanity";
+ return false;
+ }
+// printf("'%4s' %d %d\n", (const char *)&tagTable[i].signature,
+// quint32(tagTable[i].offset),
+// quint32(tagTable[i].size));
+ tagIndex.insert(Tag(quint32(tagTable[i].signature)), tagTable[i].offset);
+ }
+ // Check the profile is three-component matrix based (what we currently support):
+ if (!tagIndex.contains(Tag::rXYZ) || !tagIndex.contains(Tag::gXYZ) || !tagIndex.contains(Tag::bXYZ) ||
+ !tagIndex.contains(Tag::rTRC) || !tagIndex.contains(Tag::gTRC) || !tagIndex.contains(Tag::bTRC) ||
+ !tagIndex.contains(Tag::wtpt)) {
+ qCWarning(lcIcc) << "fromIccProfile: Unsupported ICC profile - not three component matrix based";
+ return false;
+ }
+
+ // Parse XYZ tags
+ const XYZTagData *rXyz = (const XYZTagData *)(data.constData() + tagIndex[Tag::rXYZ]);
+ const XYZTagData *gXyz = (const XYZTagData *)(data.constData() + tagIndex[Tag::gXYZ]);
+ const XYZTagData *bXyz = (const XYZTagData *)(data.constData() + tagIndex[Tag::bXYZ]);
+ const XYZTagData *wXyz = (const XYZTagData *)(data.constData() + tagIndex[Tag::wtpt]);
+ if (rXyz->type != quint32(Tag::XYZ_) || gXyz->type != quint32(Tag::XYZ_) ||
+ wXyz->type != quint32(Tag::XYZ_) || wXyz->type != quint32(Tag::XYZ_)) {
+ qCWarning(lcIcc) << "fromIccProfile: Bad XYZ data type";
+ return false;
+ }
+ QColorSpacePrivate *colorspaceDPtr = colorSpace->d_func();
+
+ colorspaceDPtr->toXyz.r = fromXyzData(rXyz);
+ colorspaceDPtr->toXyz.g = fromXyzData(gXyz);
+ colorspaceDPtr->toXyz.b = fromXyzData(bXyz);
+ QColorVector whitePoint = fromXyzData(wXyz);
+ colorspaceDPtr->whitePoint = whitePoint;
+
+ colorspaceDPtr->gamut = QColorSpace::Gamut::Custom;
+ if (colorspaceDPtr->toXyz == QColorMatrix::toXyzFromSRgb()) {
+ qCDebug(lcIcc) << "fromIccProfile: sRGB gamut detected";
+ colorspaceDPtr->gamut = QColorSpace::Gamut::SRgb;
+ } else if (colorspaceDPtr->toXyz == QColorMatrix::toXyzFromAdobeRgb()) {
+ qCDebug(lcIcc) << "fromIccProfile: Adobe RGB gamut detected";
+ colorspaceDPtr->gamut = QColorSpace::Gamut::AdobeRgb;
+ } else if (colorspaceDPtr->toXyz == QColorMatrix::toXyzFromDciP3D65()) {
+ qCDebug(lcIcc) << "fromIccProfile: DCI-P3 D65 gamut detected";
+ colorspaceDPtr->gamut = QColorSpace::Gamut::DciP3D65;
+ } else if (colorspaceDPtr->toXyz == QColorMatrix::toXyzFromBt2020()) {
+ qCDebug(lcIcc) << "fromIccProfile: BT.2020 gamut detected";
+ colorspaceDPtr->gamut = QColorSpace::Gamut::Bt2020;
+ }
+ if (colorspaceDPtr->toXyz == QColorMatrix::toXyzFromProPhotoRgb()) {
+ qCDebug(lcIcc) << "fromIccProfile: ProPhoto RGB gamut detected";
+ colorspaceDPtr->gamut = QColorSpace::Gamut::ProPhotoRgb;
+ }
+ // Reset the matrix to our canonical values:
+ if (colorspaceDPtr->gamut != QColorSpace::Gamut::Custom)
+ colorspaceDPtr->setToXyzMatrix();
+
+ // Parse TRC tags
+ const GenericTagData *rTrc;
+ const GenericTagData *gTrc;
+ const GenericTagData *bTrc;
+ if (tagIndex.contains(Tag::aarg) && tagIndex.contains(Tag::aagg) && tagIndex.contains(Tag::aabg)) {
+ // Apple extension for parametric version of TRCs in ICCv2:
+ rTrc = (const GenericTagData *)(data.constData() + tagIndex[Tag::aarg]);
+ gTrc = (const GenericTagData *)(data.constData() + tagIndex[Tag::aagg]);
+ bTrc = (const GenericTagData *)(data.constData() + tagIndex[Tag::aabg]);
+ } else {
+ rTrc = (const GenericTagData *)(data.constData() + tagIndex[Tag::rTRC]);
+ gTrc = (const GenericTagData *)(data.constData() + tagIndex[Tag::gTRC]);
+ bTrc = (const GenericTagData *)(data.constData() + tagIndex[Tag::bTRC]);
+ }
+
+ QColorTrc rCurve;
+ QColorTrc gCurve;
+ QColorTrc bCurve;
+ if (!parseTRC(rTrc, rCurve))
+ return false;
+ if (!parseTRC(gTrc, gCurve))
+ return false;
+ if (!parseTRC(bTrc, bCurve))
+ return false;
+ if (rCurve == gCurve && gCurve == bCurve && rCurve.m_type == QColorTrc::Type::Function) {
+ if (rCurve.m_fun.isLinear()) {
+ qCDebug(lcIcc) << "fromIccProfile: Linear gamma detected";
+ colorspaceDPtr->trc[0] = QColorTransferFunction();
+ colorspaceDPtr->transferFunction = QColorSpace::TransferFunction::Linear;
+ colorspaceDPtr->gamma = 1.0f;
+ } else if (rCurve.m_fun.isGamma()) {
+ qCDebug(lcIcc) << "fromIccProfile: Simple gamma detected";
+ colorspaceDPtr->trc[0] = QColorTransferFunction::fromGamma(rCurve.m_fun.m_g);
+ colorspaceDPtr->transferFunction = QColorSpace::TransferFunction::Gamma;
+ colorspaceDPtr->gamma = rCurve.m_fun.m_g;
+ } else if (rCurve.m_fun.isSRgb()) {
+ qCDebug(lcIcc) << "fromIccProfile: sRGB gamma detected";
+ colorspaceDPtr->trc[0] = QColorTransferFunction::fromSRgb();
+ colorspaceDPtr->transferFunction = QColorSpace::TransferFunction::SRgb;
+ } else {
+ colorspaceDPtr->trc[0] = rCurve;
+ colorspaceDPtr->transferFunction = QColorSpace::TransferFunction::Custom;
+ }
+
+ colorspaceDPtr->trc[1] = colorspaceDPtr->trc[0];
+ colorspaceDPtr->trc[2] = colorspaceDPtr->trc[0];
+ } else {
+ colorspaceDPtr->trc[0] = rCurve;
+ colorspaceDPtr->trc[1] = gCurve;
+ colorspaceDPtr->trc[2] = bCurve;
+ colorspaceDPtr->transferFunction = QColorSpace::TransferFunction::Custom;
+ }
+
+ // FIXME: try to parse the description..
+
+ if (!colorspaceDPtr->identifyColorSpace())
+ colorspaceDPtr->id = QColorSpace::Unknown;
+ else
+ qCDebug(lcIcc) << "fromIccProfile: Named colorspace detected: " << colorSpace->colorSpaceId();
+
+ colorspaceDPtr->iccProfile = data;
+
+ return true;
+}
+
+} // namespace QIcc
+
+QT_END_NAMESPACE
diff --git a/src/plugins/platforms/mirclient/qmirclientdebugextension.h b/src/gui/painting/qicc_p.h
index 0596561d77..c3220391f4 100644
--- a/src/plugins/platforms/mirclient/qmirclientdebugextension.h
+++ b/src/gui/painting/qicc_p.h
@@ -1,9 +1,9 @@
/****************************************************************************
**
-** Copyright (C) 2016 Canonical, Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
-** This file is part of the plugins of the Qt Toolkit.
+** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
@@ -37,27 +37,34 @@
**
****************************************************************************/
+#ifndef QICC_P_H
+#define QICC_P_H
-#ifndef QMIRCLIENTDEBUGEXTENSION_H
-#define QMIRCLIENTDEBUGEXTENSION_H
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
-#include <QPoint>
-#include <QLibrary>
-struct MirSurface;
+#include <QtCore/qbytearray.h>
+#include <QtGui/qtguiglobal.h>
-typedef bool (*MapperPrototype)(MirSurface* surface, int x, int y, int* screenX, int* screenY);
+QT_BEGIN_NAMESPACE
+class QColorSpace;
-class QMirClientDebugExtension
-{
-public:
- QMirClientDebugExtension();
+namespace QIcc {
- QPoint mapSurfacePointToScreen(MirSurface *, const QPoint &point);
+Q_GUI_EXPORT bool fromIccProfile(const QByteArray &data, QColorSpace *colorSpace);
+Q_GUI_EXPORT QByteArray toIccProfile(const QColorSpace &space);
-private:
- QLibrary m_mirclientDebug;
- MapperPrototype m_mapper;
-};
+}
-#endif // QMIRCLIENTDEBUGEXTENSION_H
+QT_END_NAMESPACE
+
+#endif // QICC_P_H
diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp
index 0f5c7756ad..66af6e3de3 100644
--- a/src/gui/painting/qpaintengine_raster.cpp
+++ b/src/gui/painting/qpaintengine_raster.cpp
@@ -555,35 +555,6 @@ bool QRasterPaintEngine::end()
/*!
\internal
*/
-void QRasterPaintEngine::releaseBuffer()
-{
- Q_D(QRasterPaintEngine);
- d->rasterBuffer.reset(new QRasterBuffer);
-}
-
-/*!
- \internal
-*/
-QSize QRasterPaintEngine::size() const
-{
- Q_D(const QRasterPaintEngine);
- return QSize(d->rasterBuffer->width(), d->rasterBuffer->height());
-}
-
-/*!
- \internal
-*/
-#ifndef QT_NO_DEBUG
-void QRasterPaintEngine::saveBuffer(const QString &s) const
-{
- Q_D(const QRasterPaintEngine);
- d->rasterBuffer->bufferImage().save(s, "PNG");
-}
-#endif
-
-/*!
- \internal
-*/
void QRasterPaintEngine::updateMatrix(const QTransform &matrix)
{
QRasterPaintEngineState *s = state();
@@ -3845,11 +3816,6 @@ QImage::Format QRasterBuffer::prepare(QImage *image)
return format;
}
-void QRasterBuffer::resetBuffer(int val)
-{
- memset(m_buffer, val, m_height*bytes_per_line);
-}
-
QClipData::QClipData(int height)
{
clipSpanHeight = height;
@@ -4272,48 +4238,6 @@ static void qt_span_clip(int count, const QSpan *spans, void *userData)
}
}
-#ifndef QT_NO_DEBUG
-QImage QRasterBuffer::bufferImage() const
-{
- QImage image(m_width, m_height, QImage::Format_ARGB32_Premultiplied);
-
- for (int y = 0; y < m_height; ++y) {
- uint *span = (uint *)const_cast<QRasterBuffer *>(this)->scanLine(y);
-
- for (int x=0; x<m_width; ++x) {
- uint argb = span[x];
- image.setPixel(x, y, argb);
- }
- }
- return image;
-}
-#endif
-
-
-void QRasterBuffer::flushToARGBImage(QImage *target) const
-{
- int w = qMin(m_width, target->width());
- int h = qMin(m_height, target->height());
-
- for (int y=0; y<h; ++y) {
- uint *sourceLine = (uint *)const_cast<QRasterBuffer *>(this)->scanLine(y);
- QRgb *dest = (QRgb *) target->scanLine(y);
- for (int x=0; x<w; ++x) {
- QRgb pixel = sourceLine[x];
- int alpha = qAlpha(pixel);
- if (!alpha) {
- dest[x] = 0;
- } else {
- dest[x] = (alpha << 24)
- | ((255*qRed(pixel)/alpha) << 16)
- | ((255*qGreen(pixel)/alpha) << 8)
- | ((255*qBlue(pixel)/alpha) << 0);
- }
- }
- }
-}
-
-
class QGradientCache
{
public:
diff --git a/src/gui/painting/qpaintengine_raster_p.h b/src/gui/painting/qpaintengine_raster_p.h
index 881144d1c2..c3734f1c62 100644
--- a/src/gui/painting/qpaintengine_raster_p.h
+++ b/src/gui/painting/qpaintengine_raster_p.h
@@ -208,15 +208,6 @@ public:
ClipType clipType() const;
QRect clipBoundingRect() const;
- void releaseBuffer();
-
- QSize size() const;
-
-#ifndef QT_NO_DEBUG
- void saveBuffer(const QString &s) const;
-#endif
-
-
#ifdef Q_OS_WIN
void setDC(HDC hdc);
HDC getDC() const;
@@ -442,20 +433,9 @@ public:
void init();
QImage::Format prepare(QImage *image);
- QImage::Format prepare(QPixmap *pix);
- void prepare(int w, int h);
- void prepareBuffer(int w, int h);
-
- void resetBuffer(int val=0);
uchar *scanLine(int y) { Q_ASSERT(y>=0); Q_ASSERT(y<m_height); return m_buffer + y * bytes_per_line; }
-#ifndef QT_NO_DEBUG
- QImage bufferImage() const;
-#endif
-
- void flushToARGBImage(QImage *image) const;
-
int width() const { return m_width; }
int height() const { return m_height; }
int bytesPerLine() const { return bytes_per_line; }
diff --git a/src/gui/painting/qpainter_p.h b/src/gui/painting/qpainter_p.h
index 930180e9fa..9857a59070 100644
--- a/src/gui/painting/qpainter_p.h
+++ b/src/gui/painting/qpainter_p.h
@@ -54,6 +54,8 @@
#include <QtCore/qvarlengtharray.h>
#include <QtGui/private/qtguiglobal_p.h>
#include "QtGui/qbrush.h"
+#include "QtGui/qcolorspace.h"
+#include "QtGui/qcolortransform.h"
#include "QtGui/qfont.h"
#include "QtGui/qpen.h"
#include "QtGui/qregion.h"
diff --git a/src/gui/painting/qpdfwriter.cpp b/src/gui/painting/qpdfwriter.cpp
index 258939a763..7f18ce42be 100644
--- a/src/gui/painting/qpdfwriter.cpp
+++ b/src/gui/painting/qpdfwriter.cpp
@@ -379,6 +379,9 @@ int QPdfWriter::resolution() const
*/
#endif
+#if QT_DEPRECATED_SINCE(5, 14)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
/*!
\reimp
@@ -404,6 +407,8 @@ void QPdfWriter::setPageSizeMM(const QSizeF &size)
{
setPageSize(QPageSize(size, QPageSize::Millimeter));
}
+QT_WARNING_POP
+#endif
/*!
\internal
@@ -427,6 +432,9 @@ bool QPdfWriter::newPage()
}
+#if QT_DEPRECATED_SINCE(5, 14)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
/*!
\reimp
@@ -438,6 +446,8 @@ void QPdfWriter::setMargins(const Margins &m)
{
setPageMargins(QMarginsF(m.left, m.top, m.right, m.bottom), QPageLayout::Millimeter);
}
+QT_WARNING_POP
+#endif
QT_END_NAMESPACE
diff --git a/src/gui/painting/qpdfwriter.h b/src/gui/painting/qpdfwriter.h
index b260805b2b..668081e008 100644
--- a/src/gui/painting/qpdfwriter.h
+++ b/src/gui/painting/qpdfwriter.h
@@ -86,10 +86,14 @@ public:
using QPagedPaintDevice::setPageSize;
#endif
+#if QT_DEPRECATED_SINCE(5, 14)
+ QT_DEPRECATED_X("Use setPageSize(QPageSize(id)) instead")
void setPageSize(PageSize size) override;
+ QT_DEPRECATED_X("Use setPageSize(QPageSize(size, QPageSize::Millimeter)) instead")
void setPageSizeMM(const QSizeF &size) override;
-
+ QT_DEPRECATED_X("Use setPageMargins(QMarginsF(l, t, r, b), QPageLayout::Millimeter) instead")
void setMargins(const Margins &m) override;
+#endif
protected:
QPaintEngine *paintEngine() const override;
diff --git a/src/gui/text/qfont.cpp b/src/gui/text/qfont.cpp
index a51e98ce85..d54fa22990 100644
--- a/src/gui/text/qfont.cpp
+++ b/src/gui/text/qfont.cpp
@@ -3164,7 +3164,104 @@ void QFontCache::decreaseCache()
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug stream, const QFont &font)
{
- return stream << "QFont(" << font.toString() << ')';
+ QDebugStateSaver saver(stream);
+ stream.nospace().noquote();
+ stream << "QFont(";
+
+ if (stream.verbosity() == QDebug::DefaultVerbosity) {
+ stream << font.toString() << ")";
+ return stream;
+ }
+
+ QString fontDescription;
+ QDebug debug(&fontDescription);
+ debug.nospace();
+
+ QFontPrivate priv;
+ const QFont defaultFont(&priv);
+
+ for (int property = QFont::FamilyResolved; property < QFont::AllPropertiesResolved; property <<= 1) {
+ const bool resolved = (font.resolve_mask & property) != 0;
+ if (!resolved && stream.verbosity() == QDebug::MinimumVerbosity)
+ continue;
+
+ #define QFONT_DEBUG_SKIP_DEFAULT(prop) \
+ if ((font.prop() == defaultFont.prop()) && stream.verbosity() == 1) \
+ continue;
+
+ QDebugStateSaver saver(debug);
+
+ switch (property) {
+ case QFont::FamilyResolved:
+ debug << font.family(); break;
+ case QFont::SizeResolved:
+ if (font.pointSizeF() >= 0)
+ debug << font.pointSizeF() << "pt";
+ else if (font.pixelSize() >= 0)
+ debug << font.pixelSize() << "px";
+ else
+ Q_UNREACHABLE();
+ break;
+ case QFont::StyleHintResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(styleHint);
+ debug.verbosity(1) << font.styleHint(); break;
+ case QFont::StyleStrategyResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(styleStrategy);
+ debug.verbosity(1) << font.styleStrategy(); break;
+ case QFont::WeightResolved:
+ debug.verbosity(1) << QFont::Weight(font.weight()); break;
+ case QFont::StyleResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(style);
+ debug.verbosity(0) << font.style(); break;
+ case QFont::UnderlineResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(underline);
+ debug << "underline=" << font.underline(); break;
+ case QFont::OverlineResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(overline);
+ debug << "overline=" << font.overline(); break;
+ case QFont::StrikeOutResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(strikeOut);
+ debug << "strikeOut=" << font.strikeOut(); break;
+ case QFont::FixedPitchResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(fixedPitch);
+ debug << "fixedPitch=" << font.fixedPitch(); break;
+ case QFont::StretchResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(stretch);
+ debug.verbosity(0) << QFont::Stretch(font.stretch()); break;
+ case QFont::KerningResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(kerning);
+ debug << "kerning=" << font.kerning(); break;
+ case QFont::CapitalizationResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(capitalization);
+ debug.verbosity(0) << font.capitalization(); break;
+ case QFont::LetterSpacingResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(letterSpacing);
+ debug << "letterSpacing=" << font.letterSpacing();
+ debug.verbosity(0) << " (" << font.letterSpacingType() << ")";
+ break;
+ case QFont::HintingPreferenceResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(hintingPreference);
+ debug.verbosity(0) << font.hintingPreference(); break;
+ case QFont::StyleNameResolved:
+ QFONT_DEBUG_SKIP_DEFAULT(styleName);
+ debug << "styleName=" << font.styleName(); break;
+ default:
+ continue;
+ };
+
+ #undef QFONT_DEBUG_SKIP_DEFAULT
+
+ debug << ", ";
+ }
+
+ if (stream.verbosity() > QDebug::MinimumVerbosity)
+ debug.verbosity(0) << "resolveMask=" << QFlags<QFont::ResolveProperties>(font.resolve_mask);
+ else
+ fontDescription.chop(2); // Last ', '
+
+ stream << fontDescription << ')';
+
+ return stream;
}
#endif
diff --git a/src/gui/text/qfont.h b/src/gui/text/qfont.h
index e86f06353a..35ef798275 100644
--- a/src/gui/text/qfont.h
+++ b/src/gui/text/qfont.h
@@ -147,6 +147,7 @@ public:
Q_ENUM(SpacingType)
enum ResolveProperties {
+ NoPropertiesResolved = 0x0000,
FamilyResolved = 0x0001,
SizeResolved = 0x0002,
StyleHintResolved = 0x0004,
@@ -167,6 +168,7 @@ public:
FamiliesResolved = 0x20000,
AllPropertiesResolved = 0x3ffff
};
+ Q_ENUM(ResolveProperties)
QFont();
QFont(const QString &family, int pointSize = -1, int weight = -1, bool italic = false);
@@ -335,6 +337,10 @@ private:
friend Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QFont &);
#endif
+#ifndef QT_NO_DEBUG_STREAM
+ friend Q_GUI_EXPORT QDebug operator<<(QDebug, const QFont &);
+#endif
+
QExplicitlySharedDataPointer<QFontPrivate> d;
uint resolve_mask;
};
diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp
index 681d84fee8..ee1e3cfb8f 100644
--- a/src/network/access/qhttpnetworkconnection.cpp
+++ b/src/network/access/qhttpnetworkconnection.cpp
@@ -398,11 +398,12 @@ void QHttpNetworkConnectionPrivate::copyCredentials(int fromChannel, QAuthentica
{
Q_ASSERT(auth);
- // NTLM is a multi phase authentication. Copying credentials between authenticators would mess things up.
+ // NTLM and Negotiate do multi-phase authentication.
+ // Copying credentialsbetween authenticators would mess things up.
if (fromChannel >= 0) {
- if (!isProxy && channels[fromChannel].authMethod == QAuthenticatorPrivate::Ntlm)
- return;
- if (isProxy && channels[fromChannel].proxyAuthMethod == QAuthenticatorPrivate::Ntlm)
+ const QHttpNetworkConnectionChannel &channel = channels[fromChannel];
+ const QAuthenticatorPrivate::Method method = isProxy ? channel.proxyAuthMethod : channel.authMethod;
+ if (method == QAuthenticatorPrivate::Ntlm || method == QAuthenticatorPrivate::Negotiate)
return;
}
@@ -592,7 +593,7 @@ void QHttpNetworkConnectionPrivate::createAuthorization(QAbstractSocket *socket,
if ((channels[i].authMethod != QAuthenticatorPrivate::Ntlm && request.headerField("Authorization").isEmpty()) || channels[i].lastStatus == 401) {
QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(channels[i].authenticator);
if (priv && priv->method != QAuthenticatorPrivate::None) {
- QByteArray response = priv->calculateResponse(request.methodName(), request.uri(false));
+ QByteArray response = priv->calculateResponse(request.methodName(), request.uri(false), request.url().host());
request.setHeaderField("Authorization", response);
channels[i].authenticationCredentialsSent = true;
}
@@ -604,7 +605,7 @@ void QHttpNetworkConnectionPrivate::createAuthorization(QAbstractSocket *socket,
if (!(channels[i].proxyAuthMethod == QAuthenticatorPrivate::Ntlm && channels[i].lastStatus != 407)) {
QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(channels[i].proxyAuthenticator);
if (priv && priv->method != QAuthenticatorPrivate::None) {
- QByteArray response = priv->calculateResponse(request.methodName(), request.uri(false));
+ QByteArray response = priv->calculateResponse(request.methodName(), request.uri(false), networkProxy.hostName());
request.setHeaderField("Proxy-Authorization", response);
channels[i].proxyCredentialsSent = true;
}
diff --git a/src/network/access/qhttpnetworkreply.cpp b/src/network/access/qhttpnetworkreply.cpp
index c9c3172304..a8b635c45a 100644
--- a/src/network/access/qhttpnetworkreply.cpp
+++ b/src/network/access/qhttpnetworkreply.cpp
@@ -444,6 +444,9 @@ QAuthenticatorPrivate::Method QHttpNetworkReplyPrivate::authenticationMethod(boo
} else if (method < QAuthenticatorPrivate::DigestMd5
&& line.startsWith("digest")) {
method = QAuthenticatorPrivate::DigestMd5;
+ } else if (method < QAuthenticatorPrivate::Negotiate
+ && line.startsWith("negotiate")) {
+ method = QAuthenticatorPrivate::Negotiate;
}
}
return method;
diff --git a/src/network/configure.json b/src/network/configure.json
index e6c87b550b..aaedc05ea4 100644
--- a/src/network/configure.json
+++ b/src/network/configure.json
@@ -199,6 +199,15 @@
]
},
"use": "openssl"
+ },
+ "gssapi": {
+ "label": "KRB5 GSSAPI support",
+ "type": "compile",
+ "test": {
+ "include": [ "gssapi/gssapi.h" ],
+ "main": ["gss_ctx_id_t ctx;"],
+ "qmake": "LIBS += -lgssapi_krb5"
+ }
}
},
@@ -374,6 +383,20 @@
"purpose": "Provides API for DNS lookups.",
"section": "Networking",
"output": [ "publicFeature" ]
+ },
+ "gssapi": {
+ "label": "GSSAPI",
+ "purpose": "Enable SPNEGO authentication through GSSAPI",
+ "section": "Networking",
+ "condition": "!config.win32 && tests.gssapi",
+ "output": [ "publicFeature", "feature" ]
+ },
+ "sspi": {
+ "label": "SSPI",
+ "purpose": "Enable NTLM/SPNEGO authentication through SSPI",
+ "section": "Networking",
+ "condition": "config.win32 && !config.winrt",
+ "output": [ "publicFeature", "feature" ]
}
},
@@ -433,7 +456,8 @@ For example:
"dtls",
"ocsp",
"sctp",
- "system-proxies"
+ "system-proxies",
+ "gssapi"
]
}
]
diff --git a/src/network/kernel/kernel.pri b/src/network/kernel/kernel.pri
index 11b80d59d5..f7269e5070 100644
--- a/src/network/kernel/kernel.pri
+++ b/src/network/kernel/kernel.pri
@@ -68,6 +68,8 @@ mac {
!uikit: LIBS_PRIVATE += -framework CoreServices -framework SystemConfiguration
}
+qtConfig(gssapi): LIBS_PRIVATE += -lgssapi_krb5
+
uikit:HEADERS += kernel/qnetworkinterface_uikit_p.h
osx:SOURCES += kernel/qnetworkproxy_mac.cpp
else:win32:!winrt: SOURCES += kernel/qnetworkproxy_win.cpp
diff --git a/src/network/kernel/qauthenticator.cpp b/src/network/kernel/qauthenticator.cpp
index 47ce9ab0c6..3ca8806c2b 100644
--- a/src/network/kernel/qauthenticator.cpp
+++ b/src/network/kernel/qauthenticator.cpp
@@ -54,20 +54,29 @@
#include <qmutex.h>
#include <private/qmutexpool_p.h>
#include <rpc.h>
-#ifndef Q_OS_WINRT
+#endif
+
+#if QT_CONFIG(sspi) // SSPI
#define SECURITY_WIN32 1
#include <security.h>
-#endif
+#elif QT_CONFIG(gssapi) // GSSAPI
+#include <gssapi/gssapi.h>
#endif
QT_BEGIN_NAMESPACE
static QByteArray qNtlmPhase1();
static QByteArray qNtlmPhase3(QAuthenticatorPrivate *ctx, const QByteArray& phase2data);
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
-static QByteArray qNtlmPhase1_SSPI(QAuthenticatorPrivate *ctx);
-static QByteArray qNtlmPhase3_SSPI(QAuthenticatorPrivate *ctx, const QByteArray& phase2data);
-#endif
+#if QT_CONFIG(sspi) // SSPI
+static QByteArray qSspiStartup(QAuthenticatorPrivate *ctx, QAuthenticatorPrivate::Method method,
+ const QString& host);
+static QByteArray qSspiContinue(QAuthenticatorPrivate *ctx, QAuthenticatorPrivate::Method method,
+ const QString& host, const QByteArray& challenge = QByteArray());
+#elif QT_CONFIG(gssapi) // GSSAPI
+static QByteArray qGssapiStartup(QAuthenticatorPrivate *ctx, const QString& host);
+static QByteArray qGssapiContinue(QAuthenticatorPrivate *ctx,
+ const QByteArray& challenge = QByteArray());
+#endif // gssapi
/*!
\class QAuthenticator
@@ -90,6 +99,7 @@ static QByteArray qNtlmPhase3_SSPI(QAuthenticatorPrivate *ctx, const QByteArray&
\li Basic
\li NTLM version 2
\li Digest-MD5
+ \li SPNEGO/Negotiate
\endlist
\target qauthenticator-options
@@ -133,6 +143,10 @@ static QByteArray qNtlmPhase3_SSPI(QAuthenticatorPrivate *ctx, const QByteArray&
The Digest-MD5 authentication mechanism supports no outgoing options.
+ \section2 SPNEGO/Negotiate
+
+ This authentication mechanism currently supports no incoming or outgoing options.
+
\sa QSslSocket
*/
@@ -187,7 +201,7 @@ QAuthenticator &QAuthenticator::operator=(const QAuthenticator &other)
d->options = other.d->options;
} else if (d->phase == QAuthenticatorPrivate::Start) {
delete d;
- d = 0;
+ d = nullptr;
}
return *this;
}
@@ -339,21 +353,25 @@ bool QAuthenticator::isNull() const
return !d;
}
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
-class QNtlmWindowsHandles
+#if QT_CONFIG(sspi) // SSPI
+class QSSPIWindowsHandles
{
public:
CredHandle credHandle;
CtxtHandle ctxHandle;
};
-#endif
+#elif QT_CONFIG(gssapi) // GSSAPI
+class QGssApiHandles
+{
+public:
+ gss_ctx_id_t gssCtx = nullptr;
+ gss_name_t targetName;
+};
+#endif // gssapi
QAuthenticatorPrivate::QAuthenticatorPrivate()
: method(None)
- #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- , ntlmWindowsHandles(0)
- #endif
, hasFailed(false)
, phase(Start)
, nonceCount(0)
@@ -363,13 +381,7 @@ QAuthenticatorPrivate::QAuthenticatorPrivate()
nonceCount = 0;
}
-QAuthenticatorPrivate::~QAuthenticatorPrivate()
-{
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- if (ntlmWindowsHandles)
- delete ntlmWindowsHandles;
-#endif
-}
+QAuthenticatorPrivate::~QAuthenticatorPrivate() = default;
void QAuthenticatorPrivate::updateCredentials()
{
@@ -424,6 +436,9 @@ void QAuthenticatorPrivate::parseHttpResponse(const QList<QPair<QByteArray, QByt
} else if (method < DigestMd5 && str.startsWith("digest")) {
method = DigestMd5;
headerVal = current.second.mid(7);
+ } else if (method < Negotiate && str.startsWith("negotiate")) {
+ method = Negotiate;
+ headerVal = current.second.mid(10);
}
}
@@ -439,6 +454,7 @@ void QAuthenticatorPrivate::parseHttpResponse(const QList<QPair<QByteArray, QByt
phase = Done;
break;
case Ntlm:
+ case Negotiate:
// work is done in calculateResponse()
break;
case DigestMd5: {
@@ -456,33 +472,36 @@ void QAuthenticatorPrivate::parseHttpResponse(const QList<QPair<QByteArray, QByt
}
}
-QByteArray QAuthenticatorPrivate::calculateResponse(const QByteArray &requestMethod, const QByteArray &path)
+QByteArray QAuthenticatorPrivate::calculateResponse(const QByteArray &requestMethod, const QByteArray &path, const QString& host)
{
+#if !QT_CONFIG(sspi) && !QT_CONFIG(gssapi)
+ Q_UNUSED(host);
+#endif
QByteArray response;
- const char *methodString = 0;
+ const char* methodString = nullptr;
switch(method) {
case QAuthenticatorPrivate::None:
methodString = "";
phase = Done;
break;
case QAuthenticatorPrivate::Basic:
- methodString = "Basic ";
+ methodString = "Basic";
response = user.toLatin1() + ':' + password.toLatin1();
response = response.toBase64();
phase = Done;
break;
case QAuthenticatorPrivate::DigestMd5:
- methodString = "Digest ";
+ methodString = "Digest";
response = digestMd5Response(challenge, requestMethod, path);
phase = Done;
break;
case QAuthenticatorPrivate::Ntlm:
- methodString = "NTLM ";
+ methodString = "NTLM";
if (challenge.isEmpty()) {
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+#if QT_CONFIG(sspi) // SSPI
QByteArray phase1Token;
if (user.isEmpty()) // Only pull from system if no user was specified in authenticator
- phase1Token = qNtlmPhase1_SSPI(this);
+ phase1Token = qSspiStartup(this, method, host);
if (!phase1Token.isEmpty()) {
response = phase1Token.toBase64();
phase = Phase2;
@@ -496,10 +515,10 @@ QByteArray QAuthenticatorPrivate::calculateResponse(const QByteArray &requestMet
phase = Phase2;
}
} else {
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+#if QT_CONFIG(sspi) // SSPI
QByteArray phase3Token;
- if (ntlmWindowsHandles)
- phase3Token = qNtlmPhase3_SSPI(this, QByteArray::fromBase64(challenge));
+ if (sspiWindowsHandles)
+ phase3Token = qSspiContinue(this, method, host, QByteArray::fromBase64(challenge));
if (!phase3Token.isEmpty()) {
response = phase3Token.toBase64();
phase = Done;
@@ -512,8 +531,39 @@ QByteArray QAuthenticatorPrivate::calculateResponse(const QByteArray &requestMet
}
break;
+ case QAuthenticatorPrivate::Negotiate:
+ methodString = "Negotiate";
+ if (challenge.isEmpty()) {
+ QByteArray phase1Token;
+#if QT_CONFIG(sspi) // SSPI
+ phase1Token = qSspiStartup(this, method, host);
+#elif QT_CONFIG(gssapi) // GSSAPI
+ phase1Token = qGssapiStartup(this, host);
+#endif
+
+ if (!phase1Token.isEmpty()) {
+ response = phase1Token.toBase64();
+ phase = Phase2;
+ } else {
+ phase = Done;
+ }
+ } else {
+ QByteArray phase3Token;
+#if QT_CONFIG(sspi) // SSPI
+ phase3Token = qSspiContinue(this, method, host, QByteArray::fromBase64(challenge));
+#elif QT_CONFIG(gssapi) // GSSAPI
+ phase3Token = qGssapiContinue(this, QByteArray::fromBase64(challenge));
+#endif
+ if (!phase3Token.isEmpty()) {
+ response = phase3Token.toBase64();
+ phase = Done;
+ }
+ }
+
+ break;
}
- return QByteArray(methodString) + response;
+
+ return QByteArray::fromRawData(methodString, qstrlen(methodString)) + ' ' + response;
}
@@ -699,9 +749,10 @@ QByteArray QAuthenticatorPrivate::digestMd5Response(const QByteArray &challenge,
return credentials;
}
-// ---------------------------- Digest Md5 code ----------------------------------------
+// ---------------------------- End of Digest Md5 code ---------------------------------
+// ---------------------------- NTLM code ----------------------------------------------
/*
* NTLM message flags.
@@ -1419,156 +1470,237 @@ static QByteArray qNtlmPhase3(QAuthenticatorPrivate *ctx, const QByteArray& phas
return rc;
}
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+// ---------------------------- End of NTLM code ---------------------------------------
+
+#if QT_CONFIG(sspi) // SSPI
+// ---------------------------- SSPI code ----------------------------------------------
// See http://davenport.sourceforge.net/ntlm.html
// and libcurl http_ntlm.c
// Handle of secur32.dll
-static HMODULE securityDLLHandle = NULL;
+static HMODULE securityDLLHandle = nullptr;
// Pointer to SSPI dispatch table
-static PSecurityFunctionTable pSecurityFunctionTable = NULL;
-
+static PSecurityFunctionTable pSecurityFunctionTable = nullptr;
-static bool q_NTLM_SSPI_library_load()
+static bool q_SSPI_library_load()
{
static QBasicMutex mutex;
QMutexLocker l(&mutex);
// Initialize security interface
- if (pSecurityFunctionTable == NULL) {
+ if (pSecurityFunctionTable == nullptr) {
securityDLLHandle = LoadLibrary(L"secur32.dll");
- if (securityDLLHandle != NULL) {
+ if (securityDLLHandle != nullptr) {
INIT_SECURITY_INTERFACE pInitSecurityInterface =
reinterpret_cast<INIT_SECURITY_INTERFACE>(
reinterpret_cast<QFunctionPointer>(GetProcAddress(securityDLLHandle, "InitSecurityInterfaceW")));
- if (pInitSecurityInterface != NULL)
+ if (pInitSecurityInterface != nullptr)
pSecurityFunctionTable = pInitSecurityInterface();
}
}
- if (pSecurityFunctionTable == NULL)
+ if (pSecurityFunctionTable == nullptr)
return false;
return true;
}
-// Phase 1:
-static QByteArray qNtlmPhase1_SSPI(QAuthenticatorPrivate *ctx)
+static QByteArray qSspiStartup(QAuthenticatorPrivate *ctx, QAuthenticatorPrivate::Method method,
+ const QString& host)
{
- QByteArray result;
+ if (!q_SSPI_library_load())
+ return QByteArray();
+
+ TimeStamp expiry; // For Windows 9x compatibility of SSPI calls
- if (!q_NTLM_SSPI_library_load())
- return result;
+ if (!ctx->sspiWindowsHandles)
+ ctx->sspiWindowsHandles.reset(new QSSPIWindowsHandles);
+ memset(&ctx->sspiWindowsHandles->credHandle, 0, sizeof(CredHandle));
- // 1. The client obtains a representation of the credential set
- // for the user via the SSPI AcquireCredentialsHandle function.
- if (!ctx->ntlmWindowsHandles)
- ctx->ntlmWindowsHandles = new QNtlmWindowsHandles;
- memset(&ctx->ntlmWindowsHandles->credHandle, 0, sizeof(CredHandle));
- TimeStamp tsDummy;
+ // Acquire our credentials handle
SECURITY_STATUS secStatus = pSecurityFunctionTable->AcquireCredentialsHandle(
- NULL, (SEC_WCHAR*)L"NTLM", SECPKG_CRED_OUTBOUND, NULL, NULL,
- NULL, NULL, &ctx->ntlmWindowsHandles->credHandle, &tsDummy);
+ nullptr,
+ (SEC_WCHAR*)(method == QAuthenticatorPrivate::Negotiate ? L"Negotiate" : L"NTLM"),
+ SECPKG_CRED_OUTBOUND, nullptr, nullptr, nullptr, nullptr,
+ &ctx->sspiWindowsHandles->credHandle, &expiry
+ );
if (secStatus != SEC_E_OK) {
- delete ctx->ntlmWindowsHandles;
- ctx->ntlmWindowsHandles = 0;
- return result;
+ ctx->sspiWindowsHandles.reset(nullptr);
+ return QByteArray();
}
- // 2. The client calls the SSPI InitializeSecurityContext function
- // to obtain an authentication request token (in our case, a Type 1 message).
- // The client sends this token to the server.
- SecBufferDesc desc;
- SecBuffer buf;
- desc.ulVersion = SECBUFFER_VERSION;
- desc.cBuffers = 1;
- desc.pBuffers = &buf;
- buf.cbBuffer = 0;
- buf.BufferType = SECBUFFER_TOKEN;
- buf.pvBuffer = NULL;
- ULONG attrs;
-
- secStatus = pSecurityFunctionTable->InitializeSecurityContext(&ctx->ntlmWindowsHandles->credHandle, NULL,
- const_cast<SEC_WCHAR*>(L"") /* host */,
- ISC_REQ_ALLOCATE_MEMORY,
- 0, SECURITY_NETWORK_DREP,
- NULL, 0,
- &ctx->ntlmWindowsHandles->ctxHandle, &desc,
- &attrs, &tsDummy);
- if (secStatus == SEC_I_COMPLETE_AND_CONTINUE ||
- secStatus == SEC_I_CONTINUE_NEEDED) {
- pSecurityFunctionTable->CompleteAuthToken(&ctx->ntlmWindowsHandles->ctxHandle, &desc);
- } else if (secStatus != SEC_E_OK) {
- if ((const char*)buf.pvBuffer)
- pSecurityFunctionTable->FreeContextBuffer(buf.pvBuffer);
- pSecurityFunctionTable->FreeCredentialsHandle(&ctx->ntlmWindowsHandles->credHandle);
- delete ctx->ntlmWindowsHandles;
- ctx->ntlmWindowsHandles = 0;
- return result;
+ return qSspiContinue(ctx, method, host);
+}
+
+static QByteArray qSspiContinue(QAuthenticatorPrivate *ctx, QAuthenticatorPrivate::Method method,
+ const QString &host, const QByteArray &challenge)
+{
+ QByteArray result;
+ SecBuffer challengeBuf;
+ SecBuffer responseBuf;
+ SecBufferDesc challengeDesc;
+ SecBufferDesc responseDesc;
+ unsigned long attrs;
+ TimeStamp expiry; // For Windows 9x compatibility of SSPI calls
+
+ if (!challenge.isEmpty())
+ {
+ // Setup the challenge "input" security buffer
+ challengeDesc.ulVersion = SECBUFFER_VERSION;
+ challengeDesc.cBuffers = 1;
+ challengeDesc.pBuffers = &challengeBuf;
+ challengeBuf.BufferType = SECBUFFER_TOKEN;
+ challengeBuf.pvBuffer = (PVOID)(challenge.data());
+ challengeBuf.cbBuffer = challenge.length();
}
- result = QByteArray((const char*)buf.pvBuffer, buf.cbBuffer);
- pSecurityFunctionTable->FreeContextBuffer(buf.pvBuffer);
+ // Setup the response "output" security buffer
+ responseDesc.ulVersion = SECBUFFER_VERSION;
+ responseDesc.cBuffers = 1;
+ responseDesc.pBuffers = &responseBuf;
+ responseBuf.BufferType = SECBUFFER_TOKEN;
+ responseBuf.pvBuffer = nullptr;
+ responseBuf.cbBuffer = 0;
+
+ // Calculate target (SPN for Negotiate, empty for NTLM)
+ std::wstring targetNameW = (method == QAuthenticatorPrivate::Negotiate
+ ? QLatin1String("HTTP/") + host : QString()).toStdWString();
+
+ // Generate our challenge-response message
+ SECURITY_STATUS secStatus = pSecurityFunctionTable->InitializeSecurityContext(
+ &ctx->sspiWindowsHandles->credHandle,
+ !challenge.isEmpty() ? &ctx->sspiWindowsHandles->ctxHandle : nullptr,
+ const_cast<wchar_t*>(targetNameW.data()),
+ ISC_REQ_ALLOCATE_MEMORY,
+ 0, SECURITY_NATIVE_DREP,
+ !challenge.isEmpty() ? &challengeDesc : nullptr,
+ 0, &ctx->sspiWindowsHandles->ctxHandle,
+ &responseDesc, &attrs,
+ &expiry
+ );
+
+ if (secStatus == SEC_I_COMPLETE_NEEDED || secStatus == SEC_I_COMPLETE_AND_CONTINUE) {
+ secStatus = pSecurityFunctionTable->CompleteAuthToken(&ctx->sspiWindowsHandles->ctxHandle,
+ &responseDesc);
+ }
+
+ if (secStatus != SEC_I_COMPLETE_AND_CONTINUE && secStatus != SEC_I_CONTINUE_NEEDED) {
+ pSecurityFunctionTable->FreeCredentialsHandle(&ctx->sspiWindowsHandles->credHandle);
+ pSecurityFunctionTable->DeleteSecurityContext(&ctx->sspiWindowsHandles->ctxHandle);
+ ctx->sspiWindowsHandles.reset(nullptr);
+ }
+
+ result = QByteArray((const char*)responseBuf.pvBuffer, responseBuf.cbBuffer);
+ pSecurityFunctionTable->FreeContextBuffer(responseBuf.pvBuffer);
+
return result;
}
-// Phase 2:
-// 3. The server receives the token from the client, and uses it as input to the
-// AcceptSecurityContext SSPI function. This creates a local security context on
-// the server to represent the client, and yields an authentication response token
-// (the Type 2 message), which is sent to the client.
+// ---------------------------- End of SSPI code ---------------------------------------
+
+#elif QT_CONFIG(gssapi) // GSSAPI
+
+// ---------------------------- GSSAPI code ----------------------------------------------
+// See postgres src/interfaces/libpq/fe-auth.c
+
+// Fetch all errors of a specific type
+static void q_GSSAPI_error_int(const char *message, OM_uint32 stat, int type)
+{
+ OM_uint32 minStat, msgCtx = 0;
+ gss_buffer_desc msg;
+
+ do {
+ gss_display_status(&minStat, stat, type, GSS_C_NO_OID, &msgCtx, &msg);
+ qDebug() << message << ": " << reinterpret_cast<const char*>(msg.value);
+ gss_release_buffer(&minStat, &msg);
+ } while (msgCtx);
+}
-// Phase 3:
-static QByteArray qNtlmPhase3_SSPI(QAuthenticatorPrivate *ctx, const QByteArray& phase2data)
+// GSSAPI errors contain two parts; extract both
+static void q_GSSAPI_error(const char *message, OM_uint32 majStat, OM_uint32 minStat)
{
- // 4. The client receives the response token from the server and calls
- // InitializeSecurityContext again, passing the server's token as input.
- // This provides us with another authentication request token (the Type 3 message).
- // The return value indicates that the security context was successfully initialized;
- // the token is sent to the server.
+ // Fetch major error codes
+ q_GSSAPI_error_int(message, majStat, GSS_C_GSS_CODE);
+ // Add the minor codes as well
+ q_GSSAPI_error_int(message, minStat, GSS_C_MECH_CODE);
+}
+
+// Send initial GSS authentication token
+static QByteArray qGssapiStartup(QAuthenticatorPrivate *ctx, const QString &host)
+{
+ OM_uint32 majStat, minStat;
+
+ if (!ctx->gssApiHandles)
+ ctx->gssApiHandles.reset(new QGssApiHandles);
+
+ // Convert target name to internal form
+ QByteArray serviceName = QStringLiteral("HTTPS@%1").arg(host).toLocal8Bit();
+ gss_buffer_desc nameDesc = {static_cast<std::size_t>(serviceName.size()), serviceName.data()};
+
+ majStat = gss_import_name(&minStat, &nameDesc,
+ GSS_C_NT_HOSTBASED_SERVICE, &ctx->gssApiHandles->targetName);
+
+ if (majStat != GSS_S_COMPLETE) {
+ q_GSSAPI_error("gss_import_name error", majStat, minStat);
+ ctx->gssApiHandles.reset(nullptr);
+ return QByteArray();
+ }
+
+ // Call qGssapiContinue with GSS_C_NO_CONTEXT to get initial packet
+ ctx->gssApiHandles->gssCtx = GSS_C_NO_CONTEXT;
+ return qGssapiContinue(ctx);
+}
+
+// Continue GSS authentication with next token as needed
+static QByteArray qGssapiContinue(QAuthenticatorPrivate *ctx, const QByteArray& challenge)
+{
+ OM_uint32 majStat, minStat, ignored;
QByteArray result;
+ gss_buffer_desc inBuf = {0, nullptr}; // GSS input token
+ gss_buffer_desc outBuf; // GSS output token
- if (pSecurityFunctionTable == NULL)
- return result;
-
- SecBuffer type_2, type_3;
- SecBufferDesc type_2_desc, type_3_desc;
- ULONG attrs;
- TimeStamp tsDummy; // For Windows 9x compatibility of SPPI calls
-
- type_2_desc.ulVersion = type_3_desc.ulVersion = SECBUFFER_VERSION;
- type_2_desc.cBuffers = type_3_desc.cBuffers = 1;
- type_2_desc.pBuffers = &type_2;
- type_3_desc.pBuffers = &type_3;
-
- type_2.BufferType = SECBUFFER_TOKEN;
- type_2.pvBuffer = (PVOID)phase2data.data();
- type_2.cbBuffer = phase2data.length();
- type_3.BufferType = SECBUFFER_TOKEN;
- type_3.pvBuffer = 0;
- type_3.cbBuffer = 0;
-
- SECURITY_STATUS secStatus = pSecurityFunctionTable->InitializeSecurityContext(&ctx->ntlmWindowsHandles->credHandle,
- &ctx->ntlmWindowsHandles->ctxHandle,
- const_cast<SEC_WCHAR*>(L"") /* host */,
- ISC_REQ_ALLOCATE_MEMORY,
- 0, SECURITY_NETWORK_DREP, &type_2_desc,
- 0, &ctx->ntlmWindowsHandles->ctxHandle, &type_3_desc,
- &attrs, &tsDummy);
-
- if (secStatus == SEC_E_OK && ((const char*)type_3.pvBuffer)) {
- result = QByteArray((const char*)type_3.pvBuffer, type_3.cbBuffer);
- pSecurityFunctionTable->FreeContextBuffer(type_3.pvBuffer);
+ if (!challenge.isEmpty()) {
+ inBuf.value = const_cast<char*>(challenge.data());
+ inBuf.length = challenge.length();
}
- pSecurityFunctionTable->FreeCredentialsHandle(&ctx->ntlmWindowsHandles->credHandle);
- pSecurityFunctionTable->DeleteSecurityContext(&ctx->ntlmWindowsHandles->ctxHandle);
- delete ctx->ntlmWindowsHandles;
- ctx->ntlmWindowsHandles = 0;
+ majStat = gss_init_sec_context(&minStat,
+ GSS_C_NO_CREDENTIAL,
+ &ctx->gssApiHandles->gssCtx,
+ ctx->gssApiHandles->targetName,
+ GSS_C_NO_OID,
+ GSS_C_MUTUAL_FLAG,
+ 0,
+ GSS_C_NO_CHANNEL_BINDINGS,
+ challenge.isEmpty() ? GSS_C_NO_BUFFER : &inBuf,
+ nullptr,
+ &outBuf,
+ nullptr,
+ nullptr);
+
+ if (outBuf.length != 0)
+ result = QByteArray(reinterpret_cast<const char*>(outBuf.value), outBuf.length);
+ gss_release_buffer(&ignored, &outBuf);
+
+ if (majStat != GSS_S_COMPLETE && majStat != GSS_S_CONTINUE_NEEDED) {
+ q_GSSAPI_error("gss_init_sec_context error", majStat, minStat);
+ gss_release_name(&ignored, &ctx->gssApiHandles->targetName);
+ if (ctx->gssApiHandles->gssCtx)
+ gss_delete_sec_context(&ignored, &ctx->gssApiHandles->gssCtx, GSS_C_NO_BUFFER);
+ ctx->gssApiHandles.reset(nullptr);
+ }
+
+ if (majStat == GSS_S_COMPLETE) {
+ gss_release_name(&ignored, &ctx->gssApiHandles->targetName);
+ ctx->gssApiHandles.reset(nullptr);
+ }
return result;
}
-#endif // Q_OS_WIN && !Q_OS_WINRT
+
+// ---------------------------- End of GSSAPI code ----------------------------------------------
+
+#endif // gssapi
QT_END_NAMESPACE
diff --git a/src/network/kernel/qauthenticator_p.h b/src/network/kernel/qauthenticator_p.h
index 265cb7afe2..e201d22650 100644
--- a/src/network/kernel/qauthenticator_p.h
+++ b/src/network/kernel/qauthenticator_p.h
@@ -54,6 +54,7 @@
#include <QtNetwork/private/qtnetworkglobal_p.h>
#include <qhash.h>
#include <qbytearray.h>
+#include <qscopedpointer.h>
#include <qstring.h>
#include <qauthenticator.h>
#include <qvariant.h>
@@ -61,14 +62,16 @@
QT_BEGIN_NAMESPACE
class QHttpResponseHeader;
-#ifdef Q_OS_WIN
-class QNtlmWindowsHandles;
+#if QT_CONFIG(sspi) // SSPI
+class QSSPIWindowsHandles;
+#elif QT_CONFIG(gssapi) // GSSAPI
+class QGssApiHandles;
#endif
class Q_AUTOTEST_EXPORT QAuthenticatorPrivate
{
public:
- enum Method { None, Basic, Ntlm, DigestMd5 };
+ enum Method { None, Basic, Ntlm, DigestMd5, Negotiate };
QAuthenticatorPrivate();
~QAuthenticatorPrivate();
@@ -79,8 +82,10 @@ public:
Method method;
QString realm;
QByteArray challenge;
-#ifdef Q_OS_WIN
- QNtlmWindowsHandles *ntlmWindowsHandles;
+#if QT_CONFIG(sspi) // SSPI
+ QScopedPointer<QSSPIWindowsHandles> sspiWindowsHandles;
+#elif QT_CONFIG(gssapi) // GSSAPI
+ QScopedPointer<QGssApiHandles> gssApiHandles;
#endif
bool hasFailed; //credentials have been tried but rejected by server.
@@ -100,7 +105,7 @@ public:
QString workstation;
QString userDomain;
- QByteArray calculateResponse(const QByteArray &method, const QByteArray &path);
+ QByteArray calculateResponse(const QByteArray &method, const QByteArray &path, const QString& host);
inline static QAuthenticatorPrivate *getPrivate(QAuthenticator &auth) { return auth.d; }
inline static const QAuthenticatorPrivate *getPrivate(const QAuthenticator &auth) { return auth.d; }
diff --git a/src/network/socket/qhttpsocketengine.cpp b/src/network/socket/qhttpsocketengine.cpp
index 49ea17f9f8..6cae29193d 100644
--- a/src/network/socket/qhttpsocketengine.cpp
+++ b/src/network/socket/qhttpsocketengine.cpp
@@ -524,7 +524,7 @@ void QHttpSocketEngine::slotSocketConnected()
//qDebug() << "slotSocketConnected: priv=" << priv << (priv ? (int)priv->method : -1);
if (priv && priv->method != QAuthenticatorPrivate::None) {
d->credentialsSent = true;
- data += "Proxy-Authorization: " + priv->calculateResponse(method, path);
+ data += "Proxy-Authorization: " + priv->calculateResponse(method, path, d->proxy.hostName());
data += "\r\n";
}
data += "\r\n";
diff --git a/src/network/ssl/qsslsocket_openssl.cpp b/src/network/ssl/qsslsocket_openssl.cpp
index c48cd42360..6a8269b521 100644
--- a/src/network/ssl/qsslsocket_openssl.cpp
+++ b/src/network/ssl/qsslsocket_openssl.cpp
@@ -476,7 +476,8 @@ bool QSslSocketBackendPrivate::initSslContext()
{
Q_Q(QSslSocket);
- // If no external context was set (e.g. bei QHttpNetworkConnection) we will create a default context
+ // If no external context was set (e.g. by QHttpNetworkConnection) we will
+ // create a default context
if (!sslContextPointer) {
// create a deep copy of our configuration
QSslConfigurationPrivate *configurationCopy = new QSslConfigurationPrivate(configuration);
diff --git a/src/platformsupport/eglconvenience/qeglstreamconvenience_p.h b/src/platformsupport/eglconvenience/qeglstreamconvenience_p.h
index c3d3070210..31a79dbc6c 100644
--- a/src/platformsupport/eglconvenience/qeglstreamconvenience_p.h
+++ b/src/platformsupport/eglconvenience/qeglstreamconvenience_p.h
@@ -131,6 +131,12 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEKHRPROC) (EGLDisplay
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMEROUTPUTEXTPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLOutputLayerEXT layer);
#endif
+#ifndef EGL_EXT_stream_acquire_mode
+#define EGL_EXT_stream_acquire_mode 1
+#define EGL_CONSUMER_AUTO_ACQUIRE_EXT 0x332B
+#define EGL_RESOURCE_BUSY_EXT 0x3353
+#endif
+
#ifndef EGL_EXT_platform_device
#define EGL_PLATFORM_DEVICE_EXT 0x313F
#endif
@@ -156,6 +162,11 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREATTRIBNVPROC) (EGLDi
typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEATTRIBNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list);
#endif
+#ifndef EGL_NV_output_drm_flip_event
+#define EGL_NV_output_drm_flip_event 1
+#define EGL_DRM_FLIP_EVENT_DATA_NV 0x333E
+#endif
+
QT_BEGIN_NAMESPACE
class QEGLStreamConvenience
diff --git a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp b/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp
index 381db1ed12..40db7dbac7 100644
--- a/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp
+++ b/src/platformsupport/fontdatabases/freetype/qfontengine_ft.cpp
@@ -121,13 +121,12 @@ class QtFreetypeData
{
public:
QtFreetypeData()
- : library(0), hasPatentFreeLcdRendering(false)
+ : library(0)
{ }
~QtFreetypeData();
FT_Library library;
QHash<QFontEngine::FaceId, QFreetypeFace *> faces;
- bool hasPatentFreeLcdRendering;
};
QtFreetypeData::~QtFreetypeData()
@@ -153,11 +152,6 @@ QtFreetypeData *qt_getFreetypeData()
FT_Bool no_darkening = false;
FT_Property_Set(freetypeData->library, "cff", "no-stem-darkening", &no_darkening);
#endif
- // FreeType has since 2.8.1 a patent free alternative to LCD-filtering.
- FT_Int amajor, aminor = 0, apatch = 0;
- FT_Library_Version(freetypeData->library, &amajor, &aminor, &apatch);
- if (QT_VERSION_CHECK(amajor, aminor, apatch) >= QT_VERSION_CHECK(2, 8, 1))
- freetypeData->hasPatentFreeLcdRendering = true;
}
return freetypeData;
}
@@ -561,26 +555,7 @@ QFontEngineFT::Glyph::~Glyph()
delete [] data;
}
-struct LcdFilterDummy
-{
- static inline void filterPixel(uchar &, uchar &, uchar &)
- {}
-};
-
-struct LcdFilterLegacy
-{
- static inline void filterPixel(uchar &red, uchar &green, uchar &blue)
- {
- uint r = red, g = green, b = blue;
- // intra-pixel filter used by the legacy filter (adopted from _ft_lcd_filter_legacy)
- red = (r * uint(65538 * 9/13) + g * uint(65538 * 1/6) + b * uint(65538 * 1/13)) / 65536;
- green = (r * uint(65538 * 3/13) + g * uint(65538 * 4/6) + b * uint(65538 * 3/13)) / 65536;
- blue = (r * uint(65538 * 1/13) + g * uint(65538 * 1/6) + b * uint(65538 * 9/13)) / 65536;
- }
-};
-
-template <typename LcdFilter>
-static void convertRGBToARGB_helper(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr)
+static inline void convertRGBToARGB(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr)
{
const int offs = bgr ? -1 : 1;
const int w = width * 3;
@@ -590,7 +565,6 @@ static void convertRGBToARGB_helper(const uchar *src, uint *dst, int width, int
uchar red = src[x + 1 - offs];
uchar green = src[x + 1];
uchar blue = src[x + 1 + offs];
- LcdFilter::filterPixel(red, green, blue);
*dd++ = (0xFFU << 24) | (red << 16) | (green << 8) | blue;
}
dst += width;
@@ -598,16 +572,7 @@ static void convertRGBToARGB_helper(const uchar *src, uint *dst, int width, int
}
}
-static inline void convertRGBToARGB(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr, bool legacyFilter)
-{
- if (!legacyFilter)
- convertRGBToARGB_helper<LcdFilterDummy>(src, dst, width, height, src_pitch, bgr);
- else
- convertRGBToARGB_helper<LcdFilterLegacy>(src, dst, width, height, src_pitch, bgr);
-}
-
-template <typename LcdFilter>
-static void convertRGBToARGB_V_helper(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr)
+static inline void convertRGBToARGB_V(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr)
{
const int offs = bgr ? -src_pitch : src_pitch;
while (height--) {
@@ -615,54 +580,12 @@ static void convertRGBToARGB_V_helper(const uchar *src, uint *dst, int width, in
uchar red = src[x + src_pitch - offs];
uchar green = src[x + src_pitch];
uchar blue = src[x + src_pitch + offs];
- LcdFilter::filterPixel(red, green, blue);
*dst++ = (0XFFU << 24) | (red << 16) | (green << 8) | blue;
}
src += 3*src_pitch;
}
}
-static inline void convertRGBToARGB_V(const uchar *src, uint *dst, int width, int height, int src_pitch, bool bgr, bool legacyFilter)
-{
- if (!legacyFilter)
- convertRGBToARGB_V_helper<LcdFilterDummy>(src, dst, width, height, src_pitch, bgr);
- else
- convertRGBToARGB_V_helper<LcdFilterLegacy>(src, dst, width, height, src_pitch, bgr);
-}
-
-static inline void convertGRAYToARGB(const uchar *src, uint *dst, int width, int height, int src_pitch)
-{
- while (height--) {
- const uchar *p = src;
- const uchar * const e = p + width;
- while (p < e) {
- uchar gray = *p++;
- *dst++ = (0xFFU << 24) | (gray << 16) | (gray << 8) | gray;
- }
- src += src_pitch;
- }
-}
-
-static void convoluteBitmap(const uchar *src, uchar *dst, int width, int height, int pitch)
-{
- // convolute the bitmap with a triangle filter to get rid of color fringes
- // If we take account for a gamma value of 2, we end up with
- // weights of 1, 4, 9, 4, 1. We use an approximation of 1, 3, 8, 3, 1 here,
- // as this nicely sums up to 16 :)
- int h = height;
- while (h--) {
- dst[0] = dst[1] = 0;
- //
- for (int x = 2; x < width - 2; ++x) {
- uint sum = src[x-2] + 3*src[x-1] + 8*src[x] + 3*src[x+1] + src[x+2];
- dst[x] = (uchar) (sum >> 4);
- }
- dst[width - 2] = dst[width - 1] = 0;
- src += pitch;
- dst += pitch;
- }
-}
-
static QFontEngine::SubpixelAntialiasingType subpixelAntialiasingTypeHint()
{
static int type = -1;
@@ -1153,196 +1076,97 @@ QFontEngineFT::Glyph *QFontEngineFT::loadGlyph(QGlyphSet *set, uint glyph,
int glyph_buffer_size = 0;
QScopedArrayPointer<uchar> glyph_buffer;
- bool useFreetypeRenderGlyph = false;
- if (slot->format == FT_GLYPH_FORMAT_OUTLINE && (hsubpixel || vfactor != 1)) {
- err = FT_Library_SetLcdFilter(slot->library, (FT_LcdFilter)lcdFilterType);
- // We use FT_Render_Glyph if freetype has support for lcd-filtering
- // or is version 2.8.1 or higher and can do without.
- if (err == FT_Err_Ok || qt_getFreetypeData()->hasPatentFreeLcdRendering)
- useFreetypeRenderGlyph = true;
+ FT_Render_Mode renderMode = (default_hint_style == HintLight) ? FT_RENDER_MODE_LIGHT : FT_RENDER_MODE_NORMAL;
+ switch (format) {
+ case Format_Mono:
+ renderMode = FT_RENDER_MODE_MONO;
+ break;
+ case Format_A32:
+ Q_ASSERT(hsubpixel || vfactor != 1);
+ renderMode = hsubpixel ? FT_RENDER_MODE_LCD : FT_RENDER_MODE_LCD_V;
+ break;
+ case Format_A8:
+ case Format_ARGB:
+ break;
+ default:
+ Q_UNREACHABLE();
}
- if (useFreetypeRenderGlyph) {
- err = FT_Render_Glyph(slot, hsubpixel ? FT_RENDER_MODE_LCD : FT_RENDER_MODE_LCD_V);
-
- if (err != FT_Err_Ok)
- qWarning("render glyph failed err=%x face=%p, glyph=%d", err, face, glyph);
-
- FT_Library_SetLcdFilter(slot->library, FT_LCD_FILTER_NONE);
+ FT_Library_SetLcdFilter(slot->library, (FT_LcdFilter)lcdFilterType);
- info.height = slot->bitmap.rows / vfactor;
- info.width = hsubpixel ? slot->bitmap.width / 3 : slot->bitmap.width;
- info.x = slot->bitmap_left;
- info.y = slot->bitmap_top;
+ err = FT_Render_Glyph(slot, renderMode);
+ if (err != FT_Err_Ok)
+ qWarning("render glyph failed err=%x face=%p, glyph=%d", err, face, glyph);
- glyph_buffer_size = info.width * info.height * 4;
- glyph_buffer.reset(new uchar[glyph_buffer_size]);
+ FT_Library_SetLcdFilter(slot->library, FT_LCD_FILTER_NONE);
- if (hsubpixel)
- convertRGBToARGB(slot->bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, slot->bitmap.pitch, subpixelType != Subpixel_RGB, false);
- else if (vfactor != 1)
- convertRGBToARGB_V(slot->bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, slot->bitmap.pitch, subpixelType != Subpixel_VRGB, false);
- } else {
- int left = slot->metrics.horiBearingX;
- int right = slot->metrics.horiBearingX + slot->metrics.width;
- int top = slot->metrics.horiBearingY;
- int bottom = slot->metrics.horiBearingY - slot->metrics.height;
- if (transform && slot->format != FT_GLYPH_FORMAT_BITMAP)
- transformBoundingBox(&left, &top, &right, &bottom, &matrix);
- left = FLOOR(left);
- right = CEIL(right);
- bottom = FLOOR(bottom);
- top = CEIL(top);
-
- int hpixels = TRUNC(right - left);
- // subpixel position requires one more pixel
- if (subPixelPosition > 0 && format != Format_Mono)
- hpixels++;
-
- if (hsubpixel)
- hpixels = hpixels*3 + 8;
- info.width = hpixels;
- info.height = TRUNC(top - bottom);
- info.x = TRUNC(left);
- info.y = TRUNC(top);
- if (hsubpixel) {
- info.width /= 3;
- info.x -= 1;
- }
-
- // If any of the metrics are too large to fit, don't cache them
- if (areMetricsTooLarge(info))
- return 0;
+ info.height = slot->bitmap.rows;
+ info.width = slot->bitmap.width;
+ info.x = slot->bitmap_left;
+ info.y = slot->bitmap_top;
+ if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_LCD)
+ info.width = info.width / 3;
+ if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_LCD_V)
+ info.height = info.height / vfactor;
int pitch = (format == Format_Mono ? ((info.width + 31) & ~31) >> 3 :
(format == Format_A8 ? (info.width + 3) & ~3 : info.width * 4));
- if (glyph_buffer_size < pitch * info.height) {
- glyph_buffer_size = pitch * info.height;
- glyph_buffer.reset(new uchar[glyph_buffer_size]);
- memset(glyph_buffer.data(), 0, glyph_buffer_size);
- }
- if (slot->format == FT_GLYPH_FORMAT_OUTLINE) {
- FT_Bitmap bitmap;
- bitmap.rows = info.height*vfactor;
- bitmap.width = hpixels;
- bitmap.pitch = format == Format_Mono ? (((info.width + 31) & ~31) >> 3) : ((bitmap.width + 3) & ~3);
- int bitmap_buffer_size = bitmap.rows * bitmap.pitch;
- if (!hsubpixel && vfactor == 1 && format != Format_A32) {
- Q_ASSERT(glyph_buffer_size <= bitmap_buffer_size);
- bitmap.buffer = glyph_buffer.data();
- } else {
- bitmap.buffer = new uchar[bitmap_buffer_size];
- memset(bitmap.buffer, 0, bitmap_buffer_size);
- }
- bitmap.pixel_mode = format == Format_Mono ? FT_PIXEL_MODE_MONO : FT_PIXEL_MODE_GRAY;
- FT_Matrix matrix;
- matrix.xx = (hsubpixel ? 3 : 1) << 16;
- matrix.yy = vfactor << 16;
- matrix.yx = matrix.xy = 0;
-
- FT_Outline_Transform(&slot->outline, &matrix);
- FT_Outline_Translate (&slot->outline, (hsubpixel ? -3*left +(4<<6) : -left), -bottom*vfactor);
- FT_Outline_Get_Bitmap(slot->library, &slot->outline, &bitmap);
- if (hsubpixel) {
- Q_ASSERT (bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
- Q_ASSERT(antialias);
- uchar *convoluted = new uchar[bitmap_buffer_size];
- bool useLegacyLcdFilter = false;
- useLegacyLcdFilter = (lcdFilterType == FT_LCD_FILTER_LEGACY);
- uchar *buffer = bitmap.buffer;
- if (!useLegacyLcdFilter) {
- convoluteBitmap(bitmap.buffer, convoluted, bitmap.width, info.height, bitmap.pitch);
- buffer = convoluted;
- }
- convertRGBToARGB(buffer + 1, (uint *)glyph_buffer.data(), info.width, info.height, bitmap.pitch, subpixelType != Subpixel_RGB, useLegacyLcdFilter);
- delete [] convoluted;
- } else if (vfactor != 1) {
- convertRGBToARGB_V(bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, bitmap.pitch, subpixelType != Subpixel_VRGB, true);
- } else if (format == Format_A32 && bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
- convertGRAYToARGB(bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, bitmap.pitch);
- }
+ glyph_buffer_size = info.height * pitch;
+ glyph_buffer.reset(new uchar[glyph_buffer_size]);
- if (bitmap.buffer != glyph_buffer.data())
- delete [] bitmap.buffer;
- } else if (slot->format == FT_GLYPH_FORMAT_BITMAP) {
-#if ((FREETYPE_MAJOR*10000 + FREETYPE_MINOR*100) >= 20500)
- Q_ASSERT(slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO || slot->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA);
-#else
- Q_ASSERT(slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO);
-#endif
+ if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
+ Q_ASSERT(format == Format_Mono);
uchar *src = slot->bitmap.buffer;
uchar *dst = glyph_buffer.data();
int h = slot->bitmap.rows;
- if (format == Format_Mono) {
- int bytes = ((info.width + 7) & ~7) >> 3;
- while (h--) {
- memcpy (dst, src, bytes);
- dst += pitch;
- src += slot->bitmap.pitch;
- }
- } else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
- if (hsubpixel) {
- while (h--) {
- uint *dd = (uint *)dst;
- *dd++ = 0;
- for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++) {
- uint a = ((src[x >> 3] & (0x80 >> (x & 7))) ? 0xffffff : 0x000000);
- *dd++ = a;
- }
- *dd++ = 0;
- dst += pitch;
- src += slot->bitmap.pitch;
- }
- } else if (vfactor != 1) {
- while (h--) {
- uint *dd = (uint *)dst;
- for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++) {
- uint a = ((src[x >> 3] & (0x80 >> (x & 7))) ? 0xffffff : 0x000000);
- *dd++ = a;
- }
- dst += pitch;
- src += slot->bitmap.pitch;
- }
- } else {
- while (h--) {
- for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++) {
- unsigned char a = ((src[x >> 3] & (0x80 >> (x & 7))) ? 0xff : 0x00);
- dst[x] = a;
- }
- dst += pitch;
- src += slot->bitmap.pitch;
- }
- }
+
+ int bytes = ((info.width + 7) & ~7) >> 3;
+ while (h--) {
+ memcpy (dst, src, bytes);
+ dst += pitch;
+ src += slot->bitmap.pitch;
}
-#if ((FREETYPE_MAJOR*10000 + FREETYPE_MINOR*100) >= 20500)
- else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA)
- {
- while (h--) {
+ } else if (slot->bitmap.pixel_mode == 7 /*FT_PIXEL_MODE_BGRA*/) {
+ Q_ASSERT(format == Format_ARGB);
+ uchar *src = slot->bitmap.buffer;
+ uchar *dst = glyph_buffer.data();
+ int h = slot->bitmap.rows;
+ while (h--) {
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
- const quint32 *srcPixel = (const quint32 *)src;
- quint32 *dstPixel = (quint32 *)dst;
- for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++, srcPixel++, dstPixel++) {
- const quint32 pixel = *srcPixel;
- *dstPixel = qbswap(pixel);
- }
+ const quint32 *srcPixel = (const quint32 *)src;
+ quint32 *dstPixel = (quint32 *)dst;
+ for (int x = 0; x < static_cast<int>(slot->bitmap.width); x++, srcPixel++, dstPixel++) {
+ const quint32 pixel = *srcPixel;
+ *dstPixel = qbswap(pixel);
+ }
#else
- memcpy(dst, src, slot->bitmap.width * 4);
+ memcpy(dst, src, slot->bitmap.width * 4);
#endif
- dst += slot->bitmap.pitch;
- src += slot->bitmap.pitch;
- }
- info.width = info.linearAdvance = info.xOff = slot->bitmap.width;
- info.height = slot->bitmap.rows;
- info.x = slot->bitmap_left;
- info.y = slot->bitmap_top;
+ dst += slot->bitmap.pitch;
+ src += slot->bitmap.pitch;
}
-#endif
+ info.linearAdvance = info.xOff = slot->bitmap.width;
+ } else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
+ Q_ASSERT(format == Format_A8);
+ uchar *src = slot->bitmap.buffer;
+ uchar *dst = glyph_buffer.data();
+ int h = slot->bitmap.rows;
+ int bytes = info.width;
+ while (h--) {
+ memcpy (dst, src, bytes);
+ dst += pitch;
+ src += slot->bitmap.pitch;
+ }
+ } else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_LCD) {
+ Q_ASSERT(format == Format_A32);
+ convertRGBToARGB(slot->bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, slot->bitmap.pitch, subpixelType != Subpixel_RGB);
+ } else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_LCD_V) {
+ Q_ASSERT(format == Format_A32);
+ convertRGBToARGB_V(slot->bitmap.buffer, (uint *)glyph_buffer.data(), info.width, info.height, slot->bitmap.pitch, subpixelType != Subpixel_VRGB);
} else {
- qWarning("QFontEngine: Glyph neither outline nor bitmap format=%d", slot->format);
+ qWarning("QFontEngine: Glyph rendered in unknown pixel_mode=%d", slot->bitmap.pixel_mode);
return 0;
}
- }
-
if (!g) {
g = new Glyph;
diff --git a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp b/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
index 1003812767..7b3f9b624a 100644
--- a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
+++ b/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
@@ -172,15 +172,9 @@ QStringList QGenericUnixTheme::xdgIconThemePaths()
if (homeIconDir.isDir())
paths.prepend(homeIconDir.absoluteFilePath());
- QString xdgDirString = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
- if (xdgDirString.isEmpty())
- xdgDirString = QLatin1String("/usr/local/share/:/usr/share/");
- const auto xdgDirs = xdgDirString.splitRef(QLatin1Char(':'));
- for (const QStringRef &xdgDir : xdgDirs) {
- const QFileInfo xdgIconsDir(xdgDir + QLatin1String("/icons"));
- if (xdgIconsDir.isDir())
- paths.append(xdgIconsDir.absoluteFilePath());
- }
+ paths.append(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
+ QStringLiteral("icons"),
+ QStandardPaths::LocateDirectory));
return paths;
}
diff --git a/src/plugins/imageformats/jpeg/qjpeghandler.cpp b/src/plugins/imageformats/jpeg/qjpeghandler.cpp
index 54fe857908..9d5ccc8a3d 100644
--- a/src/plugins/imageformats/jpeg/qjpeghandler.cpp
+++ b/src/plugins/imageformats/jpeg/qjpeghandler.cpp
@@ -40,10 +40,14 @@
#include "qjpeghandler_p.h"
#include <qimage.h>
+#include <qcolorspace.h>
+#include <qcolortransform.h>
+#include <qdebug.h>
#include <qvariant.h>
#include <qvector.h>
#include <qbuffer.h>
#include <qmath.h>
+#include <private/qicc_p.h>
#include <private/qsimd_p.h>
#include <private/qimage_p.h> // for qt_getImageText
@@ -725,6 +729,7 @@ public:
QRect clipRect;
QString description;
QStringList readTexts;
+ QByteArray iccProfile;
struct jpeg_decompress_struct info;
struct my_jpeg_source_mgr * iod_src;
@@ -887,6 +892,7 @@ bool QJpegHandlerPrivate::readJpegHeader(QIODevice *device)
if (!setjmp(err.setjmp_buffer)) {
jpeg_save_markers(&info, JPEG_COM, 0xFFFF);
jpeg_save_markers(&info, JPEG_APP0 + 1, 0xFFFF); // Exif uses APP1 marker
+ jpeg_save_markers(&info, JPEG_APP0 + 2, 0xFFFF); // ICC uses APP2 marker
(void) jpeg_read_header(&info, TRUE);
@@ -919,6 +925,10 @@ bool QJpegHandlerPrivate::readJpegHeader(QIODevice *device)
readTexts.append(value);
} else if (marker->marker == JPEG_APP0 + 1) {
exifData.append((const char*)marker->data, marker->data_length);
+ } else if (marker->marker == JPEG_APP0 + 2) {
+ if (marker->data_length > 128 + 4 + 14 && strcmp((const char *)marker->data, "ICC_PROFILE") == 0) {
+ iccProfile.append((const char*)marker->data + 14, marker->data_length - 14);
+ }
}
}
@@ -954,6 +964,9 @@ bool QJpegHandlerPrivate::read(QImage *image)
for (int i = 0; i < readTexts.size()-1; i+=2)
image->setText(readTexts.at(i), readTexts.at(i+1));
+ if (!iccProfile.isEmpty())
+ image->setColorSpace(QColorSpace::fromIccProfile(iccProfile));
+
state = ReadingEnd;
return true;
}
@@ -962,7 +975,6 @@ bool QJpegHandlerPrivate::read(QImage *image)
}
return false;
-
}
Q_GUI_EXPORT void QT_FASTCALL qt_convert_rgb888_to_rgb32_neon(quint32 *dst, const uchar *src, int len);
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp
index ab39af6b80..9f4c9f5703 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.cpp
@@ -114,14 +114,18 @@ public:
: QEglFSWindow(w)
, m_integration(integration)
, m_egl_stream(EGL_NO_STREAM_KHR)
+ , m_framePending(false)
{ }
void invalidateSurface() override;
void resetSurface() override;
+ void flip();
+ static void pageFlipHandler(int fd, unsigned int sequence, unsigned int tv_sec, unsigned int tv_usec, void *user_data);
const QEglFSKmsEglDeviceIntegration *m_integration;
EGLStreamKHR m_egl_stream;
EGLint m_latency;
+ bool m_framePending;
};
void QEglFSKmsEglDeviceWindow::invalidateSurface()
@@ -142,6 +146,9 @@ void QEglFSKmsEglDeviceWindow::resetSurface()
streamAttribs[streamAttribCount++] = EGL_STREAM_FIFO_LENGTH_KHR;
streamAttribs[streamAttribCount++] = fifoLength;
}
+
+ streamAttribs[streamAttribCount++] = EGL_CONSUMER_AUTO_ACQUIRE_EXT;
+ streamAttribs[streamAttribCount++] = EGL_FALSE;
streamAttribs[streamAttribCount++] = EGL_NONE;
m_egl_stream = m_integration->m_funcs->create_stream(display, streamAttribs);
@@ -239,6 +246,49 @@ void QEglFSKmsEglDeviceWindow::resetSurface()
qCDebug(qLcEglfsKmsDebug, "Created stream producer surface %p", m_surface);
}
+void QEglFSKmsEglDeviceWindow::flip()
+{
+ EGLDisplay display = screen()->display();
+
+ EGLAttrib acquire_attribs[3] = { EGL_NONE };
+
+ acquire_attribs[0] = EGL_DRM_FLIP_EVENT_DATA_NV;
+ acquire_attribs[1] = (EGLAttrib)this;
+ acquire_attribs[2] = EGL_NONE;
+
+ if (m_egl_stream != EGL_NO_STREAM_KHR)
+ if (!m_integration->m_funcs->acquire_stream_attrib_nv(display, m_egl_stream, acquire_attribs))
+ qWarning("eglStreamConsumerAcquireAttribNV failed: eglError: %x", eglGetError());
+
+ m_framePending = true;
+
+ while (m_framePending) {
+ drmEventContext drmEvent;
+ memset(&drmEvent, 0, sizeof(drmEvent));
+ drmEvent.version = 3;
+ drmEvent.vblank_handler = nullptr;
+ drmEvent.page_flip_handler = pageFlipHandler;
+ drmHandleEvent(m_integration->m_device->fd(), &drmEvent);
+ }
+}
+
+void QEglFSKmsEglDeviceWindow::pageFlipHandler(int fd, unsigned int sequence, unsigned int tv_sec, unsigned int tv_usec, void *user_data)
+{
+ Q_UNUSED(fd);
+ Q_UNUSED(sequence);
+ Q_UNUSED(tv_sec);
+ Q_UNUSED(tv_usec);
+
+ QEglFSKmsEglDeviceWindow *window = static_cast<QEglFSKmsEglDeviceWindow*>(user_data);
+ window->m_framePending = false;
+}
+
+void QEglFSKmsEglDeviceIntegration::presentBuffer(QPlatformSurface *surface)
+{
+ QEglFSKmsEglDeviceWindow *eglWindow = static_cast<QEglFSKmsEglDeviceWindow*>(surface);
+ eglWindow->flip();
+}
+
QEglFSWindow *QEglFSKmsEglDeviceIntegration::createWindow(QWindow *window) const
{
QEglFSKmsEglDeviceWindow *eglWindow = new QEglFSKmsEglDeviceWindow(window, this);
diff --git a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h
index 5819d82ebf..a5697ec831 100644
--- a/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h
+++ b/src/plugins/platforms/eglfs/deviceintegration/eglfs_kms_egldevice/qeglfskmsegldeviceintegration.h
@@ -62,6 +62,8 @@ public:
bool supportsPBuffers() const override;
QEglFSWindow *createWindow(QWindow *window) const override;
+ void presentBuffer(QPlatformSurface *surface) override;
+
EGLDeviceEXT eglDevice() const { return m_egl_device; }
protected:
diff --git a/src/plugins/platforms/mirclient/mirclient.json b/src/plugins/platforms/mirclient/mirclient.json
deleted file mode 100644
index c31558a2f1..0000000000
--- a/src/plugins/platforms/mirclient/mirclient.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "Keys": [ "mirclient" ]
-}
diff --git a/src/plugins/platforms/mirclient/mirclient.pro b/src/plugins/platforms/mirclient/mirclient.pro
deleted file mode 100644
index d9eb069200..0000000000
--- a/src/plugins/platforms/mirclient/mirclient.pro
+++ /dev/null
@@ -1,61 +0,0 @@
-TARGET = qmirclient
-
-QT += \
- core-private gui-private dbus \
- theme_support-private eventdispatcher_support-private \
- fontdatabase_support-private egl_support-private
-
-qtHaveModule(linuxaccessibility_support-private): \
- QT += linuxaccessibility_support-private
-
-DEFINES += MESA_EGL_NO_X11_HEADERS
-# CONFIG += c++11 # only enables C++0x
-QMAKE_CXXFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -Werror -Wall
-QMAKE_LFLAGS += -std=c++11 -Wl,-no-undefined
-
-QMAKE_USE_PRIVATE += mirclient
-
-SOURCES = \
- qmirclientappstatecontroller.cpp \
- qmirclientbackingstore.cpp \
- qmirclientclipboard.cpp \
- qmirclientcursor.cpp \
- qmirclientdebugextension.cpp \
- qmirclientdesktopwindow.cpp \
- qmirclientglcontext.cpp \
- qmirclientinput.cpp \
- qmirclientintegration.cpp \
- qmirclientnativeinterface.cpp \
- qmirclientplatformservices.cpp \
- qmirclientplugin.cpp \
- qmirclientscreen.cpp \
- qmirclientscreenobserver.cpp \
- qmirclienttheme.cpp \
- qmirclientwindow.cpp
-
-HEADERS = \
- qmirclientappstatecontroller.h \
- qmirclientbackingstore.h \
- qmirclientclipboard.h \
- qmirclientcursor.h \
- qmirclientdebugextension.h \
- qmirclientdesktopwindow.h \
- qmirclientglcontext.h \
- qmirclientinput.h \
- qmirclientintegration.h \
- qmirclientlogging.h \
- qmirclientnativeinterface.h \
- qmirclientorientationchangeevent_p.h \
- qmirclientplatformservices.h \
- qmirclientplugin.h \
- qmirclientscreen.h \
- qmirclientscreenobserver.h \
- qmirclienttheme.h \
- qmirclientwindow.h
-
-QMAKE_USE_PRIVATE += xkbcommon
-
-PLUGIN_TYPE = platforms
-PLUGIN_CLASS_NAME = MirServerIntegrationPlugin
-!equals(TARGET, $$QT_DEFAULT_QPA_PLUGIN): PLUGIN_EXTENDS = -
-load(qt_plugin)
diff --git a/src/plugins/platforms/mirclient/qmirclientappstatecontroller.cpp b/src/plugins/platforms/mirclient/qmirclientappstatecontroller.cpp
deleted file mode 100644
index 69fc9b7aa7..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientappstatecontroller.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientappstatecontroller.h"
-
-#include <qpa/qwindowsysteminterface.h>
-
-/*
- * QMirClientAppStateController - updates Qt's QApplication::applicationState property.
- *
- * Tries to avoid active-inactive-active invocations using a timer. The rapid state
- * change can confuse some applications.
- */
-
-QMirClientAppStateController::QMirClientAppStateController()
- : m_suspended(false)
- , m_lastActive(true)
-{
- m_inactiveTimer.setSingleShot(true);
- m_inactiveTimer.setInterval(10);
- QObject::connect(&m_inactiveTimer, &QTimer::timeout, []()
- {
- QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationInactive);
- });
-}
-
-void QMirClientAppStateController::setSuspended()
-{
- m_inactiveTimer.stop();
- if (!m_suspended) {
- m_suspended = true;
-
- QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationSuspended);
- }
-}
-
-void QMirClientAppStateController::setResumed()
-{
- m_inactiveTimer.stop();
- if (m_suspended) {
- m_suspended = false;
-
- if (m_lastActive) {
- QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationActive);
- } else {
- QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationInactive);
- }
- }
-}
-
-void QMirClientAppStateController::setWindowFocused(bool focused)
-{
- if (m_suspended) {
- return;
- }
-
- if (focused) {
- m_inactiveTimer.stop();
- QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationActive);
- } else {
- m_inactiveTimer.start();
- }
-
- m_lastActive = focused;
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientappstatecontroller.h b/src/plugins/platforms/mirclient/qmirclientappstatecontroller.h
deleted file mode 100644
index b3aa0022d9..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientappstatecontroller.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTAPPSTATECONTROLLER_H
-#define QMIRCLIENTAPPSTATECONTROLLER_H
-
-#include <QTimer>
-
-class QMirClientAppStateController
-{
-public:
- QMirClientAppStateController();
-
- void setSuspended();
- void setResumed();
-
- void setWindowFocused(bool focused);
-
-private:
- bool m_suspended;
- bool m_lastActive;
- QTimer m_inactiveTimer;
-};
-
-#endif // QMIRCLIENTAPPSTATECONTROLLER_H
diff --git a/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp b/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp
deleted file mode 100644
index 51363619d9..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientbackingstore.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientbackingstore.h"
-#include "qmirclientlogging.h"
-#include <QtGui/QOpenGLContext>
-#include <QtGui/QOpenGLTexture>
-#include <QtGui/QMatrix4x4>
-#include <QtGui/qopengltextureblitter.h>
-#include <QtGui/qopenglfunctions.h>
-
-QMirClientBackingStore::QMirClientBackingStore(QWindow* window)
- : QPlatformBackingStore(window)
- , mContext(new QOpenGLContext)
- , mTexture(new QOpenGLTexture(QOpenGLTexture::Target2D))
- , mBlitter(new QOpenGLTextureBlitter)
-{
- mContext->setFormat(window->requestedFormat());
- mContext->setScreen(window->screen());
- mContext->create();
-
- window->setSurfaceType(QSurface::OpenGLSurface);
-}
-
-QMirClientBackingStore::~QMirClientBackingStore()
-{
- mContext->makeCurrent(window()); // needed as QOpenGLTexture destructor assumes current context
-}
-
-void QMirClientBackingStore::flush(QWindow* window, const QRegion& region, const QPoint& offset)
-{
- Q_UNUSED(region);
- Q_UNUSED(offset);
- mContext->makeCurrent(window);
- glViewport(0, 0, window->width(), window->height());
-
- updateTexture();
-
- if (!mBlitter->isCreated())
- mBlitter->create();
-
- mBlitter->bind();
- mBlitter->blit(mTexture->textureId(), QMatrix4x4(), QOpenGLTextureBlitter::OriginTopLeft);
- mBlitter->release();
-
- mContext->swapBuffers(window);
-}
-
-void QMirClientBackingStore::updateTexture()
-{
- if (mDirty.isNull())
- return;
-
- if (!mTexture->isCreated()) {
- mTexture->setMinificationFilter(QOpenGLTexture::Nearest);
- mTexture->setMagnificationFilter(QOpenGLTexture::Nearest);
- mTexture->setWrapMode(QOpenGLTexture::ClampToEdge);
- mTexture->setData(mImage, QOpenGLTexture::DontGenerateMipMaps);
- mTexture->create();
- }
- mTexture->bind();
-
- QRegion fixed;
- QRect imageRect = mImage.rect();
-
- for (const QRect &rect : mDirty) {
- // intersect with image rect to be sure
- QRect r = imageRect & rect;
-
- // if the rect is wide enough it is cheaper to just extend it instead of doing an image copy
- if (r.width() >= imageRect.width() / 2) {
- r.setX(0);
- r.setWidth(imageRect.width());
- }
-
- fixed |= r;
- }
-
- for (const QRect &rect : fixed) {
- // if the sub-rect is full-width we can pass the image data directly to
- // OpenGL instead of copying, since there is no gap between scanlines
- if (rect.width() == imageRect.width()) {
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
- mImage.constScanLine(rect.y()));
- } else {
- glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
- mImage.copy(rect).constBits());
- }
- }
- /* End of code taken from QEGLPlatformBackingStore */
-
- mDirty = QRegion();
-}
-
-
-void QMirClientBackingStore::beginPaint(const QRegion& region)
-{
- mDirty |= region;
-}
-
-void QMirClientBackingStore::resize(const QSize& size, const QRegion& /*staticContents*/)
-{
- mImage = QImage(size, QImage::Format_RGBA8888);
-
- mContext->makeCurrent(window());
-
- if (mTexture->isCreated())
- mTexture->destroy();
-}
-
-QPaintDevice* QMirClientBackingStore::paintDevice()
-{
- return &mImage;
-}
-
-QImage QMirClientBackingStore::toImage() const
-{
- // used by QPlatformBackingStore::composeAndFlush
- return mImage;
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientclipboard.cpp b/src/plugins/platforms/mirclient/qmirclientclipboard.cpp
deleted file mode 100644
index b9fc9b3b42..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientclipboard.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientclipboard.h"
-#include "qmirclientlogging.h"
-#include "qmirclientwindow.h"
-
-#include <QDBusPendingCallWatcher>
-#include <QGuiApplication>
-#include <QSignalBlocker>
-#include <QtCore/QMimeData>
-#include <QtCore/QStringList>
-
-// content-hub
-#include <com/ubuntu/content/hub.h>
-
-// get this cumbersome nested namespace out of the way
-using namespace com::ubuntu::content;
-
-QMirClientClipboard::QMirClientClipboard()
- : mMimeData(new QMimeData)
- , mContentHub(Hub::Client::instance())
-{
- connect(mContentHub, &Hub::pasteboardChanged, this, [this]() {
- if (mClipboardState == QMirClientClipboard::SyncedClipboard) {
- mClipboardState = QMirClientClipboard::OutdatedClipboard;
- emitChanged(QClipboard::Clipboard);
- }
- });
-
- connect(qGuiApp, &QGuiApplication::applicationStateChanged,
- this, &QMirClientClipboard::onApplicationStateChanged);
-
- requestMimeData();
-}
-
-QMirClientClipboard::~QMirClientClipboard()
-{
- delete mMimeData;
-}
-
-QMimeData* QMirClientClipboard::mimeData(QClipboard::Mode mode)
-{
- if (mode != QClipboard::Clipboard)
- return nullptr;
-
- // Blocks dataChanged() signal from being emitted. Makes no sense to emit it from
- // inside the data getter.
- const QSignalBlocker blocker(this);
-
- if (mClipboardState == OutdatedClipboard) {
- updateMimeData();
- } else if (mClipboardState == SyncingClipboard) {
- mPasteReply->waitForFinished();
- }
-
- return mMimeData;
-}
-
-void QMirClientClipboard::setMimeData(QMimeData* mimeData, QClipboard::Mode mode)
-{
- QWindow *focusWindow = QGuiApplication::focusWindow();
- if (focusWindow && mode == QClipboard::Clipboard && mimeData != nullptr) {
- QString surfaceId = static_cast<QMirClientWindow*>(focusWindow->handle())->persistentSurfaceId();
-
- QDBusPendingCall reply = mContentHub->createPaste(surfaceId, *mimeData);
-
- // Don't care whether it succeeded
- QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
- connect(watcher, &QDBusPendingCallWatcher::finished,
- watcher, &QObject::deleteLater);
-
- mMimeData = mimeData;
- mClipboardState = SyncedClipboard;
- emitChanged(QClipboard::Clipboard);
- }
-}
-
-bool QMirClientClipboard::supportsMode(QClipboard::Mode mode) const
-{
- return mode == QClipboard::Clipboard;
-}
-
-bool QMirClientClipboard::ownsMode(QClipboard::Mode mode) const
-{
- Q_UNUSED(mode);
- return false;
-}
-
-void QMirClientClipboard::onApplicationStateChanged(Qt::ApplicationState state)
-{
- if (state == Qt::ApplicationActive) {
- // Only focused or active applications might be allowed to paste, so we probably
- // missed changes in the clipboard while we were hidden, inactive or, more importantly,
- // suspended.
- requestMimeData();
- }
-}
-
-void QMirClientClipboard::updateMimeData()
-{
- if (qGuiApp->applicationState() != Qt::ApplicationActive) {
- // Don't even bother asking as content-hub would probably ignore our request (and should).
- return;
- }
-
- delete mMimeData;
-
- QWindow *focusWindow = QGuiApplication::focusWindow();
- if (focusWindow) {
- QString surfaceId = static_cast<QMirClientWindow*>(focusWindow->handle())->persistentSurfaceId();
- mMimeData = mContentHub->latestPaste(surfaceId);
- mClipboardState = SyncedClipboard;
- emitChanged(QClipboard::Clipboard);
- }
-}
-
-void QMirClientClipboard::requestMimeData()
-{
- if (qGuiApp->applicationState() != Qt::ApplicationActive) {
- // Don't even bother asking as content-hub would probably ignore our request (and should).
- return;
- }
-
- QWindow *focusWindow = QGuiApplication::focusWindow();
- if (!focusWindow) {
- return;
- }
-
- QString surfaceId = static_cast<QMirClientWindow*>(focusWindow->handle())->persistentSurfaceId();
- QDBusPendingCall reply = mContentHub->requestLatestPaste(surfaceId);
- mClipboardState = SyncingClipboard;
-
- mPasteReply = new QDBusPendingCallWatcher(reply, this);
- connect(mPasteReply, &QDBusPendingCallWatcher::finished,
- this, [this]() {
- delete mMimeData;
- mMimeData = mContentHub->paste(*mPasteReply);
- mClipboardState = SyncedClipboard;
- mPasteReply->deleteLater();
- mPasteReply = nullptr;
- emitChanged(QClipboard::Clipboard);
- });
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientcursor.cpp b/src/plugins/platforms/mirclient/qmirclientcursor.cpp
deleted file mode 100644
index 812cde95c6..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientcursor.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientcursor.h"
-
-#include "qmirclientlogging.h"
-#include "qmirclientwindow.h"
-
-#include <mir_toolkit/mir_client_library.h>
-
-Q_LOGGING_CATEGORY(mirclientCursor, "qt.qpa.mirclient.cursor", QtWarningMsg)
-
-QMirClientCursor::QMirClientCursor(MirConnection *connection)
- : mConnection(connection)
-{
- /*
- * TODO: Add the missing cursors to Mir (LP: #1388987)
- * Those are the ones without a mir_ prefix, which are X11 cursors
- * and won't be understood by any shell other than Unity8.
- */
- mShapeToCursorName[Qt::ArrowCursor] = mir_arrow_cursor_name;
- mShapeToCursorName[Qt::UpArrowCursor] = "up_arrow";
- mShapeToCursorName[Qt::CrossCursor] = mir_crosshair_cursor_name;
- mShapeToCursorName[Qt::WaitCursor] = mir_busy_cursor_name;
- mShapeToCursorName[Qt::IBeamCursor] = mir_caret_cursor_name;
- mShapeToCursorName[Qt::SizeVerCursor] = mir_vertical_resize_cursor_name;
- mShapeToCursorName[Qt::SizeHorCursor] = mir_horizontal_resize_cursor_name;
- mShapeToCursorName[Qt::SizeBDiagCursor] = mir_diagonal_resize_bottom_to_top_cursor_name;
- mShapeToCursorName[Qt::SizeFDiagCursor] = mir_diagonal_resize_top_to_bottom_cursor_name;
- mShapeToCursorName[Qt::SizeAllCursor] = mir_omnidirectional_resize_cursor_name;
- mShapeToCursorName[Qt::BlankCursor] = mir_disabled_cursor_name;
- mShapeToCursorName[Qt::SplitVCursor] = mir_vsplit_resize_cursor_name;
- mShapeToCursorName[Qt::SplitHCursor] = mir_hsplit_resize_cursor_name;
- mShapeToCursorName[Qt::PointingHandCursor] = mir_pointing_hand_cursor_name;
- mShapeToCursorName[Qt::ForbiddenCursor] = "forbidden";
- mShapeToCursorName[Qt::WhatsThisCursor] = "whats_this";
- mShapeToCursorName[Qt::BusyCursor] = "left_ptr_watch";
- mShapeToCursorName[Qt::OpenHandCursor] = mir_open_hand_cursor_name;
- mShapeToCursorName[Qt::ClosedHandCursor] = mir_closed_hand_cursor_name;
- mShapeToCursorName[Qt::DragCopyCursor] = "dnd-copy";
- mShapeToCursorName[Qt::DragMoveCursor] = "dnd-move";
- mShapeToCursorName[Qt::DragLinkCursor] = "dnd-link";
-}
-
-namespace {
-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 "???";
- }
-}
-} // 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) {
- qCDebug(mirclientCursor, "changeCursor shape=%s, window=%p", 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 = 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
deleted file mode 100644
index c5de23b272..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientcursor.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef 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/qmirclientdebugextension.cpp b/src/plugins/platforms/mirclient/qmirclientdebugextension.cpp
deleted file mode 100644
index 9aa934083d..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientdebugextension.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientdebugextension.h"
-
-#include "qmirclientlogging.h"
-
-// mir client debug
-#include <mir_toolkit/debug/surface.h>
-
-Q_LOGGING_CATEGORY(mirclientDebug, "qt.qpa.mirclient.debug")
-
-QMirClientDebugExtension::QMirClientDebugExtension()
- : m_mirclientDebug(QStringLiteral("mirclient-debug-extension"), 1)
- , m_mapper(nullptr)
-{
- qCDebug(mirclientDebug) << "NOTICE: Loading mirclient-debug-extension";
- m_mapper = (MapperPrototype) m_mirclientDebug.resolve("mir_debug_surface_coords_to_screen");
-
- if (!m_mirclientDebug.isLoaded()) {
- qCWarning(mirclientDebug) << "ERROR: mirclient-debug-extension failed to load:"
- << m_mirclientDebug.errorString();
- } else if (!m_mapper) {
- qCWarning(mirclientDebug) << "ERROR: unable to find required symbols in mirclient-debug-extension:"
- << m_mirclientDebug.errorString();
- }
-}
-
-QPoint QMirClientDebugExtension::mapSurfacePointToScreen(MirSurface *surface, const QPoint &point)
-{
- if (!m_mapper) {
- return point;
- }
-
- QPoint mappedPoint;
- bool status = m_mapper(surface, point.x(), point.y(), &mappedPoint.rx(), &mappedPoint.ry());
- if (status) {
- return mappedPoint;
- } else {
- return point;
- }
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientdesktopwindow.cpp b/src/plugins/platforms/mirclient/qmirclientdesktopwindow.cpp
deleted file mode 100644
index 123f805c25..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientdesktopwindow.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientdesktopwindow.h"
-
-// local
-#include "qmirclientlogging.h"
-
-QMirClientDesktopWindow::QMirClientDesktopWindow(QWindow *window)
- : QPlatformWindow(window)
-{
- qCDebug(mirclient, "QMirClientDesktopWindow(window=%p)", window);
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientdesktopwindow.h b/src/plugins/platforms/mirclient/qmirclientdesktopwindow.h
deleted file mode 100644
index 3ba54db826..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientdesktopwindow.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTDESKTOPWINDOW_H
-#define QMIRCLIENTDESKTOPWINDOW_H
-
-#include <qpa/qplatformwindow.h>
-
-// TODO Implement it. For now it's just an empty, dummy class.
-class QMirClientDesktopWindow : public QPlatformWindow
-{
-public:
- QMirClientDesktopWindow(QWindow*);
-};
-
-#endif // QMIRCLIENTDESKTOPWINDOW_H
diff --git a/src/plugins/platforms/mirclient/qmirclientglcontext.cpp b/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
deleted file mode 100644
index fc7d90d5ec..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientglcontext.h"
-#include "qmirclientlogging.h"
-#include "qmirclientwindow.h"
-
-#include <QOpenGLFramebufferObject>
-#include <QtEglSupport/private/qeglconvenience_p.h>
-#include <QtEglSupport/private/qeglpbuffer_p.h>
-#include <QtGui/private/qopenglcontext_p.h>
-
-Q_LOGGING_CATEGORY(mirclientGraphics, "qt.qpa.mirclient.graphics", QtWarningMsg)
-
-namespace {
-
-void printEglConfig(EGLDisplay display, EGLConfig config)
-{
- Q_ASSERT(display != EGL_NO_DISPLAY);
- Q_ASSERT(config != nullptr);
-
- const char *string = eglQueryString(display, EGL_VENDOR);
- qCDebug(mirclientGraphics, "EGL vendor: %s", string);
-
- string = eglQueryString(display, EGL_VERSION);
- qCDebug(mirclientGraphics, "EGL version: %s", string);
-
- string = eglQueryString(display, EGL_EXTENSIONS);
- qCDebug(mirclientGraphics, "EGL extensions: %s", string);
-
- qCDebug(mirclientGraphics, "EGL configuration attributes:");
- q_printEglConfig(display, config);
-}
-
-} // anonymous namespace
-
-QMirClientOpenGLContext::QMirClientOpenGLContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share,
- EGLDisplay display)
- : QEGLPlatformContext(format, share, display, 0)
-{
- if (mirclientGraphics().isDebugEnabled()) {
- printEglConfig(display, eglConfig());
- }
-}
-
-static bool needsFBOReadBackWorkaround()
-{
- static bool set = false;
- static bool needsWorkaround = false;
-
- if (Q_UNLIKELY(!set)) {
- const char *rendererString = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
- needsWorkaround = qstrncmp(rendererString, "Mali-400", 8) == 0
- || qstrncmp(rendererString, "Mali-T7", 7) == 0
- || qstrncmp(rendererString, "PowerVR Rogue G6200", 19) == 0;
- set = true;
- }
-
- return needsWorkaround;
-}
-
-bool QMirClientOpenGLContext::makeCurrent(QPlatformSurface* surface)
-{
- const bool ret = QEGLPlatformContext::makeCurrent(surface);
-
- if (Q_LIKELY(ret)) {
- QOpenGLContextPrivate *ctx_d = QOpenGLContextPrivate::get(context());
- if (!ctx_d->workaround_brokenFBOReadBack && needsFBOReadBackWorkaround()) {
- ctx_d->workaround_brokenFBOReadBack = true;
- }
- }
- return ret;
-}
-
-// Following method used internally in the base class QEGLPlatformContext to access
-// the egl surface of a QPlatformSurface/QMirClientWindow
-EGLSurface QMirClientOpenGLContext::eglSurfaceForPlatformSurface(QPlatformSurface *surface)
-{
- if (surface->surface()->surfaceClass() == QSurface::Window) {
- return static_cast<QMirClientWindow *>(surface)->eglSurface();
- } else {
- return static_cast<QEGLPbuffer *>(surface)->pbuffer();
- }
-}
-
-void QMirClientOpenGLContext::swapBuffers(QPlatformSurface* surface)
-{
- QEGLPlatformContext::swapBuffers(surface);
-
- if (surface->surface()->surfaceClass() == QSurface::Window) {
- // notify window on swap completion
- auto platformWindow = static_cast<QMirClientWindow *>(surface);
- platformWindow->onSwapBuffersDone();
- }
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientglcontext.h b/src/plugins/platforms/mirclient/qmirclientglcontext.h
deleted file mode 100644
index 92331a6fb1..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientglcontext.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTGLCONTEXT_H
-#define QMIRCLIENTGLCONTEXT_H
-
-#include <qpa/qplatformopenglcontext.h>
-#include <QtEglSupport/private/qeglplatformcontext_p.h>
-
-#include <EGL/egl.h>
-
-class QMirClientOpenGLContext : public QEGLPlatformContext
-{
-public:
- QMirClientOpenGLContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share,
- EGLDisplay display);
-
- // QEGLPlatformContext methods.
- void swapBuffers(QPlatformSurface *surface) final;
- bool makeCurrent(QPlatformSurface *surface) final;
-
-protected:
- EGLSurface eglSurfaceForPlatformSurface(QPlatformSurface *surface) final;
-};
-
-#endif // QMIRCLIENTGLCONTEXT_H
diff --git a/src/plugins/platforms/mirclient/qmirclientinput.cpp b/src/plugins/platforms/mirclient/qmirclientinput.cpp
deleted file mode 100644
index e5319b0435..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientinput.cpp
+++ /dev/null
@@ -1,708 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-// Local
-#include "qmirclientinput.h"
-#include "qmirclientintegration.h"
-#include "qmirclientnativeinterface.h"
-#include "qmirclientscreen.h"
-#include "qmirclientwindow.h"
-#include "qmirclientlogging.h"
-#include "qmirclientorientationchangeevent_p.h"
-
-// Qt
-#include <QtCore/QThread>
-#include <QtCore/qglobal.h>
-#include <QtCore/QCoreApplication>
-#include <QtGui/private/qguiapplication_p.h>
-#include <qpa/qplatforminputcontext.h>
-#include <qpa/qwindowsysteminterface.h>
-#include <QTextCodec>
-
-#include <xkbcommon/xkbcommon.h>
-#include <xkbcommon/xkbcommon-keysyms.h>
-
-#include <mir_toolkit/mir_client_library.h>
-
-Q_LOGGING_CATEGORY(mirclientInput, "qt.qpa.mirclient.input", QtWarningMsg)
-
-namespace
-{
-
-// XKB Keysyms which do not map directly to Qt types (i.e. Unicode points)
-static const uint32_t KeyTable[] = {
- XKB_KEY_Escape, Qt::Key_Escape,
- XKB_KEY_Tab, Qt::Key_Tab,
- XKB_KEY_ISO_Left_Tab, Qt::Key_Backtab,
- XKB_KEY_BackSpace, Qt::Key_Backspace,
- XKB_KEY_Return, Qt::Key_Return,
- XKB_KEY_Insert, Qt::Key_Insert,
- XKB_KEY_Delete, Qt::Key_Delete,
- XKB_KEY_Clear, Qt::Key_Delete,
- XKB_KEY_Pause, Qt::Key_Pause,
- XKB_KEY_Print, Qt::Key_Print,
-
- XKB_KEY_Home, Qt::Key_Home,
- XKB_KEY_End, Qt::Key_End,
- XKB_KEY_Left, Qt::Key_Left,
- XKB_KEY_Up, Qt::Key_Up,
- XKB_KEY_Right, Qt::Key_Right,
- XKB_KEY_Down, Qt::Key_Down,
- XKB_KEY_Prior, Qt::Key_PageUp,
- XKB_KEY_Next, Qt::Key_PageDown,
-
- XKB_KEY_Shift_L, Qt::Key_Shift,
- XKB_KEY_Shift_R, Qt::Key_Shift,
- XKB_KEY_Shift_Lock, Qt::Key_Shift,
- XKB_KEY_Control_L, Qt::Key_Control,
- XKB_KEY_Control_R, Qt::Key_Control,
- XKB_KEY_Meta_L, Qt::Key_Meta,
- XKB_KEY_Meta_R, Qt::Key_Meta,
- XKB_KEY_Alt_L, Qt::Key_Alt,
- XKB_KEY_Alt_R, Qt::Key_Alt,
- XKB_KEY_Caps_Lock, Qt::Key_CapsLock,
- XKB_KEY_Num_Lock, Qt::Key_NumLock,
- XKB_KEY_Scroll_Lock, Qt::Key_ScrollLock,
- XKB_KEY_Super_L, Qt::Key_Super_L,
- XKB_KEY_Super_R, Qt::Key_Super_R,
- XKB_KEY_Menu, Qt::Key_Menu,
- XKB_KEY_Hyper_L, Qt::Key_Hyper_L,
- XKB_KEY_Hyper_R, Qt::Key_Hyper_R,
- XKB_KEY_Help, Qt::Key_Help,
-
- XKB_KEY_KP_Space, Qt::Key_Space,
- XKB_KEY_KP_Tab, Qt::Key_Tab,
- XKB_KEY_KP_Enter, Qt::Key_Enter,
- XKB_KEY_KP_Home, Qt::Key_Home,
- XKB_KEY_KP_Left, Qt::Key_Left,
- XKB_KEY_KP_Up, Qt::Key_Up,
- XKB_KEY_KP_Right, Qt::Key_Right,
- XKB_KEY_KP_Down, Qt::Key_Down,
- XKB_KEY_KP_Prior, Qt::Key_PageUp,
- XKB_KEY_KP_Next, Qt::Key_PageDown,
- XKB_KEY_KP_End, Qt::Key_End,
- XKB_KEY_KP_Begin, Qt::Key_Clear,
- XKB_KEY_KP_Insert, Qt::Key_Insert,
- XKB_KEY_KP_Delete, Qt::Key_Delete,
- XKB_KEY_KP_Equal, Qt::Key_Equal,
- XKB_KEY_KP_Multiply, Qt::Key_Asterisk,
- XKB_KEY_KP_Add, Qt::Key_Plus,
- XKB_KEY_KP_Separator, Qt::Key_Comma,
- XKB_KEY_KP_Subtract, Qt::Key_Minus,
- XKB_KEY_KP_Decimal, Qt::Key_Period,
- XKB_KEY_KP_Divide, Qt::Key_Slash,
-
- XKB_KEY_ISO_Level3_Shift, Qt::Key_AltGr,
- XKB_KEY_Multi_key, Qt::Key_Multi_key,
- XKB_KEY_Codeinput, Qt::Key_Codeinput,
- XKB_KEY_SingleCandidate, Qt::Key_SingleCandidate,
- XKB_KEY_MultipleCandidate, Qt::Key_MultipleCandidate,
- XKB_KEY_PreviousCandidate, Qt::Key_PreviousCandidate,
-
- // dead keys
- XKB_KEY_dead_grave, Qt::Key_Dead_Grave,
- XKB_KEY_dead_acute, Qt::Key_Dead_Acute,
- XKB_KEY_dead_circumflex, Qt::Key_Dead_Circumflex,
- XKB_KEY_dead_tilde, Qt::Key_Dead_Tilde,
- XKB_KEY_dead_macron, Qt::Key_Dead_Macron,
- XKB_KEY_dead_breve, Qt::Key_Dead_Breve,
- XKB_KEY_dead_abovedot, Qt::Key_Dead_Abovedot,
- XKB_KEY_dead_diaeresis, Qt::Key_Dead_Diaeresis,
- XKB_KEY_dead_abovering, Qt::Key_Dead_Abovering,
- XKB_KEY_dead_doubleacute, Qt::Key_Dead_Doubleacute,
- XKB_KEY_dead_caron, Qt::Key_Dead_Caron,
- XKB_KEY_dead_cedilla, Qt::Key_Dead_Cedilla,
- XKB_KEY_dead_ogonek, Qt::Key_Dead_Ogonek,
- XKB_KEY_dead_iota, Qt::Key_Dead_Iota,
- XKB_KEY_dead_voiced_sound, Qt::Key_Dead_Voiced_Sound,
- XKB_KEY_dead_semivoiced_sound, Qt::Key_Dead_Semivoiced_Sound,
- XKB_KEY_dead_belowdot, Qt::Key_Dead_Belowdot,
- XKB_KEY_dead_hook, Qt::Key_Dead_Hook,
- XKB_KEY_dead_horn, Qt::Key_Dead_Horn,
- XKB_KEY_dead_stroke, Qt::Key_Dead_Stroke,
- XKB_KEY_dead_abovecomma, Qt::Key_Dead_Abovecomma,
- XKB_KEY_dead_abovereversedcomma, Qt::Key_Dead_Abovereversedcomma,
- XKB_KEY_dead_doublegrave, Qt::Key_Dead_Doublegrave,
- XKB_KEY_dead_belowring, Qt::Key_Dead_Belowring,
- XKB_KEY_dead_belowmacron, Qt::Key_Dead_Belowmacron,
- XKB_KEY_dead_belowcircumflex, Qt::Key_Dead_Belowcircumflex,
- XKB_KEY_dead_belowtilde, Qt::Key_Dead_Belowtilde,
- XKB_KEY_dead_belowbreve, Qt::Key_Dead_Belowbreve,
- XKB_KEY_dead_belowdiaeresis, Qt::Key_Dead_Belowdiaeresis,
- XKB_KEY_dead_invertedbreve, Qt::Key_Dead_Invertedbreve,
- XKB_KEY_dead_belowcomma, Qt::Key_Dead_Belowcomma,
- XKB_KEY_dead_currency, Qt::Key_Dead_Currency,
- XKB_KEY_dead_a, Qt::Key_Dead_a,
- XKB_KEY_dead_A, Qt::Key_Dead_A,
- XKB_KEY_dead_e, Qt::Key_Dead_e,
- XKB_KEY_dead_E, Qt::Key_Dead_E,
- XKB_KEY_dead_i, Qt::Key_Dead_i,
- XKB_KEY_dead_I, Qt::Key_Dead_I,
- XKB_KEY_dead_o, Qt::Key_Dead_o,
- XKB_KEY_dead_O, Qt::Key_Dead_O,
- XKB_KEY_dead_u, Qt::Key_Dead_u,
- XKB_KEY_dead_U, Qt::Key_Dead_U,
- XKB_KEY_dead_small_schwa, Qt::Key_Dead_Small_Schwa,
- XKB_KEY_dead_capital_schwa, Qt::Key_Dead_Capital_Schwa,
- XKB_KEY_dead_greek, Qt::Key_Dead_Greek,
- XKB_KEY_dead_lowline, Qt::Key_Dead_Lowline,
- XKB_KEY_dead_aboveverticalline, Qt::Key_Dead_Aboveverticalline,
- XKB_KEY_dead_belowverticalline, Qt::Key_Dead_Belowverticalline,
- XKB_KEY_dead_longsolidusoverlay, Qt::Key_Dead_Longsolidusoverlay,
-
- XKB_KEY_Mode_switch, Qt::Key_Mode_switch,
- XKB_KEY_script_switch, Qt::Key_Mode_switch,
- XKB_KEY_XF86AudioRaiseVolume, Qt::Key_VolumeUp,
- XKB_KEY_XF86AudioLowerVolume, Qt::Key_VolumeDown,
- XKB_KEY_XF86PowerOff, Qt::Key_PowerOff,
- XKB_KEY_XF86PowerDown, Qt::Key_PowerDown,
-
- 0, 0
-};
-
-Qt::WindowState mirSurfaceStateToWindowState(MirSurfaceState state)
-{
- switch (state) {
- case mir_surface_state_fullscreen:
- return Qt::WindowFullScreen;
- case mir_surface_state_maximized:
- case mir_surface_state_vertmaximized:
- case mir_surface_state_horizmaximized:
- return Qt::WindowMaximized;
- case mir_surface_state_minimized:
- return Qt::WindowMinimized;
- case mir_surface_state_hidden:
- // We should be handling this state separately.
- Q_ASSERT(false);
- case mir_surface_state_restored:
- case mir_surface_state_unknown:
- default:
- return Qt::WindowNoState;
- }
-}
-
-} // namespace
-
-class UbuntuEvent : public QEvent
-{
-public:
- UbuntuEvent(QMirClientWindow* window, const MirEvent *event, QEvent::Type type)
- : QEvent(type), window(window) {
- nativeEvent = mir_event_ref(event);
- }
- ~UbuntuEvent()
- {
- mir_event_unref(nativeEvent);
- }
-
- QPointer<QMirClientWindow> window;
- const MirEvent *nativeEvent;
-};
-
-QMirClientInput::QMirClientInput(QMirClientClientIntegration* integration)
- : QObject(nullptr)
- , mIntegration(integration)
- , mEventFilterType(static_cast<QMirClientNativeInterface*>(
- integration->nativeInterface())->genericEventFilterType())
- , mEventType(static_cast<QEvent::Type>(QEvent::registerEventType()))
- , mLastInputWindow(nullptr)
-{
- // Initialize touch device.
- mTouchDevice = new QTouchDevice;
- mTouchDevice->setType(QTouchDevice::TouchScreen);
- mTouchDevice->setCapabilities(
- QTouchDevice::Position | QTouchDevice::Area | QTouchDevice::Pressure |
- QTouchDevice::NormalizedPosition);
- QWindowSystemInterface::registerTouchDevice(mTouchDevice);
-}
-
-QMirClientInput::~QMirClientInput()
-{
- // Qt will take care of deleting mTouchDevice.
-}
-
-static const char* nativeEventTypeToStr(MirEventType t)
-{
- switch (t)
- {
- case mir_event_type_key:
- return "key";
- case mir_event_type_motion:
- return "motion";
- case mir_event_type_surface:
- return "surface";
- case mir_event_type_resize:
- return "resize";
- case mir_event_type_prompt_session_state_change:
- return "prompt_session_state_change";
- case mir_event_type_orientation:
- return "orientation";
- case mir_event_type_close_surface:
- return "close_surface";
- case mir_event_type_input:
- return "input";
- case mir_event_type_keymap:
- return "keymap";
- case mir_event_type_input_configuration:
- return "input_configuration";
- case mir_event_type_surface_output:
- return "surface_output";
- case mir_event_type_input_device_state:
- return "input_device_state";
- default:
- return "unknown";
- }
-}
-
-void QMirClientInput::customEvent(QEvent* event)
-{
- Q_ASSERT(QThread::currentThread() == thread());
- UbuntuEvent* ubuntuEvent = static_cast<UbuntuEvent*>(event);
- const MirEvent *nativeEvent = ubuntuEvent->nativeEvent;
-
- if ((ubuntuEvent->window == nullptr) || (ubuntuEvent->window->window() == nullptr)) {
- qCWarning(mirclient) << "Attempted to deliver an event to a non-existent window, ignoring.";
- return;
- }
-
- // Event filtering.
- long result;
- if (QWindowSystemInterface::handleNativeEvent(
- ubuntuEvent->window->window(), mEventFilterType,
- const_cast<void *>(static_cast<const void *>(nativeEvent)), &result) == true) {
- qCDebug(mirclient, "event filtered out by native interface");
- return;
- }
-
- qCDebug(mirclientInput, "customEvent(type=%s)", nativeEventTypeToStr(mir_event_get_type(nativeEvent)));
-
- // Event dispatching.
- switch (mir_event_get_type(nativeEvent))
- {
- case mir_event_type_input:
- dispatchInputEvent(ubuntuEvent->window, mir_event_get_input_event(nativeEvent));
- break;
- case mir_event_type_resize:
- {
- auto resizeEvent = mir_event_get_resize_event(nativeEvent);
-
- // Enable workaround for Screen rotation
- auto const targetWindow = ubuntuEvent->window;
- if (targetWindow) {
- auto const screen = static_cast<QMirClientScreen*>(targetWindow->screen());
- if (screen) {
- screen->handleWindowSurfaceResize(
- mir_resize_event_get_width(resizeEvent),
- mir_resize_event_get_height(resizeEvent));
- }
-
- targetWindow->handleSurfaceResized(
- mir_resize_event_get_width(resizeEvent),
- mir_resize_event_get_height(resizeEvent));
- }
- break;
- }
- case mir_event_type_surface:
- handleSurfaceEvent(ubuntuEvent->window, mir_event_get_surface_event(nativeEvent));
- break;
- case mir_event_type_surface_output:
- handleSurfaceOutputEvent(ubuntuEvent->window, mir_event_get_surface_output_event(nativeEvent));
- break;
- case mir_event_type_orientation:
- dispatchOrientationEvent(ubuntuEvent->window->window(), mir_event_get_orientation_event(nativeEvent));
- break;
- case mir_event_type_close_surface:
- QWindowSystemInterface::handleCloseEvent(ubuntuEvent->window->window());
- break;
- default:
- qCDebug(mirclient, "unhandled event type: %d", static_cast<int>(mir_event_get_type(nativeEvent)));
- }
-}
-
-void QMirClientInput::postEvent(QMirClientWindow *platformWindow, const MirEvent *event)
-{
- QWindow *window = platformWindow->window();
-
- QCoreApplication::postEvent(this, new UbuntuEvent(
- platformWindow, event, mEventType));
-
- if ((window->flags().testFlag(Qt::WindowTransparentForInput)) && window->parent()) {
- QCoreApplication::postEvent(this, new UbuntuEvent(
- static_cast<QMirClientWindow*>(platformWindow->QPlatformWindow::parent()),
- event, mEventType));
- }
-}
-
-void QMirClientInput::dispatchInputEvent(QMirClientWindow *window, const MirInputEvent *ev)
-{
- switch (mir_input_event_get_type(ev))
- {
- case mir_input_event_type_key:
- dispatchKeyEvent(window, ev);
- break;
- case mir_input_event_type_touch:
- dispatchTouchEvent(window, ev);
- break;
- case mir_input_event_type_pointer:
- dispatchPointerEvent(window, ev);
- break;
- default:
- break;
- }
-}
-
-void QMirClientInput::dispatchTouchEvent(QMirClientWindow *window, const MirInputEvent *ev)
-{
- const MirTouchEvent *tev = mir_input_event_get_touch_event(ev);
-
- // FIXME(loicm) Max pressure is device specific. That one is for the Samsung Galaxy Nexus. That
- // needs to be fixed as soon as the compat input lib adds query support.
- const float kMaxPressure = 1.28;
- const QRect kWindowGeometry = window->geometry();
- QList<QWindowSystemInterface::TouchPoint> touchPoints;
-
-
- // TODO: Is it worth setting the Qt::TouchPointStationary ones? Currently they are left
- // as Qt::TouchPointMoved
- const unsigned int kPointerCount = mir_touch_event_point_count(tev);
- touchPoints.reserve(int(kPointerCount));
- for (unsigned int i = 0; i < kPointerCount; ++i) {
- QWindowSystemInterface::TouchPoint touchPoint;
-
- const float kX = mir_touch_event_axis_value(tev, i, mir_touch_axis_x) + kWindowGeometry.x();
- const float kY = mir_touch_event_axis_value(tev, i, mir_touch_axis_y) + kWindowGeometry.y(); // see bug lp:1346633 workaround comments elsewhere
- const float kW = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_major);
- const float kH = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_minor);
- const float kP = mir_touch_event_axis_value(tev, i, mir_touch_axis_pressure);
- touchPoint.id = mir_touch_event_id(tev, i);
- touchPoint.normalPosition = QPointF(kX / kWindowGeometry.width(), kY / kWindowGeometry.height());
- touchPoint.area = QRectF(kX - (kW / 2.0), kY - (kH / 2.0), kW, kH);
- touchPoint.pressure = kP / kMaxPressure;
-
- MirTouchAction touch_action = mir_touch_event_action(tev, i);
- switch (touch_action)
- {
- case mir_touch_action_down:
- mLastInputWindow = window;
- touchPoint.state = Qt::TouchPointPressed;
- break;
- case mir_touch_action_up:
- touchPoint.state = Qt::TouchPointReleased;
- break;
- case mir_touch_action_change:
- touchPoint.state = Qt::TouchPointMoved;
- break;
- default:
- Q_UNREACHABLE();
- }
-
- touchPoints.append(touchPoint);
- }
-
- ulong timestamp = mir_input_event_get_event_time(ev) / 1000000;
- QWindowSystemInterface::handleTouchEvent(window->window(), timestamp,
- mTouchDevice, touchPoints);
-}
-
-static uint32_t translateKeysym(uint32_t sym, const QString &text) {
- int code = 0;
-
- QTextCodec *systemCodec = QTextCodec::codecForLocale();
- if (sym < 128 || (sym < 256 && systemCodec->mibEnum() == 4)) {
- // upper-case key, if known
- code = isprint((int)sym) ? toupper((int)sym) : 0;
- } else if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F35) {
- return Qt::Key_F1 + (int(sym) - XKB_KEY_F1);
- } else if (text.length() == 1 && text.unicode()->unicode() > 0x1f
- && text.unicode()->unicode() != 0x7f
- && !(sym >= XKB_KEY_dead_grave && sym <= XKB_KEY_dead_currency)) {
- code = text.unicode()->toUpper().unicode();
- } else {
- for (int i = 0; KeyTable[i]; i += 2)
- if (sym == KeyTable[i])
- code = KeyTable[i + 1];
- }
-
- return code;
-}
-
-namespace
-{
-Qt::KeyboardModifiers qt_modifiers_from_mir(MirInputEventModifiers modifiers)
-{
- Qt::KeyboardModifiers q_modifiers = Qt::NoModifier;
- if (modifiers & mir_input_event_modifier_shift) {
- q_modifiers |= Qt::ShiftModifier;
- }
- if (modifiers & mir_input_event_modifier_ctrl) {
- q_modifiers |= Qt::ControlModifier;
- }
- if (modifiers & mir_input_event_modifier_alt_left) {
- q_modifiers |= Qt::AltModifier;
- }
- if (modifiers & mir_input_event_modifier_meta) {
- q_modifiers |= Qt::MetaModifier;
- }
- if (modifiers & mir_input_event_modifier_alt_right) {
- q_modifiers |= Qt::GroupSwitchModifier;
- }
- return q_modifiers;
-}
-}
-
-void QMirClientInput::dispatchKeyEvent(QMirClientWindow *window, const MirInputEvent *event)
-{
- const MirKeyboardEvent *key_event = mir_input_event_get_keyboard_event(event);
-
- ulong timestamp = mir_input_event_get_event_time(event) / 1000000;
- xkb_keysym_t xk_sym = mir_keyboard_event_key_code(key_event);
- quint32 scan_code = mir_keyboard_event_scan_code(key_event);
- quint32 native_modifiers = mir_keyboard_event_modifiers(key_event);
-
- // Key modifier and unicode index mapping.
- auto modifiers = qt_modifiers_from_mir(native_modifiers);
-
- MirKeyboardAction action = mir_keyboard_event_action(key_event);
- QEvent::Type keyType = action == mir_keyboard_action_up
- ? QEvent::KeyRelease : QEvent::KeyPress;
-
- if (action == mir_keyboard_action_down)
- mLastInputWindow = window;
-
- QString text;
- QVarLengthArray<char, 32> chars(32);
- {
- int result = xkb_keysym_to_utf8(xk_sym, chars.data(), chars.size());
-
- if (result > 0) {
- text = QString::fromUtf8(chars.constData());
- }
- }
- int sym = translateKeysym(xk_sym, text);
-
- bool is_auto_rep = action == mir_keyboard_action_repeat;
-
- QPlatformInputContext *context = QGuiApplicationPrivate::platformIntegration()->inputContext();
- if (context) {
- QKeyEvent qKeyEvent(keyType, sym, modifiers, scan_code, xk_sym, native_modifiers, text, is_auto_rep);
- qKeyEvent.setTimestamp(timestamp);
- if (context->filterEvent(&qKeyEvent)) {
- qCDebug(mirclient, "key event filtered out by input context");
- return;
- }
- }
-
- QWindowSystemInterface::handleExtendedKeyEvent(window->window(), timestamp, keyType, sym, modifiers, scan_code, xk_sym, native_modifiers, text, is_auto_rep);
-}
-
-namespace
-{
-Qt::MouseButtons extract_buttons(const MirPointerEvent *pev)
-{
- Qt::MouseButtons buttons = Qt::NoButton;
- if (mir_pointer_event_button_state(pev, mir_pointer_button_primary))
- buttons |= Qt::LeftButton;
- 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::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;
-
- return buttons;
-}
-}
-
-void QMirClientInput::dispatchPointerEvent(QMirClientWindow *platformWindow, const MirInputEvent *ev)
-{
- const auto window = platformWindow->window();
- const auto timestamp = mir_input_event_get_event_time(ev) / 1000000;
-
- const auto pev = mir_input_event_get_pointer_event(ev);
- const auto action = mir_pointer_event_action(pev);
-
- const auto modifiers = qt_modifiers_from_mir(mir_pointer_event_modifiers(pev));
- const auto localPoint = QPointF(mir_pointer_event_axis_value(pev, mir_pointer_axis_x),
- mir_pointer_event_axis_value(pev, mir_pointer_axis_y));
-
- mLastInputWindow = platformWindow;
-
- 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);
-
- if (hDelta != 0 || vDelta != 0) {
- // QWheelEvent::DefaultDeltasPerStep = 120 but doesn't exist on vivid
- const QPoint angleDelta(120 * hDelta, 120 * vDelta);
- 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:
- Q_UNREACHABLE();
- }
-}
-
-static const char* nativeOrientationDirectionToStr(MirOrientation orientation)
-{
- switch (orientation) {
- case mir_orientation_normal:
- return "Normal";
- case mir_orientation_left:
- return "Left";
- case mir_orientation_inverted:
- return "Inverted";
- case mir_orientation_right:
- return "Right";
- }
- Q_UNREACHABLE();
-}
-
-void QMirClientInput::dispatchOrientationEvent(QWindow *window, const MirOrientationEvent *event)
-{
- MirOrientation mir_orientation = mir_orientation_event_get_direction(event);
- qCDebug(mirclientInput, "orientation direction: %s", nativeOrientationDirectionToStr(mir_orientation));
-
- if (!window->screen()) {
- qCDebug(mirclient, "Window has no associated screen, dropping orientation event");
- return;
- }
-
- OrientationChangeEvent::Orientation orientation;
- switch (mir_orientation) {
- case mir_orientation_normal:
- orientation = OrientationChangeEvent::TopUp;
- break;
- case mir_orientation_left:
- orientation = OrientationChangeEvent::LeftUp;
- break;
- case mir_orientation_inverted:
- orientation = OrientationChangeEvent::TopDown;
- break;
- case mir_orientation_right:
- orientation = OrientationChangeEvent::RightUp;
- break;
- default:
- qCDebug(mirclient, "No such orientation %d", mir_orientation);
- return;
- }
-
- // Dispatch orientation event to [Platform]Screen, as that is where Qt reads it. Screen will handle
- // notifying Qt of the actual orientation change - done to prevent multiple Windows each creating
- // an identical orientation change event and passing it directly to Qt.
- // [Platform]Screen can also factor in the native orientation.
- QCoreApplication::postEvent(static_cast<QMirClientScreen*>(window->screen()->handle()),
- new OrientationChangeEvent(OrientationChangeEvent::mType, orientation));
-}
-
-void QMirClientInput::handleSurfaceEvent(const QPointer<QMirClientWindow> &window, const MirSurfaceEvent *event)
-{
- auto surfaceEventAttribute = mir_surface_event_get_attribute(event);
-
- switch (surfaceEventAttribute) {
- case mir_surface_attrib_focus: {
- window->handleSurfaceFocusChanged(
- mir_surface_event_get_attribute_value(event) == mir_surface_focused);
- break;
- }
- case mir_surface_attrib_visibility: {
- window->handleSurfaceExposeChange(
- mir_surface_event_get_attribute_value(event) == mir_surface_visibility_exposed);
- break;
- }
- // Remaining attributes are ones client sets for server, and server should not override them
- case mir_surface_attrib_state: {
- MirSurfaceState state = static_cast<MirSurfaceState>(mir_surface_event_get_attribute_value(event));
-
- if (state == mir_surface_state_hidden) {
- window->handleSurfaceVisibilityChanged(false);
- } else {
- // it's visible!
- window->handleSurfaceVisibilityChanged(true);
- window->handleSurfaceStateChanged(mirSurfaceStateToWindowState(state));
- }
- break;
- }
- case mir_surface_attrib_type:
- case mir_surface_attrib_swapinterval:
- case mir_surface_attrib_dpi:
- case mir_surface_attrib_preferred_orientation:
- case mir_surface_attribs:
- break;
- }
-}
-
-void QMirClientInput::handleSurfaceOutputEvent(const QPointer<QMirClientWindow> &window, const MirSurfaceOutputEvent *event)
-{
- const uint32_t outputId = mir_surface_output_event_get_output_id(event);
- const int dpi = mir_surface_output_event_get_dpi(event);
- const MirFormFactor formFactor = mir_surface_output_event_get_form_factor(event);
- const float scale = mir_surface_output_event_get_scale(event);
-
- const auto screenObserver = mIntegration->screenObserver();
- QMirClientScreen *screen = screenObserver->findScreenWithId(outputId);
- if (!screen) {
- qCWarning(mirclient) << "Mir notified window" << window->window() << "on an unknown screen with id" << outputId;
- return;
- }
-
- screenObserver->handleScreenPropertiesChange(screen, dpi, formFactor, scale);
- window->handleScreenPropertiesChange(formFactor, scale);
-
- if (window->screen() != screen) {
- QWindowSystemInterface::handleWindowScreenChanged(window->window(), screen->screen());
- }
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientinput.h b/src/plugins/platforms/mirclient/qmirclientinput.h
deleted file mode 100644
index 263cb5e54e..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientinput.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTINPUT_H
-#define QMIRCLIENTINPUT_H
-
-// Qt
-#include <qpa/qwindowsysteminterface.h>
-
-#include <mir_toolkit/mir_client_library.h>
-
-class QMirClientClientIntegration;
-class QMirClientWindow;
-
-class QMirClientInput : public QObject
-{
- Q_OBJECT
-
-public:
- QMirClientInput(QMirClientClientIntegration* integration);
- virtual ~QMirClientInput();
-
- // QObject methods.
- void customEvent(QEvent* event) override;
-
- void postEvent(QMirClientWindow* window, const MirEvent *event);
- QMirClientClientIntegration* integration() const { return mIntegration; }
- QMirClientWindow *lastInputWindow() const {return mLastInputWindow; }
-
-protected:
- 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);
- void handleSurfaceEvent(const QPointer<QMirClientWindow> &window, const MirSurfaceEvent *event);
- void handleSurfaceOutputEvent(const QPointer<QMirClientWindow> &window, const MirSurfaceOutputEvent *event);
-
-private:
- QMirClientClientIntegration* mIntegration;
- QTouchDevice* mTouchDevice;
- const QByteArray mEventFilterType;
- const QEvent::Type mEventType;
-
- QMirClientWindow *mLastInputWindow;
-};
-
-#endif // QMIRCLIENTINPUT_H
diff --git a/src/plugins/platforms/mirclient/qmirclientintegration.cpp b/src/plugins/platforms/mirclient/qmirclientintegration.cpp
deleted file mode 100644
index eef96ee3de..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientintegration.cpp
+++ /dev/null
@@ -1,411 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-// Local
-#include "qmirclientintegration.h"
-#include "qmirclientbackingstore.h"
-#include "qmirclientclipboard.h"
-#include "qmirclientdebugextension.h"
-#include "qmirclientdesktopwindow.h"
-#include "qmirclientglcontext.h"
-#include "qmirclientinput.h"
-#include "qmirclientlogging.h"
-#include "qmirclientnativeinterface.h"
-#include "qmirclientscreen.h"
-#include "qmirclienttheme.h"
-#include "qmirclientwindow.h"
-
-// Qt
-#include <QFileInfo>
-#include <QGuiApplication>
-#include <qpa/qplatformnativeinterface.h>
-#include <qpa/qplatforminputcontextfactory_p.h>
-#include <qpa/qplatforminputcontext.h>
-#include <QtEglSupport/private/qeglconvenience_p.h>
-#include <QtEglSupport/private/qeglpbuffer_p.h>
-#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include <qpa/qplatformaccessibility.h>
-#ifndef QT_NO_ACCESSIBILITY_ATSPI_BRIDGE
-#include <QtLinuxAccessibilitySupport/private/bridge_p.h>
-#endif
-#endif
-
-#include <QOpenGLContext>
-#include <QOffscreenSurface>
-
-// platform-api
-#include <ubuntu/application/lifecycle_delegate.h>
-#include <ubuntu/application/id.h>
-#include <ubuntu/application/options.h>
-
-static void resumedCallback(const UApplicationOptions */*options*/, void* context)
-{
- auto integration = static_cast<QMirClientClientIntegration*>(context);
- integration->appStateController()->setResumed();
-}
-
-static void aboutToStopCallback(UApplicationArchive */*archive*/, void* context)
-{
- auto integration = static_cast<QMirClientClientIntegration*>(context);
- auto inputContext = integration->inputContext();
- if (inputContext) {
- inputContext->hideInputPanel();
- } else {
- qCWarning(mirclient) << "aboutToStopCallback(): no input context";
- }
- integration->appStateController()->setSuspended();
-}
-
-QMirClientClientIntegration::QMirClientClientIntegration(int argc, char **argv)
- : QPlatformIntegration()
- , mNativeInterface(new QMirClientNativeInterface(this))
- , mFontDb(new QGenericUnixFontDatabase)
- , mServices(new QMirClientPlatformServices)
- , mAppStateController(new QMirClientAppStateController)
- , mScaleFactor(1.0)
-{
- {
- QStringList args = QCoreApplication::arguments();
- setupOptions(args);
- QByteArray sessionName = generateSessionName(args);
- setupDescription(sessionName);
- }
-
- // Create new application instance
- mInstance = u_application_instance_new_from_description_with_options(mDesc, mOptions);
-
- if (Q_UNLIKELY(!mInstance))
- qFatal("QMirClientClientIntegration: connection to Mir server failed. Check that a Mir server is\n"
- "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");
-
- mMirConnection = u_application_instance_get_mir_connection(mInstance);
-
- // Choose the default surface format suited to the Mir platform
- QSurfaceFormat defaultFormat;
- defaultFormat.setRedBufferSize(8);
- defaultFormat.setGreenBufferSize(8);
- defaultFormat.setBlueBufferSize(8);
- QSurfaceFormat::setDefaultFormat(defaultFormat);
-
- // Initialize EGL.
- mEglNativeDisplay = mir_connection_get_egl_native_display(mMirConnection);
- ASSERT((mEglDisplay = eglGetDisplay(mEglNativeDisplay)) != EGL_NO_DISPLAY);
- ASSERT(eglInitialize(mEglDisplay, nullptr, nullptr) == EGL_TRUE);
-
- // Has debug mode been requsted, either with "-testability" switch or QT_LOAD_TESTABILITY env var
- bool testability = qEnvironmentVariableIsSet("QT_LOAD_TESTABILITY");
- for (int i=1; !testability && i<argc; i++) {
- if (strcmp(argv[i], "-testability") == 0) {
- testability = true;
- }
- }
- if (testability) {
- mDebugExtension.reset(new QMirClientDebugExtension);
- }
-}
-
-void QMirClientClientIntegration::initialize()
-{
- // Init the ScreenObserver
- mScreenObserver.reset(new QMirClientScreenObserver(mMirConnection));
- connect(mScreenObserver.data(), &QMirClientScreenObserver::screenAdded,
- [this](QMirClientScreen *screen) { this->screenAdded(screen); });
- connect(mScreenObserver.data(), &QMirClientScreenObserver::screenRemoved,
- this, &QMirClientClientIntegration::destroyScreen);
-
- Q_FOREACH (auto screen, mScreenObserver->screens()) {
- screenAdded(screen);
- }
-
- // Initialize input.
- mInput = new QMirClientInput(this);
- mInputContext = QPlatformInputContextFactory::create();
-
- // compute the scale factor
- const int defaultGridUnit = 8;
- int gridUnit = defaultGridUnit;
- QByteArray gridUnitString = qgetenv("GRID_UNIT_PX");
- if (!gridUnitString.isEmpty()) {
- bool ok;
- gridUnit = gridUnitString.toInt(&ok);
- if (!ok) {
- gridUnit = defaultGridUnit;
- }
- }
- mScaleFactor = static_cast<qreal>(gridUnit) / defaultGridUnit;
-}
-
-QMirClientClientIntegration::~QMirClientClientIntegration()
-{
- eglTerminate(mEglDisplay);
- delete mInput;
- delete mInputContext;
- delete mServices;
-}
-
-QPlatformServices *QMirClientClientIntegration::services() const
-{
- return mServices;
-}
-
-void QMirClientClientIntegration::setupOptions(QStringList &args)
-{
- int argc = args.size() + 1;
- char **argv = new char*[argc];
- for (int i = 0; i < argc - 1; i++)
- argv[i] = qstrdup(args.at(i).toLocal8Bit());
- argv[argc - 1] = nullptr;
-
- mOptions = u_application_options_new_from_cmd_line(argc - 1, argv);
-
- for (int i = 0; i < argc; i++)
- delete [] argv[i];
- delete [] argv;
-}
-
-void QMirClientClientIntegration::setupDescription(QByteArray &sessionName)
-{
- mDesc = u_application_description_new();
-
- UApplicationId* id = u_application_id_new_from_stringn(sessionName.data(), sessionName.count());
- u_application_description_set_application_id(mDesc, id);
-
- UApplicationLifecycleDelegate* delegate = u_application_lifecycle_delegate_new();
- u_application_lifecycle_delegate_set_application_resumed_cb(delegate, &resumedCallback);
- u_application_lifecycle_delegate_set_application_about_to_stop_cb(delegate, &aboutToStopCallback);
- u_application_lifecycle_delegate_set_context(delegate, this);
- u_application_description_set_application_lifecycle_delegate(mDesc, delegate);
-}
-
-QByteArray QMirClientClientIntegration::generateSessionName(QStringList &args)
-{
- // Try to come up with some meaningful session name to uniquely identify this session,
- // helping with shell debugging
-
- if (args.count() == 0) {
- return QByteArray("QtUbuntu");
- } if (args[0].contains("qmlscene")) {
- return generateSessionNameFromQmlFile(args);
- } else {
- // use the executable name
- QFileInfo fileInfo(args[0]);
- return fileInfo.fileName().toLocal8Bit();
- }
-}
-
-QByteArray QMirClientClientIntegration::generateSessionNameFromQmlFile(QStringList &args)
-{
- Q_FOREACH (QString arg, args) {
- if (arg.endsWith(".qml")) {
- QFileInfo fileInfo(arg);
- return fileInfo.fileName().toLocal8Bit();
- }
- }
-
- // give up
- return "qmlscene";
-}
-
-QPlatformWindow* QMirClientClientIntegration::createPlatformWindow(QWindow* window) const
-{
- if (window->type() == Qt::Desktop) {
- // Desktop windows should not be backed up by a mir surface as they don't draw anything (nor should).
- return new QMirClientDesktopWindow(window);
- } else {
- return new QMirClientWindow(window, mInput, mNativeInterface, mAppStateController.data(),
- mEglDisplay, mMirConnection, mDebugExtension.data());
- }
-}
-
-bool QMirClientClientIntegration::hasCapability(QPlatformIntegration::Capability cap) const
-{
- switch (cap) {
- case ThreadedOpenGL:
- if (qEnvironmentVariableIsEmpty("QTUBUNTU_NO_THREADED_OPENGL")) {
- return true;
- } else {
- qCDebug(mirclient, "disabled threaded OpenGL");
- return false;
- }
-
- case ThreadedPixmaps:
- case OpenGL:
- case ApplicationState:
- case MultipleWindows:
- case NonFullScreenWindows:
-#if QT_VERSION > QT_VERSION_CHECK(5, 5, 0)
- case SwitchableWidgetComposition:
-#endif
- case RasterGLSurface: // needed for QQuickWidget
- return true;
- default:
- return QPlatformIntegration::hasCapability(cap);
- }
-}
-
-QAbstractEventDispatcher *QMirClientClientIntegration::createEventDispatcher() const
-{
- return createUnixEventDispatcher();
-}
-
-QPlatformBackingStore* QMirClientClientIntegration::createPlatformBackingStore(QWindow* window) const
-{
- return new QMirClientBackingStore(window);
-}
-
-QPlatformOpenGLContext* QMirClientClientIntegration::createPlatformOpenGLContext(
- QOpenGLContext* context) const
-{
- QSurfaceFormat format(context->format());
-
- auto platformContext = new QMirClientOpenGLContext(format, context->shareHandle(), mEglDisplay);
- if (!platformContext->isValid()) {
- // Older Intel Atom-based devices only support OpenGL 1.4 compatibility profile but by default
- // QML asks for at least OpenGL 2.0. The XCB GLX backend ignores this request and returns a
- // 1.4 context, but the XCB EGL backend tries to honor it, and fails. The 1.4 context appears to
- // have sufficient capabilities on MESA (i915) to render correctly however. So reduce the default
- // requested OpenGL version to 1.0 to ensure EGL will give us a working context (lp:1549455).
- static const bool isMesa = QString(eglQueryString(mEglDisplay, EGL_VENDOR)).contains(QStringLiteral("Mesa"));
- if (isMesa) {
- qCDebug(mirclientGraphics, "Attempting to choose OpenGL 1.4 context which may suit Mesa");
- format.setMajorVersion(1);
- format.setMinorVersion(4);
- delete platformContext;
- platformContext = new QMirClientOpenGLContext(format, context->shareHandle(), mEglDisplay);
- }
- }
- return platformContext;
-}
-
-QStringList QMirClientClientIntegration::themeNames() const
-{
- return QStringList(QMirClientTheme::name);
-}
-
-QPlatformTheme* QMirClientClientIntegration::createPlatformTheme(const QString& name) const
-{
- Q_UNUSED(name);
- return new QMirClientTheme;
-}
-
-QVariant QMirClientClientIntegration::styleHint(StyleHint hint) const
-{
- switch (hint) {
- case QPlatformIntegration::StartDragDistance: {
- // default is 10 pixels (see QPlatformTheme::defaultThemeHint)
- return 10.0 * mScaleFactor;
- }
- case QPlatformIntegration::PasswordMaskDelay: {
- // return time in milliseconds - 1 second
- return QVariant(1000);
- }
- default:
- break;
- }
- return QPlatformIntegration::styleHint(hint);
-}
-
-QPlatformClipboard* QMirClientClientIntegration::clipboard() const
-{
- static QPlatformClipboard *clipboard = nullptr;
- if (!clipboard) {
- clipboard = new QMirClientClipboard;
- }
- return clipboard;
-}
-
-QPlatformNativeInterface* QMirClientClientIntegration::nativeInterface() const
-{
- return mNativeInterface;
-}
-
-QPlatformOffscreenSurface *QMirClientClientIntegration::createPlatformOffscreenSurface(
- QOffscreenSurface *surface) const
-{
- return new QEGLPbuffer(mEglDisplay, surface->requestedFormat(), surface);
-}
-
-void QMirClientClientIntegration::destroyScreen(QMirClientScreen *screen)
-{
- // FIXME: on deleting a screen while a Window is on it, Qt will automatically
- // move the window to the primaryScreen(). This will trigger a screenChanged
- // signal, causing things like QQuickScreenAttached to re-fetch screen properties
- // like DPI and physical size. However this is crashing, as Qt is calling virtual
- // functions on QPlatformScreen, for reasons unclear. As workaround, move window
- // to primaryScreen() before deleting the screen. Might be QTBUG-38650
-
- QScreen *primaryScreen = QGuiApplication::primaryScreen();
- if (screen != primaryScreen->handle()) {
- uint32_t movedWindowCount = 0;
- Q_FOREACH (QWindow *w, QGuiApplication::topLevelWindows()) {
- if (w->screen()->handle() == screen) {
- QWindowSystemInterface::handleWindowScreenChanged(w, primaryScreen);
- ++movedWindowCount;
- }
- }
- if (movedWindowCount > 0) {
- QWindowSystemInterface::flushWindowSystemEvents();
- }
- }
-
- qCDebug(mirclient) << "Removing Screen with id" << screen->mirOutputId() << "and geometry" << screen->geometry();
-#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)
- delete screen;
-#else
- QPlatformIntegration::destroyScreen(screen);
-#endif
-}
-
-#ifndef QT_NO_ACCESSIBILITY
-QPlatformAccessibility *QMirClientClientIntegration::accessibility() const
-{
-#if !defined(QT_NO_ACCESSIBILITY_ATSPI_BRIDGE)
- if (!mAccessibility) {
- Q_ASSERT_X(QCoreApplication::eventDispatcher(), "QMirClientIntegration",
- "Initializing accessibility without event-dispatcher!");
- mAccessibility.reset(new QSpiAccessibleBridge());
- }
-#endif
- return mAccessibility.data();
-}
-#endif
diff --git a/src/plugins/platforms/mirclient/qmirclientintegration.h b/src/plugins/platforms/mirclient/qmirclientintegration.h
deleted file mode 100644
index 035117f4da..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientintegration.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTINTEGRATION_H
-#define QMIRCLIENTINTEGRATION_H
-
-#include <qpa/qplatformintegration.h>
-#include <QSharedPointer>
-
-#include "qmirclientappstatecontroller.h"
-#include "qmirclientplatformservices.h"
-#include "qmirclientscreenobserver.h"
-
-// platform-api
-#include <ubuntu/application/description.h>
-#include <ubuntu/application/instance.h>
-
-#include <EGL/egl.h>
-
-class QMirClientDebugExtension;
-class QMirClientInput;
-class QMirClientNativeInterface;
-class QMirClientScreen;
-class MirConnection;
-
-class QMirClientClientIntegration : public QObject, public QPlatformIntegration
-{
- Q_OBJECT
-
-public:
- QMirClientClientIntegration(int argc, char **argv);
- virtual ~QMirClientClientIntegration();
-
- // QPlatformIntegration methods.
- bool hasCapability(QPlatformIntegration::Capability cap) const override;
- QAbstractEventDispatcher *createEventDispatcher() const override;
- QPlatformNativeInterface* nativeInterface() const override;
- QPlatformBackingStore* createPlatformBackingStore(QWindow* window) const override;
- QPlatformOpenGLContext* createPlatformOpenGLContext(QOpenGLContext* context) const override;
- QPlatformFontDatabase* fontDatabase() const override { return mFontDb; }
- QStringList themeNames() const override;
- QPlatformTheme* createPlatformTheme(const QString& name) const override;
- QVariant styleHint(StyleHint hint) const override;
- QPlatformServices *services() const override;
- QPlatformWindow* createPlatformWindow(QWindow* window) const override;
- QPlatformInputContext* inputContext() const override { return mInputContext; }
- QPlatformClipboard* clipboard() const override;
- void initialize() override;
- QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const override;
- QPlatformAccessibility *accessibility() const override;
-
- // New methods.
- MirConnection *mirConnection() const { return mMirConnection; }
- EGLDisplay eglDisplay() const { return mEglDisplay; }
- EGLNativeDisplayType eglNativeDisplay() const { return mEglNativeDisplay; }
- QMirClientAppStateController *appStateController() const { return mAppStateController.data(); }
- QMirClientScreenObserver *screenObserver() const { return mScreenObserver.data(); }
- QMirClientDebugExtension *debugExtension() const { return mDebugExtension.data(); }
-
-private Q_SLOTS:
- void destroyScreen(QMirClientScreen *screen);
-
-private:
- void setupOptions(QStringList &args);
- void setupDescription(QByteArray &sessionName);
- static QByteArray generateSessionName(QStringList &args);
- static QByteArray generateSessionNameFromQmlFile(QStringList &args);
-
- QMirClientNativeInterface* mNativeInterface;
- QPlatformFontDatabase* mFontDb;
-
- QMirClientPlatformServices* mServices;
-
- QMirClientInput* mInput;
- QPlatformInputContext* mInputContext;
- mutable QScopedPointer<QPlatformAccessibility> mAccessibility;
- QScopedPointer<QMirClientDebugExtension> mDebugExtension;
- QScopedPointer<QMirClientScreenObserver> mScreenObserver;
- QScopedPointer<QMirClientAppStateController> mAppStateController;
- qreal mScaleFactor;
-
- MirConnection *mMirConnection;
-
- // Platform API stuff
- UApplicationOptions* mOptions;
- UApplicationDescription* mDesc;
- UApplicationInstance* mInstance;
-
- // EGL related
- EGLDisplay mEglDisplay{EGL_NO_DISPLAY};
- EGLNativeDisplayType mEglNativeDisplay;
-};
-
-#endif // QMIRCLIENTINTEGRATION_H
diff --git a/src/plugins/platforms/mirclient/qmirclientlogging.h b/src/plugins/platforms/mirclient/qmirclientlogging.h
deleted file mode 100644
index 4921864ced..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientlogging.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTLOGGING_H
-#define QMIRCLIENTLOGGING_H
-
-#include <QLoggingCategory>
-
-#define ASSERT(cond) ((!(cond)) ? qt_assert(#cond,__FILE__,__LINE__) : qt_noop())
-
-Q_DECLARE_LOGGING_CATEGORY(mirclient)
-Q_DECLARE_LOGGING_CATEGORY(mirclientBufferSwap)
-Q_DECLARE_LOGGING_CATEGORY(mirclientInput)
-Q_DECLARE_LOGGING_CATEGORY(mirclientGraphics)
-Q_DECLARE_LOGGING_CATEGORY(mirclientCursor)
-Q_DECLARE_LOGGING_CATEGORY(mirclientDebug)
-
-#endif // QMIRCLIENTLOGGING_H
diff --git a/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp b/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp
deleted file mode 100644
index b85e6fedfa..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp
+++ /dev/null
@@ -1,217 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-// Local
-#include "qmirclientnativeinterface.h"
-#include "qmirclientscreen.h"
-#include "qmirclientglcontext.h"
-#include "qmirclientwindow.h"
-
-// Qt
-#include <QtGui/private/qguiapplication_p.h>
-#include <QtGui/qopenglcontext.h>
-#include <QtGui/qscreen.h>
-#include <QtCore/QMap>
-
-class UbuntuResourceMap : public QMap<QByteArray, QMirClientNativeInterface::ResourceType>
-{
-public:
- UbuntuResourceMap()
- : QMap<QByteArray, QMirClientNativeInterface::ResourceType>() {
- insert("egldisplay", QMirClientNativeInterface::EglDisplay);
- insert("eglcontext", QMirClientNativeInterface::EglContext);
- insert("nativeorientation", QMirClientNativeInterface::NativeOrientation);
- insert("display", QMirClientNativeInterface::Display);
- insert("mirconnection", QMirClientNativeInterface::MirConnection);
- insert("mirsurface", QMirClientNativeInterface::MirSurface);
- insert("scale", QMirClientNativeInterface::Scale);
- insert("formfactor", QMirClientNativeInterface::FormFactor);
- }
-};
-
-Q_GLOBAL_STATIC(UbuntuResourceMap, ubuntuResourceMap)
-
-QMirClientNativeInterface::QMirClientNativeInterface(const QMirClientClientIntegration *integration)
- : mIntegration(integration)
- , mGenericEventFilterType(QByteArrayLiteral("Event"))
- , mNativeOrientation(nullptr)
-{
-}
-
-QMirClientNativeInterface::~QMirClientNativeInterface()
-{
- delete mNativeOrientation;
- 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 mIntegration->mirConnection();
- } else {
- return nullptr;
- }
-}
-
-void* QMirClientNativeInterface::nativeResourceForContext(
- const QByteArray& resourceString, QOpenGLContext* context)
-{
- if (!context)
- return nullptr;
-
- const QByteArray kLowerCaseResource = resourceString.toLower();
-
- if (!ubuntuResourceMap()->contains(kLowerCaseResource))
- return nullptr;
-
- const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource);
-
- if (kResourceType == QMirClientNativeInterface::EglContext)
- return static_cast<QMirClientOpenGLContext*>(context->handle())->eglContext();
- else
- return nullptr;
-}
-
-void* QMirClientNativeInterface::nativeResourceForWindow(const QByteArray& resourceString, QWindow* window)
-{
- const QByteArray kLowerCaseResource = resourceString.toLower();
- if (!ubuntuResourceMap()->contains(kLowerCaseResource))
- return NULL;
- const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource);
-
- switch (kResourceType) {
- case EglDisplay:
- return mIntegration->eglDisplay();
- case NativeOrientation:
- // Return the device's native screen orientation.
- if (window) {
- QMirClientScreen *ubuntuScreen = static_cast<QMirClientScreen*>(window->screen()->handle());
- mNativeOrientation = new Qt::ScreenOrientation(ubuntuScreen->nativeOrientation());
- } else {
- QPlatformScreen *platformScreen = QGuiApplication::primaryScreen()->handle();
- mNativeOrientation = new Qt::ScreenOrientation(platformScreen->nativeOrientation());
- }
- return mNativeOrientation;
- case MirSurface:
- if (window) {
- auto ubuntuWindow = static_cast<QMirClientWindow*>(window->handle());
- if (ubuntuWindow) {
- return ubuntuWindow->mirSurface();
- } else {
- return nullptr;
- }
- } else {
- return nullptr;
- }
- default:
- return nullptr;
- }
-}
-
-void* QMirClientNativeInterface::nativeResourceForScreen(const QByteArray& resourceString, QScreen* screen)
-{
- const QByteArray kLowerCaseResource = resourceString.toLower();
- if (!ubuntuResourceMap()->contains(kLowerCaseResource))
- return NULL;
- const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource);
- if (!screen)
- screen = QGuiApplication::primaryScreen();
- auto ubuntuScreen = static_cast<QMirClientScreen*>(screen->handle());
- if (kResourceType == QMirClientNativeInterface::Display) {
- return mIntegration->eglNativeDisplay();
- // Changes to the following properties are emitted via the QMirClientNativeInterface::screenPropertyChanged
- // signal fired by QMirClientScreen. Connect to this signal for these properties updates.
- // WARNING: code highly thread unsafe!
- } else if (kResourceType == QMirClientNativeInterface::Scale) {
- // In application code, read with:
- // float scale = *reinterpret_cast<float*>(nativeResourceForScreen("scale", screen()));
- return &ubuntuScreen->mScale;
- } else if (kResourceType == QMirClientNativeInterface::FormFactor) {
- return &ubuntuScreen->mFormFactor;
- } else
- return NULL;
-}
-
-// Changes to these properties are emitted via the QMirClientNativeInterface::windowPropertyChanged
-// signal fired by QMirClientWindow. Connect to this signal for these properties updates.
-QVariantMap QMirClientNativeInterface::windowProperties(QPlatformWindow *window) const
-{
- QVariantMap propertyMap;
- auto w = static_cast<QMirClientWindow*>(window);
- if (w) {
- propertyMap.insert("scale", w->scale());
- propertyMap.insert("formFactor", w->formFactor());
- }
- return propertyMap;
-}
-
-QVariant QMirClientNativeInterface::windowProperty(QPlatformWindow *window, const QString &name) const
-{
- auto w = static_cast<QMirClientWindow*>(window);
- if (!w) {
- return QVariant();
- }
-
- if (name == QStringLiteral("scale")) {
- return w->scale();
- } else if (name == QStringLiteral("formFactor")) {
- return w->formFactor();
- } else {
- return QVariant();
- }
-}
-
-QVariant QMirClientNativeInterface::windowProperty(QPlatformWindow *window, const QString &name, const QVariant &defaultValue) const
-{
- QVariant returnVal = windowProperty(window, name);
- if (!returnVal.isValid()) {
- return defaultValue;
- } else {
- return returnVal;
- }
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientnativeinterface.h b/src/plugins/platforms/mirclient/qmirclientnativeinterface.h
deleted file mode 100644
index eb601de301..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientnativeinterface.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTNATIVEINTERFACE_H
-#define QMIRCLIENTNATIVEINTERFACE_H
-
-#include <qpa/qplatformnativeinterface.h>
-
-#include "qmirclientintegration.h"
-
-class QPlatformScreen;
-
-class QMirClientNativeInterface : public QPlatformNativeInterface {
- Q_OBJECT
-public:
- enum ResourceType { EglDisplay, EglContext, NativeOrientation, Display, MirConnection, MirSurface, Scale, FormFactor };
-
- QMirClientNativeInterface(const QMirClientClientIntegration *integration);
- ~QMirClientNativeInterface();
-
- // QPlatformNativeInterface methods.
- void* nativeResourceForIntegration(const QByteArray &resource) override;
- void* nativeResourceForContext(const QByteArray& resourceString,
- QOpenGLContext* context) override;
- void* nativeResourceForWindow(const QByteArray& resourceString,
- QWindow* window) override;
- void* nativeResourceForScreen(const QByteArray& resourceString,
- QScreen* screen) override;
-
- QVariantMap windowProperties(QPlatformWindow *window) const override;
- QVariant windowProperty(QPlatformWindow *window, const QString &name) const override;
- QVariant windowProperty(QPlatformWindow *window, const QString &name, const QVariant &defaultValue) const override;
-
- // New methods.
- const QByteArray& genericEventFilterType() const { return mGenericEventFilterType; }
-
-Q_SIGNALS: // New signals
- void screenPropertyChanged(QPlatformScreen *screen, const QString &propertyName);
-
-private:
- const QMirClientClientIntegration *mIntegration;
- const QByteArray mGenericEventFilterType;
- Qt::ScreenOrientation* mNativeOrientation;
-};
-
-#endif // QMIRCLIENTNATIVEINTERFACE_H
diff --git a/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h b/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h
deleted file mode 100644
index 5abd3262dc..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTORIENTATIONCHANGEEVENT_P_H
-#define QMIRCLIENTORIENTATIONCHANGEEVENT_P_H
-
-#include <QEvent>
-#include "qmirclientlogging.h"
-
-class OrientationChangeEvent : public QEvent {
-public:
- enum Orientation { TopUp, LeftUp, TopDown, RightUp };
-
- OrientationChangeEvent(QEvent::Type type, Orientation orientation)
- : QEvent(type)
- , mOrientation(orientation)
- {
- }
-
- static const QEvent::Type mType;
- Orientation mOrientation;
-};
-
-#endif // QMIRCLIENTORIENTATIONCHANGEEVENT_P_H
diff --git a/src/plugins/platforms/mirclient/qmirclientplatformservices.cpp b/src/plugins/platforms/mirclient/qmirclientplatformservices.cpp
deleted file mode 100644
index 1ccd57fc28..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientplatformservices.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientplatformservices.h"
-
-#include <QUrl>
-
-#include <ubuntu/application/url_dispatcher/service.h>
-#include <ubuntu/application/url_dispatcher/session.h>
-
-bool QMirClientPlatformServices::openUrl(const QUrl &url)
-{
- return callDispatcher(url);
-}
-
-bool QMirClientPlatformServices::openDocument(const QUrl &url)
-{
- return callDispatcher(url);
-}
-
-bool QMirClientPlatformServices::callDispatcher(const QUrl &url)
-{
- UAUrlDispatcherSession* session = ua_url_dispatcher_session();
- if (!session)
- return false;
-
- ua_url_dispatcher_session_open(session, url.toEncoded().constData(), NULL, NULL);
-
- free(session);
-
- // We are returning true here because the other option
- // is spawning a nested event loop and wait for the
- // callback. But there is no guarantee on how fast
- // the callback is going to be so we prefer to avoid the
- // nested event loop. Long term plan is improve Qt API
- // to support an async openUrl
- return true;
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientplatformservices.h b/src/plugins/platforms/mirclient/qmirclientplatformservices.h
deleted file mode 100644
index a1cd5758ca..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientplatformservices.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTPLATFORMSERVICES_H
-#define QMIRCLIENTPLATFORMSERVICES_H
-
-#include <qpa/qplatformservices.h>
-#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
-
-class QMirClientPlatformServices : public QPlatformServices {
-public:
- bool openUrl(const QUrl &url) override;
- bool openDocument(const QUrl &url) override;
-
-private:
- bool callDispatcher(const QUrl &url);
-};
-
-#endif // QMIRCLIENTPLATFORMSERVICES_H
diff --git a/src/plugins/platforms/mirclient/qmirclientplugin.cpp b/src/plugins/platforms/mirclient/qmirclientplugin.cpp
deleted file mode 100644
index fc44edfe40..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientplugin.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientplugin.h"
-#include "qmirclientintegration.h"
-#include "qmirclientlogging.h"
-
-Q_LOGGING_CATEGORY(mirclient, "qt.qpa.mirclient", QtWarningMsg)
-
-QPlatformIntegration *QMirClientIntegrationPlugin::create(const QString &system,
- const QStringList &/*paramList*/,
- int &argc, char **argv)
-{
- if (system.toLower() == QLatin1String("mirclient")) {
- return new QMirClientClientIntegration(argc, argv);
- } else {
- return 0;
- }
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientplugin.h b/src/plugins/platforms/mirclient/qmirclientplugin.h
deleted file mode 100644
index 207d97b5af..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientplugin.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTPLUGIN_H
-#define QMIRCLIENTPLUGIN_H
-
-#include <qpa/qplatformintegrationplugin.h>
-
-class QMirClientIntegrationPlugin : public QPlatformIntegrationPlugin
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID QPlatformIntegrationFactoryInterface_iid FILE "mirclient.json")
-
-public:
- QPlatformIntegration *create(const QString &system, const QStringList &paramList,
- int &argc, char **argv) override;
-};
-
-#endif // QMIRCLIENTPLUGIN_H
diff --git a/src/plugins/platforms/mirclient/qmirclientscreen.cpp b/src/plugins/platforms/mirclient/qmirclientscreen.cpp
deleted file mode 100644
index cc8db830aa..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientscreen.cpp
+++ /dev/null
@@ -1,262 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-// local
-#include "qmirclientscreen.h"
-#include "qmirclientlogging.h"
-#include "qmirclientorientationchangeevent_p.h"
-#include "qmirclientnativeinterface.h"
-
-#include <mir_toolkit/mir_client_library.h>
-
-// Qt
-#include <QGuiApplication>
-#include <QtCore/qmath.h>
-#include <QScreen>
-#include <QThread>
-#include <qpa/qwindowsysteminterface.h>
-#include <QtEglSupport/private/qeglconvenience_p.h>
-
-#include <memory>
-
-static const int overrideDevicePixelRatio = qgetenv("QT_DEVICE_PIXEL_RATIO").toInt();
-
-static const char *orientationToStr(Qt::ScreenOrientation orientation) {
- switch (orientation) {
- case Qt::PrimaryOrientation:
- return "primary";
- case Qt::PortraitOrientation:
- return "portrait";
- case Qt::LandscapeOrientation:
- return "landscape";
- case Qt::InvertedPortraitOrientation:
- return "inverted portrait";
- case Qt::InvertedLandscapeOrientation:
- return "inverted landscape";
- }
- Q_UNREACHABLE();
-}
-
-const QEvent::Type OrientationChangeEvent::mType =
- static_cast<QEvent::Type>(QEvent::registerEventType());
-
-
-QMirClientScreen::QMirClientScreen(const MirOutput *output, MirConnection *connection)
- : mDevicePixelRatio(1.0)
- , mFormat(QImage::Format_RGB32)
- , mDepth(32)
- , mDpi{0}
- , mFormFactor{mir_form_factor_unknown}
- , mScale{1.0}
- , mOutputId(0)
- , mCursor(connection)
-{
- setMirOutput(output);
-}
-
-QMirClientScreen::~QMirClientScreen()
-{
-}
-
-void QMirClientScreen::customEvent(QEvent* event) {
- Q_ASSERT(QThread::currentThread() == thread());
-
- OrientationChangeEvent* oReadingEvent = static_cast<OrientationChangeEvent*>(event);
- switch (oReadingEvent->mOrientation) {
- case OrientationChangeEvent::LeftUp: {
- mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
- Qt::InvertedPortraitOrientation : Qt::LandscapeOrientation;
- break;
- }
- case OrientationChangeEvent::TopUp: {
- mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
- Qt::LandscapeOrientation : Qt::PortraitOrientation;
- break;
- }
- case OrientationChangeEvent::RightUp: {
- mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
- Qt::PortraitOrientation : Qt::InvertedLandscapeOrientation;
- break;
- }
- case OrientationChangeEvent::TopDown: {
- mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ?
- Qt::InvertedLandscapeOrientation : Qt::InvertedPortraitOrientation;
- break;
- }
- }
-
- // Raise the event signal so that client apps know the orientation changed
- qCDebug(mirclient, "QMirClientScreen::customEvent - handling orientation change to %s", orientationToStr(mCurrentOrientation));
- QWindowSystemInterface::handleScreenOrientationChange(screen(), mCurrentOrientation);
-}
-
-void QMirClientScreen::handleWindowSurfaceResize(int windowWidth, int windowHeight)
-{
- if ((windowWidth > windowHeight && mGeometry.width() < mGeometry.height())
- || (windowWidth < windowHeight && mGeometry.width() > mGeometry.height())) {
-
- // The window aspect ratio differ's from the screen one. This means that
- // unity8 has rotated the window in its scene.
- // As there's no way to express window rotation in Qt's API, we have
- // Flip QScreen's dimensions so that orientation properties match
- // (primaryOrientation particularly).
- // FIXME: This assumes a phone scenario. Won't work, or make sense,
- // on the desktop
-
- QRect currGeometry = mGeometry;
- mGeometry.setWidth(currGeometry.height());
- mGeometry.setHeight(currGeometry.width());
-
- qCDebug(mirclient, "QMirClientScreen::handleWindowSurfaceResize - new screen geometry (w=%d, h=%d)",
- mGeometry.width(), mGeometry.height());
- QWindowSystemInterface::handleScreenGeometryChange(screen(),
- mGeometry /* newGeometry */,
- mGeometry /* newAvailableGeometry */);
-
- if (mGeometry.width() < mGeometry.height()) {
- mCurrentOrientation = Qt::PortraitOrientation;
- } else {
- mCurrentOrientation = Qt::LandscapeOrientation;
- }
- qCDebug(mirclient, "QMirClientScreen::handleWindowSurfaceResize - new orientation %s",orientationToStr(mCurrentOrientation));
- QWindowSystemInterface::handleScreenOrientationChange(screen(), mCurrentOrientation);
- }
-}
-
-void QMirClientScreen::setMirOutput(const MirOutput *output)
-{
- // Physical screen size (in mm)
- mPhysicalSize.setWidth(mir_output_get_physical_width_mm(output));
- mPhysicalSize.setHeight(mir_output_get_physical_height_mm(output));
-
- // Pixel Format
-// mFormat = qImageFormatFromMirPixelFormat(mir_output_get_current_pixel_format(output)); // GERRY: TODO
-
- // Pixel depth
- mDepth = 8 * MIR_BYTES_PER_PIXEL(mir_output_get_current_pixel_format(output));
-
- // Mode = Resolution & refresh rate
- const MirOutputMode *mode = mir_output_get_current_mode(output);
- mNativeGeometry.setX(mir_output_get_position_x(output));
- mNativeGeometry.setY(mir_output_get_position_y(output));
- mNativeGeometry.setWidth(mir_output_mode_get_width(mode));
- mNativeGeometry.setHeight(mir_output_mode_get_height(mode));
-
- mRefreshRate = mir_output_mode_get_refresh_rate(mode);
-
- // UI scale & DPR
- mScale = mir_output_get_scale_factor(output);
- if (overrideDevicePixelRatio > 0) {
- mDevicePixelRatio = overrideDevicePixelRatio;
- } else {
- mDevicePixelRatio = 1.0; // FIXME - need to determine suitable DPR for the specified scale
- }
-
- mFormFactor = mir_output_get_form_factor(output);
-
- mOutputId = mir_output_get_id(output);
-
- mGeometry.setX(mNativeGeometry.x());
- mGeometry.setY(mNativeGeometry.y());
- mGeometry.setWidth(mNativeGeometry.width());
- mGeometry.setHeight(mNativeGeometry.height());
-
- // Set the default orientation based on the initial screen dimensions.
- mNativeOrientation = (mGeometry.width() >= mGeometry.height()) ? Qt::LandscapeOrientation : Qt::PortraitOrientation;
-
- // If it's a landscape device (i.e. some tablets), start in landscape, otherwise portrait
- mCurrentOrientation = (mNativeOrientation == Qt::LandscapeOrientation) ? Qt::LandscapeOrientation : Qt::PortraitOrientation;
-}
-
-void QMirClientScreen::updateMirOutput(const MirOutput *output)
-{
- auto oldRefreshRate = mRefreshRate;
- auto oldScale = mScale;
- auto oldFormFactor = mFormFactor;
- auto oldGeometry = mGeometry;
-
- setMirOutput(output);
-
- // Emit change signals in particular order
- if (oldGeometry != mGeometry) {
- QWindowSystemInterface::handleScreenGeometryChange(screen(),
- mGeometry /* newGeometry */,
- mGeometry /* newAvailableGeometry */);
- }
-
- if (!qFuzzyCompare(mRefreshRate, oldRefreshRate)) {
- QWindowSystemInterface::handleScreenRefreshRateChange(screen(), mRefreshRate);
- }
-
- auto nativeInterface = static_cast<QMirClientNativeInterface *>(qGuiApp->platformNativeInterface());
- if (!qFuzzyCompare(mScale, oldScale)) {
- nativeInterface->screenPropertyChanged(this, QStringLiteral("scale"));
- }
- if (mFormFactor != oldFormFactor) {
- nativeInterface->screenPropertyChanged(this, QStringLiteral("formFactor"));
- }
-}
-
-void QMirClientScreen::setAdditionalMirDisplayProperties(float scale, MirFormFactor formFactor, int dpi)
-{
- if (mDpi != dpi) {
- mDpi = dpi;
- QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(screen(), dpi, dpi);
- }
-
- auto nativeInterface = static_cast<QMirClientNativeInterface *>(qGuiApp->platformNativeInterface());
- if (!qFuzzyCompare(mScale, scale)) {
- mScale = scale;
- nativeInterface->screenPropertyChanged(this, QStringLiteral("scale"));
- }
- if (mFormFactor != formFactor) {
- mFormFactor = formFactor;
- nativeInterface->screenPropertyChanged(this, QStringLiteral("formFactor"));
- }
-}
-
-QDpi QMirClientScreen::logicalDpi() const
-{
- if (mDpi > 0) {
- return QDpi(mDpi, mDpi);
- } else {
- return QPlatformScreen::logicalDpi();
- }
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientscreen.h b/src/plugins/platforms/mirclient/qmirclientscreen.h
deleted file mode 100644
index b31cba1964..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientscreen.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTSCREEN_H
-#define QMIRCLIENTSCREEN_H
-
-#include <qpa/qplatformscreen.h>
-#include <QSurfaceFormat>
-
-#include <mir_toolkit/common.h> // just for MirFormFactor enum
-
-#include "qmirclientcursor.h"
-
-struct MirConnection;
-struct MirOutput;
-
-class QMirClientScreen : public QObject, public QPlatformScreen
-{
- Q_OBJECT
-public:
- QMirClientScreen(const MirOutput *output, MirConnection *connection);
- virtual ~QMirClientScreen();
-
- // QPlatformScreen methods.
- QImage::Format format() const override { return mFormat; }
- int depth() const override { return mDepth; }
- QRect geometry() const override { return mGeometry; }
- QRect availableGeometry() const override { return mGeometry; }
- QSizeF physicalSize() const override { return mPhysicalSize; }
- qreal devicePixelRatio() const override { return mDevicePixelRatio; }
- QDpi logicalDpi() const override;
- Qt::ScreenOrientation nativeOrientation() const override { return mNativeOrientation; }
- Qt::ScreenOrientation orientation() const override { return mNativeOrientation; }
- QPlatformCursor *cursor() const override { return const_cast<QMirClientCursor*>(&mCursor); }
-
- // Additional Screen properties from Mir
- int mirOutputId() const { return mOutputId; }
- MirFormFactor formFactor() const { return mFormFactor; }
- float scale() const { return mScale; }
-
- // Internally used methods
- void updateMirOutput(const MirOutput *output);
- void setAdditionalMirDisplayProperties(float scale, MirFormFactor formFactor, int dpi);
- void handleWindowSurfaceResize(int width, int height);
-
- // QObject methods.
- void customEvent(QEvent* event) override;
-
-private:
- void setMirOutput(const MirOutput *output);
-
- QRect mGeometry, mNativeGeometry;
- QSizeF mPhysicalSize;
- qreal mDevicePixelRatio;
- Qt::ScreenOrientation mNativeOrientation;
- Qt::ScreenOrientation mCurrentOrientation;
- QImage::Format mFormat;
- int mDepth;
- int mDpi;
- qreal mRefreshRate;
- MirFormFactor mFormFactor;
- float mScale;
- int mOutputId;
- QMirClientCursor mCursor;
-
- friend class QMirClientNativeInterface;
-};
-
-#endif // QMIRCLIENTSCREEN_H
diff --git a/src/plugins/platforms/mirclient/qmirclientscreenobserver.cpp b/src/plugins/platforms/mirclient/qmirclientscreenobserver.cpp
deleted file mode 100644
index 792aeca351..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientscreenobserver.cpp
+++ /dev/null
@@ -1,161 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclientscreenobserver.h"
-#include "qmirclientscreen.h"
-#include "qmirclientwindow.h"
-#include "qmirclientlogging.h"
-
-// Qt
-#include <QMetaObject>
-#include <QPointer>
-
-// Mir
-#include <mirclient/mir_toolkit/mir_connection.h>
-#include <mirclient/mir_toolkit/mir_display_configuration.h>
-
-#include <memory>
-
-namespace {
- static void displayConfigurationChangedCallback(MirConnection */*connection*/, void* context)
- {
- ASSERT(context != NULL);
- QMirClientScreenObserver *observer = static_cast<QMirClientScreenObserver *>(context);
- QMetaObject::invokeMethod(observer, "update");
- }
-
- const char *mirFormFactorToStr(MirFormFactor formFactor)
- {
- switch (formFactor) {
- case mir_form_factor_unknown: return "unknown";
- case mir_form_factor_phone: return "phone";
- case mir_form_factor_tablet: return "tablet";
- case mir_form_factor_monitor: return "monitor";
- case mir_form_factor_tv: return "tv";
- case mir_form_factor_projector: return "projector";
- }
- Q_UNREACHABLE();
- }
-} // anonymous namespace
-
-QMirClientScreenObserver::QMirClientScreenObserver(MirConnection *mirConnection)
- : mMirConnection(mirConnection)
-{
- mir_connection_set_display_config_change_callback(mirConnection, ::displayConfigurationChangedCallback, this);
- update();
-}
-
-void QMirClientScreenObserver::update()
-{
- // Wrap MirDisplayConfiguration to always delete when out of scope
- auto configDeleter = [](MirDisplayConfig *config) { mir_display_config_release(config); };
- using configUp = std::unique_ptr<MirDisplayConfig, decltype(configDeleter)>;
- configUp displayConfig(mir_connection_create_display_configuration(mMirConnection), configDeleter);
-
- // Mir only tells us something changed, it is up to us to figure out what.
- QList<QMirClientScreen*> newScreenList;
- QList<QMirClientScreen*> oldScreenList = mScreenList;
- mScreenList.clear();
-
- for (int i = 0; i < mir_display_config_get_num_outputs(displayConfig.get()); i++) {
- const MirOutput *output = mir_display_config_get_output(displayConfig.get(), i);
- if (mir_output_is_enabled(output)) {
- QMirClientScreen *screen = findScreenWithId(oldScreenList, mir_output_get_id(output));
- if (screen) { // we've already set up this display before
- screen->updateMirOutput(output);
- oldScreenList.removeAll(screen);
- } else {
- // new display, so create QMirClientScreen for it
- screen = new QMirClientScreen(output, mMirConnection);
- newScreenList.append(screen);
- qCDebug(mirclient) << "Added Screen with id" << mir_output_get_id(output)
- << "and geometry" << screen->geometry();
- }
- mScreenList.append(screen);
- }
- }
-
- // Announce old & unused Screens, should be deleted by the slot
- Q_FOREACH (const auto screen, oldScreenList) {
- Q_EMIT screenRemoved(screen);
- }
-
- /*
- * Mir's MirDisplayOutput does not include formFactor or scale for some reason, but Qt
- * will want that information on creating the QScreen. Only way we get that info is when
- * Mir positions a Window on that Screen. See "handleScreenPropertiesChange" method
- */
-
- // Announce new Screens
- Q_FOREACH (const auto screen, newScreenList) {
- Q_EMIT screenAdded(screen);
- }
-
- qCDebug(mirclient) << "=======================================";
- for (auto screen: mScreenList) {
- qCDebug(mirclient) << screen << "- id:" << screen->mirOutputId()
- << "geometry:" << screen->geometry()
- << "form factor:" << mirFormFactorToStr(screen->formFactor())
- << "scale:" << screen->scale();
- }
- qCDebug(mirclient) << "=======================================";
-}
-
-QMirClientScreen *QMirClientScreenObserver::findScreenWithId(int id)
-{
- return findScreenWithId(mScreenList, id);
-}
-
-QMirClientScreen *QMirClientScreenObserver::findScreenWithId(const QList<QMirClientScreen *> &list, int id)
-{
- Q_FOREACH (const auto screen, list) {
- if (screen->mirOutputId() == id) {
- return screen;
- }
- }
- return nullptr;
-}
-
-void QMirClientScreenObserver::handleScreenPropertiesChange(QMirClientScreen *screen, int dpi,
- MirFormFactor formFactor, float scale)
-{
- screen->setAdditionalMirDisplayProperties(scale, formFactor, dpi);
-}
-
diff --git a/src/plugins/platforms/mirclient/qmirclienttheme.cpp b/src/plugins/platforms/mirclient/qmirclienttheme.cpp
deleted file mode 100644
index dcfef7ca67..0000000000
--- a/src/plugins/platforms/mirclient/qmirclienttheme.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qmirclienttheme.h"
-
-#include <QtCore/QVariant>
-
-const char *QMirClientTheme::name = "ubuntu";
-
-QMirClientTheme::QMirClientTheme()
-{
-}
-
-QMirClientTheme::~QMirClientTheme()
-{
-}
-
-QVariant QMirClientTheme::themeHint(ThemeHint hint) const
-{
- if (hint == QPlatformTheme::SystemIconThemeName) {
- QByteArray iconTheme = qgetenv("QTUBUNTU_ICON_THEME");
- if (iconTheme.isEmpty()) {
- return QVariant(QStringLiteral("ubuntu-mobile"));
- } else {
- return QVariant(QString(iconTheme));
- }
- } else {
- return QGenericUnixTheme::themeHint(hint);
- }
-}
diff --git a/src/plugins/platforms/mirclient/qmirclienttheme.h b/src/plugins/platforms/mirclient/qmirclienttheme.h
deleted file mode 100644
index 4bab1d0ee0..0000000000
--- a/src/plugins/platforms/mirclient/qmirclienttheme.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTTHEME_H
-#define QMIRCLIENTTHEME_H
-
-#include <QtThemeSupport/private/qgenericunixthemes_p.h>
-
-class QMirClientTheme : public QGenericUnixTheme
-{
-public:
- static const char* name;
- QMirClientTheme();
- virtual ~QMirClientTheme();
-
- // From QPlatformTheme
- QVariant themeHint(ThemeHint hint) const override;
-};
-
-#endif // QMIRCLIENTTHEME_H
diff --git a/src/plugins/platforms/mirclient/qmirclientwindow.cpp b/src/plugins/platforms/mirclient/qmirclientwindow.cpp
deleted file mode 100644
index decd21516e..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientwindow.cpp
+++ /dev/null
@@ -1,968 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-// Local
-#include "qmirclientwindow.h"
-#include "qmirclientdebugextension.h"
-#include "qmirclientnativeinterface.h"
-#include "qmirclientinput.h"
-#include "qmirclientintegration.h"
-#include "qmirclientscreen.h"
-#include "qmirclientlogging.h"
-
-#include <mir_toolkit/mir_client_library.h>
-#include <mir_toolkit/version.h>
-
-// Qt
-#include <qpa/qwindowsysteminterface.h>
-#include <QMutexLocker>
-#include <QSize>
-#include <QtMath>
-#include <QtEglSupport/private/qeglconvenience_p.h>
-
-// Platform API
-#include <ubuntu/application/instance.h>
-
-#include <EGL/egl.h>
-
-Q_LOGGING_CATEGORY(mirclientBufferSwap, "qt.qpa.mirclient.bufferSwap", QtWarningMsg)
-
-namespace
-{
-const Qt::WindowType LowChromeWindowHint = (Qt::WindowType)0x00800000;
-
-// 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));
-}
-
-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";
- case Qt::WindowActive:
- return "Active";
- }
- Q_UNREACHABLE();
-}
-
-const char *mirSurfaceStateToStr(MirSurfaceState surfaceState)
-{
- switch (surfaceState) {
- case mir_surface_state_unknown: return "unknown";
- case mir_surface_state_restored: return "restored";
- case mir_surface_state_minimized: return "minimized";
- case mir_surface_state_maximized: return "vertmaximized";
- case mir_surface_state_vertmaximized: return "vertmaximized";
- case mir_surface_state_fullscreen: return "fullscreen";
- case mir_surface_state_horizmaximized: return "horizmaximized";
- case mir_surface_state_hidden: return "hidden";
- case mir_surface_states: Q_UNREACHABLE();
- }
- Q_UNREACHABLE();
-}
-
-const char *mirPixelFormatToStr(MirPixelFormat pixelFormat)
-{
- switch (pixelFormat) {
- case mir_pixel_format_invalid: return "invalid";
- case mir_pixel_format_abgr_8888: return "ABGR8888";
- case mir_pixel_format_xbgr_8888: return "XBGR8888";
- case mir_pixel_format_argb_8888: return "ARGB8888";
- case mir_pixel_format_xrgb_8888: return "XRGB8888";
- case mir_pixel_format_bgr_888: return "BGR888";
- case mir_pixel_format_rgb_888: return "RGB888";
- case mir_pixel_format_rgb_565: return "RGB565";
- case mir_pixel_format_rgba_5551: return "RGBA5551";
- case mir_pixel_format_rgba_4444: return "RGBA4444";
- case mir_pixel_formats: Q_UNREACHABLE();
- }
- Q_UNREACHABLE();
-}
-
-const char *mirSurfaceTypeToStr(MirSurfaceType type)
-{
- switch (type) {
- case mir_surface_type_normal: return "Normal"; /**< AKA "regular" */
- case mir_surface_type_utility: return "Utility"; /**< AKA "floating regular" */
- case mir_surface_type_dialog: return "Dialog";
- case mir_surface_type_gloss: return "Gloss";
- case mir_surface_type_freestyle: return "Freestyle";
- case mir_surface_type_menu: return "Menu";
- case mir_surface_type_inputmethod: return "Input Method"; /**< AKA "OSK" or handwriting etc. */
- case mir_surface_type_satellite: return "Satellite"; /**< AKA "toolbox"/"toolbar" */
- case mir_surface_type_tip: return "Tip"; /**< AKA "tooltip" */
- case mir_surface_types: Q_UNREACHABLE();
- }
- return "";
-}
-
-MirSurfaceState qtWindowStateToMirSurfaceState(Qt::WindowState state)
-{
- switch (state) {
- case Qt::WindowNoState:
- case Qt::WindowActive:
- 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;
- }
- return mir_surface_state_unknown; // should never be reached
-}
-
-MirSurfaceType qtWindowTypeToMirSurfaceType(Qt::WindowType type)
-{
- switch (type & Qt::WindowType_Mask) {
- case Qt::Dialog:
- return mir_surface_type_dialog;
- case Qt::Sheet:
- case Qt::Drawer:
- return mir_surface_type_utility;
- case Qt::Popup:
- case Qt::Tool:
- return mir_surface_type_menu;
- case Qt::ToolTip:
- return mir_surface_type_tip;
- case Qt::SplashScreen:
- return mir_surface_type_freestyle;
- case Qt::Window:
- default:
- return mir_surface_type_normal;
- }
-}
-
-WId makeId()
-{
- static int id = 1;
- return id++;
-}
-
-UAUiWindowRole roleFor(QWindow *window)
-{
- QVariant roleVariant = window->property("role");
- if (!roleVariant.isValid())
- return U_MAIN_ROLE;
-
- uint role = roleVariant.toUInt();
- if (role < U_MAIN_ROLE || role > U_SHUTDOWN_DIALOG_ROLE)
- return U_MAIN_ROLE;
-
- return static_cast<UAUiWindowRole>(role);
-}
-
-QMirClientWindow *transientParentFor(QWindow *window)
-{
- QWindow *parent = window->transientParent();
- return parent ? static_cast<QMirClientWindow *>(parent->handle()) : nullptr;
-}
-
-bool requiresParent(const MirSurfaceType type)
-{
- switch (type) {
- case mir_surface_type_dialog: //FIXME - not quite what the specification dictates, but is what Mir's api dictates
- case mir_surface_type_utility:
- case mir_surface_type_gloss:
- case mir_surface_type_menu:
- case mir_surface_type_satellite:
- case mir_surface_type_tip:
- return true;
- default:
- return false;
- }
-}
-
-bool requiresParent(const Qt::WindowType type)
-{
- return requiresParent(qtWindowTypeToMirSurfaceType(type));
-}
-
-bool isMovable(const Qt::WindowType type)
-{
- auto mirType = qtWindowTypeToMirSurfaceType(type);
- switch (mirType) {
- case mir_surface_type_menu:
- case mir_surface_type_tip:
- return true;
- default:
- return false;
- }
-}
-
-Spec makeSurfaceSpec(QWindow *window, MirPixelFormat pixelFormat, QMirClientWindow *parentWindowHandle,
- MirConnection *connection)
-{
- const auto geometry = window->geometry();
- const int width = geometry.width() > 0 ? geometry.width() : 1;
- const int height = geometry.height() > 0 ? geometry.height() : 1;
- auto type = qtWindowTypeToMirSurfaceType(window->type());
-
- if (U_ON_SCREEN_KEYBOARD_ROLE == roleFor(window)) {
- type = mir_surface_type_inputmethod;
- }
-
- MirRectangle location{geometry.x(), geometry.y(), 0, 0};
- MirSurface *parent = nullptr;
- if (parentWindowHandle) {
- parent = parentWindowHandle->mirSurface();
- // Qt uses absolute positioning, but Mir positions surfaces relative to parent.
- location.top -= parentWindowHandle->geometry().top();
- location.left -= parentWindowHandle->geometry().left();
- }
-
- Spec spec;
-
- switch (type) {
- case mir_surface_type_menu:
- spec = Spec{mir_connection_create_spec_for_menu(connection, width, height, pixelFormat, parent,
- &location, mir_edge_attachment_any)};
- break;
- case mir_surface_type_dialog:
- spec = Spec{mir_connection_create_spec_for_modal_dialog(connection, width, height, pixelFormat, parent)};
- break;
- case mir_surface_type_utility:
- spec = Spec{mir_connection_create_spec_for_dialog(connection, width, height, pixelFormat)};
- break;
- case mir_surface_type_tip:
-#if MIR_CLIENT_VERSION < MIR_VERSION_NUMBER(3, 4, 0)
- spec = Spec{mir_connection_create_spec_for_tooltip(connection, width, height, pixelFormat, parent,
- &location)};
-#else
- spec = Spec{mir_connection_create_spec_for_tip(connection, width, height, pixelFormat, parent,
- &location, mir_edge_attachment_any)};
-#endif
- break;
- case mir_surface_type_inputmethod:
- spec = Spec{mir_connection_create_spec_for_input_method(connection, width, height, pixelFormat)};
- break;
- default:
- spec = Spec{mir_connection_create_spec_for_normal_surface(connection, width, height, pixelFormat)};
- break;
- }
-
- qCDebug(mirclient, "makeSurfaceSpec(window=%p): %s spec (type=0x%x, position=(%d, %d)px, size=(%dx%d)px)",
- window, mirSurfaceTypeToStr(type), window->type(), location.left, location.top, width, height);
-
- return std::move(spec);
-}
-
-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());
- }
-}
-
-MirSurface *createMirSurface(QWindow *window, int mirOutputId, QMirClientWindow *parentWindowHandle,
- MirPixelFormat pixelFormat, MirConnection *connection,
- mir_surface_event_callback inputCallback, void *inputContext)
-{
- auto spec = makeSurfaceSpec(window, pixelFormat, parentWindowHandle, connection);
-
- // Install event handler as early as possible
- mir_surface_spec_set_event_handler(spec.get(), inputCallback, inputContext);
-
- 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(), mirOutputId);
- }
-
- if (window->flags() & LowChromeWindowHint) {
- mir_surface_spec_set_shell_chrome(spec.get(), mir_shell_chrome_low);
- }
-
- if (!window->isVisible()) {
- mir_surface_spec_set_state(spec.get(), mir_surface_state_hidden);
- }
-
- auto surface = mir_surface_create_sync(spec.get());
- Q_ASSERT(mir_surface_is_valid(surface));
- return surface;
-}
-
-QMirClientWindow *getParentIfNecessary(QWindow *window, QMirClientInput *input)
-{
- QMirClientWindow *parentWindowHandle = nullptr;
- if (requiresParent(window->type())) {
- parentWindowHandle = transientParentFor(window);
- if (parentWindowHandle == nullptr) {
- // NOTE: Mir requires this surface have a parent. Try using the last surface to receive input as that will
- // most likely be the one that caused this surface to be created
- parentWindowHandle = input->lastInputWindow();
- }
- }
- return parentWindowHandle;
-}
-
-MirPixelFormat disableAlphaBufferIfPossible(MirPixelFormat pixelFormat)
-{
- switch (pixelFormat) {
- case mir_pixel_format_abgr_8888:
- return mir_pixel_format_xbgr_8888;
- case mir_pixel_format_argb_8888:
- return mir_pixel_format_xrgb_8888;
- default: // can do nothing, leave it alone
- return pixelFormat;
- }
-}
-} //namespace
-
-
-
-class UbuntuSurface
-{
-public:
- UbuntuSurface(QMirClientWindow *platformWindow, EGLDisplay display, QMirClientInput *input, MirConnection *connection);
- ~UbuntuSurface();
-
- UbuntuSurface(const UbuntuSurface &) = delete;
- UbuntuSurface& operator=(const UbuntuSurface &) = delete;
-
- void updateGeometry(const QRect &newGeometry);
- 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;
-
- MirSurfaceState state() const { return mir_surface_get_state(mMirSurface); }
- void setState(MirSurfaceState state);
-
- MirSurfaceType type() const { return mir_surface_get_type(mMirSurface); }
-
- void setShellChrome(MirShellChrome shellChrome);
-
- EGLSurface eglSurface() const { return mEglSurface; }
- MirSurface *mirSurface() const { return mMirSurface; }
-
- void setSurfaceParent(MirSurface*);
- bool hasParent() const { return mParented; }
-
- QSurfaceFormat format() const { return mFormat; }
-
- bool mNeedsExposeCatchup;
-
- QString persistentSurfaceId();
-
-private:
- static void surfaceEventCallback(MirSurface* surface, const MirEvent *event, void* context);
- void postEvent(const MirEvent *event);
-
- QWindow * const mWindow;
- QMirClientWindow * const mPlatformWindow;
- QMirClientInput * const mInput;
- MirConnection * const mConnection;
- QMirClientWindow * mParentWindowHandle{nullptr};
-
- MirSurface* mMirSurface;
- const EGLDisplay mEglDisplay;
- EGLSurface mEglSurface;
-
- bool mNeedsRepaint;
- bool mParented;
- QSize mBufferSize;
- QSurfaceFormat mFormat;
- MirPixelFormat mPixelFormat;
-
- QMutex mTargetSizeMutex;
- QSize mTargetSize;
- MirShellChrome mShellChrome;
- QString mPersistentIdStr;
-};
-
-UbuntuSurface::UbuntuSurface(QMirClientWindow *platformWindow, EGLDisplay display, QMirClientInput *input, MirConnection *connection)
- : mWindow(platformWindow->window())
- , mPlatformWindow(platformWindow)
- , mInput(input)
- , mConnection(connection)
- , mEglDisplay(display)
- , mNeedsRepaint(false)
- , mParented(mWindow->transientParent() || mWindow->parent())
- , mFormat(mWindow->requestedFormat())
- , mShellChrome(mWindow->flags() & LowChromeWindowHint ? mir_shell_chrome_low : mir_shell_chrome_normal)
-{
- // Have Qt choose most suitable EGLConfig for the requested surface format, and update format to reflect it
- EGLConfig config = q_configFromGLFormat(display, mFormat, true);
- if (config == 0) {
- // Older Intel Atom-based devices only support OpenGL 1.4 compatibility profile but by default
- // QML asks for at least OpenGL 2.0. The XCB GLX backend ignores this request and returns a
- // 1.4 context, but the XCB EGL backend tries to honor it, and fails. The 1.4 context appears to
- // have sufficient capabilities on MESA (i915) to render correctly however. So reduce the default
- // requested OpenGL version to 1.0 to ensure EGL will give us a working context (lp:1549455).
- static const bool isMesa = QString(eglQueryString(display, EGL_VENDOR)).contains(QStringLiteral("Mesa"));
- if (isMesa) {
- qCDebug(mirclientGraphics, "Attempting to choose OpenGL 1.4 context which may suit Mesa");
- mFormat.setMajorVersion(1);
- mFormat.setMinorVersion(4);
- config = q_configFromGLFormat(display, mFormat, true);
- }
- }
- if (config == 0) {
- qCritical() << "Qt failed to choose a suitable EGLConfig to suit the surface format" << mFormat;
- }
-
- mFormat = q_glFormatFromConfig(display, config, mFormat);
-
- // Have Mir decide the pixel format most suited to the chosen EGLConfig. This is the only way
- // Mir will know what EGLConfig has been chosen - it cannot deduce it from the buffers.
- mPixelFormat = mir_connection_get_egl_pixel_format(connection, display, config);
- // But the chosen EGLConfig might have an alpha buffer enabled, even if not requested by the client.
- // If that's the case, try to edit the chosen pixel format in order to disable the alpha buffer.
- // This is an optimization for the compositor, as it can avoid blending this surface.
- if (mWindow->requestedFormat().alphaBufferSize() < 0) {
- mPixelFormat = disableAlphaBufferIfPossible(mPixelFormat);
- }
-
- const auto outputId = static_cast<QMirClientScreen *>(mWindow->screen()->handle())->mirOutputId();
-
- mParentWindowHandle = getParentIfNecessary(mWindow, input);
-
- mMirSurface = createMirSurface(mWindow, outputId, mParentWindowHandle, mPixelFormat, connection, surfaceEventCallback, this);
- mEglSurface = eglCreateWindowSurface(mEglDisplay, config, nativeWindowFor(mMirSurface), nullptr);
-
- mNeedsExposeCatchup = mir_surface_get_visibility(mMirSurface) == mir_surface_visibility_occluded;
-
- // 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);
-
- // Assume that the buffer size matches the surface size at creation time
- mBufferSize = geom.size();
- QWindowSystemInterface::handleGeometryChange(mWindow, geom);
-
- qCDebug(mirclient) << "Created surface with geometry:" << geom << "title:" << mWindow->title()
- << "role:" << roleFor(mWindow);
- qCDebug(mirclientGraphics)
- << "Requested format:" << mWindow->requestedFormat()
- << "\nActual format:" << mFormat
- << "with associated Mir pixel format:" << mirPixelFormatToStr(mPixelFormat);
-}
-
-UbuntuSurface::~UbuntuSurface()
-{
- if (mEglSurface != EGL_NO_SURFACE)
- eglDestroySurface(mEglDisplay, mEglSurface);
- if (mMirSurface) {
- mir_surface_release_sync(mMirSurface);
- }
-}
-
-void UbuntuSurface::updateGeometry(const QRect &newGeometry)
-{
- qCDebug(mirclient,"updateGeometry(window=%p, width=%d, height=%d)", mWindow,
- newGeometry.width(), newGeometry.height());
-
- Spec spec;
- if (isMovable(mWindow->type())) {
- spec = Spec{makeSurfaceSpec(mWindow, mPixelFormat, mParentWindowHandle, mConnection)};
- } else {
- spec = Spec{mir_connection_create_spec_for_changes(mConnection)};
- mir_surface_spec_set_width(spec.get(), newGeometry.width());
- mir_surface_spec_set_height(spec.get(), newGeometry.height());
- }
- mir_surface_apply_spec(mMirSurface, spec.get());
-}
-
-void UbuntuSurface::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());
-}
-
-void UbuntuSurface::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 UbuntuSurface::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 UbuntuSurface::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 UbuntuSurface::setState(MirSurfaceState state)
-{
- mir_wait_for(mir_surface_set_state(mMirSurface, state));
-}
-
-void UbuntuSurface::setShellChrome(MirShellChrome chrome)
-{
- if (chrome != mShellChrome) {
- auto spec = Spec{mir_connection_create_spec_for_changes(mConnection)};
- mir_surface_spec_set_shell_chrome(spec.get(), chrome);
- mir_surface_apply_spec(mMirSurface, spec.get());
-
- mShellChrome = chrome;
- }
-}
-
-void UbuntuSurface::onSwapBuffersDone()
-{
- static int sFrameNumber = 0;
- ++sFrameNumber;
-
- EGLint eglSurfaceWidth = -1;
- EGLint eglSurfaceHeight = -1;
- eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, &eglSurfaceWidth);
- eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, &eglSurfaceHeight);
-
- const bool validSize = eglSurfaceWidth > 0 && eglSurfaceHeight > 0;
-
- if (validSize && (mBufferSize.width() != eglSurfaceWidth || mBufferSize.height() != eglSurfaceHeight)) {
-
- qCDebug(mirclientBufferSwap, "onSwapBuffersDone(window=%p) [%d] - size changed (%d, %d) => (%d, %d)",
- mWindow, sFrameNumber, mBufferSize.width(), mBufferSize.height(), eglSurfaceWidth, eglSurfaceHeight);
-
- mBufferSize.rwidth() = eglSurfaceWidth;
- mBufferSize.rheight() = eglSurfaceHeight;
-
- QRect newGeometry = mPlatformWindow->geometry();
- newGeometry.setSize(mBufferSize);
-
- QWindowSystemInterface::handleGeometryChange(mWindow, newGeometry);
- } else {
- qCDebug(mirclientBufferSwap, "onSwapBuffersDone(window=%p) [%d] - buffer size (%d,%d)",
- mWindow, sFrameNumber, mBufferSize.width(), mBufferSize.height());
- }
-}
-
-void UbuntuSurface::surfaceEventCallback(MirSurface *surface, const MirEvent *event, void* context)
-{
- Q_UNUSED(surface);
- Q_ASSERT(context != nullptr);
-
- auto s = static_cast<UbuntuSurface *>(context);
- s->postEvent(event);
-}
-
-void UbuntuSurface::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);
- qCDebug(mirclient, "resizeEvent(window=%p, width=%d, height=%d)", mWindow, width, height);
-
- QMutexLocker lock(&mTargetSizeMutex);
- mTargetSize.rwidth() = width;
- mTargetSize.rheight() = height;
- }
-
- mInput->postEvent(mPlatformWindow, event);
-}
-
-void UbuntuSurface::setSurfaceParent(MirSurface* parent)
-{
- qCDebug(mirclient, "setSurfaceParent(window=%p)", mWindow);
-
- mParented = true;
- Spec spec{mir_connection_create_spec_for_changes(mConnection)};
- mir_surface_spec_set_parent(spec.get(), parent);
- mir_surface_apply_spec(mMirSurface, spec.get());
-}
-
-QString UbuntuSurface::persistentSurfaceId()
-{
- if (mPersistentIdStr.isEmpty()) {
- MirPersistentId* mirPermaId = mir_surface_request_persistent_id_sync(mMirSurface);
- mPersistentIdStr = mir_persistent_id_as_string(mirPermaId);
- mir_persistent_id_release(mirPermaId);
- }
- return mPersistentIdStr;
-}
-
-QMirClientWindow::QMirClientWindow(QWindow *w, QMirClientInput *input, QMirClientNativeInterface *native,
- QMirClientAppStateController *appState, EGLDisplay eglDisplay,
- MirConnection *mirConnection, QMirClientDebugExtension *debugExt)
- : QObject(nullptr)
- , QPlatformWindow(w)
- , mId(makeId())
- , mWindowState(w->windowState())
- , mWindowFlags(w->flags())
- , mWindowVisible(false)
- , mAppStateController(appState)
- , mDebugExtention(debugExt)
- , mNativeInterface(native)
- , mSurface(new UbuntuSurface{this, eglDisplay, input, mirConnection})
- , mScale(1.0)
- , mFormFactor(mir_form_factor_unknown)
-{
- mWindowExposed = mSurface->mNeedsExposeCatchup == false;
-
- qCDebug(mirclient, "QMirClientWindow(window=%p, screen=%p, input=%p, surf=%p) with title '%s', role: '%d'",
- w, w->screen()->handle(), input, mSurface.get(), qPrintable(window()->title()), roleFor(window()));
-}
-
-QMirClientWindow::~QMirClientWindow()
-{
- qCDebug(mirclient, "~QMirClientWindow(window=%p)", this);
-}
-
-void QMirClientWindow::handleSurfaceResized(int width, int height)
-{
- QMutexLocker lock(&mMutex);
- qCDebug(mirclient, "handleSurfaceResize(window=%p, size=(%dx%d)px", 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();
- lock.unlock();
- qCDebug(mirclient, "handleSurfaceResize(window=%p) redraw %d times", window(), numRepaints);
- for (int i = 0; i < numRepaints; i++) {
- qCDebug(mirclient, "handleSurfaceResize(window=%p) repainting size=(%dx%d)dp", window(), geometry().size().width(), geometry().size().height());
- QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
- }
-}
-
-void QMirClientWindow::handleSurfaceExposeChange(bool exposed)
-{
- QMutexLocker lock(&mMutex);
- qCDebug(mirclient, "handleSurfaceExposeChange(window=%p, exposed=%s)", window(), exposed ? "true" : "false");
-
- mSurface->mNeedsExposeCatchup = false;
- if (mWindowExposed == exposed) return;
- mWindowExposed = exposed;
-
- lock.unlock();
- QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
-}
-
-void QMirClientWindow::handleSurfaceFocusChanged(bool focused)
-{
- qCDebug(mirclient, "handleSurfaceFocusChanged(window=%p, focused=%d)", window(), focused);
- if (focused) {
- mAppStateController->setWindowFocused(true);
- QWindowSystemInterface::handleWindowActivated(window(), Qt::ActiveWindowFocusReason);
- } else {
- mAppStateController->setWindowFocused(false);
- }
-}
-
-void QMirClientWindow::handleSurfaceVisibilityChanged(bool visible)
-{
- qCDebug(mirclient, "handleSurfaceVisibilityChanged(window=%p, visible=%d)", window(), visible);
-
- if (mWindowVisible == visible) return;
- mWindowVisible = visible;
-
- QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
-}
-
-void QMirClientWindow::handleSurfaceStateChanged(Qt::WindowState state)
-{
- qCDebug(mirclient, "handleSurfaceStateChanged(window=%p, %s)", window(), qtWindowStateToStr(state));
-
- if (mWindowState == state) return;
- mWindowState = state;
-
- QWindowSystemInterface::handleWindowStateChanged(window(), state);
-}
-
-void QMirClientWindow::setWindowState(Qt::WindowStates states)
-{
- Qt::WindowState state = Qt::WindowNoState;
- if (states & Qt::WindowMinimized)
- state = Qt::WindowMinimized;
- else if (states & Qt::WindowFullScreen)
- state = Qt::WindowFullScreen;
- else if (states & Qt::WindowMaximized)
- state = Qt::WindowMaximized;
-
- QMutexLocker lock(&mMutex);
- qCDebug(mirclient, "setWindowState(window=%p, %s)", this, qtWindowStateToStr(state));
-
- if (mWindowState == state) return;
- mWindowState = state;
-
- lock.unlock();
- updateSurfaceState();
-}
-
-void QMirClientWindow::setWindowFlags(Qt::WindowFlags flags)
-{
- QMutexLocker lock(&mMutex);
- qCDebug(mirclient, "setWindowFlags(window=%p, 0x%x)", this, (int)flags);
-
- if (mWindowFlags == flags) return;
- mWindowFlags = flags;
-
- mSurface->setShellChrome(mWindowFlags & LowChromeWindowHint ? mir_shell_chrome_low : mir_shell_chrome_normal);
-}
-
-QRect QMirClientWindow::geometry() const
-{
- if (mDebugExtention) {
- auto geom = QPlatformWindow::geometry();
- geom.moveTopLeft(mDebugExtention->mapSurfacePointToScreen(mSurface->mirSurface(), QPoint(0,0)));
- return geom;
- } else {
- return QPlatformWindow::geometry();
- }
-}
-
-void QMirClientWindow::setGeometry(const QRect& rect)
-{
- QMutexLocker lock(&mMutex);
-
- if (window()->windowState() == Qt::WindowFullScreen || window()->windowState() == Qt::WindowMaximized) {
- qCDebug(mirclient, "setGeometry(window=%p) - not resizing, window is maximized or fullscreen", window());
- return;
- }
-
- qCDebug(mirclient, "setGeometry (window=%p, position=(%d, %d)dp, size=(%dx%d)dp)",
- window(), rect.x(), rect.y(), rect.width(), rect.height());
- // Immediately update internal geometry so Qt believes position updated
- QRect newPosition(geometry());
- newPosition.moveTo(rect.topLeft());
- QPlatformWindow::setGeometry(newPosition);
-
- mSurface->updateGeometry(rect);
- // Note: don't call handleGeometryChange here, wait to see what Mir replies with.
-}
-
-void QMirClientWindow::setVisible(bool visible)
-{
- QMutexLocker lock(&mMutex);
- qCDebug(mirclient, "setVisible (window=%p, visible=%s)", window(), visible ? "true" : "false");
-
- if (mWindowVisible == visible) return;
- mWindowVisible = visible;
-
- if (visible) {
- if (!mSurface->hasParent() && window()->type() == Qt::Dialog) {
- // The dialog may have been parented after creation time
- // so morph it into a modal dialog
- auto parent = transientParentFor(window());
- if (parent) {
- mSurface->setSurfaceParent(parent->mirSurface());
- }
- }
- }
-
- lock.unlock();
- updateSurfaceState();
- QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
-}
-
-void QMirClientWindow::setWindowTitle(const QString& title)
-{
- QMutexLocker lock(&mMutex);
- qCDebug(mirclient, "setWindowTitle(window=%p) title=%s)", window(), title.toUtf8().constData());
- mSurface->updateTitle(title);
-}
-
-void QMirClientWindow::propagateSizeHints()
-{
- QMutexLocker lock(&mMutex);
- const auto win = window();
- qCDebug(mirclient, "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());
-}
-
-bool QMirClientWindow::isExposed() const
-{
- // mNeedsExposeCatchup because we need to render a frame to get the expose surface event from mir.
- return mWindowVisible && (mWindowExposed || (mSurface && mSurface->mNeedsExposeCatchup));
-}
-
-QSurfaceFormat QMirClientWindow::format() const
-{
- return mSurface->format();
-}
-
-QPoint QMirClientWindow::mapToGlobal(const QPoint &pos) const
-{
- if (mDebugExtention) {
- return mDebugExtention->mapSurfacePointToScreen(mSurface->mirSurface(), pos);
- } else {
- return pos;
- }
-}
-
-void* QMirClientWindow::eglSurface() const
-{
- return mSurface->eglSurface();
-}
-
-MirSurface *QMirClientWindow::mirSurface() const
-{
- return mSurface->mirSurface();
-}
-
-WId QMirClientWindow::winId() const
-{
- return mId;
-}
-
-void QMirClientWindow::onSwapBuffersDone()
-{
- QMutexLocker lock(&mMutex);
- mSurface->onSwapBuffersDone();
-
- if (mSurface->mNeedsExposeCatchup) {
- mSurface->mNeedsExposeCatchup = false;
- mWindowExposed = false;
-
- lock.unlock();
- QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
- }
-}
-
-void QMirClientWindow::handleScreenPropertiesChange(MirFormFactor formFactor, float scale)
-{
- // Update the scale & form factor native-interface properties for the windows affected
- // as there is no convenient way to emit signals for those custom properties on a QScreen
- if (formFactor != mFormFactor) {
- mFormFactor = formFactor;
- Q_EMIT mNativeInterface->windowPropertyChanged(this, QStringLiteral("formFactor"));
- }
-
- if (!qFuzzyCompare(scale, mScale)) {
- mScale = scale;
- Q_EMIT mNativeInterface->windowPropertyChanged(this, QStringLiteral("scale"));
- }
-}
-
-void QMirClientWindow::updateSurfaceState()
-{
- QMutexLocker lock(&mMutex);
- MirSurfaceState newState = mWindowVisible ? qtWindowStateToMirSurfaceState(mWindowState) :
- mir_surface_state_hidden;
- qCDebug(mirclient, "updateSurfaceState (window=%p, surfaceState=%s)", window(), mirSurfaceStateToStr(newState));
- if (newState != mSurface->state()) {
- mSurface->setState(newState);
- }
-}
-
-QString QMirClientWindow::persistentSurfaceId()
-{
- return mSurface->persistentSurfaceId();
-}
diff --git a/src/plugins/platforms/mirclient/qmirclientwindow.h b/src/plugins/platforms/mirclient/qmirclientwindow.h
deleted file mode 100644
index 6c5695d62f..0000000000
--- a/src/plugins/platforms/mirclient/qmirclientwindow.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2014-2016 Canonical, Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the plugins of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMIRCLIENTWINDOW_H
-#define QMIRCLIENTWINDOW_H
-
-#include <qpa/qplatformwindow.h>
-#include <QSharedPointer>
-#include <QMutex>
-
-#include <mir_toolkit/common.h> // needed only for MirFormFactor enum
-
-#include <memory>
-
-#include <EGL/egl.h>
-
-class QMirClientAppStateController;
-class QMirClientDebugExtension;
-class QMirClientNativeInterface;
-class QMirClientInput;
-class QMirClientScreen;
-class UbuntuSurface;
-struct MirSurface;
-class MirConnection;
-
-class QMirClientWindow : public QObject, public QPlatformWindow
-{
- Q_OBJECT
-public:
- QMirClientWindow(QWindow *w, QMirClientInput *input, QMirClientNativeInterface* native,
- QMirClientAppStateController *appState, EGLDisplay eglDisplay,
- MirConnection *mirConnection, QMirClientDebugExtension *debugExt);
- virtual ~QMirClientWindow();
-
- // QPlatformWindow methods.
- WId winId() const override;
- QRect geometry() const override;
- void setGeometry(const QRect&) override;
- void setWindowState(Qt::WindowStates state) override;
- void setWindowFlags(Qt::WindowFlags flags) override;
- void setVisible(bool visible) override;
- void setWindowTitle(const QString &title) override;
- void propagateSizeHints() override;
- bool isExposed() const override;
-
- QPoint mapToGlobal(const QPoint &pos) const override;
- QSurfaceFormat format() const override;
-
- // Additional Window properties exposed by NativeInterface
- MirFormFactor formFactor() const { return mFormFactor; }
- float scale() const { return mScale; }
-
- // New methods.
- void *eglSurface() const;
- MirSurface *mirSurface() const;
- void handleSurfaceResized(int width, int height);
- void handleSurfaceExposeChange(bool exposed);
- void handleSurfaceFocusChanged(bool focused);
- void handleSurfaceVisibilityChanged(bool visible);
- void handleSurfaceStateChanged(Qt::WindowState state);
- void onSwapBuffersDone();
- void handleScreenPropertiesChange(MirFormFactor formFactor, float scale);
- QString persistentSurfaceId();
-
-private:
- void updateSurfaceState();
- mutable QMutex mMutex;
- const WId mId;
- Qt::WindowState mWindowState;
- Qt::WindowFlags mWindowFlags;
- bool mWindowVisible;
- bool mWindowExposed;
- QMirClientAppStateController *mAppStateController;
- QMirClientDebugExtension *mDebugExtention;
- QMirClientNativeInterface *mNativeInterface;
- std::unique_ptr<UbuntuSurface> mSurface;
- float mScale;
- MirFormFactor mFormFactor;
-};
-
-#endif // QMIRCLIENTWINDOW_H
diff --git a/src/plugins/platforms/platforms.pro b/src/plugins/platforms/platforms.pro
index acc55adf6f..c4f2b30965 100644
--- a/src/plugins/platforms/platforms.pro
+++ b/src/plugins/platforms/platforms.pro
@@ -48,6 +48,4 @@ haiku {
wasm: SUBDIRS += wasm
-qtConfig(mirclient): SUBDIRS += mirclient
-
qtConfig(integrityfb): SUBDIRS += integrity
diff --git a/src/printsupport/dialogs/qpagesetupdialog_unix.cpp b/src/printsupport/dialogs/qpagesetupdialog_unix.cpp
index d9b4a84aa9..1d8af9dbf0 100644
--- a/src/printsupport/dialogs/qpagesetupdialog_unix.cpp
+++ b/src/printsupport/dialogs/qpagesetupdialog_unix.cpp
@@ -361,13 +361,21 @@ void QPageSetupWidget::initPageSizes()
QPlatformPrinterSupport *ps = QPlatformPrinterSupportPlugin::get();
if (ps) {
QPrintDevice printDevice = ps->createPrintDevice(m_printerName);
+ const QPageSize defaultSize = printDevice.defaultPageSize();
const auto pageSizes = printDevice.supportedPageSizes();
for (const QPageSize &pageSize : pageSizes)
m_ui.pageSizeCombo->addItem(pageSize.name(), QVariant::fromValue(pageSize));
- if (m_ui.pageSizeCombo->count() > 0 && printDevice.supportsCustomPageSizes()) {
- m_ui.pageSizeCombo->addItem(tr("Custom"));
- m_realCustomPageSizeIndex = m_ui.pageSizeCombo->count() - 1;
+ if (m_ui.pageSizeCombo->count() > 0) {
+ if (printDevice.supportsCustomPageSizes()) {
+ m_ui.pageSizeCombo->addItem(tr("Custom"));
+ m_realCustomPageSizeIndex = m_ui.pageSizeCombo->count() - 1;
+ }
m_blockSignals = false;
+
+ // If the defaultSize is index 0, setCurrentIndex won't emit the currentIndexChanged
+ // signal; workaround the issue by initially setting the currentIndex to -1
+ m_ui.pageSizeCombo->setCurrentIndex(-1);
+ m_ui.pageSizeCombo->setCurrentIndex(m_ui.pageSizeCombo->findData(QVariant::fromValue(defaultSize)));
return;
}
}
@@ -403,12 +411,6 @@ void QPageSetupWidget::setPrinter(QPrinter *printer, QPrintDevice *printDevice,
// Initialize the layout to the current QPrinter layout
m_pageLayout = m_printer->pageLayout();
- if (printDevice) {
- const QPageSize pageSize = printDevice->defaultPageSize();
- const QMarginsF printable = printDevice->printableMargins(pageSize, m_pageLayout.orientation(), m_printer->resolution());
- m_pageLayout.setPageSize(pageSize, qt_convertMargins(printable, QPageLayout::Point, m_pageLayout.units()));
- }
-
// Assume if margins are Points then is by default, so set to locale default units
if (m_pageLayout.units() == QPageLayout::Point) {
if (QLocale().measurementSystem() == QLocale::MetricSystem)
@@ -735,8 +737,12 @@ int QPageSetupDialog::exec()
Q_D(QPageSetupDialog);
int ret = QDialog::exec();
- if (ret == Accepted)
+ if (ret == Accepted) {
static_cast <QUnixPageSetupDialogPrivate*>(d)->widget->setupPrinter();
+ static_cast <QUnixPageSetupDialogPrivate*>(d)->widget->updateSavedValues();
+ } else {
+ static_cast <QUnixPageSetupDialogPrivate*>(d)->widget->revertToSavedValues();
+ }
return ret;
}
diff --git a/src/printsupport/dialogs/qprintpreviewdialog.cpp b/src/printsupport/dialogs/qprintpreviewdialog.cpp
index e6b665f82c..258741c35c 100644
--- a/src/printsupport/dialogs/qprintpreviewdialog.cpp
+++ b/src/printsupport/dialogs/qprintpreviewdialog.cpp
@@ -152,8 +152,8 @@ class QPrintPreviewDialogPrivate : public QDialogPrivate
Q_DECLARE_PUBLIC(QPrintPreviewDialog)
public:
QPrintPreviewDialogPrivate()
- : printDialog(nullptr), ownPrinter(false),
- initialized(false) {}
+ : printDialog(nullptr), pageSetupDialog(nullptr),
+ ownPrinter(false), initialized(false) {}
// private slots
void _q_fit(QAction *action);
@@ -178,6 +178,7 @@ public:
void updateZoomFactor();
QPrintDialog *printDialog;
+ QPageSetupDialog *pageSetupDialog;
QPrintPreviewWidget *preview;
QPrinter *printer;
bool ownPrinter;
@@ -602,8 +603,10 @@ void QPrintPreviewDialogPrivate::_q_pageSetup()
{
Q_Q(QPrintPreviewDialog);
- QPageSetupDialog pageSetup(printer, q);
- if (pageSetup.exec() == QDialog::Accepted) {
+ if (!pageSetupDialog)
+ pageSetupDialog = new QPageSetupDialog(printer, q);
+
+ if (pageSetupDialog->exec() == QDialog::Accepted) {
// update possible orientation changes
if (preview->orientation() == QPrinter::Portrait) {
portraitAction->setChecked(true);
@@ -713,6 +716,7 @@ QPrintPreviewDialog::~QPrintPreviewDialog()
if (d->ownPrinter)
delete d->printer;
delete d->printDialog;
+ delete d->pageSetupDialog;
}
/*!
diff --git a/src/testlib/qsignaldumper.cpp b/src/testlib/qsignaldumper.cpp
index 8305c5d424..b3360b4e6c 100644
--- a/src/testlib/qsignaldumper.cpp
+++ b/src/testlib/qsignaldumper.cpp
@@ -170,13 +170,12 @@ void QSignalDumper::startDump()
{
static QSignalSpyCallbackSet set = { QTest::qSignalDumperCallback,
QTest::qSignalDumperCallbackSlot, QTest::qSignalDumperCallbackEndSignal, 0 };
- qt_register_signal_spy_callbacks(set);
+ qt_register_signal_spy_callbacks(&set);
}
void QSignalDumper::endDump()
{
- static QSignalSpyCallbackSet nset = { 0, 0, 0 ,0 };
- qt_register_signal_spy_callbacks(nset);
+ qt_register_signal_spy_callbacks(nullptr);
}
void QSignalDumper::ignoreClass(const QByteArray &klass)
diff --git a/src/tools/bootstrap/bootstrap.pro b/src/tools/bootstrap/bootstrap.pro
index 83e44ff9a4..3a1a186e8e 100644
--- a/src/tools/bootstrap/bootstrap.pro
+++ b/src/tools/bootstrap/bootstrap.pro
@@ -19,8 +19,6 @@ DEFINES += \
QT_NO_FOREACH \
QT_NO_CAST_FROM_ASCII
-DEFINES -= QT_EVAL
-
SOURCES += \
../../corelib/codecs/qlatincodec.cpp \
../../corelib/codecs/qtextcodec.cpp \
diff --git a/src/tools/moc/moc.cpp b/src/tools/moc/moc.cpp
index 5d777ece2e..c82a6d71ae 100644
--- a/src/tools/moc/moc.cpp
+++ b/src/tools/moc/moc.cpp
@@ -565,6 +565,7 @@ void Moc::parse()
} else if (!test(SEMIC)) {
NamespaceDef def;
def.classname = nsName;
+ def.doGenerate = currentFilenames.size() <= 1;
next(LBRACE);
def.begin = index - 1;
@@ -572,25 +573,22 @@ void Moc::parse()
def.end = index;
index = def.begin + 1;
- const bool parseNamespace = currentFilenames.size() <= 1;
- if (parseNamespace) {
- for (int i = namespaceList.size() - 1; i >= 0; --i) {
- if (inNamespace(&namespaceList.at(i))) {
- def.qualified.prepend(namespaceList.at(i).classname + "::");
- }
- }
- for (const QByteArray &ns : nested) {
- NamespaceDef parentNs;
- parentNs.classname = ns;
- parentNs.qualified = def.qualified;
- def.qualified += ns + "::";
- parentNs.begin = def.begin;
- parentNs.end = def.end;
- namespaceList += parentNs;
+ for (int i = namespaceList.size() - 1; i >= 0; --i) {
+ if (inNamespace(&namespaceList.at(i))) {
+ def.qualified.prepend(namespaceList.at(i).classname + "::");
}
}
+ for (const QByteArray &ns : nested) {
+ NamespaceDef parentNs;
+ parentNs.classname = ns;
+ parentNs.qualified = def.qualified;
+ def.qualified += ns + "::";
+ parentNs.begin = def.begin;
+ parentNs.end = def.end;
+ namespaceList += parentNs;
+ }
- while (parseNamespace && inNamespace(&def) && hasNext()) {
+ while (inNamespace(&def) && hasNext()) {
switch (next()) {
case NAMESPACE:
if (test(IDENTIFIER)) {
@@ -915,7 +913,8 @@ void Moc::parse()
} else {
knownGadgets.insert(def.classname, def.qualified);
knownGadgets.insert(def.qualified, def.qualified);
- classList += def;
+ if (n.doGenerate)
+ classList += def;
}
}
}
diff --git a/src/tools/moc/moc.h b/src/tools/moc/moc.h
index d6482f4e44..54f935a8da 100644
--- a/src/tools/moc/moc.h
+++ b/src/tools/moc/moc.h
@@ -188,6 +188,7 @@ Q_DECLARE_TYPEINFO(ClassDef::Interface, Q_MOVABLE_TYPE);
struct NamespaceDef : BaseDef {
bool hasQNamespace = false;
+ bool doGenerate = false;
};
Q_DECLARE_TYPEINFO(NamespaceDef, Q_MOVABLE_TYPE);
diff --git a/src/widgets/doc/snippets/timeline/main.cpp b/src/widgets/doc/snippets/timeline/main.cpp
index 74aa749254..4dfa2400d0 100644
--- a/src/widgets/doc/snippets/timeline/main.cpp
+++ b/src/widgets/doc/snippets/timeline/main.cpp
@@ -48,7 +48,7 @@
**
****************************************************************************/
-#include <QtGui>
+#include <QtWidgets>
#include <math.h>
int main(int argv, char *args[])
@@ -68,7 +68,7 @@ int main(int argv, char *args[])
for (int i = 0; i < 200; ++i)
animation->setPosAt(i / 200.0, QPointF(i, i));
- QGraphicsScene *scene = new QGraphicsScene();
+ QGraphicsScene *scene = new QGraphicsScene;
scene->setSceneRect(0, 0, 250, 250);
scene->addItem(ball);
diff --git a/src/widgets/graphicsview/qgraphicsitemanimation.cpp b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
index 78b91d5c39..ad77e2f260 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.cpp
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
@@ -115,7 +115,7 @@ public:
QGraphicsItem *item;
QPointF startPos;
- QMatrix startMatrix;
+ QTransform startTransform;
qreal step;
@@ -294,23 +294,38 @@ QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::posList() const
return list;
}
+#if QT_DEPRECATED_SINCE(5, 14)
/*!
Returns the matrix used to transform the item at the specified \a step value.
+
+ \obsolete Use transformAt() instead
*/
QMatrix QGraphicsItemAnimation::matrixAt(qreal step) const
{
check_step_valid(step, "matrixAt");
+ return transformAt(step).toAffine();
+}
+#endif
+
+/*!
+ Returns the transform used for the item at the specified \a step value.
+
+ \since 5.14
+*/
+QTransform QGraphicsItemAnimation::transformAt(qreal step) const
+{
+ check_step_valid(step, "transformAt");
- QMatrix matrix;
+ QTransform transform;
if (!d->rotation.isEmpty())
- matrix.rotate(rotationAt(step));
+ transform.rotate(rotationAt(step));
if (!d->verticalScale.isEmpty())
- matrix.scale(horizontalScaleAt(step), verticalScaleAt(step));
+ transform.scale(horizontalScaleAt(step), verticalScaleAt(step));
if (!d->verticalShear.isEmpty())
- matrix.shear(horizontalShearAt(step), verticalShearAt(step));
+ transform.shear(horizontalShearAt(step), verticalShearAt(step));
if (!d->xTranslation.isEmpty())
- matrix.translate(xTranslationAt(step), yTranslationAt(step));
- return matrix;
+ transform.translate(xTranslationAt(step), yTranslationAt(step));
+ return transform;
}
/*!
@@ -542,7 +557,7 @@ void QGraphicsItemAnimation::setStep(qreal step)
|| !d->horizontalShear.isEmpty()
|| !d->xTranslation.isEmpty()
|| !d->yTranslation.isEmpty()) {
- d->item->setMatrix(d->startMatrix * matrixAt(step));
+ d->item->setTransform(d->startTransform * transformAt(step));
}
}
@@ -562,7 +577,7 @@ void QGraphicsItemAnimation::reset()
if (!d->item)
return;
d->startPos = d->item->pos();
- d->startMatrix = d->item->matrix();
+ d->startTransform = d->item->transform();
}
#endif
diff --git a/src/widgets/graphicsview/qgraphicsitemanimation.h b/src/widgets/graphicsview/qgraphicsitemanimation.h
index f983bd8026..3051fb2e2b 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.h
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.h
@@ -51,6 +51,7 @@ class QGraphicsItem;
class QMatrix;
class QPointF;
class QTimeLine;
+class QTransform;
template <class T1, class T2> struct QPair;
class QGraphicsItemAnimationPrivate;
@@ -71,7 +72,11 @@ public:
QList<QPair<qreal, QPointF> > posList() const;
void setPosAt(qreal step, const QPointF &pos);
+#if QT_DEPRECATED_SINCE(5, 14)
+ QT_DEPRECATED_X("Use transformAt() instead")
QMatrix matrixAt(qreal step) const;
+#endif
+ QTransform transformAt(qreal step) const;
qreal rotationAt(qreal step) const;
QList<QPair<qreal, qreal> > rotationList() const;
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index 7c44bfe39d..9e784b41c6 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -575,10 +575,6 @@ void QApplicationPrivate::init()
initialize();
eventDispatcher->startingUp();
-#ifdef QT_EVAL
- extern void qt_gui_eval_init(QCoreApplicationPrivate::Type);
- qt_gui_eval_init(application_type);
-#endif
#ifndef QT_NO_ACCESSIBILITY
// factory for accessible interfaces for widgets shipped with Qt
QAccessible::installFactory(&qAccessibleFactory);
diff --git a/src/widgets/kernel/qformlayout.cpp b/src/widgets/kernel/qformlayout.cpp
index bd0ea2598a..9146ba84c8 100644
--- a/src/widgets/kernel/qformlayout.cpp
+++ b/src/widgets/kernel/qformlayout.cpp
@@ -783,7 +783,7 @@ void QFormLayoutPrivate::setupVerticalLayoutData(int width)
vLayouts[vidx].expansive = expanding || (vLayouts[vidx].stretch > 0);
vLayouts[vidx].empty = false;
- if (vLayouts[vidx].stretch > 0)
+ if (vLayouts[vidx].expansive)
addTopBottomStretch = false;
if (vidx > 1)
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index 6a5f80f1ff..51b2bf8b5f 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -1348,11 +1348,6 @@ void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
setAttribute(Qt::WA_DropSiteRegistered, true);
-#ifdef QT_EVAL
- extern void qt_eval_init_widget(QWidget *w);
- qt_eval_init_widget(this);
-#endif
-
// need to force the resting of the icon after changing parents
if (testAttribute(Qt::WA_SetWindowIcon))
d->setWindowIcon_sys();
@@ -6054,13 +6049,7 @@ QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widg
{
Q_ASSERT(widget);
-#ifdef QT_EVAL
- extern QString qt_eval_adapt_window_title(const QString &title);
- QString cap = qt_eval_adapt_window_title(title);
-#else
QString cap = title;
-#endif
-
if (cap.isEmpty())
return cap;
diff --git a/src/widgets/kernel/qwidgetbackingstore.cpp b/src/widgets/kernel/qwidgetbackingstore.cpp
index 0481dffda8..595beeaf47 100644
--- a/src/widgets/kernel/qwidgetbackingstore.cpp
+++ b/src/widgets/kernel/qwidgetbackingstore.cpp
@@ -310,12 +310,6 @@ bool QWidgetBackingStore::bltRect(const QRect &rect, int dx, int dy, QWidget *wi
return store->scroll(tlwRect, dx, dy);
}
-void QWidgetBackingStore::releaseBuffer()
-{
- if (store)
- store->resize(QSize());
-}
-
/*!
Prepares the window surface to paint a\ toClean region of the \a widget and
updates the BeginPaintInfo struct accordingly.
diff --git a/src/widgets/kernel/qwidgetbackingstore_p.h b/src/widgets/kernel/qwidgetbackingstore_p.h
index 4d15ab138e..e7a2bca33a 100644
--- a/src/widgets/kernel/qwidgetbackingstore_p.h
+++ b/src/widgets/kernel/qwidgetbackingstore_p.h
@@ -149,7 +149,6 @@ private:
void doSync();
bool bltRect(const QRect &rect, int dx, int dy, QWidget *widget);
- void releaseBuffer();
void beginPaint(QRegion &toClean, QWidget *widget, QBackingStore *backingStore,
BeginPaintInfo *returnInfo, bool toCleanIsInTopLevelCoordinates = true);
diff --git a/src/widgets/styles/qstylesheetstyle.cpp b/src/widgets/styles/qstylesheetstyle.cpp
index b058d4c557..1ad67f248a 100644
--- a/src/widgets/styles/qstylesheetstyle.cpp
+++ b/src/widgets/styles/qstylesheetstyle.cpp
@@ -4090,6 +4090,11 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
if (subRule.hasFont)
p->setFont(subRule.font);
boxCopy.rect = subRule.contentsRect(opt->rect);
+ if (subRule.hasImage()) {
+ // the image is already drawn with CE_ToolBoxTabShape, adjust rect here
+ const int iconExtent = proxy()->pixelMetric(QStyle::PM_SmallIconSize, box, w);
+ boxCopy.rect.setLeft(boxCopy.rect.left() + iconExtent);
+ }
QWindowsStyle::drawControl(ce, &boxCopy, p , w);
if (subRule.hasFont)
p->setFont(oldFont);
diff --git a/src/widgets/widgets.pro b/src/widgets/widgets.pro
index e556cb8b10..6f807e1696 100644
--- a/src/widgets/widgets.pro
+++ b/src/widgets/widgets.pro
@@ -32,8 +32,6 @@ qtConfig(graphicseffect) {
QMAKE_LIBS += $$QMAKE_LIBS_GUI
-contains(DEFINES,QT_EVAL):include($$QT_SOURCE_TREE/src/corelib/eval.pri)
-
QMAKE_DYNAMIC_LIST_FILE = $$PWD/QtWidgets.dynlist
# Code coverage with TestCocoon
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index 1ad43fffb4..aa520e37a2 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -1364,7 +1364,10 @@ void QComboBoxPrivate::emitActivated(const QModelIndex &index)
return;
QString text(itemText(index));
emit q->activated(index.row());
+ emit q->textActivated(text);
+#if QT_DEPRECATED_SINCE(5, 15)
emit q->activated(text);
+#endif
}
void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
@@ -1374,7 +1377,10 @@ void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
return;
QString text(itemText(index));
emit q->highlighted(index.row());
+ emit q->textHighlighted(text);
+#if QT_DEPRECATED_SINCE(5, 15)
emit q->highlighted(text);
+#endif
}
void QComboBoxPrivate::_q_emitCurrentIndexChanged(const QModelIndex &index)
diff --git a/src/widgets/widgets/qcombobox.h b/src/widgets/widgets/qcombobox.h
index 64fbebb3c5..6a87a675a4 100644
--- a/src/widgets/widgets/qcombobox.h
+++ b/src/widgets/widgets/qcombobox.h
@@ -220,15 +220,21 @@ public Q_SLOTS:
Q_SIGNALS:
void editTextChanged(const QString &);
void activated(int index);
- void activated(const QString &);
+ void textActivated(const QString &);
void highlighted(int index);
- void highlighted(const QString &);
+ void textHighlighted(const QString &);
void currentIndexChanged(int index);
+ void currentTextChanged(const QString &);
#if QT_DEPRECATED_SINCE(5, 13)
QT_DEPRECATED_X("Use currentTextChanged() instead")
void currentIndexChanged(const QString &);
#endif
- void currentTextChanged(const QString &);
+#if QT_DEPRECATED_SINCE(5, 15)
+ QT_DEPRECATED_X("Use textActivated() instead")
+ void activated(const QString &);
+ QT_DEPRECATED_X("Use textHighlighted() instead")
+ void highlighted(const QString &);
+#endif
protected:
void focusInEvent(QFocusEvent *e) override;
diff --git a/src/widgets/widgets/qlineedit.cpp b/src/widgets/widgets/qlineedit.cpp
index ad3d372bd3..02aa703289 100644
--- a/src/widgets/widgets/qlineedit.cpp
+++ b/src/widgets/widgets/qlineedit.cpp
@@ -315,7 +315,7 @@ QString QLineEdit::text() const
void QLineEdit::setText(const QString& text)
{
Q_D(QLineEdit);
- d->control->setText(text);
+ d->setText(text);
}
/*!
@@ -1483,8 +1483,11 @@ bool QLineEdit::event(QEvent * e)
} else if (e->type() == QEvent::LeaveEditFocus) {
d->setCursorVisible(false);
d->control->setCursorBlinkEnabled(false);
- if (d->control->hasAcceptableInput() || d->control->fixup())
+ if (d->edited && (d->control->hasAcceptableInput()
+ || d->control->fixup())) {
emit editingFinished();
+ d->edited = false;
+ }
}
}
#endif
@@ -1891,7 +1894,6 @@ void QLineEdit::focusInEvent(QFocusEvent *e)
/*!\reimp
*/
-
void QLineEdit::focusOutEvent(QFocusEvent *e)
{
Q_D(QLineEdit);
@@ -1914,8 +1916,10 @@ void QLineEdit::focusOutEvent(QFocusEvent *e)
#endif
if (reason != Qt::PopupFocusReason
|| !(QApplication::activePopupWidget() && QApplication::activePopupWidget()->parentWidget() == this)) {
- if (hasAcceptableInput() || d->control->fixup())
+ if (d->edited && (hasAcceptableInput() || d->control->fixup())) {
emit editingFinished();
+ d->edited = false;
+ }
}
#ifdef QT_KEYPAD_NAVIGATION
d->control->setCancelText(QString());
diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp
index 2a5a0c34dc..21e70db0ac 100644
--- a/src/widgets/widgets/qlineedit_p.cpp
+++ b/src/widgets/widgets/qlineedit_p.cpp
@@ -127,6 +127,7 @@ void QLineEditPrivate::_q_handleWindowActivate()
void QLineEditPrivate::_q_textEdited(const QString &text)
{
Q_Q(QLineEdit);
+ edited = true;
emit q->textEdited(text);
#if QT_CONFIG(completer)
if (control->completer()
@@ -272,6 +273,12 @@ void QLineEditPrivate::setCursorVisible(bool visible)
q->update();
}
+void QLineEditPrivate::setText(const QString& text)
+{
+ edited = true;
+ control->setText(text);
+}
+
void QLineEditPrivate::updatePasswordEchoEditing(bool editing)
{
Q_Q(QLineEdit);
diff --git a/src/widgets/widgets/qlineedit_p.h b/src/widgets/widgets/qlineedit_p.h
index 12a2f1ddfd..dce5bf605a 100644
--- a/src/widgets/widgets/qlineedit_p.h
+++ b/src/widgets/widgets/qlineedit_p.h
@@ -151,7 +151,7 @@ public:
QLineEditPrivate()
: control(0), frame(1), contextMenuEnabled(1), cursorVisible(0),
- dragEnabled(0), clickCausedFocus(0), hscroll(0), vscroll(0),
+ dragEnabled(0), clickCausedFocus(0), edited(0), hscroll(0), vscroll(0),
alignment(Qt::AlignLeading | Qt::AlignVCenter),
leftTextMargin(0), topTextMargin(0), rightTextMargin(0), bottomTextMargin(0),
lastTextSize(0), mouseYThreshold(0)
@@ -176,6 +176,7 @@ public:
bool inSelection(int x) const;
QRect cursorRect() const;
void setCursorVisible(bool visible);
+ void setText(const QString& text);
void updatePasswordEchoEditing(bool);
@@ -202,6 +203,7 @@ public:
uint cursorVisible : 1;
uint dragEnabled : 1;
uint clickCausedFocus : 1;
+ uint edited : 1;
int hscroll;
int vscroll;
uint alignment;
diff --git a/src/widgets/widgets/qmdiarea.cpp b/src/widgets/widgets/qmdiarea.cpp
index feea7cd050..0ce561860e 100644
--- a/src/widgets/widgets/qmdiarea.cpp
+++ b/src/widgets/widgets/qmdiarea.cpp
@@ -1988,9 +1988,11 @@ QMdiSubWindow *QMdiArea::addSubWindow(QWidget *widget, Qt::WindowFlags windowFla
Q_ASSERT(child->testAttribute(Qt::WA_DeleteOnClose));
}
+ d->appendChild(child);
+
if (childFocus)
childFocus->setFocus();
- d->appendChild(child);
+
return child;
}
diff --git a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
index 31268c5cf3..b823ca2aab 100644
--- a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
+++ b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
@@ -154,6 +154,8 @@ private slots:
void mutableFunctor();
void checkArgumentsForNarrowing();
void nullReceiver();
+ void functorReferencesConnection();
+ void disconnectDisconnects();
};
struct QObjectCreatedOnShutdown
@@ -7487,6 +7489,169 @@ void tst_QObject::nullReceiver()
QVERIFY(!connect(&o, SIGNAL(destroyed()), nullObj, SLOT(deleteLater())));
}
+void tst_QObject::functorReferencesConnection()
+{
+ countedStructObjectsCount = 0;
+ QMetaObject::Connection globalCon;
+ {
+ GetSenderObject obj;
+ CountedStruct counted(&obj);
+ QCOMPARE(countedStructObjectsCount, 1);
+ auto c = QSharedPointer<QMetaObject::Connection>::create();
+ int slotCalled = 0;
+ *c = connect(&obj, &GetSenderObject::aSignal, &obj, [&slotCalled, c, counted] {
+ QObject::disconnect(*c);
+ slotCalled++;
+ });
+ globalCon = *c; // keep a handle to the connection somewhere;
+ QVERIFY(globalCon);
+ QCOMPARE(countedStructObjectsCount, 2);
+ obj.triggerSignal();
+ QCOMPARE(slotCalled, 1);
+ QCOMPARE(countedStructObjectsCount, 1);
+ QVERIFY(!globalCon);
+ obj.triggerSignal();
+ QCOMPARE(slotCalled, 1);
+ QCOMPARE(countedStructObjectsCount, 1);
+ }
+ QCOMPARE(countedStructObjectsCount, 0);
+
+ {
+ GetSenderObject obj;
+ CountedStruct counted(&obj);
+ QCOMPARE(countedStructObjectsCount, 1);
+ auto *rec = new QObject;
+ int slotCalled = 0;
+ globalCon = connect(&obj, &GetSenderObject::aSignal, rec, [&slotCalled, rec, counted] {
+ delete rec;
+ slotCalled++;
+ });
+ QCOMPARE(countedStructObjectsCount, 2);
+ obj.triggerSignal();
+ QCOMPARE(slotCalled, 1);
+ QCOMPARE(countedStructObjectsCount, 1);
+ QVERIFY(!globalCon);
+ obj.triggerSignal();
+ QCOMPARE(slotCalled, 1);
+ QCOMPARE(countedStructObjectsCount, 1);
+ }
+ QCOMPARE(countedStructObjectsCount, 0);
+ {
+ int slotCalled = 0;
+ QEventLoop eventLoop;
+ {
+ // Sender will be destroyed when the labda goes out of scope lambda, so it will exit the event loop
+ auto sender = QSharedPointer<GetSenderObject>::create();
+ connect(sender.data(), &QObject::destroyed, &eventLoop, &QEventLoop::quit, Qt::QueuedConnection);
+ globalCon = connect(sender.data(), &GetSenderObject::aSignal, this, [&slotCalled, sender, &globalCon, this] {
+ ++slotCalled;
+ // This signal will be connected, but should never be called as the sender will be destroyed before
+ auto c2 = connect(sender.data(), &GetSenderObject::aSignal, [] { QFAIL("Should not be called"); });
+ QVERIFY(c2);
+ QVERIFY(QObject::disconnect(sender.data(), nullptr, this, nullptr));
+ QVERIFY(!globalCon); // this connection has been disconnected
+ QVERIFY(c2); // sender should not have been deleted yet, only after the emission is done
+ });
+ QMetaObject::invokeMethod(sender.data(), &GetSenderObject::triggerSignal, Qt::QueuedConnection);
+ QMetaObject::invokeMethod(sender.data(), &GetSenderObject::triggerSignal, Qt::QueuedConnection);
+ QMetaObject::invokeMethod(sender.data(), &GetSenderObject::triggerSignal, Qt::QueuedConnection);
+ }
+ eventLoop.exec();
+ QCOMPARE(slotCalled, 1);
+ }
+
+ {
+ GetSenderObject obj;
+ CountedStruct counted(&obj);
+ QCOMPARE(countedStructObjectsCount, 1);
+ auto c1 = QSharedPointer<QMetaObject::Connection>::create();
+ auto c2 = QSharedPointer<QMetaObject::Connection>::create();
+ int slot1Called = 0;
+ int slot3Called = 0;
+ *c1 = connect(&obj, &GetSenderObject::aSignal, &obj, [&slot1Called, &slot3Called, &obj, c1, c2, counted] {
+ auto c3 = connect(&obj, &GetSenderObject::aSignal, [counted, &slot3Called] {
+ slot3Called++;
+ });
+ // top-level + the one in the 3 others lambdas
+ QCOMPARE(countedStructObjectsCount, 4);
+ QObject::disconnect(*c2);
+ // the one in the c2's lambda is gone
+ QCOMPARE(countedStructObjectsCount, 3);
+ slot1Called++;
+ });
+ connect(&obj, &GetSenderObject::aSignal, [] {}); // just a dummy signal to fill the connection list
+ *c2 = connect(&obj, &GetSenderObject::aSignal, [counted, c2] { QFAIL("should not be called"); });
+ QVERIFY(c1 && c2);
+ QCOMPARE(countedStructObjectsCount, 3); // top-level + c1 + c2
+ obj.triggerSignal();
+ QCOMPARE(slot1Called, 1);
+ QCOMPARE(slot3Called, 0);
+ QCOMPARE(countedStructObjectsCount, 3); // top-level + c1 + c3
+ QObject::disconnect(*c1);
+ QCOMPARE(countedStructObjectsCount, 2); // top-level + c3
+ obj.triggerSignal();
+ QCOMPARE(slot1Called, 1);
+ QCOMPARE(slot3Called, 1);
+ }
+ {
+ struct DestroyEmit {
+ Q_DISABLE_COPY(DestroyEmit);
+ explicit DestroyEmit(SenderObject *obj) : obj(obj) {}
+ SenderObject *obj;
+ ~DestroyEmit() {
+ obj->emitSignal1();
+ }
+ };
+ SenderObject obj;
+ int slot1Called = 0;
+ int slot2Called = 0;
+ int slot3Called = 0;
+ auto c1 = QSharedPointer<QMetaObject::Connection>::create();
+ auto de = QSharedPointer<DestroyEmit>::create(&obj);
+ *c1 = connect(&obj, &SenderObject::signal1, [&slot1Called, &slot3Called, de, c1, &obj] {
+ connect(&obj, &SenderObject::signal1, [&slot3Called] { slot3Called++; });
+ slot1Called++;
+ QObject::disconnect(*c1);
+ });
+ de.clear();
+ connect(&obj, &SenderObject::signal1, [&slot2Called] { slot2Called++; });
+ obj.emitSignal1();
+ QCOMPARE(slot1Called, 1);
+ QCOMPARE(slot2Called, 2); // because also called from ~DestroyEmit
+ QCOMPARE(slot3Called, 1);
+ }
+}
+
+void tst_QObject::disconnectDisconnects()
+{
+ // Test what happens if the destructor of an functor slot also disconnects more slot;
+
+ SenderObject s1;
+ QScopedPointer<QObject> receiver(new QObject);
+
+ auto s2 = QSharedPointer<SenderObject>::create();
+ QPointer<QObject> s2_tracker = s2.data();
+ int count = 0;
+ connect(&s1, &SenderObject::signal1, [&count] { count++; }); // α
+ connect(&s1, &SenderObject::signal1, receiver.data(), [s2] { QFAIL("!!"); }); // β
+ connect(s2.data(), &SenderObject::signal1, receiver.data(), [] { QFAIL("!!"); });
+ connect(&s1, &SenderObject::signal2, receiver.data(), [] { QFAIL("!!"); });
+ connect(s2.data(), &SenderObject::signal2, receiver.data(), [] { QFAIL("!!"); });
+ connect(&s1, &SenderObject::signal1, [&count] { count++; }); // γ
+ connect(&s1, &SenderObject::signal2, [&count] { count++; }); // δ
+ s2.clear();
+
+ QVERIFY(s2_tracker);
+ receiver
+ .reset(); // this will delete the receiver which must also delete s2 as β is disconnected
+ QVERIFY(!s2_tracker);
+ // test that the data structures are still in order
+ s1.emitSignal1();
+ QCOMPARE(count, 2); // α + γ
+ s1.emitSignal2();
+ QCOMPARE(count, 3); // + δ
+}
+
// Test for QtPrivate::HasQ_OBJECT_Macro
Q_STATIC_ASSERT(QtPrivate::HasQ_OBJECT_Macro<tst_QObject>::Value);
Q_STATIC_ASSERT(!QtPrivate::HasQ_OBJECT_Macro<SiblingDeleter>::Value);
diff --git a/tests/auto/gui/painting/painting.pro b/tests/auto/gui/painting/painting.pro
index 831fffab30..26e84c1b15 100644
--- a/tests/auto/gui/painting/painting.pro
+++ b/tests/auto/gui/painting/painting.pro
@@ -3,6 +3,7 @@ SUBDIRS=\
qpainterpath \
qpainterpathstroker \
qcolor \
+ qcolorspace \
qbrush \
qregion \
qpagelayout \
diff --git a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
index 17289e0b85..13d0618bd9 100644
--- a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
+++ b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp
@@ -33,7 +33,7 @@
#include <qcolor.h>
#include <qdebug.h>
-#include <private/qcolorprofile_p.h>
+#include <private/qcolortrclut_p.h>
#include <private/qdrawingprimitive_sse2_p.h>
#include <qrgba64.h>
@@ -1632,14 +1632,13 @@ void tst_QColor::qcolorprofile_data()
QTest::newRow("gamma=1.7") << qreal(1.7) << 2;
QTest::newRow("gamma=2.0") << qreal(2.0) << 8;
QTest::newRow("gamma=2.31") << qreal(2.31) << 33;
- QTest::newRow("SRgb") << qreal(0.0) << 7;
}
void tst_QColor::qcolorprofile()
{
QFETCH(qreal, gammaC);
QFETCH(int, tolerance);
- QColorProfile *cp = (gammaC == 0) ? QColorProfile::fromSRgb(): QColorProfile::fromGamma(gammaC);
+ QColorTrcLut *cp = QColorTrcLut::fromGamma(gammaC);
// Test we are accurate for most values after converting through gamma-correction.
int error = 0;
diff --git a/tests/auto/gui/painting/qcolorspace/qcolorspace.pro b/tests/auto/gui/painting/qcolorspace/qcolorspace.pro
new file mode 100644
index 0000000000..14bd699bf7
--- /dev/null
+++ b/tests/auto/gui/painting/qcolorspace/qcolorspace.pro
@@ -0,0 +1,9 @@
+CONFIG += testcase
+QT += testlib gui-private core-private
+
+TARGET = tst_qcolorspace
+SOURCES += tst_qcolorspace.cpp
+
+RESOURCES += $$files(resources/*)
+
+TESTDATA += resources/*
diff --git a/tests/auto/gui/painting/qcolorspace/resources/ProPhoto.jpg b/tests/auto/gui/painting/qcolorspace/resources/ProPhoto.jpg
new file mode 100644
index 0000000000..481d35ca8e
--- /dev/null
+++ b/tests/auto/gui/painting/qcolorspace/resources/ProPhoto.jpg
Binary files differ
diff --git a/tests/auto/gui/painting/qcolorspace/resources/sRGB2014.icc b/tests/auto/gui/painting/qcolorspace/resources/sRGB2014.icc
new file mode 100644
index 0000000000..49afbfef10
--- /dev/null
+++ b/tests/auto/gui/painting/qcolorspace/resources/sRGB2014.icc
Binary files differ
diff --git a/tests/auto/gui/painting/qcolorspace/tst_qcolorspace.cpp b/tests/auto/gui/painting/qcolorspace/tst_qcolorspace.cpp
new file mode 100644
index 0000000000..9bd4b75443
--- /dev/null
+++ b/tests/auto/gui/painting/qcolorspace/tst_qcolorspace.cpp
@@ -0,0 +1,238 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:GPL-EXCEPT$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3 as published by the Free Software
+** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include <QtTest/QtTest>
+
+#include <qcolorspace.h>
+#include <qimage.h>
+#include <qimagereader.h>
+
+Q_DECLARE_METATYPE(QColorSpace::ColorSpaceId)
+Q_DECLARE_METATYPE(QColorSpace::Gamut)
+Q_DECLARE_METATYPE(QColorSpace::TransferFunction)
+
+class tst_QColorSpace : public QObject
+{
+ Q_OBJECT
+
+public:
+ tst_QColorSpace();
+
+private slots:
+ void namedColorSpaces_data();
+ void namedColorSpaces();
+
+ void toIccProfile_data();
+ void toIccProfile();
+
+ void fromIccProfile();
+
+ void imageConversion_data();
+ void imageConversion();
+
+ void loadImage();
+};
+
+tst_QColorSpace::tst_QColorSpace()
+{ }
+
+
+void tst_QColorSpace::namedColorSpaces_data()
+{
+ QTest::addColumn<QColorSpace::ColorSpaceId>("colorSpaceId");
+ QTest::addColumn<QColorSpace::Gamut>("gamutId");
+ QTest::addColumn<QColorSpace::TransferFunction>("transferFunctionId");
+
+ QTest::newRow("sRGB") << QColorSpace::SRgb
+ << QColorSpace::Gamut::SRgb
+ << QColorSpace::TransferFunction::SRgb;
+ QTest::newRow("sRGB Linear") << QColorSpace::SRgbLinear
+ << QColorSpace::Gamut::SRgb
+ << QColorSpace::TransferFunction::Linear;
+ QTest::newRow("Adobe RGB") << QColorSpace::AdobeRgb
+ << QColorSpace::Gamut::AdobeRgb
+ << QColorSpace::TransferFunction::Gamma;
+ QTest::newRow("Display-P3") << QColorSpace::DisplayP3
+ << QColorSpace::Gamut::DciP3D65
+ << QColorSpace::TransferFunction::SRgb;
+ QTest::newRow("ProPhoto RGB") << QColorSpace::ProPhotoRgb
+ << QColorSpace::Gamut::ProPhotoRgb
+ << QColorSpace::TransferFunction::ProPhotoRgb;
+ QTest::newRow("BT.2020") << QColorSpace::Bt2020
+ << QColorSpace::Gamut::Bt2020
+ << QColorSpace::TransferFunction::Bt2020;
+}
+
+void tst_QColorSpace::namedColorSpaces()
+{
+ QFETCH(QColorSpace::ColorSpaceId, colorSpaceId);
+ QFETCH(QColorSpace::Gamut, gamutId);
+ QFETCH(QColorSpace::TransferFunction, transferFunctionId);
+
+ QColorSpace colorSpace = colorSpaceId;
+
+ QVERIFY(colorSpace.isValid());
+
+ QCOMPARE(colorSpace.colorSpaceId(), colorSpaceId);
+ QCOMPARE(colorSpace.gamut(), gamutId);
+ QCOMPARE(colorSpace.transferFunction(), transferFunctionId);
+}
+
+
+void tst_QColorSpace::toIccProfile_data()
+{
+ namedColorSpaces_data();
+}
+
+void tst_QColorSpace::toIccProfile()
+{
+ QFETCH(QColorSpace::ColorSpaceId, colorSpaceId);
+ QFETCH(QColorSpace::Gamut, gamutId);
+ QFETCH(QColorSpace::TransferFunction, transferFunctionId);
+
+ Q_UNUSED(gamutId);
+ Q_UNUSED(transferFunctionId);
+
+ QColorSpace colorSpace = colorSpaceId;
+ QByteArray iccProfile = colorSpace.iccProfile();
+ QVERIFY(!iccProfile.isEmpty());
+
+ QColorSpace colorSpace2 = QColorSpace::fromIccProfile(iccProfile);
+ QVERIFY(colorSpace2.isValid());
+
+ QCOMPARE(colorSpace2, colorSpace);
+
+ QByteArray iccProfile2 = colorSpace2.iccProfile();
+ QVERIFY(!iccProfile2.isEmpty());
+
+ QCOMPARE(iccProfile2, iccProfile);
+}
+
+void tst_QColorSpace::fromIccProfile()
+{
+ // Read the official sRGB ICCv2 profile:
+ QString prefix = QFINDTESTDATA("resources/");
+ QFile file(prefix + "sRGB2014.icc");
+ file.open(QIODevice::ReadOnly);
+ QByteArray iccProfile = file.readAll();
+ QColorSpace stdSRgb = QColorSpace::fromIccProfile(iccProfile);
+ QVERIFY(stdSRgb.isValid());
+
+ QCOMPARE(stdSRgb.gamut(), QColorSpace::Gamut::SRgb);
+ QCOMPARE(stdSRgb.transferFunction(), QColorSpace::TransferFunction::SRgb);
+ QCOMPARE(stdSRgb.colorSpaceId(), QColorSpace::SRgb);
+
+ QCOMPARE(stdSRgb, QColorSpace(QColorSpace::SRgb));
+}
+
+void tst_QColorSpace::imageConversion_data()
+{
+ QTest::addColumn<QColorSpace::ColorSpaceId>("fromColorSpace");
+ QTest::addColumn<QColorSpace::ColorSpaceId>("toColorSpace");
+ QTest::addColumn<int>("tolerance");
+
+ QTest::newRow("sRGB -> Display-P3") << QColorSpace::SRgb << QColorSpace::DisplayP3 << 0;
+ QTest::newRow("sRGB -> Adobe RGB") << QColorSpace::SRgb << QColorSpace::AdobeRgb << 2;
+ QTest::newRow("Display-P3 -> sRGB") << QColorSpace::DisplayP3 << QColorSpace::SRgb << 0;
+ QTest::newRow("Adobe RGB -> sRGB") << QColorSpace::AdobeRgb << QColorSpace::SRgb << 2;
+ QTest::newRow("Display-P3 -> Adobe RGB") << QColorSpace::DisplayP3 << QColorSpace::AdobeRgb << 2;
+ QTest::newRow("Display-P3 -> BT.2020") << QColorSpace::DisplayP3 << QColorSpace::Bt2020 << 4;
+ QTest::newRow("sRGB -> sRGB Linear") << QColorSpace::SRgb << QColorSpace::SRgbLinear << 0;
+}
+
+void tst_QColorSpace::imageConversion()
+{
+ QFETCH(QColorSpace::ColorSpaceId, fromColorSpace);
+ QFETCH(QColorSpace::ColorSpaceId, toColorSpace);
+ QFETCH(int, tolerance);
+
+ QImage testImage(256, 1, QImage::Format_RGB32);
+
+ for (int i = 0; i < 256; ++i)
+ testImage.setPixel(i, 0, qRgb(i, i, i));
+
+ testImage.setColorSpace(fromColorSpace);
+ QCOMPARE(testImage.colorSpace(), QColorSpace(fromColorSpace));
+
+ testImage.convertToColorSpace(toColorSpace);
+ QCOMPARE(testImage.colorSpace(), QColorSpace(toColorSpace));
+
+ int lastRed = 0;
+ int lastGreen = 0;
+ int lastBlue = 0;
+ for (int i = 0; i < 256; ++i) {
+ QRgb p = testImage.pixel(i, 0);
+ QVERIFY(qRed(p) >= lastRed);
+ QVERIFY(qGreen(p) >= lastGreen);
+ QVERIFY(qBlue(p) >= lastBlue);
+ lastRed = qRed(p);
+ lastGreen = qGreen(p);
+ lastBlue = qBlue(p);
+ }
+
+ lastRed = 0;
+ lastGreen = 0;
+ lastBlue = 0;
+ testImage.convertToColorSpace(fromColorSpace);
+ QCOMPARE(testImage.colorSpace(), QColorSpace(fromColorSpace));
+ for (int i = 0; i < 256; ++i) {
+ QRgb p = testImage.pixel(i, 0);
+ QVERIFY(qAbs(qRed(p) - qGreen(p)) <= tolerance);
+ QVERIFY(qAbs(qRed(p) - qBlue(p)) <= tolerance);
+ QVERIFY((lastRed - qRed(p)) <= (tolerance / 2));
+ QVERIFY((lastGreen - qGreen(p)) <= (tolerance / 2));
+ QVERIFY((lastBlue - qBlue(p)) <= (tolerance / 2));
+ lastRed = qRed(p);
+ lastGreen = qGreen(p);
+ lastBlue = qBlue(p);
+ }
+}
+
+
+void tst_QColorSpace::loadImage()
+{
+ QString prefix = QFINDTESTDATA("resources/");
+ QImageReader reader(prefix + "ProPhoto.jpg");
+ QImage image = reader.read();
+
+ QVERIFY(!image.isNull());
+ QVERIFY(image.colorSpace().isValid());
+ QCOMPARE(image.colorSpace().colorSpaceId(), QColorSpace::ProPhotoRgb);
+ QVERIFY(!image.colorSpace().iccProfile().isEmpty());
+
+ QColorSpace defaultProPhotoRgb = QColorSpace::ProPhotoRgb;
+ QVERIFY(!defaultProPhotoRgb.iccProfile().isEmpty());
+
+ // Test the iccProfile getter returns the ICC profile from the image
+ // which since we didn't write it, isn't identical to our defaults.
+ QVERIFY(defaultProPhotoRgb.iccProfile() != image.colorSpace().iccProfile());
+}
+
+QTEST_MAIN(tst_QColorSpace)
+#include "tst_qcolorspace.moc"
diff --git a/tests/auto/network-settings.h b/tests/auto/network-settings.h
index f162c3ae9f..bf632c9846 100644
--- a/tests/auto/network-settings.h
+++ b/tests/auto/network-settings.h
@@ -72,15 +72,20 @@ public:
}
#ifdef QT_NETWORK_LIB
- static QHostAddress serverIP()
+ static QHostAddress getServerIpImpl(const QString &serverName)
{
- const QHostInfo info = QHostInfo::fromName(serverName());
+ const QHostInfo info = QHostInfo::fromName(serverName);
if (info.error()) {
QTest::qFail(qPrintable(info.errorString()), __FILE__, __LINE__);
return QHostAddress();
}
return info.addresses().constFirst();
}
+
+ static QHostAddress serverIP()
+ {
+ return getServerIpImpl(serverName());
+ }
#endif
static bool compareReplyIMAP(QByteArray const& actual)
@@ -214,4 +219,67 @@ public:
return serverName();
#endif
}
+ static QString imapServerName()
+ {
+#ifdef QT_TEST_SERVER_NAME
+ return QString("cyrus.") % serverDomainName();
+#else
+ return serverName();
+#endif
+ }
+
+ static QString echoServerName()
+ {
+#ifdef QT_TEST_SERVER_NAME
+ return QString("echo.") % serverDomainName();
+#else
+ return serverName();
+#endif
+ }
+
+ static QString firewallServerName()
+ {
+#ifdef QT_TEST_SERVER_NAME
+ return QString("iptables.") % serverDomainName();
+#else
+ return serverName();
+#endif
+ }
+
+#ifdef QT_NETWORK_LIB
+ static QHostAddress imapServerIp()
+ {
+ return getServerIpImpl(imapServerName());
+ }
+
+ static QHostAddress httpServerIp()
+ {
+ return getServerIpImpl(httpServerName());
+ }
+
+ static QHostAddress httpProxyServerIp()
+ {
+ return getServerIpImpl(httpProxyServerName());
+ }
+
+ static QHostAddress socksProxyServerIp()
+ {
+ return getServerIpImpl(socksProxyServerName());
+ }
+
+ static QHostAddress ftpProxyServerIp()
+ {
+ return getServerIpImpl(ftpProxyServerName());
+ }
+
+ static QHostAddress ftpServerIp()
+ {
+ return getServerIpImpl(ftpServerName());
+ }
+
+ static QHostAddress firewallServerIp()
+ {
+ return getServerIpImpl(firewallServerName());
+ }
+#endif
};
diff --git a/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro b/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro
index 1874f001ab..bdd9d4eb7e 100644
--- a/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro
+++ b/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro
@@ -5,3 +5,5 @@ SOURCES += tst_qabstractnetworkcache.cpp
TESTDATA += tests/*
+QT_TEST_SERVER_LIST = apache2
+include($$dirname(_QMAKE_CONF_)/tests/auto/testserver.pri)
diff --git a/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp b/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp
index 0da42b8b87..92384e85bc 100644
--- a/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp
+++ b/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp
@@ -39,7 +39,7 @@
#include <algorithm>
-#define TESTFILE QLatin1String("http://") + QtNetworkSettings::serverName() + QLatin1String("/qtest/cgi-bin/")
+#define TESTFILE QLatin1String("http://") + QtNetworkSettings::httpServerName() + QLatin1String("/qtest/cgi-bin/")
class tst_QAbstractNetworkCache : public QObject
{
@@ -127,8 +127,13 @@ Q_DECLARE_METATYPE(QNetworkRequest::CacheLoadControl)
void tst_QAbstractNetworkCache::initTestCase()
{
+#if defined(QT_TEST_SERVER)
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 80));
+#else
if (!QtNetworkSettings::verifyTestNetworkSettings())
QSKIP("No network test server available");
+#endif
+
#ifndef QT_NO_BEARERMANAGEMENT
netConfMan = new QNetworkConfigurationManager(this);
networkConfiguration = netConfMan->defaultConfiguration();
diff --git a/tests/auto/network/access/qhttpnetworkconnection/qhttpnetworkconnection.pro b/tests/auto/network/access/qhttpnetworkconnection/qhttpnetworkconnection.pro
index d32b651b86..69a4a50144 100644
--- a/tests/auto/network/access/qhttpnetworkconnection/qhttpnetworkconnection.pro
+++ b/tests/auto/network/access/qhttpnetworkconnection/qhttpnetworkconnection.pro
@@ -4,3 +4,7 @@ SOURCES += tst_qhttpnetworkconnection.cpp
requires(qtConfig(private_tests))
QT = core-private network-private testlib
+
+QT_TEST_SERVER_LIST = apache2
+include($$dirname(_QMAKE_CONF_)/tests/auto/testserver.pri)
+
diff --git a/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp b/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp
index 84766f5484..0a9320118d 100644
--- a/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp
+++ b/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp
@@ -50,6 +50,7 @@ private:
bool finishedCalled;
bool finishedWithErrorCalled;
QNetworkReply::NetworkError netErrorCode;
+ QString (*httpServerName)() = QtNetworkSettings::httpServerName;
private Q_SLOTS:
void initTestCase();
@@ -101,7 +102,11 @@ private Q_SLOTS:
void tst_QHttpNetworkConnection::initTestCase()
{
+#if defined(QT_TEST_SERVER)
+ QVERIFY(QtNetworkSettings::verifyConnection(httpServerName(), 80));
+#else
QVERIFY(QtNetworkSettings::verifyTestNetworkSettings());
+#endif
}
void tst_QHttpNetworkConnection::options_data()
@@ -126,10 +131,9 @@ void tst_QHttpNetworkConnection::head_data()
QTest::addColumn<QString>("statusString");
QTest::addColumn<int>("contentLength");
- QTest::newRow("success-internal") << "http://" << QtNetworkSettings::serverName() << "/qtest/rfc3252.txt" << ushort(80) << false << 200 << "OK" << 25962;
-
- QTest::newRow("failure-path") << "http://" << QtNetworkSettings::serverName() << "/t" << ushort(80) << false << 404 << "Not Found" << -1;
- QTest::newRow("failure-protocol") << "" << QtNetworkSettings::serverName() << "/qtest/rfc3252.txt" << ushort(80) << false << 400 << "Bad Request" << -1;
+ QTest::newRow("success-internal") << "http://" << httpServerName() << "/qtest/rfc3252.txt" << ushort(80) << false << 200 << "OK" << 25962;
+ QTest::newRow("failure-path") << "http://" << httpServerName() << "/t" << ushort(80) << false << 404 << "Not Found" << -1;
+ QTest::newRow("failure-protocol") << "" << httpServerName() << "/qtest/rfc3252.txt" << ushort(80) << false << 400 << "Bad Request" << -1;
}
void tst_QHttpNetworkConnection::head()
@@ -175,10 +179,10 @@ void tst_QHttpNetworkConnection::get_data()
QTest::addColumn<int>("contentLength");
QTest::addColumn<int>("downloadSize");
- QTest::newRow("success-internal") << "http://" << QtNetworkSettings::serverName() << "/qtest/rfc3252.txt" << ushort(80) << false << 200 << "OK" << 25962 << 25962;
+ QTest::newRow("success-internal") << "http://" << httpServerName() << "/qtest/rfc3252.txt" << ushort(80) << false << 200 << "OK" << 25962 << 25962;
- QTest::newRow("failure-path") << "http://" << QtNetworkSettings::serverName() << "/t" << ushort(80) << false << 404 << "Not Found" << -1 << -1;
- QTest::newRow("failure-protocol") << "" << QtNetworkSettings::serverName() << "/qtest/rfc3252.txt" << ushort(80) << false << 400 << "Bad Request" << -1 << -1;
+ QTest::newRow("failure-path") << "http://" << httpServerName() << "/t" << ushort(80) << false << 404 << "Not Found" << -1 << -1;
+ QTest::newRow("failure-protocol") << "" << httpServerName() << "/qtest/rfc3252.txt" << ushort(80) << false << 400 << "Bad Request" << -1 << -1;
}
void tst_QHttpNetworkConnection::get()
@@ -244,8 +248,8 @@ void tst_QHttpNetworkConnection::put_data()
QTest::addColumn<QString>("data");
QTest::addColumn<bool>("succeed");
- QTest::newRow("success-internal") << "http://" << QtNetworkSettings::serverName() << "/dav/file1.txt" << ushort(80) << false << "Hello World\nEnd of file\n"<<true;
- QTest::newRow("fail-internal") << "http://" << QtNetworkSettings::serverName() << "/dav2/file1.txt" << ushort(80) << false << "Hello World\nEnd of file\n"<<false;
+ QTest::newRow("success-internal") << "http://" << httpServerName() << "/dav/file1.txt" << ushort(80) << false << "Hello World\nEnd of file\n"<<true;
+ QTest::newRow("fail-internal") << "http://" << httpServerName() << "/dav2/file1.txt" << ushort(80) << false << "Hello World\nEnd of file\n"<<false;
QTest::newRow("fail-host") << "http://" << "invalid.test.qt-project.org" << "/dav2/file1.txt" << ushort(80) << false << "Hello World\nEnd of file\n"<<false;
}
@@ -324,8 +328,8 @@ void tst_QHttpNetworkConnection::post_data()
QTest::addColumn<int>("contentLength");
QTest::addColumn<int>("downloadSize");
- QTest::newRow("success-internal") << "http://" << QtNetworkSettings::serverName() << "/qtest/cgi-bin/echo.cgi" << ushort(80) << false << "7 bytes" << 200 << "OK" << 7 << 7;
- QTest::newRow("failure-internal") << "http://" << QtNetworkSettings::serverName() << "/t" << ushort(80) << false << "Hello World" << 404 << "Not Found" << -1 << -1;
+ QTest::newRow("success-internal") << "http://" << httpServerName() << "/qtest/cgi-bin/echo.cgi" << ushort(80) << false << "7 bytes" << 200 << "OK" << 7 << 7;
+ QTest::newRow("failure-internal") << "http://" << httpServerName() << "/t" << ushort(80) << false << "Hello World" << 404 << "Not Found" << -1 << -1;
}
void tst_QHttpNetworkConnection::post()
@@ -449,11 +453,11 @@ void tst_QHttpNetworkConnection::get401_data()
QTest::addColumn<QString>("password");
QTest::addColumn<int>("statusCode");
- QTest::newRow("no-credentials") << "http://" << QtNetworkSettings::serverName() << "/qtest/rfcs-auth/index.html" << ushort(80) << false << false << "" << ""<<401;
- QTest::newRow("invalid-credentials") << "http://" << QtNetworkSettings::serverName() << "/qtest/rfcs-auth/index.html" << ushort(80) << false << true << "test" << "test"<<401;
- QTest::newRow("valid-credentials") << "http://" << QtNetworkSettings::serverName() << "/qtest/rfcs-auth/index.html" << ushort(80) << false << true << "httptest" << "httptest"<<200;
- QTest::newRow("digest-authentication-invalid") << "http://" << QtNetworkSettings::serverName() << "/qtest/auth-digest/index.html" << ushort(80) << false << true << "wrong" << "wrong"<<401;
- QTest::newRow("digest-authentication-valid") << "http://" << QtNetworkSettings::serverName() << "/qtest/auth-digest/index.html" << ushort(80) << false << true << "httptest" << "httptest"<<200;
+ QTest::newRow("no-credentials") << "http://" << httpServerName() << "/qtest/rfcs-auth/index.html" << ushort(80) << false << false << "" << ""<<401;
+ QTest::newRow("invalid-credentials") << "http://" << httpServerName() << "/qtest/rfcs-auth/index.html" << ushort(80) << false << true << "test" << "test"<<401;
+ QTest::newRow("valid-credentials") << "http://" << httpServerName() << "/qtest/rfcs-auth/index.html" << ushort(80) << false << true << "httptest" << "httptest"<<200;
+ QTest::newRow("digest-authentication-invalid") << "http://" << httpServerName() << "/qtest/auth-digest/index.html" << ushort(80) << false << true << "wrong" << "wrong"<<401;
+ QTest::newRow("digest-authentication-valid") << "http://" << httpServerName() << "/qtest/auth-digest/index.html" << ushort(80) << false << true << "httptest" << "httptest"<<200;
}
void tst_QHttpNetworkConnection::get401()
@@ -508,9 +512,9 @@ void tst_QHttpNetworkConnection::compression_data()
QTest::addColumn<bool>("autoCompress");
QTest::addColumn<QString>("contentCoding");
- QTest::newRow("success-autogzip-temp") << "http://" << QtNetworkSettings::serverName() << "/qtest/rfcs/rfc2616.html" << ushort(80) << false << 200 << "OK" << -1 << 418321 << true << "";
- QTest::newRow("success-nogzip-temp") << "http://" << QtNetworkSettings::serverName() << "/qtest/rfcs/rfc2616.html" << ushort(80) << false << 200 << "OK" << 418321 << 418321 << false << "identity";
- QTest::newRow("success-manualgzip-temp") << "http://" << QtNetworkSettings::serverName() << "/qtest/deflate/rfc2616.html" << ushort(80) << false << 200 << "OK" << 119124 << 119124 << false << "gzip";
+ QTest::newRow("success-autogzip-temp") << "http://" << httpServerName() << "/qtest/rfcs/rfc2616.html" << ushort(80) << false << 200 << "OK" << -1 << 418321 << true << "";
+ QTest::newRow("success-nogzip-temp") << "http://" << httpServerName() << "/qtest/rfcs/rfc2616.html" << ushort(80) << false << 200 << "OK" << 418321 << 418321 << false << "identity";
+ QTest::newRow("success-manualgzip-temp") << "http://" << httpServerName() << "/qtest/deflate/rfc2616.html" << ushort(80) << false << 200 << "OK" << 119124 << 119124 << false << "gzip";
}
@@ -586,9 +590,9 @@ void tst_QHttpNetworkConnection::ignoresslerror_data()
// fluke's certificate is signed by a non-standard authority.
// Since we don't introduce that CA into the SSL verification chain,
// connecting should fail.
- QTest::newRow("success-init") << "https://" << QtNetworkSettings::serverName() << "/" << ushort(443) << true << true << false << 200;
- QTest::newRow("success-fromSignal") << "https://" << QtNetworkSettings::serverName() << "/" << ushort(443) << true << false << true << 200;
- QTest::newRow("failure") << "https://" << QtNetworkSettings::serverName() << "/" << ushort(443) << true << false << false << 100;
+ QTest::newRow("success-init") << "https://" << httpServerName() << "/" << ushort(443) << true << true << false << 200;
+ QTest::newRow("success-fromSignal") << "https://" << httpServerName() << "/" << ushort(443) << true << false << true << 200;
+ QTest::newRow("failure") << "https://" << httpServerName() << "/" << ushort(443) << true << false << false << 100;
}
void tst_QHttpNetworkConnection::ignoresslerror()
@@ -635,7 +639,7 @@ void tst_QHttpNetworkConnection::nossl_data()
QTest::addColumn<bool>("encrypt");
QTest::addColumn<QNetworkReply::NetworkError>("networkError");
- QTest::newRow("protocol-error") << "https://" << QtNetworkSettings::serverName() << "/" << ushort(443) << true <<QNetworkReply::ProtocolUnknownError;
+ QTest::newRow("protocol-error") << "https://" << httpServerName() << "/" << ushort(443) << true <<QNetworkReply::ProtocolUnknownError;
}
void tst_QHttpNetworkConnection::nossl()
@@ -696,7 +700,7 @@ void tst_QHttpNetworkConnection::getMultiple()
QFETCH(bool, pipeliningAllowed);
QFETCH(int, requestCount);
- QHttpNetworkConnection connection(connectionCount, QtNetworkSettings::serverName());
+ QHttpNetworkConnection connection(connectionCount, httpServerName());
QList<QHttpNetworkRequest*> requests;
QList<QHttpNetworkReply*> replies;
@@ -705,7 +709,7 @@ void tst_QHttpNetworkConnection::getMultiple()
// depending on what you use the results will vary.
// for the "real" results, use a URL that has "internet latency" for you. Then (6 connections, pipelining) will win.
// for LAN latency, you will possibly get that (1 connection, no pipelining) is the fastest
- QHttpNetworkRequest *request = new QHttpNetworkRequest("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt");
+ QHttpNetworkRequest *request = new QHttpNetworkRequest("http://" + httpServerName() + "/qtest/rfc3252.txt");
if (pipeliningAllowed)
request->setPipeliningAllowed(true);
requests.append(request);
@@ -723,7 +727,7 @@ void tst_QHttpNetworkConnection::getMultipleWithPipeliningAndMultiplePriorities(
quint16 requestCount = 100;
// use 2 connections.
- QHttpNetworkConnection connection(2, QtNetworkSettings::serverName());
+ QHttpNetworkConnection connection(2, httpServerName());
QList<QHttpNetworkRequest*> requests;
QList<QHttpNetworkReply*> replies;
@@ -731,9 +735,9 @@ void tst_QHttpNetworkConnection::getMultipleWithPipeliningAndMultiplePriorities(
for (int i = 0; i < requestCount; i++) {
QHttpNetworkRequest *request = 0;
if (i % 3)
- request = new QHttpNetworkRequest("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt", QHttpNetworkRequest::Get);
+ request = new QHttpNetworkRequest("http://" + httpServerName() + "/qtest/rfc3252.txt", QHttpNetworkRequest::Get);
else
- request = new QHttpNetworkRequest("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt", QHttpNetworkRequest::Head);
+ request = new QHttpNetworkRequest("http://" + httpServerName() + "/qtest/rfc3252.txt", QHttpNetworkRequest::Head);
if (i % 2 || i % 3)
request->setPipeliningAllowed(true);
@@ -800,9 +804,9 @@ void tst_QHttpNetworkConnection::getMultipleWithPriorities()
{
quint16 requestCount = 100;
// use 2 connections.
- QHttpNetworkConnection connection(2, QtNetworkSettings::serverName());
+ QHttpNetworkConnection connection(2, httpServerName());
GetMultipleWithPrioritiesReceiver receiver(requestCount);
- QUrl url("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt");
+ QUrl url("http://" + httpServerName() + "/qtest/rfc3252.txt");
QList<QHttpNetworkRequest*> requests;
QList<QHttpNetworkReply*> replies;
@@ -854,10 +858,10 @@ void tst_QHttpNetworkConnection::getEmptyWithPipelining()
{
quint16 requestCount = 50;
// use 2 connections.
- QHttpNetworkConnection connection(2, QtNetworkSettings::serverName());
+ QHttpNetworkConnection connection(2, httpServerName());
GetEmptyWithPipeliningReceiver receiver(requestCount);
- QUrl url("http://" + QtNetworkSettings::serverName() + "/cgi-bin/echo.cgi"); // a get on this = getting an empty file
+ QUrl url("http://" + httpServerName() + "/cgi-bin/echo.cgi"); // a get on this = getting an empty file
QList<QHttpNetworkRequest*> requests;
QList<QHttpNetworkReply*> replies;
@@ -901,8 +905,8 @@ void tst_QHttpNetworkConnection::getAndEverythingShouldBePipelined()
{
quint16 requestCount = 100;
// use 1 connection.
- QHttpNetworkConnection connection(1, QtNetworkSettings::serverName());
- QUrl url("http://" + QtNetworkSettings::serverName() + "/qtest/rfc3252.txt");
+ QHttpNetworkConnection connection(1, httpServerName());
+ QUrl url("http://" + httpServerName() + "/qtest/rfc3252.txt");
QList<QHttpNetworkRequest*> requests;
QList<QHttpNetworkReply*> replies;
@@ -937,8 +941,8 @@ void tst_QHttpNetworkConnection::getAndThenDeleteObject_data()
void tst_QHttpNetworkConnection::getAndThenDeleteObject()
{
// yes, this will leak if the testcase fails. I don't care. It must not fail then :P
- QHttpNetworkConnection *connection = new QHttpNetworkConnection(QtNetworkSettings::serverName());
- QHttpNetworkRequest request("http://" + QtNetworkSettings::serverName() + "/qtest/bigfile");
+ QHttpNetworkConnection *connection = new QHttpNetworkConnection(httpServerName());
+ QHttpNetworkRequest request("http://" + httpServerName() + "/qtest/bigfile");
QHttpNetworkReply *reply = connection->sendRequest(request);
reply->setDownstreamLimited(true);
diff --git a/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp b/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
index 55053842dc..8cef351554 100644
--- a/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
+++ b/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
@@ -93,7 +93,7 @@ void tst_QAuthenticator::basicAuth()
QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
- QCOMPARE(priv->calculateResponse("GET", "/").constData(), QByteArray("Basic " + expectedReply).constData());
+ QCOMPARE(priv->calculateResponse("GET", "/", "").constData(), QByteArray("Basic " + expectedReply).constData());
}
void tst_QAuthenticator::ntlmAuth_data()
@@ -133,9 +133,9 @@ void tst_QAuthenticator::ntlmAuth()
headers << qMakePair<QByteArray, QByteArray>("WWW-Authenticate", "NTLM");
priv->parseHttpResponse(headers, /*isProxy = */ false);
if (sso)
- QVERIFY(priv->calculateResponse("GET", "/").startsWith("NTLM "));
+ QVERIFY(priv->calculateResponse("GET", "/", "").startsWith("NTLM "));
else
- QCOMPARE(priv->calculateResponse("GET", "/").constData(), "NTLM TlRMTVNTUAABAAAABYIIAAAAAAAAAAAAAAAAAAAAAAA=");
+ QCOMPARE(priv->calculateResponse("GET", "/", "").constData(), "NTLM TlRMTVNTUAABAAAABYIIAAAAAAAAAAAAAAAAAAAAAAA=");
// NTLM phase 2: challenge
headers.clear();
@@ -146,7 +146,7 @@ void tst_QAuthenticator::ntlmAuth()
QEXPECT_FAIL("with-realm-sso", "NTLM authentication code doesn't extract the realm", Continue);
QCOMPARE(auth.realm(), realm);
- QVERIFY(priv->calculateResponse("GET", "/").startsWith("NTLM "));
+ QVERIFY(priv->calculateResponse("GET", "/", "").startsWith("NTLM "));
}
void tst_QAuthenticator::equalityOperators()
diff --git a/tests/auto/network/socket/qsocks5socketengine/qsocks5socketengine.pro b/tests/auto/network/socket/qsocks5socketengine/qsocks5socketengine.pro
index 71ceafa133..ca9e44873c 100644
--- a/tests/auto/network/socket/qsocks5socketengine/qsocks5socketengine.pro
+++ b/tests/auto/network/socket/qsocks5socketengine/qsocks5socketengine.pro
@@ -11,3 +11,9 @@ MOC_DIR=tmp
QT = core-private network-private testlib
requires(qtConfig(private_tests))
+
+# Only on Linux until cyrus has been added to docker-compose-for-{windows,macOS}.yml and tested
+linux {
+ QT_TEST_SERVER_LIST = danted apache2 cyrus
+ include($$dirname(_QMAKE_CONF_)/tests/auto/testserver.pri)
+}
diff --git a/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp b/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
index 1212ea20e5..464054f8a6 100644
--- a/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
+++ b/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
@@ -137,7 +137,13 @@ private slots:
void tst_QSocks5SocketEngine::initTestCase()
{
+#ifdef QT_TEST_SERVER
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::socksProxyServerName(), 1080));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 80));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::imapServerName(), 143));
+#else
QVERIFY(QtNetworkSettings::verifyTestNetworkSettings());
+#endif
}
//---------------------------------------------------------------------------
@@ -293,13 +299,13 @@ void tst_QSocks5SocketEngine::simpleConnectToIMAP()
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
- socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080));
+ socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080));
- QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
+ QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::imapServerIp(), 143));
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
- QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::imapServerIp());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
@@ -347,10 +353,10 @@ void tst_QSocks5SocketEngine::simpleErrorsAndStates()
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080));
+ socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080));
QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
- QVERIFY(!socketDevice.connectToHost(QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first(), 8088));
+ QVERIFY(!socketDevice.connectToHost(QHostInfo::fromName(QtNetworkSettings::socksProxyServerName()).addresses().first(), 8088));
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
if (socketDevice.waitForWrite(15000)) {
QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState ||
@@ -433,7 +439,7 @@ void tst_QSocks5SocketEngine::serverTest()
// Initialize a Tcp socket
QVERIFY(server.initialize(QAbstractSocket::TcpSocket));
- QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080);
+ QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080);
server.setProxy(proxy);
@@ -510,7 +516,7 @@ void tst_QSocks5SocketEngine::udpTest()
QVERIFY(udpSocket.initialize(QAbstractSocket::UdpSocket));
QVERIFY(udpSocket.isValid());
- QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080);
+ QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080);
udpSocket.setProxy(proxy);
@@ -564,7 +570,7 @@ void tst_QSocks5SocketEngine::tcpSocketBlockingTest()
QTcpSocket socket;
// Connect
- socket.connectToHost(QtNetworkSettings::serverName(), 143);
+ socket.connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket.waitForConnected());
QCOMPARE(socket.state(), QTcpSocket::ConnectedState);
@@ -635,7 +641,7 @@ void tst_QSocks5SocketEngine::tcpSocketNonBlockingTest()
});
// Connect
- socket.connectToHost(QtNetworkSettings::serverName(), 143);
+ socket.connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket.state() == QTcpSocket::HostLookupState ||
socket.state() == QTcpSocket::ConnectingState);
@@ -754,13 +760,13 @@ void tst_QSocks5SocketEngine::downloadBigFile()
<< " (" << stopWatch.elapsed() << "ms)";
});
- socket.connectToHost(QtNetworkSettings::serverName(), 80);
+ socket.connectToHost(QtNetworkSettings::httpServerName(), 80);
QTestEventLoop::instance().enterLoop(30);
if (QTestEventLoop::instance().timeout())
QFAIL("Network operation timed out");
- QByteArray hostName = QtNetworkSettings::serverName().toLatin1();
+ QByteArray hostName = QtNetworkSettings::httpServerName().toLatin1();
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QVERIFY(socket.write("GET /qtest/mediumfile HTTP/1.0\r\n") > 0);
QVERIFY(socket.write("HOST: ") > 0);
@@ -791,13 +797,13 @@ void tst_QSocks5SocketEngine::passwordAuth()
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
- socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080, "qsockstest", "password"));
+ socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080, "qsockstest", "password"));
// Connect to imap.trolltech.com's IP
- QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
+ QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::imapServerIp(), 143));
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
- if (!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143)) {
+ if (!socketDevice.connectToHost(QtNetworkSettings::imapServerIp(), 143)) {
qDebug("%d, %s", socketDevice.error(), socketDevice.errorString().toLatin1().constData());
}
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
@@ -857,19 +863,19 @@ void tst_QSocks5SocketEngine::passwordAuth2()
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
- socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081));
+ socketDevice.setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081));
socketDevice.setReceiver(this);
- QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143));
+ QVERIFY(!socketDevice.connectToHost(QtNetworkSettings::imapServerIp(), 143));
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
while (socketDevice.state() == QAbstractSocket::ConnectingState) {
QVERIFY(socketDevice.waitForWrite());
- socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143);
+ socketDevice.connectToHost(QtNetworkSettings::imapServerIp(), 143);
}
if (socketDevice.state() != QAbstractSocket::ConnectedState)
qDebug("%d, %s", socketDevice.error(), socketDevice.errorString().toLatin1().constData());
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
- QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::imapServerIp());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
diff --git a/tests/auto/network/socket/qtcpserver/test/test.pro b/tests/auto/network/socket/qtcpserver/test/test.pro
index 4491523383..ac4ed9a989 100644
--- a/tests/auto/network/socket/qtcpserver/test/test.pro
+++ b/tests/auto/network/socket/qtcpserver/test/test.pro
@@ -16,3 +16,9 @@ win32 {
QT = core network testlib
MOC_DIR=tmp
+
+# Only on Linux until cyrus has been added to docker-compose-for-{windows,macOS}.yml and tested
+linux {
+ QT_TEST_SERVER_LIST = danted cyrus squid ftp-proxy
+ include($$dirname(_QMAKE_CONF_)/tests/auto/testserver.pri)
+}
diff --git a/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp b/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
index 161d94d642..22ac9aa076 100644
--- a/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
+++ b/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
@@ -160,8 +160,15 @@ void tst_QTcpServer::initTestCase_data()
void tst_QTcpServer::initTestCase()
{
+#ifdef QT_TEST_SERVER
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::socksProxyServerName(), 1080));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpProxyServerName(), 3128));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::imapServerName(), 143));
+#else
if (!QtNetworkSettings::verifyTestNetworkSettings())
QSKIP("No network test server available");
+#endif
#ifndef QT_NO_BEARERMANAGEMENT
QNetworkConfigurationManager man;
networkSession = new QNetworkSession(man.defaultConfiguration(), this);
@@ -177,7 +184,7 @@ void tst_QTcpServer::init()
#ifndef QT_NO_NETWORKPROXY
QFETCH_GLOBAL(int, proxyType);
if (proxyType == QNetworkProxy::Socks5Proxy) {
- QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080));
+ QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080));
}
#else // !QT_NO_NETWORKPROXY
QSKIP("No proxy support");
@@ -513,7 +520,7 @@ void tst_QTcpServer::waitForConnectionTest()
}
QTcpSocket findLocalIpSocket;
- findLocalIpSocket.connectToHost(QtNetworkSettings::serverName(), 143);
+ findLocalIpSocket.connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(findLocalIpSocket.waitForConnected(5000));
QTcpServer server;
@@ -668,16 +675,18 @@ void tst_QTcpServer::invalidProxy_data()
QTest::addColumn<int>("port");
QTest::addColumn<int>("expectedError");
- QString fluke = QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first().toString();
- QTest::newRow("ftp-proxy") << int(QNetworkProxy::FtpCachingProxy) << fluke << 143
+ const QString imapIp = QtNetworkSettings::imapServerIp().toString();
+ const QString httpProxyIp = QtNetworkSettings::httpProxyServerIp().toString();
+ const QString socksIp = QtNetworkSettings::socksProxyServerIp().toString();
+ QTest::newRow("ftp-proxy") << int(QNetworkProxy::FtpCachingProxy) << imapIp << 143
<< int(QAbstractSocket::UnsupportedSocketOperationError);
- QTest::newRow("http-proxy") << int(QNetworkProxy::HttpProxy) << fluke << 3128
+ QTest::newRow("http-proxy") << int(QNetworkProxy::HttpProxy) << httpProxyIp << 3128
<< int(QAbstractSocket::UnsupportedSocketOperationError);
QTest::newRow("no-such-host") << int(QNetworkProxy::Socks5Proxy)
<< "invalid.test.qt-project.org" << 1080
<< int(QAbstractSocket::ProxyNotFoundError);
- QTest::newRow("socks5-on-http") << int(QNetworkProxy::Socks5Proxy) << fluke << 3128
+ QTest::newRow("socks5-on-http") << int(QNetworkProxy::Socks5Proxy) << httpProxyIp << 3128
<< int(QAbstractSocket::SocketTimeoutError);
}
@@ -740,48 +749,48 @@ void tst_QTcpServer::proxyFactory_data()
// tests that do get to listen
- proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080);
+ proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080);
QTest::newRow("socks5")
<< proxyList << proxyList.at(0)
<< false << int(QAbstractSocket::UnknownSocketError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3128)
- << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080);
+ proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3128)
+ << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080);
QTest::newRow("cachinghttp+socks5")
<< proxyList << proxyList.at(1)
<< false << int(QAbstractSocket::UnknownSocketError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121)
- << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3128)
- << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1080);
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
+ << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3128)
+ << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080);
QTest::newRow("ftp+cachinghttp+socks5")
<< proxyList << proxyList.at(2)
<< false << int(QAbstractSocket::UnknownSocketError);
// tests that fail to listen
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3128);
+ proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3128);
QTest::newRow("http")
<< proxyList << proxyList.at(0)
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3128);
+ proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3128);
QTest::newRow("cachinghttp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121);
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
QTest::newRow("ftp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121)
- << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3128);
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
+ << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3128);
QTest::newRow("ftp+cachinghttp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
diff --git a/tests/auto/network/socket/qtcpsocket/test/test.pro b/tests/auto/network/socket/qtcpsocket/test/test.pro
index 337e75b372..29d9414b03 100644
--- a/tests/auto/network/socket/qtcpsocket/test/test.pro
+++ b/tests/auto/network/socket/qtcpsocket/test/test.pro
@@ -15,3 +15,9 @@ win32 {
} else {
DESTDIR = ../
}
+
+# Only on Linux until cyrus has been added to docker-compose-for-{windows,macOS}.yml and tested
+linux {
+ QT_TEST_SERVER_LIST = danted squid apache2 ftp-proxy vsftpd iptables cyrus
+ include($$dirname(_QMAKE_CONF_)/tests/auto/testserver.pri)
+}
diff --git a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
index c473230246..abe9845213 100644
--- a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
+++ b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
@@ -317,7 +317,7 @@ tst_QTcpSocket::tst_QTcpSocket()
connect(earlyConstructedSockets->endPoints[1], SIGNAL(bytesWritten(qint64)), this, SLOT(earlySocketBytesSent(qint64)));
earlyConstructedSockets->endPoints[1]->write("hello work");
- firstFailInfo.setAddresses(QList<QHostAddress>() << QHostAddress("224.0.0.0") << QtNetworkSettings::serverIP());
+ firstFailInfo.setAddresses(QList<QHostAddress>() << QHostAddress("224.0.0.0") << QtNetworkSettings::httpServerIp());
}
void tst_QTcpSocket::initTestCase_data()
@@ -326,7 +326,6 @@ void tst_QTcpSocket::initTestCase_data()
QTest::addColumn<int>("proxyType");
QTest::addColumn<bool>("ssl");
- qDebug() << QtNetworkSettings::serverName();
QTest::newRow("WithoutProxy") << false << 0 << false;
//QTest::newRow("WithSocks5Proxy") << true << int(Socks5Proxy) << false; ### temporarily disabled, QTBUG-38385
//QTest::newRow("WithSocks5ProxyAuth") << true << int(Socks5Proxy | AuthBasic) << false; ### temporarily disabled, QTBUG-38385
@@ -352,7 +351,17 @@ void tst_QTcpSocket::initTestCase_data()
void tst_QTcpSocket::initTestCase()
{
+#ifdef QT_TEST_SERVER
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 80));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpProxyServerName(), 3128));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::imapServerName(), 143));
+ //QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::firewallServerName(), 1357));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::socksProxyServerName(), 1080));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpServerName(), 21));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
+#else
QVERIFY(QtNetworkSettings::verifyTestNetworkSettings());
+#endif
}
void tst_QTcpSocket::init()
@@ -361,30 +370,33 @@ void tst_QTcpSocket::init()
if (setProxy) {
#ifndef QT_NO_NETWORKPROXY
QFETCH_GLOBAL(int, proxyType);
- QList<QHostAddress> addresses = QHostInfo::fromName(QtNetworkSettings::serverName()).addresses();
- QVERIFY2(addresses.count() > 0, "failed to get ip address for test server");
- QString fluke = addresses.first().toString();
+ QList<QHostAddress> socks5Addresses = QHostInfo::fromName(QtNetworkSettings::socksProxyServerName()).addresses();
+ QList<QHostAddress> httpProxyAddresses = QHostInfo::fromName(QtNetworkSettings::httpProxyServerName()).addresses();
+ QVERIFY2(socks5Addresses.count() > 0, "failed to get ip address for SOCKS5 proxy server");
+ QVERIFY2(httpProxyAddresses.count() > 0, "failed to get ip address for HTTP proxy server");
+ QString socks5Address = socks5Addresses.first().toString();
+ QString httpProxyAddress = httpProxyAddresses.first().toString();
QNetworkProxy proxy;
switch (proxyType) {
case Socks5Proxy:
- proxy = QNetworkProxy(QNetworkProxy::Socks5Proxy, fluke, 1080);
+ proxy = QNetworkProxy(QNetworkProxy::Socks5Proxy, socks5Address, 1080);
break;
case Socks5Proxy | AuthBasic:
- proxy = QNetworkProxy(QNetworkProxy::Socks5Proxy, fluke, 1081);
+ proxy = QNetworkProxy(QNetworkProxy::Socks5Proxy, socks5Address, 1081);
break;
case HttpProxy | NoAuth:
- proxy = QNetworkProxy(QNetworkProxy::HttpProxy, fluke, 3128);
+ proxy = QNetworkProxy(QNetworkProxy::HttpProxy, httpProxyAddress, 3128);
break;
case HttpProxy | AuthBasic:
- proxy = QNetworkProxy(QNetworkProxy::HttpProxy, fluke, 3129);
+ proxy = QNetworkProxy(QNetworkProxy::HttpProxy, httpProxyAddress, 3129);
break;
case HttpProxy | AuthNtlm:
- proxy = QNetworkProxy(QNetworkProxy::HttpProxy, fluke, 3130);
+ proxy = QNetworkProxy(QNetworkProxy::HttpProxy, httpProxyAddress, 3130);
break;
}
QNetworkProxy::setApplicationProxy(proxy);
@@ -644,8 +656,8 @@ void tst_QTcpSocket::bind()
void tst_QTcpSocket::bindThenResolveHost_data()
{
QTest::addColumn<QString>("hostName");
- QTest::newRow("ip-literal") << QtNetworkSettings::serverIP().toString();
- QTest::newRow("name") << QtNetworkSettings::serverName();
+ QTest::newRow("ip-literal") << QtNetworkSettings::httpServerIp().toString();
+ QTest::newRow("name") << QtNetworkSettings::httpServerName();
QTest::newRow("first-fail") << firstFailName;
}
@@ -715,7 +727,7 @@ void tst_QTcpSocket::setSocketDescriptor()
#ifdef Q_OS_WIN
// need the dummy to ensure winsock is started
QTcpSocket *dummy = newSocket();
- dummy->connectToHost(QtNetworkSettings::serverName(), 143);
+ dummy->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(dummy->waitForConnected());
SOCKET sock = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
@@ -737,7 +749,7 @@ void tst_QTcpSocket::setSocketDescriptor()
QCOMPARE(socket->socketDescriptor(), (qintptr)sock);
qt_qhostinfo_clear_cache(); //avoid the HostLookupState being skipped due to address being in cache from previous test.
- socket->connectToHost(QtNetworkSettings::serverName(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 80);
QCOMPARE(socket->state(), QTcpSocket::HostLookupState);
QCOMPARE(socket->socketDescriptor(), (qintptr)sock);
QVERIFY(socket->waitForConnected(10000));
@@ -758,7 +770,7 @@ void tst_QTcpSocket::socketDescriptor()
QTcpSocket *socket = newSocket();
QCOMPARE(socket->socketDescriptor(), (qintptr)-1);
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->state() == QAbstractSocket::HostLookupState ||
socket->state() == QAbstractSocket::ConnectingState);
QVERIFY(socket->waitForConnected(10000));
@@ -775,7 +787,7 @@ void tst_QTcpSocket::blockingIMAP()
QTcpSocket *socket = newSocket();
// Connect
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(10000));
QCOMPARE(socket->state(), QTcpSocket::ConnectedState);
QVERIFY(socket->isValid());
@@ -852,6 +864,14 @@ void tst_QTcpSocket::hostNotFound()
socket->connectToHost("nosuchserver.qt-project.org", 80);
QVERIFY(!socket->waitForConnected());
QCOMPARE(socket->state(), QTcpSocket::UnconnectedState);
+#ifdef QT_TEST_SERVER
+ QFETCH_GLOBAL(bool, setProxy);
+ if (setProxy) {
+ QEXPECT_FAIL("", "QTBUG-73953: The version of Squid in the docker container behaves "
+ "differently to the one in the network testing server, returning 503 "
+ "when we expect 404", Continue);
+ }
+#endif
QCOMPARE(int(socket->error()), int(QTcpSocket::HostNotFoundError));
delete socket;
@@ -861,8 +881,8 @@ void tst_QTcpSocket::hostNotFound()
void tst_QTcpSocket::timeoutConnect_data()
{
QTest::addColumn<QString>("address");
- QTest::newRow("host") << QtNetworkSettings::serverName();
- QTest::newRow("ip") << QtNetworkSettings::serverIP().toString();
+ QTest::newRow("host") << QtNetworkSettings::firewallServerName();
+ QTest::newRow("ip") << QtNetworkSettings::firewallServerIp().toString();
}
void tst_QTcpSocket::timeoutConnect()
@@ -910,7 +930,7 @@ void tst_QTcpSocket::nonBlockingIMAP()
nonBlockingIMAP_socket = socket;
// Connect
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->state() == QTcpSocket::HostLookupState ||
socket->state() == QTcpSocket::ConnectingState);
@@ -1036,7 +1056,7 @@ void tst_QTcpSocket::delayedClose()
connect(socket, SIGNAL(connected()), SLOT(nonBlockingIMAP_connected()));
connect(socket, SIGNAL(disconnected()), SLOT(exitLoopSlot()));
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
enterLoop(30);
if (timeout())
@@ -1082,7 +1102,7 @@ QByteArray tst_QTcpSocket::expectedReplyIMAP()
void tst_QTcpSocket::fetchExpectedReplyIMAP()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY2(socket->waitForConnected(10000), qPrintable(socket->errorString()));
QVERIFY2(socket->state() == QTcpSocket::ConnectedState, qPrintable(socket->errorString()));
@@ -1101,7 +1121,7 @@ void tst_QTcpSocket::fetchExpectedReplyIMAP()
void tst_QTcpSocket::partialRead()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(10000));
QCOMPARE(socket->state(), QTcpSocket::ConnectedState);
char buf[512];
@@ -1125,7 +1145,7 @@ void tst_QTcpSocket::partialRead()
void tst_QTcpSocket::unget()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(10000));
QCOMPARE(socket->state(), QTcpSocket::ConnectedState);
char buf[512];
@@ -1162,7 +1182,7 @@ void tst_QTcpSocket::readRegularFile_readyRead()
void tst_QTcpSocket::readAllAfterClose()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
connect(socket, SIGNAL(readyRead()), SLOT(readRegularFile_readyRead()));
enterLoop(10);
if (timeout())
@@ -1202,7 +1222,7 @@ void tst_QTcpSocket::openCloseOpenClose()
QCOMPARE(socket->state(), QTcpSocket::UnconnectedState);
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(10000));
socket->close();
}
@@ -1225,7 +1245,7 @@ void tst_QTcpSocket::connectDisconnectConnectDisconnect()
QCOMPARE(int(socket->peerPort()), 0);
QCOMPARE(socket->peerAddress(), QHostAddress());
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForReadyRead(10000));
QCOMPARE(QString::fromLatin1(socket->read(4)), QString("* OK"));
@@ -1429,7 +1449,7 @@ void tst_QTcpSocket::disconnectWhileLookingUp()
// just connect and disconnect, then make sure nothing weird happened
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 21);
+ socket->connectToHost(QtNetworkSettings::ftpServerName(), 21);
// check that connect is in progress
QVERIFY(socket->state() != QAbstractSocket::UnconnectedState);
@@ -1477,7 +1497,7 @@ void tst_QTcpSocket::downloadBigFile()
connect(tmpSocket, SIGNAL(readyRead()), SLOT(downloadBigFileSlot()));
connect(tmpSocket, SIGNAL(disconnected()), SLOT(exitLoopSlot()));
- tmpSocket->connectToHost(QtNetworkSettings::serverName(), 80);
+ tmpSocket->connectToHost(QtNetworkSettings::httpServerName(), 80);
enterLoop(30);
if (timeout()) {
@@ -1486,7 +1506,7 @@ void tst_QTcpSocket::downloadBigFile()
QFAIL("Network operation timed out");
}
- QByteArray hostName = QtNetworkSettings::serverName().toLatin1();
+ QByteArray hostName = QtNetworkSettings::httpServerName().toLatin1();
QCOMPARE(tmpSocket->state(), QAbstractSocket::ConnectedState);
QVERIFY(tmpSocket->write("GET /qtest/mediumfile HTTP/1.0\r\n") > 0);
QVERIFY(tmpSocket->write("HOST: ") > 0);
@@ -1552,7 +1572,7 @@ void tst_QTcpSocket::downloadBigFileSlot()
void tst_QTcpSocket::readLine()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(5000));
while (!socket->canReadLine())
@@ -1601,7 +1621,7 @@ void tst_QTcpSocket::readLine()
void tst_QTcpSocket::readLineString()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForReadyRead(10000));
QByteArray arr = socket->readLine();
@@ -1614,7 +1634,7 @@ void tst_QTcpSocket::readLineString()
void tst_QTcpSocket::readChunks()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(10000));
QVERIFY(socket->waitForReadyRead(5000));
@@ -1634,7 +1654,7 @@ void tst_QTcpSocket::readChunks()
void tst_QTcpSocket::waitForBytesWritten()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 80);
QVERIFY(socket->waitForConnected(10000));
socket->write("GET / HTTP/1.0\r\n\r\n");
@@ -1652,7 +1672,7 @@ void tst_QTcpSocket::waitForBytesWrittenMinusOne()
QSKIP("QTBUG-24451 - indefinite wait may hang");
#endif
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 80);
QVERIFY(socket->waitForConnected(10000));
socket->write("GET / HTTP/1.0\r\n\r\n");
@@ -1667,7 +1687,7 @@ void tst_QTcpSocket::waitForBytesWrittenMinusOne()
void tst_QTcpSocket::waitForReadyRead()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 80);
socket->write("GET / HTTP/1.0\r\n\r\n");
QVERIFY(socket->waitForReadyRead(5000));
delete socket;
@@ -1680,7 +1700,7 @@ void tst_QTcpSocket::waitForReadyReadMinusOne()
QSKIP("QTBUG-24451 - indefinite wait may hang");
#endif
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 80);
socket->write("GET / HTTP/1.0\r\n\r\n");
QVERIFY(socket->waitForReadyRead(-1));
delete socket;
@@ -1693,7 +1713,7 @@ void tst_QTcpSocket::flush()
socket->flush();
connect(socket, SIGNAL(connected()), SLOT(exitLoopSlot()));
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
enterLoop(60);
QVERIFY(socket->isOpen());
@@ -1710,7 +1730,7 @@ void tst_QTcpSocket::flush()
void tst_QTcpSocket::synchronousApi()
{
QTcpSocket *ftpSocket = newSocket();
- ftpSocket->connectToHost(QtNetworkSettings::serverName(), 21);
+ ftpSocket->connectToHost(QtNetworkSettings::ftpServerName(), 21);
ftpSocket->write("QUIT\r\n");
QVERIFY(ftpSocket->waitForDisconnected(10000));
QVERIFY(ftpSocket->bytesAvailable() > 0);
@@ -1757,10 +1777,10 @@ void tst_QTcpSocket::recursiveReadyRead()
QSignalSpy spy(testSocket, SIGNAL(readyRead()));
- testSocket->connectToHost(QtNetworkSettings::serverName(), 143);
+ testSocket->connectToHost(QtNetworkSettings::imapServerName(), 143);
enterLoop(30);
QVERIFY2(!timeout(),
- "Timed out when connecting to QtNetworkSettings::serverName().");
+ "Timed out when connecting to QtNetworkSettings::imapServerName().");
enterLoop(30);
QVERIFY2(!timeout(),
@@ -1794,7 +1814,7 @@ void tst_QTcpSocket::recursiveReadyReadSlot()
void tst_QTcpSocket::atEnd()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 21);
+ socket->connectToHost(QtNetworkSettings::ftpServerName(), 21);
QVERIFY(socket->waitForReadyRead(15000));
QTextStream stream(socket);
@@ -1802,9 +1822,15 @@ void tst_QTcpSocket::atEnd()
QString greeting = stream.readLine();
QVERIFY(stream.atEnd());
+#ifdef QT_TEST_SERVER
+ // Test server must use some vsFTPd 3.x.x version
+ QVERIFY2(greeting.length() == sizeof("220 (vsFTPd 3.x.x)")-1, qPrintable(greeting));
+ QVERIFY2(greeting.startsWith("220 (vsFTPd 3."), qPrintable(greeting));
+#else
// Test server must use some vsFTPd 2.x.x version
QVERIFY2(greeting.length() == sizeof("220 (vsFTPd 2.x.x)")-1, qPrintable(greeting));
QVERIFY2(greeting.startsWith("220 (vsFTPd 2."), qPrintable(greeting));
+#endif
QVERIFY2(greeting.endsWith(QLatin1Char(')')), qPrintable(greeting));
delete socket;
@@ -1835,7 +1861,7 @@ protected:
connect(socket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), Qt::DirectConnection);
- socket->connectToHost(QtNetworkSettings::serverName(), 21);
+ socket->connectToHost(QtNetworkSettings::ftpServerName(), 21);
socket->write("QUIT\r\n");
exec();
@@ -1909,7 +1935,7 @@ void tst_QTcpSocket::waitForReadyReadInASlot()
tmpSocket = socket;
connect(socket, SIGNAL(connected()), this, SLOT(waitForReadyReadInASlotSlot()));
- socket->connectToHost(QtNetworkSettings::serverName(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 80);
socket->write("GET / HTTP/1.0\r\n\r\n");
enterLoop(30);
@@ -2073,7 +2099,7 @@ void tst_QTcpSocket::waitForConnectedInHostLookupSlot()
timer.start(15000);
connect(tmpSocket, SIGNAL(hostFound()), this, SLOT(hostLookupSlot()));
- tmpSocket->connectToHost(QtNetworkSettings::serverName(), 143);
+ tmpSocket->connectToHost(QtNetworkSettings::imapServerName(), 143);
// only execute the loop if not already connected
if (tmpSocket->state() != QAbstractSocket::ConnectedState)
@@ -2128,7 +2154,7 @@ public slots:
inline void doIt()
{
attemptedToConnect = true;
- sock->connectToHost(QtNetworkSettings::serverName(), 80);
+ sock->connectToHost(QtNetworkSettings::httpServerName(), 80);
#if defined(Q_OS_MAC)
pthread_yield_np();
@@ -2179,7 +2205,7 @@ void tst_QTcpSocket::readyReadSignalsAfterWaitForReadyRead()
QSignalSpy readyReadSpy(socket, SIGNAL(readyRead()));
// Connect
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
// Wait for the read
QVERIFY(socket->waitForReadyRead(10000));
@@ -2315,7 +2341,7 @@ void tst_QTcpSocket::localAddressEmptyOnBSD()
void tst_QTcpSocket::zeroAndMinusOneReturns()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 80);
socket->write("GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n");
QVERIFY(socket->waitForReadyRead(15000));
@@ -2376,7 +2402,7 @@ void tst_QTcpSocket::connectionRefused()
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
- socket->connectToHost(QtNetworkSettings::serverName(), 144);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 144);
enterLoop(10);
disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
@@ -2523,7 +2549,7 @@ void tst_QTcpSocket::moveToThread0()
{
// Case 1: Moved after connecting, before waiting for connection.
QTcpSocket *socket = newSocket();;
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
socket->moveToThread(0);
QVERIFY(socket->waitForConnected(5000));
socket->write("XXX LOGOUT\r\n");
@@ -2535,7 +2561,7 @@ void tst_QTcpSocket::moveToThread0()
// Case 2: Moved before connecting
QTcpSocket *socket = newSocket();
socket->moveToThread(0);
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(5000));
socket->write("XXX LOGOUT\r\n");
QVERIFY(socket->waitForBytesWritten(5000));
@@ -2545,7 +2571,7 @@ void tst_QTcpSocket::moveToThread0()
{
// Case 3: Moved after writing, while waiting for bytes to be written.
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(5000));
socket->write("XXX LOGOUT\r\n");
socket->moveToThread(0);
@@ -2556,7 +2582,7 @@ void tst_QTcpSocket::moveToThread0()
{
// Case 4: Moved after writing, while waiting for response.
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 143);
+ socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
QVERIFY(socket->waitForConnected(5000));
socket->write("XXX LOGOUT\r\n");
QVERIFY(socket->waitForBytesWritten(5000));
@@ -2687,7 +2713,7 @@ void tst_QTcpSocket::taskQtBug5799ConnectionErrorWaitForConnected()
// use waitForConnected, e.g. this should use a synchronous select() on the OS level
QTcpSocket socket;
- socket.connectToHost(QtNetworkSettings::serverName(), 12346);
+ socket.connectToHost(QtNetworkSettings::httpServerName(), 12346);
QTime timer;
timer.start();
socket.waitForConnected(10000);
@@ -2707,7 +2733,7 @@ void tst_QTcpSocket::taskQtBug5799ConnectionErrorEventLoop()
// This testcase uses an event loop
QTcpSocket socket;
connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), &QTestEventLoop::instance(), SLOT(exitLoop()));
- socket.connectToHost(QtNetworkSettings::serverName(), 12346);
+ socket.connectToHost(QtNetworkSettings::httpServerName(), 12346);
QTestEventLoop::instance().enterLoop(10);
QVERIFY2(!QTestEventLoop::instance().timeout(), "Connection to closed port timed out instead of refusing, something is wrong");
@@ -2720,7 +2746,7 @@ void tst_QTcpSocket::taskQtBug7054TimeoutErrorResetting()
{
QTcpSocket *socket = newSocket();
- socket->connectToHost(QtNetworkSettings::serverName(), 443);
+ socket->connectToHost(QtNetworkSettings::httpServerName(), 443);
QVERIFY(socket->waitForConnected(5*1000));
QCOMPARE(socket->error(), QAbstractSocket::UnknownSocketError);
@@ -2749,10 +2775,12 @@ void tst_QTcpSocket::invalidProxy_data()
QTest::addColumn<bool>("failsAtConnect");
QTest::addColumn<int>("expectedError");
- QString fluke = QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first().toString();
- QTest::newRow("ftp-proxy") << int(QNetworkProxy::FtpCachingProxy) << fluke << 21 << true
+ const QString ftpAddress = QtNetworkSettings::ftpServerIp().toString();
+ const QString httpProxyAddress = QtNetworkSettings::httpProxyServerIp().toString();
+ const QString socksProxyAddress = QtNetworkSettings::socksProxyServerIp().toString();
+ QTest::newRow("ftp-proxy") << int(QNetworkProxy::FtpCachingProxy) << ftpAddress << 21 << true
<< int(QAbstractSocket::UnsupportedSocketOperationError);
- QTest::newRow("http-caching-proxy") << int(QNetworkProxy::HttpCachingProxy) << fluke << 3128 << true
+ QTest::newRow("http-caching-proxy") << int(QNetworkProxy::HttpCachingProxy) << httpProxyAddress << 3128 << true
<< int(QAbstractSocket::UnsupportedSocketOperationError);
QTest::newRow("no-such-host-socks5") << int(QNetworkProxy::Socks5Proxy)
<< "this-host-will-never-exist.qt-project.org" << 1080 << false
@@ -2760,9 +2788,9 @@ void tst_QTcpSocket::invalidProxy_data()
QTest::newRow("no-such-host-http") << int(QNetworkProxy::HttpProxy)
<< "this-host-will-never-exist.qt-project.org" << 3128 << false
<< int(QAbstractSocket::ProxyNotFoundError);
- QTest::newRow("http-on-socks5") << int(QNetworkProxy::HttpProxy) << fluke << 1080 << false
+ QTest::newRow("http-on-socks5") << int(QNetworkProxy::HttpProxy) << socksProxyAddress << 1080 << false
<< int(QAbstractSocket::ProxyConnectionClosedError);
- QTest::newRow("socks5-on-http") << int(QNetworkProxy::Socks5Proxy) << fluke << 3128 << false
+ QTest::newRow("socks5-on-http") << int(QNetworkProxy::Socks5Proxy) << httpProxyAddress << 3128 << false
<< int(QAbstractSocket::SocketTimeoutError);
}
@@ -2781,7 +2809,7 @@ void tst_QTcpSocket::invalidProxy()
QTcpSocket *socket = newSocket();
socket->setProxy(proxy);
- socket->connectToHost(QHostInfo::fromName(QtNetworkSettings::serverName()).addresses().first().toString(), 80);
+ socket->connectToHost(QtNetworkSettings::httpServerIp().toString(), 80);
if (failsAtConnect) {
QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
@@ -2833,48 +2861,48 @@ void tst_QTcpSocket::proxyFactory_data()
// tests that do connect
- proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::serverName(), 3129);
+ proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3129);
QTest::newRow("http")
<< proxyList << proxyList.at(0)
<< false << int(QAbstractSocket::UnknownSocketError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
+ proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081);
QTest::newRow("socks5")
<< proxyList << proxyList.at(0)
<< false << int(QAbstractSocket::UnknownSocketError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
- << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
+ proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129)
+ << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081);
QTest::newRow("cachinghttp+socks5")
<< proxyList << proxyList.at(1)
<< false << int(QAbstractSocket::UnknownSocketError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121)
- << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129)
- << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::serverName(), 1081);
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
+ << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129)
+ << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081);
QTest::newRow("ftp+cachinghttp+socks5")
<< proxyList << proxyList.at(2)
<< false << int(QAbstractSocket::UnknownSocketError);
// tests that fail to connect
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129);
+ proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129);
QTest::newRow("cachinghttp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121);
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
QTest::newRow("ftp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::serverName(), 2121)
- << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::serverName(), 3129);
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
+ << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129);
QTest::newRow("ftp+cachinghttp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
@@ -2895,7 +2923,7 @@ void tst_QTcpSocket::proxyFactory()
QNetworkProxyFactory::setApplicationProxyFactory(factory);
QTcpSocket *socket = newSocket();
- QString host = QtNetworkSettings::serverName();
+ QString host = QtNetworkSettings::httpServerName();
socket->connectToHost(host, 80);
// Verify that the factory was called properly
diff --git a/tests/auto/other/toolsupport/tst_toolsupport.cpp b/tests/auto/other/toolsupport/tst_toolsupport.cpp
index f31a755f9e..8c129adaf3 100644
--- a/tests/auto/other/toolsupport/tst_toolsupport.cpp
+++ b/tests/auto/other/toolsupport/tst_toolsupport.cpp
@@ -126,9 +126,9 @@ void tst_toolsupport::offsets_data()
#ifdef Q_PROCESSOR_X86
// x86 32-bit has weird alignment rules. Refer to QtPrivate::AlignOf in
// qglobal.h for more details.
- data << 168 << 248;
+ data << 152 << 224;
#else
- data << 172 << 248;
+ data << 156 << 224;
#endif
}
#endif
diff --git a/tests/auto/testlib/selftests/blacklisted/tst_blacklisted.cpp b/tests/auto/testlib/selftests/blacklisted/tst_blacklisted.cpp
index 2f6d633e9d..49c08982ad 100644
--- a/tests/auto/testlib/selftests/blacklisted/tst_blacklisted.cpp
+++ b/tests/auto/testlib/selftests/blacklisted/tst_blacklisted.cpp
@@ -75,6 +75,17 @@ void tst_Blacklisted::xpass()
QVERIFY2(true, "This test should BXPASS");
}
+#ifndef Q_OS_WIN
+#include <signal.h>
+#include <setjmp.h>
+
+static jmp_buf state;
+static void abort_handler(int signal)
+{
+ longjmp(state, 1);
+}
+#endif
+
void tst_Blacklisted::messages()
{
qWarning("This is a warning that should not appear in silent test output");
@@ -83,7 +94,15 @@ void tst_Blacklisted::messages()
qCritical("This is a critical message that should not appear in silent test output");
qInfo("This is an info message that should not appear in silent test output");
QTestLog::info("This is an internal testlib info message that should not appear in silent test output", __FILE__, __LINE__);
- qFatal("This is a fatal error message that should still appear in silent test output");
+
+#ifndef Q_OS_WIN
+ // We're testing qFatal, but we don't want to actually std::abort() !
+ auto prior = signal(SIGABRT, abort_handler);
+ if (setjmp(state))
+ signal(SIGABRT, prior);
+ else
+#endif
+ qFatal("This is a fatal error message that should still appear in silent test output");
}
QTEST_MAIN(tst_Blacklisted)
diff --git a/tests/auto/testlib/selftests/expected_crashes_5.txt b/tests/auto/testlib/selftests/expected_crashes_5.txt
new file mode 100644
index 0000000000..088b9c5324
--- /dev/null
+++ b/tests/auto/testlib/selftests/expected_crashes_5.txt
@@ -0,0 +1,5 @@
+********* Start testing of tst_Crashes *********
+Config: Using QtTest library @INSERT_QT_VERSION_HERE@, Qt @INSERT_QT_VERSION_HERE@
+PASS : tst_Crashes::initTestCase()
+QFATAL : tst_Crashes::crash() Received signal 11
+ Function time: ms Total time: ms
diff --git a/tests/auto/testlib/selftests/silent/tst_silent.cpp b/tests/auto/testlib/selftests/silent/tst_silent.cpp
index 97fbbfd30a..cf3c35dec4 100644
--- a/tests/auto/testlib/selftests/silent/tst_silent.cpp
+++ b/tests/auto/testlib/selftests/silent/tst_silent.cpp
@@ -72,6 +72,17 @@ void tst_Silent::xpass()
QVERIFY2(true, "This test should XPASS");
}
+#ifndef Q_OS_WIN
+#include <signal.h>
+#include <setjmp.h>
+
+static jmp_buf state;
+static void abort_handler(int signal)
+{
+ longjmp(state, 1);
+}
+#endif
+
void tst_Silent::messages()
{
qWarning("This is a warning that should not appear in silent test output");
@@ -80,7 +91,15 @@ void tst_Silent::messages()
qCritical("This is a critical message that should not appear in silent test output");
qInfo("This is an info message that should not appear in silent test output");
QTestLog::info("This is an internal testlib info message that should not appear in silent test output", __FILE__, __LINE__);
- qFatal("This is a fatal error message that should still appear in silent test output");
+
+#ifndef Q_OS_WIN
+ // We're testing qFatal, but we don't want to actually std::abort() !
+ auto prior = signal(SIGABRT, abort_handler);
+ if (setjmp(state))
+ signal(SIGABRT, prior);
+ else
+#endif
+ qFatal("This is a fatal error message that should still appear in silent test output");
}
QTEST_MAIN(tst_Silent)
diff --git a/tests/auto/testserver.pri b/tests/auto/testserver.pri
index 26e7f6ab8a..eb83c6c2cc 100644
--- a/tests/auto/testserver.pri
+++ b/tests/auto/testserver.pri
@@ -58,9 +58,9 @@ debug_and_release:!build_pass: return()
DOCKER_ENABLED = 1
-equals(QMAKE_HOST.os, Darwin) {
+equals(QMAKE_HOST.os, Darwin) | equals(QMAKE_HOST.os, Windows) {
DOCKER_ENABLED = 0
- message("Not using docker network test server on macOS, see QTQAINFRA-2717 and QTQAINFRA-2750")
+ message("Not using docker network test server on macOS and Windows, see QTQAINFRA-2717 and QTQAINFRA-2750")
}
TESTSERVER_VERSION = ""
diff --git a/tests/auto/tools/moc/tst_moc.cpp b/tests/auto/tools/moc/tst_moc.cpp
index 74ddfd5620..0acc90fd11 100644
--- a/tests/auto/tools/moc/tst_moc.cpp
+++ b/tests/auto/tools/moc/tst_moc.cpp
@@ -3847,6 +3847,14 @@ static void checkEnum(const QMetaEnum &enumerator, const QByteArray &name, const
}
}
+class EnumFromNamespaceClass : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(FooNamespace::Enum1 prop READ prop CONSTANT)
+public:
+ FooNamespace::Enum1 prop() { return FooNamespace::Enum1::Key2; }
+};
+
void tst_Moc::testQNamespace()
{
QCOMPARE(TestQNamespace::staticMetaObject.enumeratorCount(), 4);
@@ -3874,6 +3882,11 @@ void tst_Moc::testQNamespace()
QCOMPARE(FooNamespace::staticMetaObject.enumeratorCount(), 1);
QCOMPARE(FooNamespace::FooNestedNamespace::staticMetaObject.enumeratorCount(), 2);
QCOMPARE(FooNamespace::FooNestedNamespace::FooMoreNestedNamespace::staticMetaObject.enumeratorCount(), 1);
+
+ EnumFromNamespaceClass obj;
+ const QVariant prop = obj.property("prop");
+ QCOMPARE(prop.type(), QMetaType::Int);
+ QCOMPARE(prop.toInt(), int(FooNamespace::Enum1::Key2));
}
void tst_Moc::cxx17Namespaces()
diff --git a/tests/auto/widgets/graphicsview/qgraphicsitemanimation/tst_qgraphicsitemanimation.cpp b/tests/auto/widgets/graphicsview/qgraphicsitemanimation/tst_qgraphicsitemanimation.cpp
index dfb2752ee0..ed79904ed8 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsitemanimation/tst_qgraphicsitemanimation.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsitemanimation/tst_qgraphicsitemanimation.cpp
@@ -54,9 +54,9 @@ void tst_QGraphicsItemAnimation::construction()
QCOMPARE(animation.posAt(0), QPointF());
QCOMPARE(animation.posAt(0.5), QPointF());
QCOMPARE(animation.posAt(1), QPointF());
- QCOMPARE(animation.matrixAt(0), QMatrix());
- QCOMPARE(animation.matrixAt(0.5), QMatrix());
- QCOMPARE(animation.matrixAt(1), QMatrix());
+ QCOMPARE(animation.transformAt(0), QTransform());
+ QCOMPARE(animation.transformAt(0.5), QTransform());
+ QCOMPARE(animation.transformAt(1), QTransform());
QCOMPARE(animation.rotationAt(0), qreal(0.0));
QCOMPARE(animation.rotationAt(0.5), qreal(0.0));
QCOMPARE(animation.rotationAt(1), qreal(0.0));
diff --git a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
index eaf75e7494..42258c85b9 100644
--- a/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
+++ b/tests/auto/widgets/itemviews/qheaderview/tst_qheaderview.cpp
@@ -85,8 +85,8 @@ class XResetModel : public QStandardItemModel
blockSignals(true);
bool r = QStandardItemModel::removeRows(row, count, parent);
blockSignals(false);
- emit beginResetModel();
- emit endResetModel();
+ beginResetModel();
+ endResetModel();
return r;
}
virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex())
@@ -94,8 +94,8 @@ class XResetModel : public QStandardItemModel
blockSignals(true);
bool r = QStandardItemModel::insertRows(row, count, parent);
blockSignals(false);
- emit beginResetModel();
- emit endResetModel();
+ beginResetModel();
+ endResetModel();
return r;
}
};
diff --git a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
index 95799905de..7861065de9 100644
--- a/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
+++ b/tests/auto/widgets/widgets/qlineedit/tst_qlineedit.cpp
@@ -3615,6 +3615,14 @@ void tst_QLineEdit::task174640_editingFinished()
le2->setFocus();
QTRY_VERIFY(le2->hasFocus());
+ // editingFinished will not be emitted anew because no editing happened
+ QCOMPARE(editingFinishedSpy.count(), 0);
+
+ le1->setFocus();
+ QTRY_VERIFY(le1->hasFocus());
+ QTest::keyPress(le1, Qt::Key_Plus);
+ le2->setFocus();
+ QTRY_VERIFY(le2->hasFocus());
QCOMPARE(editingFinishedSpy.count(), 1);
editingFinishedSpy.clear();
@@ -3632,6 +3640,8 @@ void tst_QLineEdit::task174640_editingFinished()
delete testMenu1;
QCOMPARE(editingFinishedSpy.count(), 0);
QTRY_VERIFY(le1->hasFocus());
+ // Ensure le1 has been edited
+ QTest::keyPress(le1, Qt::Key_Plus);
QMenu *testMenu2 = new QMenu(le2);
testMenu2->addAction("foo2");
diff --git a/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp b/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
index 67b79e3faf..046899ce05 100644
--- a/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
+++ b/tests/auto/widgets/widgets/qmdiarea/tst_qmdiarea.cpp
@@ -333,6 +333,7 @@ void tst_QMdiArea::subWindowActivated()
for ( i = 0; i < count; ++i ) {
QWidget *widget = new QWidget(workspace, 0);
widget->setAttribute(Qt::WA_DeleteOnClose);
+ widget->setFocus();
workspace->addSubWindow(widget)->show();
widget->show();
qApp->processEvents();
diff --git a/tests/testserver/apache2/apache2.sh b/tests/testserver/apache2/apache2.sh
index 4b0c74e2c4..d5075c7096 100755
--- a/tests/testserver/apache2/apache2.sh
+++ b/tests/testserver/apache2/apache2.sh
@@ -73,5 +73,8 @@ touch -d "2007-05-22 12:04:57 GMT" /home/$USER/www/htdocs/fluke.gif
# Create 10MB file for use by tst_Q*::downloadBigFile and interruption tests:
su $USER -c "/bin/dd if=/dev/zero of=~/www/htdocs/mediumfile bs=1 count=0 seek=10000000"
+# Emulate test server's hierarchy:
+su $USER -c "ln -s ~/www/htdocs/rfcs/rfc2616.html ~/www/htdocs/deflate/"
+
# enable service with installed configurations
service apache2 restart
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol-expire.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol-expire.cgi
new file mode 100755
index 0000000000..7dc506fc1e
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol-expire.cgi
@@ -0,0 +1,7 @@
+#!/bin/bash
+# cache control takes precedence over expires
+echo "Cache-Control: max-age=-1"
+echo "Expires: Mon, 30 Oct 2028 14:19:41 GMT"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol.cgi
new file mode 100755
index 0000000000..f2edfc161f
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol.cgi
@@ -0,0 +1,13 @@
+#!/bin/bash
+if [ ! -z ${HTTP_IF_MODIFIED_SINCE} ] ; then
+ echo "Status: 304"
+ echo ""
+ exit;
+fi
+
+cc=`echo "${QUERY_STRING}" | sed -e s/%20/\ /g`
+echo "Cache-Control: $cc"
+echo "Last-Modified: Sat, 31 Oct 1981 06:00:00 GMT"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol200.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol200.cgi
new file mode 100755
index 0000000000..e44d5ed570
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_cachecontrol200.cgi
@@ -0,0 +1,9 @@
+#!/bin/bash
+cc=`echo "${QUERY_STRING}" | sed -e s/%20/\ /g`
+echo "Status: 200"
+echo "Cache-Control: $cc"
+echo "Last-Modified: Sat, 31 Oct 1981 06:00:00 GMT"
+echo "Content-type: text/html";
+echo "X-Script: $0"
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag200.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag200.cgi
new file mode 100755
index 0000000000..0966abfdd1
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag200.cgi
@@ -0,0 +1,5 @@
+#!/bin/bash
+echo "ETag: foo"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag304.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag304.cgi
new file mode 100755
index 0000000000..91a4b922bd
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_etag304.cgi
@@ -0,0 +1,11 @@
+#!/bin/bash
+if [ ! -z ${HTTP_IF_NONE_MATCH} ] ; then
+ echo "Status: 304"
+ echo ""
+ exit;
+fi
+
+echo "ETag: foo"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires200.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires200.cgi
new file mode 100755
index 0000000000..e18ebc86ad
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires200.cgi
@@ -0,0 +1,5 @@
+#!/bin/bash
+echo "Expires: Sat, 31 Oct 1981 6:00:00 GMT"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires304.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires304.cgi
new file mode 100755
index 0000000000..1c7de1cd77
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_expires304.cgi
@@ -0,0 +1,11 @@
+#!/bin/bash
+if [ ${HTTP_IF_MODIFIED_SINCE} == "Mon, 30 Oct 2028 14:19:41 GMT" ] ; then
+ echo "Status: 304"
+ echo ""
+ exit;
+fi
+
+echo "Expires: Mon, 30 Oct 2028 14:19:41 GMT"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified200.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified200.cgi
new file mode 100755
index 0000000000..5dc219b1e7
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified200.cgi
@@ -0,0 +1,5 @@
+#!/bin/bash
+echo "Last-Modified: Sat, 31 Oct 1981 6:00:00 GMT"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified304.cgi b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified304.cgi
new file mode 100755
index 0000000000..bdf23bed2f
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/cgi-bin/httpcachetest_lastModified304.cgi
@@ -0,0 +1,11 @@
+#!/bin/bash
+if [ ${HTTP_IF_MODIFIED_SINCE} == "Sat, 31 Oct 1981 06:00:00 GMT" ] ; then
+ echo "Status: 304"
+ echo ""
+ exit;
+fi
+
+echo "Last-Modified: Sat, 31 Oct 1981 06:00:00 GMT"
+echo "Content-type: text/html";
+echo ""
+echo "Hello World!"
diff --git a/tests/testserver/apache2/testdata/www/htdocs/rfcs/.gitattributes b/tests/testserver/apache2/testdata/www/htdocs/rfcs/.gitattributes
new file mode 100644
index 0000000000..1d09ee726e
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/htdocs/rfcs/.gitattributes
@@ -0,0 +1 @@
+rfc2616.html binary
diff --git a/tests/testserver/apache2/testdata/www/htdocs/rfcs/rfc2616.html b/tests/testserver/apache2/testdata/www/htdocs/rfcs/rfc2616.html
new file mode 100644
index 0000000000..0e3282fb8d
--- /dev/null
+++ b/tests/testserver/apache2/testdata/www/htdocs/rfcs/rfc2616.html
@@ -0,0 +1,8380 @@
+<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
+<html><head><title>RFC 2616 (rfc2616) - Hypertext Transfer Protocol -- HTTP/1.1</title>
+
+
+
+<meta name="description" content="RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1">
+<meta name="obsoletes" content="RFC2068">
+<script language="JavaScript1.2">
+function erfc(s)
+{document.write("<A href=\"/rfccomment.php?rfcnum="+s+"\" target=\"_blank\" onclick=\"window.open('/rfccomment.php?rfcnum="+s+"','Popup','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=680,height=530,left=30,top=43'); return false;\")>Comment on RFC "+s+"</A>\n");}
+//-->
+</script></head><body bgcolor="#ffffff" text="#000000">
+<p align="center"><img src="rfc2616_files/library.htm" alt="" align="middle" border="0" height="62" width="150"></p>
+<h1 align="center">RFC 2616 (RFC2616)</h1>
+<p align="center">Internet RFC/STD/FYI/BCP Archives</p>
+
+<div align="center">[ <a href="http://firefly.troll.no/rfcs/">RFC Index</a> | <a href="http://firefly.troll.no/rfcs/rfcsearch.html">RFC Search</a> | <a href="http://firefly.troll.no/faqs/">Usenet FAQs</a> | <a href="http://firefly.troll.no/contrib/">Web FAQs</a> | <a href="http://firefly.troll.no/docs/">Documents</a> | <a href="http://www.city-data.com/">Cities</a> ]
+<p>
+<strong>Alternate Formats:</strong>
+ <a href="http://firefly.troll.no/ftp/rfc/rfc2616.txt">rfc2616.txt</a> |
+ <a href="http://firefly.troll.no/ftp/rfc/rfc2616.ps">rfc2616.ps</a> |
+ <a href="http://firefly.troll.no/ftp/rfc/rfc2616.pdf">rfc2616.pdf</a></p></div>
+<p align="center"><script language="JavaScript"><!--
+erfc("2616");
+// --></script><a href="http://firefly.troll.no/rfccomment.php?rfcnum=2616" target="_blank" onclick="window.open('/rfccomment.php?rfcnum=2616','Popup','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=680,height=530,left=30,top=43'); return false;" )="">Comment on RFC 2616</a>
+</p>
+<h3 align="center">RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1</h3>
+<hr noshade="noshade" size="2">
+<pre>
+Network Working Group R. Fielding
+Request for Comments: 2616 UC Irvine
+Obsoletes: 2068 J. Gettys
+Category: Standards Track Compaq/W3C
+ J. Mogul
+ Compaq
+ H. Frystyk
+ W3C/MIT
+ L. Masinter
+ Xerox
+ P. Leach
+ Microsoft
+ T. Berners-Lee
+ W3C/MIT
+ June 1999
+
+ Hypertext Transfer Protocol -- HTTP/1.1
+
+Status of this Memo
+
+ This document specifies an Internet standards track protocol for the
+ Internet community, and requests discussion and suggestions for
+ improvements. Please refer to the current edition of the "Internet
+ Official Protocol Standards" (STD 1) for the standardization state
+ and status of this protocol. Distribution of this memo is unlimited.
+
+Copyright Notice
+
+ Copyright (C) The Internet Society (1999). All Rights Reserved.
+
+Abstract
+
+ The Hypertext Transfer Protocol (HTTP) is an application-level
+ protocol for distributed, collaborative, hypermedia information
+ systems. It is a generic, stateless, protocol which can be used for
+ many tasks beyond its use for hypertext, such as name servers and
+ distributed object management systems, through extension of its
+ request methods, error codes and headers [47]. A feature of HTTP is
+ the typing and negotiation of data representation, allowing systems
+ to be built independently of the data being transferred.
+
+ HTTP has been in use by the World-Wide Web global information
+ initiative since 1990. This specification defines the protocol
+ referred to as "HTTP/1.1", and is an update to <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> [33].
+
+Table of Contents
+
+ 1 Introduction ...................................................7
+ 1.1 Purpose......................................................7
+ 1.2 Requirements .................................................8
+ 1.3 Terminology ..................................................8
+ 1.4 Overall Operation ...........................................12
+ 2 Notational Conventions and Generic Grammar ....................14
+ 2.1 Augmented BNF ...............................................14
+ 2.2 Basic Rules .................................................15
+ 3 Protocol Parameters ...........................................17
+ 3.1 HTTP Version ................................................17
+ 3.2 Uniform Resource Identifiers ................................18
+ 3.2.1 General Syntax ...........................................19
+ 3.2.2 http URL .................................................19
+ 3.2.3 URI Comparison ...........................................20
+ 3.3 Date/Time Formats ...........................................20
+ 3.3.1 Full Date ................................................20
+ 3.3.2 Delta Seconds ............................................21
+ 3.4 Character Sets ..............................................21
+ 3.4.1 Missing Charset ..........................................22
+ 3.5 Content Codings .............................................23
+ 3.6 Transfer Codings ............................................24
+ 3.6.1 Chunked Transfer Coding ..................................25
+ 3.7 Media Types .................................................26
+ 3.7.1 Canonicalization and Text Defaults .......................27
+ 3.7.2 Multipart Types ..........................................27
+ 3.8 Product Tokens ..............................................28
+ 3.9 Quality Values ..............................................29
+ 3.10 Language Tags ...............................................29
+ 3.11 Entity Tags .................................................30
+ 3.12 Range Units .................................................30
+ 4 HTTP Message ..................................................31
+ 4.1 Message Types ...............................................31
+ 4.2 Message Headers .............................................31
+ 4.3 Message Body ................................................32
+ 4.4 Message Length ..............................................33
+ 4.5 General Header Fields .......................................34
+ 5 Request .......................................................35
+ 5.1 Request-Line ................................................35
+ 5.1.1 Method ...................................................36
+ 5.1.2 Request-URI ..............................................36
+ 5.2 The Resource Identified by a Request ........................38
+ 5.3 Request Header Fields .......................................38
+ 6 Response ......................................................39
+ 6.1 Status-Line .................................................39
+ 6.1.1 Status Code and Reason Phrase ............................39
+ 6.2 Response Header Fields ......................................41
+
+ 7 Entity ........................................................42
+ 7.1 Entity Header Fields ........................................42
+ 7.2 Entity Body .................................................43
+ 7.2.1 Type .....................................................43
+ 7.2.2 Entity Length ............................................43
+ 8 Connections ...................................................44
+ 8.1 Persistent Connections ......................................44
+ 8.1.1 Purpose ..................................................44
+ 8.1.2 Overall Operation ........................................45
+ 8.1.3 Proxy Servers ............................................46
+ 8.1.4 Practical Considerations .................................46
+ 8.2 Message Transmission Requirements ...........................47
+ 8.2.1 Persistent Connections and Flow Control ..................47
+ 8.2.2 Monitoring Connections for Error Status Messages .........48
+ 8.2.3 Use of the 100 (Continue) Status .........................48
+ 8.2.4 Client Behavior if Server Prematurely Closes Connection ..50
+ 9 Method Definitions ............................................51
+ 9.1 Safe and Idempotent Methods .................................51
+ 9.1.1 Safe Methods .............................................51
+ 9.1.2 Idempotent Methods .......................................51
+ 9.2 OPTIONS .....................................................52
+ 9.3 GET .........................................................53
+ 9.4 HEAD ........................................................54
+ 9.5 POST ........................................................54
+ 9.6 PUT .........................................................55
+ 9.7 DELETE ......................................................56
+ 9.8 TRACE .......................................................56
+ 9.9 CONNECT .....................................................57
+ 10 Status Code Definitions ......................................57
+ 10.1 Informational 1xx ...........................................57
+ 10.1.1 100 Continue .............................................58
+ 10.1.2 101 Switching Protocols ..................................58
+ 10.2 Successful 2xx ..............................................58
+ 10.2.1 200 OK ...................................................58
+ 10.2.2 201 Created ..............................................59
+ 10.2.3 202 Accepted .............................................59
+ 10.2.4 203 Non-Authoritative Information ........................59
+ 10.2.5 204 No Content ...........................................60
+ 10.2.6 205 Reset Content ........................................60
+ 10.2.7 206 Partial Content ......................................60
+ 10.3 Redirection 3xx .............................................61
+ 10.3.1 300 Multiple Choices .....................................61
+ 10.3.2 301 Moved Permanently ....................................62
+ 10.3.3 302 Found ................................................62
+ 10.3.4 303 See Other ............................................63
+ 10.3.5 304 Not Modified .........................................63
+ 10.3.6 305 Use Proxy ............................................64
+ 10.3.7 306 (Unused) .............................................64
+
+ 10.3.8 307 Temporary Redirect ...................................65
+ 10.4 Client Error 4xx ............................................65
+ 10.4.1 400 Bad Request .........................................65
+ 10.4.2 401 Unauthorized ........................................66
+ 10.4.3 402 Payment Required ....................................66
+ 10.4.4 403 Forbidden ...........................................66
+ 10.4.5 404 Not Found ...........................................66
+ 10.4.6 405 Method Not Allowed ..................................66
+ 10.4.7 406 Not Acceptable ......................................67
+ 10.4.8 407 Proxy Authentication Required .......................67
+ 10.4.9 408 Request Timeout .....................................67
+ 10.4.10 409 Conflict ............................................67
+ 10.4.11 410 Gone ................................................68
+ 10.4.12 411 Length Required .....................................68
+ 10.4.13 412 Precondition Failed .................................68
+ 10.4.14 413 Request Entity Too Large ............................69
+ 10.4.15 414 Request-URI Too Long ................................69
+ 10.4.16 415 Unsupported Media Type ..............................69
+ 10.4.17 416 Requested Range Not Satisfiable .....................69
+ 10.4.18 417 Expectation Failed ..................................70
+ 10.5 Server Error 5xx ............................................70
+ 10.5.1 500 Internal Server Error ................................70
+ 10.5.2 501 Not Implemented ......................................70
+ 10.5.3 502 Bad Gateway ..........................................70
+ 10.5.4 503 Service Unavailable ..................................70
+ 10.5.5 504 Gateway Timeout ......................................71
+ 10.5.6 505 HTTP Version Not Supported ...........................71
+ 11 Access Authentication ........................................71
+ 12 Content Negotiation ..........................................71
+ 12.1 Server-driven Negotiation ...................................72
+ 12.2 Agent-driven Negotiation ....................................73
+ 12.3 Transparent Negotiation .....................................74
+ 13 Caching in HTTP ..............................................74
+ 13.1.1 Cache Correctness ........................................75
+ 13.1.2 Warnings .................................................76
+ 13.1.3 Cache-control Mechanisms .................................77
+ 13.1.4 Explicit User Agent Warnings .............................78
+ 13.1.5 Exceptions to the Rules and Warnings .....................78
+ 13.1.6 Client-controlled Behavior ...............................79
+ 13.2 Expiration Model ............................................79
+ 13.2.1 Server-Specified Expiration ..............................79
+ 13.2.2 Heuristic Expiration .....................................80
+ 13.2.3 Age Calculations .........................................80
+ 13.2.4 Expiration Calculations ..................................83
+ 13.2.5 Disambiguating Expiration Values .........................84
+ 13.2.6 Disambiguating Multiple Responses ........................84
+ 13.3 Validation Model ............................................85
+ 13.3.1 Last-Modified Dates ......................................86
+
+ 13.3.2 Entity Tag Cache Validators ..............................86
+ 13.3.3 Weak and Strong Validators ...............................86
+ 13.3.4 Rules for When to Use Entity Tags and Last-Modified Dates.89
+ 13.3.5 Non-validating Conditionals ..............................90
+ 13.4 Response Cacheability .......................................91
+ 13.5 Constructing Responses From Caches ..........................92
+ 13.5.1 End-to-end and Hop-by-hop Headers ........................92
+ 13.5.2 Non-modifiable Headers ...................................92
+ 13.5.3 Combining Headers ........................................94
+ 13.5.4 Combining Byte Ranges ....................................95
+ 13.6 Caching Negotiated Responses ................................95
+ 13.7 Shared and Non-Shared Caches ................................96
+ 13.8 Errors or Incomplete Response Cache Behavior ................97
+ 13.9 Side Effects of GET and HEAD ................................97
+ 13.10 Invalidation After Updates or Deletions ...................97
+ 13.11 Write-Through Mandatory ...................................98
+ 13.12 Cache Replacement .........................................99
+ 13.13 History Lists .............................................99
+ 14 Header Field Definitions ....................................100
+ 14.1 Accept .....................................................100
+ 14.2 Accept-Charset .............................................102
+ 14.3 Accept-Encoding ............................................102
+ 14.4 Accept-Language ............................................104
+ 14.5 Accept-Ranges ..............................................105
+ 14.6 Age ........................................................106
+ 14.7 Allow ......................................................106
+ 14.8 Authorization ..............................................107
+ 14.9 Cache-Control ..............................................108
+ 14.9.1 What is Cacheable .......................................109
+ 14.9.2 What May be Stored by Caches ............................110
+ 14.9.3 Modifications of the Basic Expiration Mechanism .........111
+ 14.9.4 Cache Revalidation and Reload Controls ..................113
+ 14.9.5 No-Transform Directive ..................................115
+ 14.9.6 Cache Control Extensions ................................116
+ 14.10 Connection ...............................................117
+ 14.11 Content-Encoding .........................................118
+ 14.12 Content-Language .........................................118
+ 14.13 Content-Length ...........................................119
+ 14.14 Content-Location .........................................120
+ 14.15 Content-MD5 ..............................................121
+ 14.16 Content-Range ............................................122
+ 14.17 Content-Type .............................................124
+ 14.18 Date .....................................................124
+ 14.18.1 Clockless Origin Server Operation ......................125
+ 14.19 ETag .....................................................126
+ 14.20 Expect ...................................................126
+ 14.21 Expires ..................................................127
+ 14.22 From .....................................................128
+
+ 14.23 Host .....................................................128
+ 14.24 If-Match .................................................129
+ 14.25 If-Modified-Since ........................................130
+ 14.26 If-None-Match ............................................132
+ 14.27 If-Range .................................................133
+ 14.28 If-Unmodified-Since ......................................134
+ 14.29 Last-Modified ............................................134
+ 14.30 Location .................................................135
+ 14.31 Max-Forwards .............................................136
+ 14.32 Pragma ...................................................136
+ 14.33 Proxy-Authenticate .......................................137
+ 14.34 Proxy-Authorization ......................................137
+ 14.35 Range ....................................................138
+ 14.35.1 Byte Ranges ...........................................138
+ 14.35.2 Range Retrieval Requests ..............................139
+ 14.36 Referer ..................................................140
+ 14.37 Retry-After ..............................................141
+ 14.38 Server ...................................................141
+ 14.39 TE .......................................................142
+ 14.40 Trailer ..................................................143
+ 14.41 Transfer-Encoding..........................................143
+ 14.42 Upgrade ..................................................144
+ 14.43 User-Agent ...............................................145
+ 14.44 Vary .....................................................145
+ 14.45 Via ......................................................146
+ 14.46 Warning ..................................................148
+ 14.47 WWW-Authenticate .........................................150
+ 15 Security Considerations .......................................150
+ 15.1 Personal Information....................................151
+ 15.1.1 Abuse of Server Log Information .........................151
+ 15.1.2 Transfer of Sensitive Information .......................151
+ 15.1.3 Encoding Sensitive Information in URI's .................152
+ 15.1.4 Privacy Issues Connected to Accept Headers ..............152
+ 15.2 Attacks Based On File and Path Names .......................153
+ 15.3 DNS Spoofing ...............................................154
+ 15.4 Location Headers and Spoofing ..............................154
+ 15.5 Content-Disposition Issues .................................154
+ 15.6 Authentication Credentials and Idle Clients ................155
+ 15.7 Proxies and Caching ........................................155
+ 15.7.1 Denial of Service Attacks on Proxies....................156
+ 16 Acknowledgments .............................................156
+ 17 References ..................................................158
+ 18 Authors' Addresses ..........................................162
+ 19 Appendices ..................................................164
+ 19.1 Internet Media Type message/http and application/http ......164
+ 19.2 Internet Media Type multipart/byteranges ...................165
+ 19.3 Tolerant Applications ......................................166
+ 19.4 Differences Between HTTP Entities and <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a> Entities ....167
+
+ 19.4.1 MIME-Version ............................................167
+ 19.4.2 Conversion to Canonical Form ............................167
+ 19.4.3 Conversion of Date Formats ..............................168
+ 19.4.4 Introduction of Content-Encoding ........................168
+ 19.4.5 No Content-Transfer-Encoding ............................168
+ 19.4.6 Introduction of Transfer-Encoding .......................169
+ 19.4.7 MHTML and Line Length Limitations .......................169
+ 19.5 Additional Features ........................................169
+ 19.5.1 Content-Disposition .....................................170
+ 19.6 Compatibility with Previous Versions .......................170
+ 19.6.1 Changes from HTTP/1.0 ...................................171
+ 19.6.2 Compatibility with HTTP/1.0 Persistent Connections ......172
+ 19.6.3 Changes from <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> ...................................172
+ 20 Index .......................................................175
+ 21 Full Copyright Statement ....................................176
+
+1 Introduction
+
+1.1 Purpose
+
+ The Hypertext Transfer Protocol (HTTP) is an application-level
+ protocol for distributed, collaborative, hypermedia information
+ systems. HTTP has been in use by the World-Wide Web global
+ information initiative since 1990. The first version of HTTP,
+ referred to as HTTP/0.9, was a simple protocol for raw data transfer
+ across the Internet. HTTP/1.0, as defined by <a href="http://firefly.troll.no/rfcs/rfc1945.html">RFC 1945</a> [6], improved
+ the protocol by allowing messages to be in the format of MIME-like
+ messages, containing metainformation about the data transferred and
+ modifiers on the request/response semantics. However, HTTP/1.0 does
+ not sufficiently take into consideration the effects of hierarchical
+ proxies, caching, the need for persistent connections, or virtual
+ hosts. In addition, the proliferation of incompletely-implemented
+ applications calling themselves "HTTP/1.0" has necessitated a
+ protocol version change in order for two communicating applications
+ to determine each other's true capabilities.
+
+ This specification defines the protocol referred to as "HTTP/1.1".
+ This protocol includes more stringent requirements than HTTP/1.0 in
+ order to ensure reliable implementation of its features.
+
+ Practical information systems require more functionality than simple
+ retrieval, including search, front-end update, and annotation. HTTP
+ allows an open-ended set of methods and headers that indicate the
+ purpose of a request [47]. It builds on the discipline of reference
+ provided by the Uniform Resource Identifier (URI) [3], as a location
+ (URL) [4] or name (URN) [20], for indicating the resource to which a
+
+ method is to be applied. Messages are passed in a format similar to
+ that used by Internet mail [9] as defined by the Multipurpose
+ Internet Mail Extensions (MIME) [7].
+
+ HTTP is also used as a generic protocol for communication between
+ user agents and proxies/gateways to other Internet systems, including
+ those supported by the SMTP [16], NNTP [13], FTP [18], Gopher [2],
+ and WAIS [10] protocols. In this way, HTTP allows basic hypermedia
+ access to resources available from diverse applications.
+
+1.2 Requirements
+
+ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+ "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+ document are to be interpreted as described in <a href="http://firefly.troll.no/rfcs/rfc2119.html">RFC 2119</a> [34].
+
+ An implementation is not compliant if it fails to satisfy one or more
+ of the MUST or REQUIRED level requirements for the protocols it
+ implements. An implementation that satisfies all the MUST or REQUIRED
+ level and all the SHOULD level requirements for its protocols is said
+ to be "unconditionally compliant"; one that satisfies all the MUST
+ level requirements but not all the SHOULD level requirements for its
+ protocols is said to be "conditionally compliant."
+
+1.3 Terminology
+
+ This specification uses a number of terms to refer to the roles
+ played by participants in, and objects of, the HTTP communication.
+
+ connection
+ A transport layer virtual circuit established between two programs
+ for the purpose of communication.
+
+ message
+ The basic unit of HTTP communication, consisting of a structured
+ sequence of octets matching the syntax defined in section 4 and
+ transmitted via the connection.
+
+ request
+ An HTTP request message, as defined in section 5.
+
+ response
+ An HTTP response message, as defined in section 6.
+
+ resource
+ A network data object or service that can be identified by a URI,
+ as defined in section 3.2. Resources may be available in multiple
+ representations (e.g. multiple languages, data formats, size, and
+ resolutions) or vary in other ways.
+
+ entity
+ The information transferred as the payload of a request or
+ response. An entity consists of metainformation in the form of
+ entity-header fields and content in the form of an entity-body, as
+ described in section 7.
+
+ representation
+ An entity included with a response that is subject to content
+ negotiation, as described in section 12. There may exist multiple
+ representations associated with a particular response status.
+
+ content negotiation
+ The mechanism for selecting the appropriate representation when
+ servicing a request, as described in section 12. The
+ representation of entities in any response can be negotiated
+ (including error responses).
+
+ variant
+ A resource may have one, or more than one, representation(s)
+ associated with it at any given instant. Each of these
+ representations is termed a `varriant'. Use of the term `variant'
+ does not necessarily imply that the resource is subject to content
+ negotiation.
+
+ client
+ A program that establishes connections for the purpose of sending
+ requests.
+
+ user agent
+ The client which initiates a request. These are often browsers,
+ editors, spiders (web-traversing robots), or other end user tools.
+
+ server
+ An application program that accepts connections in order to
+ service requests by sending back responses. Any given program may
+ be capable of being both a client and a server; our use of these
+ terms refers only to the role being performed by the program for a
+ particular connection, rather than to the program's capabilities
+ in general. Likewise, any server may act as an origin server,
+ proxy, gateway, or tunnel, switching behavior based on the nature
+ of each request.
+
+ origin server
+ The server on which a given resource resides or is to be created.
+
+ proxy
+ An intermediary program which acts as both a server and a client
+ for the purpose of making requests on behalf of other clients.
+ Requests are serviced internally or by passing them on, with
+ possible translation, to other servers. A proxy MUST implement
+ both the client and server requirements of this specification. A
+ "transparent proxy" is a proxy that does not modify the request or
+ response beyond what is required for proxy authentication and
+ identification. A "non-transparent proxy" is a proxy that modifies
+ the request or response in order to provide some added service to
+ the user agent, such as group annotation services, media type
+ transformation, protocol reduction, or anonymity filtering. Except
+ where either transparent or non-transparent behavior is explicitly
+ stated, the HTTP proxy requirements apply to both types of
+ proxies.
+
+ gateway
+ A server which acts as an intermediary for some other server.
+ Unlike a proxy, a gateway receives requests as if it were the
+ origin server for the requested resource; the requesting client
+ may not be aware that it is communicating with a gateway.
+
+ tunnel
+ An intermediary program which is acting as a blind relay between
+ two connections. Once active, a tunnel is not considered a party
+ to the HTTP communication, though the tunnel may have been
+ initiated by an HTTP request. The tunnel ceases to exist when both
+ ends of the relayed connections are closed.
+
+ cache
+ A program's local store of response messages and the subsystem
+ that controls its message storage, retrieval, and deletion. A
+ cache stores cacheable responses in order to reduce the response
+ time and network bandwidth consumption on future, equivalent
+ requests. Any client or server may include a cache, though a cache
+ cannot be used by a server that is acting as a tunnel.
+
+ cacheable
+ A response is cacheable if a cache is allowed to store a copy of
+ the response message for use in answering subsequent requests. The
+ rules for determining the cacheability of HTTP responses are
+ defined in section 13. Even if a resource is cacheable, there may
+ be additional constraints on whether a cache can use the cached
+ copy for a particular request.
+
+ first-hand
+ A response is first-hand if it comes directly and without
+ unnecessary delay from the origin server, perhaps via one or more
+ proxies. A response is also first-hand if its validity has just
+ been checked directly with the origin server.
+
+ explicit expiration time
+ The time at which the origin server intends that an entity should
+ no longer be returned by a cache without further validation.
+
+ heuristic expiration time
+ An expiration time assigned by a cache when no explicit expiration
+ time is available.
+
+ age
+ The age of a response is the time since it was sent by, or
+ successfully validated with, the origin server.
+
+ freshness lifetime
+ The length of time between the generation of a response and its
+ expiration time.
+
+ fresh
+ A response is fresh if its age has not yet exceeded its freshness
+ lifetime.
+
+ stale
+ A response is stale if its age has passed its freshness lifetime.
+
+ semantically transparent
+ A cache behaves in a "semantically transparent" manner, with
+ respect to a particular response, when its use affects neither the
+ requesting client nor the origin server, except to improve
+ performance. When a cache is semantically transparent, the client
+ receives exactly the same response (except for hop-by-hop headers)
+ that it would have received had its request been handled directly
+ by the origin server.
+
+ validator
+ A protocol element (e.g., an entity tag or a Last-Modified time)
+ that is used to find out whether a cache entry is an equivalent
+ copy of an entity.
+
+ upstream/downstream
+ Upstream and downstream describe the flow of a message: all
+ messages flow from upstream to downstream.
+
+ inbound/outbound
+ Inbound and outbound refer to the request and response paths for
+ messages: "inbound" means "traveling toward the origin server",
+ and "outbound" means "traveling toward the user agent"
+
+1.4 Overall Operation
+
+ The HTTP protocol is a request/response protocol. A client sends a
+ request to the server in the form of a request method, URI, and
+ protocol version, followed by a MIME-like message containing request
+ modifiers, client information, and possible body content over a
+ connection with a server. The server responds with a status line,
+ including the message's protocol version and a success or error code,
+ followed by a MIME-like message containing server information, entity
+ metainformation, and possible entity-body content. The relationship
+ between HTTP and MIME is described in appendix 19.4.
+
+ Most HTTP communication is initiated by a user agent and consists of
+ a request to be applied to a resource on some origin server. In the
+ simplest case, this may be accomplished via a single connection (v)
+ between the user agent (UA) and the origin server (O).
+
+ request chain ------------------------&gt;
+ UA -------------------v------------------- O
+ &lt;----------------------- response chain
+
+ A more complicated situation occurs when one or more intermediaries
+ are present in the request/response chain. There are three common
+ forms of intermediary: proxy, gateway, and tunnel. A proxy is a
+ forwarding agent, receiving requests for a URI in its absolute form,
+ rewriting all or part of the message, and forwarding the reformatted
+ request toward the server identified by the URI. A gateway is a
+ receiving agent, acting as a layer above some other server(s) and, if
+ necessary, translating the requests to the underlying server's
+ protocol. A tunnel acts as a relay point between two connections
+ without changing the messages; tunnels are used when the
+ communication needs to pass through an intermediary (such as a
+ firewall) even when the intermediary cannot understand the contents
+ of the messages.
+
+ request chain --------------------------------------&gt;
+ UA -----v----- A -----v----- B -----v----- C -----v----- O
+ &lt;------------------------------------- response chain
+
+ The figure above shows three intermediaries (A, B, and C) between the
+ user agent and origin server. A request or response message that
+ travels the whole chain will pass through four separate connections.
+ This distinction is important because some HTTP communication options
+
+ may apply only to the connection with the nearest, non-tunnel
+ neighbor, only to the end-points of the chain, or to all connections
+ along the chain. Although the diagram is linear, each participant may
+ be engaged in multiple, simultaneous communications. For example, B
+ may be receiving requests from many clients other than A, and/or
+ forwarding requests to servers other than C, at the same time that it
+ is handling A's request.
+
+ Any party to the communication which is not acting as a tunnel may
+ employ an internal cache for handling requests. The effect of a cache
+ is that the request/response chain is shortened if one of the
+ participants along the chain has a cached response applicable to that
+ request. The following illustrates the resulting chain if B has a
+ cached copy of an earlier response from O (via C) for a request which
+ has not been cached by UA or A.
+
+ request chain ----------&gt;
+ UA -----v----- A -----v----- B - - - - - - C - - - - - - O
+ &lt;--------- response chain
+
+ Not all responses are usefully cacheable, and some requests may
+ contain modifiers which place special requirements on cache behavior.
+ HTTP requirements for cache behavior and cacheable responses are
+ defined in section 13.
+
+ In fact, there are a wide variety of architectures and configurations
+ of caches and proxies currently being experimented with or deployed
+ across the World Wide Web. These systems include national hierarchies
+ of proxy caches to save transoceanic bandwidth, systems that
+ broadcast or multicast cache entries, organizations that distribute
+ subsets of cached data via CD-ROM, and so on. HTTP systems are used
+ in corporate intranets over high-bandwidth links, and for access via
+ PDAs with low-power radio links and intermittent connectivity. The
+ goal of HTTP/1.1 is to support the wide diversity of configurations
+ already deployed while introducing protocol constructs that meet the
+ needs of those who build web applications that require high
+ reliability and, failing that, at least reliable indications of
+ failure.
+
+ HTTP communication usually takes place over TCP/IP connections. The
+ default port is TCP 80 [19], but other ports can be used. This does
+ not preclude HTTP from being implemented on top of any other protocol
+ on the Internet, or on other networks. HTTP only presumes a reliable
+ transport; any protocol that provides such guarantees can be used;
+ the mapping of the HTTP/1.1 request and response structures onto the
+ transport data units of the protocol in question is outside the scope
+ of this specification.
+
+ In HTTP/1.0, most implementations used a new connection for each
+ request/response exchange. In HTTP/1.1, a connection may be used for
+ one or more request/response exchanges, although connections may be
+ closed for a variety of reasons (see section 8.1).
+
+2 Notational Conventions and Generic Grammar
+
+2.1 Augmented BNF
+
+ All of the mechanisms specified in this document are described in
+ both prose and an augmented Backus-Naur Form (BNF) similar to that
+ used by <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a> [9]. Implementors will need to be familiar with the
+ notation in order to understand this specification. The augmented BNF
+ includes the following constructs:
+
+ name = definition
+ The name of a rule is simply the name itself (without any
+ enclosing "&lt;" and "&gt;") and is separated from its definition by the
+ equal "=" character. White space is only significant in that
+ indentation of continuation lines is used to indicate a rule
+ definition that spans more than one line. Certain basic rules are
+ in uppercase, such as SP, LWS, HT, CRLF, DIGIT, ALPHA, etc. Angle
+ brackets are used within definitions whenever their presence will
+ facilitate discerning the use of rule names.
+
+ "literal"
+ Quotation marks surround literal text. Unless stated otherwise,
+ the text is case-insensitive.
+
+ rule1 | rule2
+ Elements separated by a bar ("|") are alternatives, e.g., "yes |
+ no" will accept yes or no.
+
+ (rule1 rule2)
+ Elements enclosed in parentheses are treated as a single element.
+ Thus, "(elem (foo | bar) elem)" allows the token sequences "elem
+ foo elem" and "elem bar elem".
+
+ *rule
+ The character "*" preceding an element indicates repetition. The
+ full form is "&lt;n&gt;*&lt;m&gt;element" indicating at least &lt;n&gt; and at most
+ &lt;m&gt; occurrences of element. Default values are 0 and infinity so
+ that "*(element)" allows any number, including zero; "1*element"
+ requires at least one; and "1*2element" allows one or two.
+
+ [rule]
+ Square brackets enclose optional elements; "[foo bar]" is
+ equivalent to "*1(foo bar)".
+
+ N rule
+ Specific repetition: "&lt;n&gt;(element)" is equivalent to
+ "&lt;n&gt;*&lt;n&gt;(element)"; that is, exactly &lt;n&gt; occurrences of (element).
+ Thus 2DIGIT is a 2-digit number, and 3ALPHA is a string of three
+ alphabetic characters.
+
+ #rule
+ A construct "#" is defined, similar to "*", for defining lists of
+ elements. The full form is "&lt;n&gt;#&lt;m&gt;element" indicating at least
+ &lt;n&gt; and at most &lt;m&gt; elements, each separated by one or more commas
+ (",") and OPTIONAL linear white space (LWS). This makes the usual
+ form of lists very easy; a rule such as
+ ( *LWS element *( *LWS "," *LWS element ))
+ can be shown as
+ 1#element
+ Wherever this construct is used, null elements are allowed, but do
+ not contribute to the count of elements present. That is,
+ "(element), , (element) " is permitted, but counts as only two
+ elements. Therefore, where at least one element is required, at
+ least one non-null element MUST be present. Default values are 0
+ and infinity so that "#element" allows any number, including zero;
+ "1#element" requires at least one; and "1#2element" allows one or
+ two.
+
+ ; comment
+ A semi-colon, set off some distance to the right of rule text,
+ starts a comment that continues to the end of line. This is a
+ simple way of including useful notes in parallel with the
+ specifications.
+
+ implied *LWS
+ The grammar described by this specification is word-based. Except
+ where noted otherwise, linear white space (LWS) can be included
+ between any two adjacent words (token or quoted-string), and
+ between adjacent words and separators, without changing the
+ interpretation of a field. At least one delimiter (LWS and/or
+
+ separators) MUST exist between any two tokens (for the definition
+ of "token" below), since they would otherwise be interpreted as a
+ single token.
+
+2.2 Basic Rules
+
+ The following rules are used throughout this specification to
+ describe basic parsing constructs. The US-ASCII coded character set
+ is defined by ANSI X3.4-1986 [21].
+
+ OCTET = &lt;any 8-bit sequence of data&gt;
+ CHAR = &lt;any US-ASCII character (octets 0 - 127)&gt;
+ UPALPHA = &lt;any US-ASCII uppercase letter "A".."Z"&gt;
+ LOALPHA = &lt;any US-ASCII lowercase letter "a".."z"&gt;
+ ALPHA = UPALPHA | LOALPHA
+ DIGIT = &lt;any US-ASCII digit "0".."9"&gt;
+ CTL = &lt;any US-ASCII control character
+ (octets 0 - 31) and DEL (127)&gt;
+ CR = &lt;US-ASCII CR, carriage return (13)&gt;
+ LF = &lt;US-ASCII LF, linefeed (10)&gt;
+ SP = &lt;US-ASCII SP, space (32)&gt;
+ HT = &lt;US-ASCII HT, horizontal-tab (9)&gt;
+ &lt;"&gt; = &lt;US-ASCII double-quote mark (34)&gt;
+
+ HTTP/1.1 defines the sequence CR LF as the end-of-line marker for all
+ protocol elements except the entity-body (see appendix 19.3 for
+ tolerant applications). The end-of-line marker within an entity-body
+ is defined by its associated media type, as described in section 3.7.
+
+ CRLF = CR LF
+
+ HTTP/1.1 header field values can be folded onto multiple lines if the
+ continuation line begins with a space or horizontal tab. All linear
+ white space, including folding, has the same semantics as SP. A
+ recipient MAY replace any linear white space with a single SP before
+ interpreting the field value or forwarding the message downstream.
+
+ LWS = [CRLF] 1*( SP | HT )
+
+ The TEXT rule is only used for descriptive field contents and values
+ that are not intended to be interpreted by the message parser. Words
+ of *TEXT MAY contain characters from character sets other than ISO-
+ 8859-1 [22] only when encoded according to the rules of <a href="http://firefly.troll.no/rfcs/rfc2047.html">RFC 2047</a>
+ [14].
+
+ TEXT = &lt;any OCTET except CTLs,
+ but including LWS&gt;
+
+ A CRLF is allowed in the definition of TEXT only as part of a header
+ field continuation. It is expected that the folding LWS will be
+ replaced with a single SP before interpretation of the TEXT value.
+
+ Hexadecimal numeric characters are used in several protocol elements.
+
+ HEX = "A" | "B" | "C" | "D" | "E" | "F"
+ | "a" | "b" | "c" | "d" | "e" | "f" | DIGIT
+
+ Many HTTP/1.1 header field values consist of words separated by LWS
+ or special characters. These special characters MUST be in a quoted
+ string to be used within a parameter value (as defined in section
+ 3.6).
+
+ token = 1*&lt;any CHAR except CTLs or separators&gt;
+ separators = "(" | ")" | "&lt;" | "&gt;" | "@"
+ | "," | ";" | ":" | "\" | &lt;"&gt;
+ | "/" | "[" | "]" | "?" | "="
+ | "{" | "}" | SP | HT
+
+ Comments can be included in some HTTP header fields by surrounding
+ the comment text with parentheses. Comments are only allowed in
+ fields containing "comment" as part of their field value definition.
+ In all other fields, parentheses are considered part of the field
+ value.
+
+ comment = "(" *( ctext | quoted-pair | comment ) ")"
+ ctext = &lt;any TEXT excluding "(" and ")"&gt;
+
+ A string of text is parsed as a single word if it is quoted using
+ double-quote marks.
+
+ quoted-string = ( &lt;"&gt; *(qdtext | quoted-pair ) &lt;"&gt; )
+ qdtext = &lt;any TEXT except &lt;"&gt;&gt;
+
+ The backslash character ("\") MAY be used as a single-character
+ quoting mechanism only within quoted-string and comment constructs.
+
+ quoted-pair = "\" CHAR
+
+3 Protocol Parameters
+
+3.1 HTTP Version
+
+ HTTP uses a "&lt;major&gt;.&lt;minor&gt;" numbering scheme to indicate versions
+ of the protocol. The protocol versioning policy is intended to allow
+ the sender to indicate the format of a message and its capacity for
+ understanding further HTTP communication, rather than the features
+ obtained via that communication. No change is made to the version
+ number for the addition of message components which do not affect
+ communication behavior or which only add to extensible field values.
+ The &lt;minor&gt; number is incremented when the changes made to the
+ protocol add features which do not change the general message parsing
+ algorithm, but which may add to the message semantics and imply
+ additional capabilities of the sender. The &lt;major&gt; number is
+ incremented when the format of a message within the protocol is
+ changed. See <a href="http://firefly.troll.no/rfcs/rfc2145.html">RFC 2145</a> [36] for a fuller explanation.
+
+ The version of an HTTP message is indicated by an HTTP-Version field
+ in the first line of the message.
+
+ HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
+
+ Note that the major and minor numbers MUST be treated as separate
+ integers and that each MAY be incremented higher than a single digit.
+ Thus, HTTP/2.4 is a lower version than HTTP/2.13, which in turn is
+ lower than HTTP/12.3. Leading zeros MUST be ignored by recipients and
+ MUST NOT be sent.
+
+ An application that sends a request or response message that includes
+ HTTP-Version of "HTTP/1.1" MUST be at least conditionally compliant
+ with this specification. Applications that are at least conditionally
+ compliant with this specification SHOULD use an HTTP-Version of
+ "HTTP/1.1" in their messages, and MUST do so for any message that is
+ not compatible with HTTP/1.0. For more details on when to send
+ specific HTTP-Version values, see <a href="http://firefly.troll.no/rfcs/rfc2145.html">RFC 2145</a> [36].
+
+ The HTTP version of an application is the highest HTTP version for
+ which the application is at least conditionally compliant.
+
+ Proxy and gateway applications need to be careful when forwarding
+ messages in protocol versions different from that of the application.
+ Since the protocol version indicates the protocol capability of the
+ sender, a proxy/gateway MUST NOT send a message with a version
+ indicator which is greater than its actual version. If a higher
+ version request is received, the proxy/gateway MUST either downgrade
+ the request version, or respond with an error, or switch to tunnel
+ behavior.
+
+ Due to interoperability problems with HTTP/1.0 proxies discovered
+ since the publication of <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a>[33], caching proxies MUST, gateways
+ MAY, and tunnels MUST NOT upgrade the request to the highest version
+ they support. The proxy/gateway's response to that request MUST be in
+ the same major version as the request.
+
+ Note: Converting between versions of HTTP may involve modification
+ of header fields required or forbidden by the versions involved.
+
+3.2 Uniform Resource Identifiers
+
+ URIs have been known by many names: WWW addresses, Universal Document
+ Identifiers, Universal Resource Identifiers [3], and finally the
+ combination of Uniform Resource Locators (URL) [4] and Names (URN)
+ [20]. As far as HTTP is concerned, Uniform Resource Identifiers are
+ simply formatted strings which identify--via name, location, or any
+ other characteristic--a resource.
+
+3.2.1 General Syntax
+
+ URIs in HTTP can be represented in absolute form or relative to some
+ known base URI [11], depending upon the context of their use. The two
+ forms are differentiated by the fact that absolute URIs always begin
+ with a scheme name followed by a colon. For definitive information on
+ URL syntax and semantics, see "Uniform Resource Identifiers (URI):
+ Generic Syntax and Semantics," <a href="http://firefly.troll.no/rfcs/rfc2396.html">RFC 2396</a> [42] (which replaces RFCs
+ 1738 [4] and <a href="http://firefly.troll.no/rfcs/rfc1808.html">RFC 1808</a> [11]). This specification adopts the
+ definitions of "URI-reference", "absoluteURI", "relativeURI", "port",
+ "host","abs_path", "rel_path", and "authority" from that
+ specification.
+
+ The HTTP protocol does not place any a priori limit on the length of
+ a URI. Servers MUST be able to handle the URI of any resource they
+ serve, and SHOULD be able to handle URIs of unbounded length if they
+ provide GET-based forms that could generate such URIs. A server
+ SHOULD return 414 (Request-URI Too Long) status if a URI is longer
+ than the server can handle (see section 10.4.15).
+
+ Note: Servers ought to be cautious about depending on URI lengths
+ above 255 bytes, because some older client or proxy
+ implementations might not properly support these lengths.
+
+3.2.2 http URL
+
+ The "http" scheme is used to locate network resources via the HTTP
+ protocol. This section defines the scheme-specific syntax and
+ semantics for http URLs.
+
+ http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
+
+ If the port is empty or not given, port 80 is assumed. The semantics
+ are that the identified resource is located at the server listening
+ for TCP connections on that port of that host, and the Request-URI
+ for the resource is abs_path (section 5.1.2). The use of IP addresses
+ in URLs SHOULD be avoided whenever possible (see <a href="http://firefly.troll.no/rfcs/rfc1900.html">RFC 1900</a> [24]). If
+ the abs_path is not present in the URL, it MUST be given as "/" when
+ used as a Request-URI for a resource (section 5.1.2). If a proxy
+ receives a host name which is not a fully qualified domain name, it
+ MAY add its domain to the host name it received. If a proxy receives
+ a fully qualified domain name, the proxy MUST NOT change the host
+ name.
+
+3.2.3 URI Comparison
+
+ When comparing two URIs to decide if they match or not, a client
+ SHOULD use a case-sensitive octet-by-octet comparison of the entire
+ URIs, with these exceptions:
+
+ - A port that is empty or not given is equivalent to the default
+ port for that URI-reference;
+
+ - Comparisons of host names MUST be case-insensitive;
+
+ - Comparisons of scheme names MUST be case-insensitive;
+
+ - An empty abs_path is equivalent to an abs_path of "/".
+
+ Characters other than those in the "reserved" and "unsafe" sets (see
+ <a href="http://firefly.troll.no/rfcs/rfc2396.html">RFC 2396</a> [42]) are equivalent to their ""%" HEX HEX" encoding.
+
+ For example, the following three URIs are equivalent:
+
+ <a href="http://abc.com/%7Esmith/home.html">http://abc.com:80/~smith/home.html</a>
+ <a href="http://abc.com/%7Esmith/home.html">http://ABC.com/%7Esmith/home.html</a>
+ <a href="http://firefly.troll.no/%3CA%20HREF=" ftp:="" abc.com="" %7esmith="" home.html="">/ABC.com:/%7esmith/home.html</a>"&gt;http:/<a href="ftp://abc.com/%7esmith/home.html%3C/A%3E">/ABC.com:/%7esmith/home.html</a>
+
+3.3 Date/Time Formats
+
+3.3.1 Full Date
+
+ HTTP applications have historically allowed three different formats
+ for the representation of date/time stamps:
+
+ Sun, 06 Nov 1994 08:49:37 GMT ; <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a>, updated by <a href="http://firefly.troll.no/rfcs/rfc1123.html">RFC 1123</a>
+ Sunday, 06-Nov-94 08:49:37 GMT ; <a href="http://firefly.troll.no/rfcs/rfc850.html">RFC 850</a>, obsoleted by <a href="http://firefly.troll.no/rfcs/rfc1036.html">RFC 1036</a>
+ Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
+
+ The first format is preferred as an Internet standard and represents
+ a fixed-length subset of that defined by <a href="http://firefly.troll.no/rfcs/rfc1123.html">RFC 1123</a> [8] (an update to
+ <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a> [9]). The second format is in common use, but is based on the
+ obsolete <a href="http://firefly.troll.no/rfcs/rfc850.html">RFC 850</a> [12] date format and lacks a four-digit year.
+ HTTP/1.1 clients and servers that parse the date value MUST accept
+ all three formats (for compatibility with HTTP/1.0), though they MUST
+ only generate the <a href="http://firefly.troll.no/rfcs/rfc1123.html">RFC 1123</a> format for representing HTTP-date values
+ in header fields. See section 19.3 for further information.
+
+ Note: Recipients of date values are encouraged to be robust in
+ accepting date values that may have been sent by non-HTTP
+ applications, as is sometimes the case when retrieving or posting
+ messages via proxies/gateways to SMTP or NNTP.
+
+ All HTTP date/time stamps MUST be represented in Greenwich Mean Time
+ (GMT), without exception. For the purposes of HTTP, GMT is exactly
+ equal to UTC (Coordinated Universal Time). This is indicated in the
+ first two formats by the inclusion of "GMT" as the three-letter
+ abbreviation for time zone, and MUST be assumed when reading the
+ asctime format. HTTP-date is case sensitive and MUST NOT include
+ additional LWS beyond that specifically included as SP in the
+ grammar.
+
+ HTTP-date = <a href="http://firefly.troll.no/rfcs/rfc1123.html">rfc1123</a>-date | <a href="http://firefly.troll.no/rfcs/rfc850.html">rfc850</a>-date | asctime-date
+ <a href="http://firefly.troll.no/rfcs/rfc1123.html">rfc1123</a>-date = wkday "," SP date1 SP time SP "GMT"
+ <a href="http://firefly.troll.no/rfcs/rfc850.html">rfc850</a>-date = weekday "," SP date2 SP time SP "GMT"
+ asctime-date = wkday SP date3 SP time SP 4DIGIT
+ date1 = 2DIGIT SP month SP 4DIGIT
+ ; day month year (e.g., 02 Jun 1982)
+ date2 = 2DIGIT "-" month "-" 2DIGIT
+ ; day-month-year (e.g., 02-Jun-82)
+ date3 = month SP ( 2DIGIT | ( SP 1DIGIT ))
+ ; month day (e.g., Jun 2)
+ time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
+ ; 00:00:00 - 23:59:59
+ wkday = "Mon" | "Tue" | "Wed"
+ | "Thu" | "Fri" | "Sat" | "Sun"
+ weekday = "Monday" | "Tuesday" | "Wednesday"
+ | "Thursday" | "Friday" | "Saturday" | "Sunday"
+ month = "Jan" | "Feb" | "Mar" | "Apr"
+ | "May" | "Jun" | "Jul" | "Aug"
+ | "Sep" | "Oct" | "Nov" | "Dec"
+
+ Note: HTTP requirements for the date/time stamp format apply only
+ to their usage within the protocol stream. Clients and servers are
+ not required to use these formats for user presentation, request
+ logging, etc.
+
+3.3.2 Delta Seconds
+
+ Some HTTP header fields allow a time value to be specified as an
+ integer number of seconds, represented in decimal, after the time
+ that the message was received.
+
+ delta-seconds = 1*DIGIT
+
+3.4 Character Sets
+
+ HTTP uses the same definition of the term "character set" as that
+ described for MIME:
+
+ The term "character set" is used in this document to refer to a
+ method used with one or more tables to convert a sequence of octets
+ into a sequence of characters. Note that unconditional conversion in
+ the other direction is not required, in that not all characters may
+ be available in a given character set and a character set may provide
+ more than one sequence of octets to represent a particular character.
+ This definition is intended to allow various kinds of character
+ encoding, from simple single-table mappings such as US-ASCII to
+ complex table switching methods such as those that use ISO-2022's
+ techniques. However, the definition associated with a MIME character
+ set name MUST fully specify the mapping to be performed from octets
+ to characters. In particular, use of external profiling information
+ to determine the exact mapping is not permitted.
+
+ Note: This use of the term "character set" is more commonly
+ referred to as a "character encoding." However, since HTTP and
+ MIME share the same registry, it is important that the terminology
+ also be shared.
+
+ HTTP character sets are identified by case-insensitive tokens. The
+ complete set of tokens is defined by the IANA Character Set registry
+ [19].
+
+ charset = token
+
+ Although HTTP allows an arbitrary token to be used as a charset
+ value, any token that has a predefined value within the IANA
+ Character Set registry [19] MUST represent the character set defined
+ by that registry. Applications SHOULD limit their use of character
+ sets to those defined by the IANA registry.
+
+ Implementors should be aware of IETF character set requirements [38]
+ [41].
+
+3.4.1 Missing Charset
+
+ Some HTTP/1.0 software has interpreted a Content-Type header without
+ charset parameter incorrectly to mean "recipient should guess."
+ Senders wishing to defeat this behavior MAY include a charset
+ parameter even when the charset is ISO-8859-1 and SHOULD do so when
+ it is known that it will not confuse the recipient.
+
+ Unfortunately, some older HTTP/1.0 clients did not deal properly with
+ an explicit charset parameter. HTTP/1.1 recipients MUST respect the
+ charset label provided by the sender; and those user agents that have
+ a provision to "guess" a charset MUST use the charset from the
+
+ content-type field if they support that charset, rather than the
+ recipient's preference, when initially displaying a document. See
+ section 3.7.1.
+
+3.5 Content Codings
+
+ Content coding values indicate an encoding transformation that has
+ been or can be applied to an entity. Content codings are primarily
+ used to allow a document to be compressed or otherwise usefully
+ transformed without losing the identity of its underlying media type
+ and without loss of information. Frequently, the entity is stored in
+ coded form, transmitted directly, and only decoded by the recipient.
+
+ content-coding = token
+
+ All content-coding values are case-insensitive. HTTP/1.1 uses
+ content-coding values in the Accept-Encoding (section 14.3) and
+ Content-Encoding (section 14.11) header fields. Although the value
+ describes the content-coding, what is more important is that it
+ indicates what decoding mechanism will be required to remove the
+ encoding.
+
+ The Internet Assigned Numbers Authority (IANA) acts as a registry for
+ content-coding value tokens. Initially, the registry contains the
+ following tokens:
+
+ gzip An encoding format produced by the file compression program
+ "gzip" (GNU zip) as described in <a href="http://firefly.troll.no/rfcs/rfc1952.html">RFC 1952</a> [25]. This format is a
+ Lempel-Ziv coding (LZ77) with a 32 bit CRC.
+
+ compress
+ The encoding format produced by the common UNIX file compression
+ program "compress". This format is an adaptive Lempel-Ziv-Welch
+ coding (LZW).
+
+ Use of program names for the identification of encoding formats
+ is not desirable and is discouraged for future encodings. Their
+ use here is representative of historical practice, not good
+ design. For compatibility with previous implementations of HTTP,
+ applications SHOULD consider "x-gzip" and "x-compress" to be
+ equivalent to "gzip" and "compress" respectively.
+
+ deflate
+ The "zlib" format defined in <a href="http://firefly.troll.no/rfcs/rfc1950.html">RFC 1950</a> [31] in combination with
+ the "deflate" compression mechanism described in <a href="http://firefly.troll.no/rfcs/rfc1951.html">RFC 1951</a> [29].
+
+ identity
+ The default (identity) encoding; the use of no transformation
+ whatsoever. This content-coding is used only in the Accept-
+ Encoding header, and SHOULD NOT be used in the Content-Encoding
+ header.
+
+ New content-coding value tokens SHOULD be registered; to allow
+ interoperability between clients and servers, specifications of the
+ content coding algorithms needed to implement a new value SHOULD be
+ publicly available and adequate for independent implementation, and
+ conform to the purpose of content coding defined in this section.
+
+3.6 Transfer Codings
+
+ Transfer-coding values are used to indicate an encoding
+ transformation that has been, can be, or may need to be applied to an
+ entity-body in order to ensure "safe transport" through the network.
+ This differs from a content coding in that the transfer-coding is a
+ property of the message, not of the original entity.
+
+ transfer-coding = "chunked" | transfer-extension
+ transfer-extension = token *( ";" parameter )
+
+ Parameters are in the form of attribute/value pairs.
+
+ parameter = attribute "=" value
+ attribute = token
+ value = token | quoted-string
+
+ All transfer-coding values are case-insensitive. HTTP/1.1 uses
+ transfer-coding values in the TE header field (section 14.39) and in
+ the Transfer-Encoding header field (section 14.41).
+
+ Whenever a transfer-coding is applied to a message-body, the set of
+ transfer-codings MUST include "chunked", unless the message is
+ terminated by closing the connection. When the "chunked" transfer-
+ coding is used, it MUST be the last transfer-coding applied to the
+ message-body. The "chunked" transfer-coding MUST NOT be applied more
+ than once to a message-body. These rules allow the recipient to
+ determine the transfer-length of the message (section 4.4).
+
+ Transfer-codings are analogous to the Content-Transfer-Encoding
+ values of MIME [7], which were designed to enable safe transport of
+ binary data over a 7-bit transport service. However, safe transport
+ has a different focus for an 8bit-clean transfer protocol. In HTTP,
+ the only unsafe characteristic of message-bodies is the difficulty in
+ determining the exact body length (section 7.2.2), or the desire to
+ encrypt data over a shared transport.
+
+ The Internet Assigned Numbers Authority (IANA) acts as a registry for
+ transfer-coding value tokens. Initially, the registry contains the
+ following tokens: "chunked" (section 3.6.1), "identity" (section
+ 3.6.2), "gzip" (section 3.5), "compress" (section 3.5), and "deflate"
+ (section 3.5).
+
+ New transfer-coding value tokens SHOULD be registered in the same way
+ as new content-coding value tokens (section 3.5).
+
+ A server which receives an entity-body with a transfer-coding it does
+ not understand SHOULD return 501 (Unimplemented), and close the
+ connection. A server MUST NOT send transfer-codings to an HTTP/1.0
+ client.
+
+3.6.1 Chunked Transfer Coding
+
+ The chunked encoding modifies the body of a message in order to
+ transfer it as a series of chunks, each with its own size indicator,
+ followed by an OPTIONAL trailer containing entity-header fields. This
+ allows dynamically produced content to be transferred along with the
+ information necessary for the recipient to verify that it has
+ received the full message.
+
+ Chunked-Body = *chunk
+ last-chunk
+ trailer
+ CRLF
+
+ chunk = chunk-size [ chunk-extension ] CRLF
+ chunk-data CRLF
+ chunk-size = 1*HEX
+ last-chunk = 1*("0") [ chunk-extension ] CRLF
+
+ chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
+ chunk-ext-name = token
+ chunk-ext-val = token | quoted-string
+ chunk-data = chunk-size(OCTET)
+ trailer = *(entity-header CRLF)
+
+ The chunk-size field is a string of hex digits indicating the size of
+ the chunk. The chunked encoding is ended by any chunk whose size is
+ zero, followed by the trailer, which is terminated by an empty line.
+
+ The trailer allows the sender to include additional HTTP header
+ fields at the end of the message. The Trailer header field can be
+ used to indicate which header fields are included in a trailer (see
+ section 14.40).
+
+ A server using chunked transfer-coding in a response MUST NOT use the
+ trailer for any header fields unless at least one of the following is
+ true:
+
+ a)the request included a TE header field that indicates "trailers" is
+ acceptable in the transfer-coding of the response, as described in
+ section 14.39; or,
+
+ b)the server is the origin server for the response, the trailer
+ fields consist entirely of optional metadata, and the recipient
+ could use the message (in a manner acceptable to the origin server)
+ without receiving this metadata. In other words, the origin server
+ is willing to accept the possibility that the trailer fields might
+ be silently discarded along the path to the client.
+
+ This requirement prevents an interoperability failure when the
+ message is being received by an HTTP/1.1 (or later) proxy and
+ forwarded to an HTTP/1.0 recipient. It avoids a situation where
+ compliance with the protocol would have necessitated a possibly
+ infinite buffer on the proxy.
+
+ An example process for decoding a Chunked-Body is presented in
+ appendix 19.4.6.
+
+ All HTTP/1.1 applications MUST be able to receive and decode the
+ "chunked" transfer-coding, and MUST ignore chunk-extension extensions
+ they do not understand.
+
+3.7 Media Types
+
+ HTTP uses Internet Media Types [17] in the Content-Type (section
+ 14.17) and Accept (section 14.1) header fields in order to provide
+ open and extensible data typing and type negotiation.
+
+ media-type = type "/" subtype *( ";" parameter )
+ type = token
+ subtype = token
+
+ Parameters MAY follow the type/subtype in the form of attribute/value
+ pairs (as defined in section 3.6).
+
+ The type, subtype, and parameter attribute names are case-
+ insensitive. Parameter values might or might not be case-sensitive,
+ depending on the semantics of the parameter name. Linear white space
+ (LWS) MUST NOT be used between the type and subtype, nor between an
+ attribute and its value. The presence or absence of a parameter might
+ be significant to the processing of a media-type, depending on its
+ definition within the media type registry.
+
+ Note that some older HTTP applications do not recognize media type
+ parameters. When sending data to older HTTP applications,
+ implementations SHOULD only use media type parameters when they are
+ required by that type/subtype definition.
+
+ Media-type values are registered with the Internet Assigned Number
+ Authority (IANA [19]). The media type registration process is
+ outlined in <a href="http://firefly.troll.no/rfcs/rfc1590.html">RFC 1590</a> [17]. Use of non-registered media types is
+ discouraged.
+
+3.7.1 Canonicalization and Text Defaults
+
+ Internet media types are registered with a canonical form. An
+ entity-body transferred via HTTP messages MUST be represented in the
+ appropriate canonical form prior to its transmission except for
+ "text" types, as defined in the next paragraph.
+
+ When in canonical form, media subtypes of the "text" type use CRLF as
+ the text line break. HTTP relaxes this requirement and allows the
+ transport of text media with plain CR or LF alone representing a line
+ break when it is done consistently for an entire entity-body. HTTP
+ applications MUST accept CRLF, bare CR, and bare LF as being
+ representative of a line break in text media received via HTTP. In
+ addition, if the text is represented in a character set that does not
+ use octets 13 and 10 for CR and LF respectively, as is the case for
+ some multi-byte character sets, HTTP allows the use of whatever octet
+ sequences are defined by that character set to represent the
+ equivalent of CR and LF for line breaks. This flexibility regarding
+ line breaks applies only to text media in the entity-body; a bare CR
+ or LF MUST NOT be substituted for CRLF within any of the HTTP control
+ structures (such as header fields and multipart boundaries).
+
+ If an entity-body is encoded with a content-coding, the underlying
+ data MUST be in a form defined above prior to being encoded.
+
+ The "charset" parameter is used with some media types to define the
+ character set (section 3.4) of the data. When no explicit charset
+ parameter is provided by the sender, media subtypes of the "text"
+ type are defined to have a default charset value of "ISO-8859-1" when
+ received via HTTP. Data in character sets other than "ISO-8859-1" or
+ its subsets MUST be labeled with an appropriate charset value. See
+ section 3.4.1 for compatibility problems.
+
+3.7.2 Multipart Types
+
+ MIME provides for a number of "multipart" types -- encapsulations of
+ one or more entities within a single message-body. All multipart
+ types share a common syntax, as defined in section 5.1.1 of <a href="http://firefly.troll.no/rfcs/rfc2046.html">RFC 2046</a>
+
+ [40], and MUST include a boundary parameter as part of the media type
+ value. The message body is itself a protocol element and MUST
+ therefore use only CRLF to represent line breaks between body-parts.
+ Unlike in <a href="http://firefly.troll.no/rfcs/rfc2046.html">RFC 2046</a>, the epilogue of any multipart message MUST be
+ empty; HTTP applications MUST NOT transmit the epilogue (even if the
+ original multipart contains an epilogue). These restrictions exist in
+ order to preserve the self-delimiting nature of a multipart message-
+ body, wherein the "end" of the message-body is indicated by the
+ ending multipart boundary.
+
+ In general, HTTP treats a multipart message-body no differently than
+ any other media type: strictly as payload. The one exception is the
+ "multipart/byteranges" type (appendix 19.2) when it appears in a 206
+ (Partial Content) response, which will be interpreted by some HTTP
+ caching mechanisms as described in sections 13.5.4 and 14.16. In all
+ other cases, an HTTP user agent SHOULD follow the same or similar
+ behavior as a MIME user agent would upon receipt of a multipart type.
+ The MIME header fields within each body-part of a multipart message-
+ body do not have any significance to HTTP beyond that defined by
+ their MIME semantics.
+
+ In general, an HTTP user agent SHOULD follow the same or similar
+ behavior as a MIME user agent would upon receipt of a multipart type.
+ If an application receives an unrecognized multipart subtype, the
+ application MUST treat it as being equivalent to "multipart/mixed".
+
+ Note: The "multipart/form-data" type has been specifically defined
+ for carrying form data suitable for processing via the POST
+ request method, as described in <a href="http://firefly.troll.no/rfcs/rfc1867.html">RFC 1867</a> [15].
+
+3.8 Product Tokens
+
+ Product tokens are used to allow communicating applications to
+ identify themselves by software name and version. Most fields using
+ product tokens also allow sub-products which form a significant part
+ of the application to be listed, separated by white space. By
+ convention, the products are listed in order of their significance
+ for identifying the application.
+
+ product = token ["/" product-version]
+ product-version = token
+
+ Examples:
+
+ User-Agent: CERN-LineMode/2.15 libwww/2.17b3
+ Server: Apache/0.8.4
+
+ Product tokens SHOULD be short and to the point. They MUST NOT be
+ used for advertising or other non-essential information. Although any
+ token character MAY appear in a product-version, this token SHOULD
+ only be used for a version identifier (i.e., successive versions of
+ the same product SHOULD only differ in the product-version portion of
+ the product value).
+
+3.9 Quality Values
+
+ HTTP content negotiation (section 12) uses short "floating point"
+ numbers to indicate the relative importance ("weight") of various
+ negotiable parameters. A weight is normalized to a real number in
+ the range 0 through 1, where 0 is the minimum and 1 the maximum
+ value. If a parameter has a quality value of 0, then content with
+ this parameter is `not acceptable' for the client. HTTP/1.1
+ applications MUST NOT generate more than three digits after the
+ decimal point. User configuration of these values SHOULD also be
+ limited in this fashion.
+
+ qvalue = ( "0" [ "." 0*3DIGIT ] )
+ | ( "1" [ "." 0*3("0") ] )
+
+ "Quality values" is a misnomer, since these values merely represent
+ relative degradation in desired quality.
+
+3.10 Language Tags
+
+ A language tag identifies a natural language spoken, written, or
+ otherwise conveyed by human beings for communication of information
+ to other human beings. Computer languages are explicitly excluded.
+ HTTP uses language tags within the Accept-Language and Content-
+ Language fields.
+
+ The syntax and registry of HTTP language tags is the same as that
+ defined by <a href="http://firefly.troll.no/rfcs/rfc1766.html">RFC 1766</a> [1]. In summary, a language tag is composed of 1
+ or more parts: A primary language tag and a possibly empty series of
+ subtags:
+
+ language-tag = primary-tag *( "-" subtag )
+ primary-tag = 1*8ALPHA
+ subtag = 1*8ALPHA
+
+ White space is not allowed within the tag and all tags are case-
+ insensitive. The name space of language tags is administered by the
+ IANA. Example tags include:
+
+ en, en-US, en-cockney, i-cherokee, x-pig-latin
+
+ where any two-letter primary-tag is an ISO-639 language abbreviation
+ and any two-letter initial subtag is an ISO-3166 country code. (The
+ last three tags above are not registered tags; all but the last are
+ examples of tags which could be registered in future.)
+
+3.11 Entity Tags
+
+ Entity tags are used for comparing two or more entities from the same
+ requested resource. HTTP/1.1 uses entity tags in the ETag (section
+ 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and
+ If-Range (section 14.27) header fields. The definition of how they
+ are used and compared as cache validators is in section 13.3.3. An
+ entity tag consists of an opaque quoted string, possibly prefixed by
+ a weakness indicator.
+
+ entity-tag = [ weak ] opaque-tag
+ weak = "W/"
+ opaque-tag = quoted-string
+
+ A "strong entity tag" MAY be shared by two entities of a resource
+ only if they are equivalent by octet equality.
+
+ A "weak entity tag," indicated by the "W/" prefix, MAY be shared by
+ two entities of a resource only if the entities are equivalent and
+ could be substituted for each other with no significant change in
+ semantics. A weak entity tag can only be used for weak comparison.
+
+ An entity tag MUST be unique across all versions of all entities
+ associated with a particular resource. A given entity tag value MAY
+ be used for entities obtained by requests on different URIs. The use
+ of the same entity tag value in conjunction with entities obtained by
+ requests on different URIs does not imply the equivalence of those
+ entities.
+
+3.12 Range Units
+
+ HTTP/1.1 allows a client to request that only part (a range of) the
+ response entity be included within the response. HTTP/1.1 uses range
+ units in the Range (section 14.35) and Content-Range (section 14.16)
+ header fields. An entity can be broken down into subranges according
+ to various structural units.
+
+ range-unit = bytes-unit | other-range-unit
+ bytes-unit = "bytes"
+ other-range-unit = token
+
+ The only range unit defined by HTTP/1.1 is "bytes". HTTP/1.1
+ implementations MAY ignore ranges specified using other units.
+
+ HTTP/1.1 has been designed to allow implementations of applications
+ that do not depend on knowledge of ranges.
+
+4 HTTP Message
+
+4.1 Message Types
+
+ HTTP messages consist of requests from client to server and responses
+ from server to client.
+
+ HTTP-message = Request | Response ; HTTP/1.1 messages
+
+ Request (section 5) and Response (section 6) messages use the generic
+ message format of <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a> [9] for transferring entities (the payload
+ of the message). Both types of message consist of a start-line, zero
+ or more header fields (also known as "headers"), an empty line (i.e.,
+ a line with nothing preceding the CRLF) indicating the end of the
+ header fields, and possibly a message-body.
+
+ generic-message = start-line
+ *(message-header CRLF)
+ CRLF
+ [ message-body ]
+ start-line = Request-Line | Status-Line
+
+ In the interest of robustness, servers SHOULD ignore any empty
+ line(s) received where a Request-Line is expected. In other words, if
+ the server is reading the protocol stream at the beginning of a
+ message and receives a CRLF first, it should ignore the CRLF.
+
+ Certain buggy HTTP/1.0 client implementations generate extra CRLF's
+ after a POST request. To restate what is explicitly forbidden by the
+ BNF, an HTTP/1.1 client MUST NOT preface or follow a request with an
+ extra CRLF.
+
+4.2 Message Headers
+
+ HTTP header fields, which include general-header (section 4.5),
+ request-header (section 5.3), response-header (section 6.2), and
+ entity-header (section 7.1) fields, follow the same generic format as
+ that given in Section 3.1 of <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a> [9]. Each header field consists
+ of a name followed by a colon (":") and the field value. Field names
+ are case-insensitive. The field value MAY be preceded by any amount
+ of LWS, though a single SP is preferred. Header fields can be
+ extended over multiple lines by preceding each extra line with at
+ least one SP or HT. Applications ought to follow "common form", where
+ one is known or indicated, when generating HTTP constructs, since
+ there might exist some implementations that fail to accept anything
+
+ beyond the common forms.
+
+ message-header = field-name ":" [ field-value ]
+ field-name = token
+ field-value = *( field-content | LWS )
+ field-content = &lt;the OCTETs making up the field-value
+ and consisting of either *TEXT or combinations
+ of token, separators, and quoted-string&gt;
+
+ The field-content does not include any leading or trailing LWS:
+ linear white space occurring before the first non-whitespace
+ character of the field-value or after the last non-whitespace
+ character of the field-value. Such leading or trailing LWS MAY be
+ removed without changing the semantics of the field value. Any LWS
+ that occurs between field-content MAY be replaced with a single SP
+ before interpreting the field value or forwarding the message
+ downstream.
+
+ The order in which header fields with differing field names are
+ received is not significant. However, it is "good practice" to send
+ general-header fields first, followed by request-header or response-
+ header fields, and ending with the entity-header fields.
+
+ Multiple message-header fields with the same field-name MAY be
+ present in a message if and only if the entire field-value for that
+ header field is defined as a comma-separated list [i.e., #(values)].
+ It MUST be possible to combine the multiple header fields into one
+ "field-name: field-value" pair, without changing the semantics of the
+ message, by appending each subsequent field-value to the first, each
+ separated by a comma. The order in which header fields with the same
+ field-name are received is therefore significant to the
+ interpretation of the combined field value, and thus a proxy MUST NOT
+ change the order of these field values when a message is forwarded.
+
+4.3 Message Body
+
+ The message-body (if any) of an HTTP message is used to carry the
+ entity-body associated with the request or response. The message-body
+ differs from the entity-body only when a transfer-coding has been
+ applied, as indicated by the Transfer-Encoding header field (section
+ 14.41).
+
+ message-body = entity-body
+ | &lt;entity-body encoded as per Transfer-Encoding&gt;
+
+ Transfer-Encoding MUST be used to indicate any transfer-codings
+ applied by an application to ensure safe and proper transfer of the
+ message. Transfer-Encoding is a property of the message, not of the
+
+ entity, and thus MAY be added or removed by any application along the
+ request/response chain. (However, section 3.6 places restrictions on
+ when certain transfer-codings may be used.)
+
+ The rules for when a message-body is allowed in a message differ for
+ requests and responses.
+
+ The presence of a message-body in a request is signaled by the
+ inclusion of a Content-Length or Transfer-Encoding header field in
+ the request's message-headers. A message-body MUST NOT be included in
+ a request if the specification of the request method (section 5.1.1)
+ does not allow sending an entity-body in requests. A server SHOULD
+ read and forward a message-body on any request; if the request method
+ does not include defined semantics for an entity-body, then the
+ message-body SHOULD be ignored when handling the request.
+
+ For response messages, whether or not a message-body is included with
+ a message is dependent on both the request method and the response
+ status code (section 6.1.1). All responses to the HEAD request method
+ MUST NOT include a message-body, even though the presence of entity-
+ header fields might lead one to believe they do. All 1xx
+ (informational), 204 (no content), and 304 (not modified) responses
+ MUST NOT include a message-body. All other responses do include a
+ message-body, although it MAY be of zero length.
+
+4.4 Message Length
+
+ The transfer-length of a message is the length of the message-body as
+ it appears in the message; that is, after any transfer-codings have
+ been applied. When a message-body is included with a message, the
+ transfer-length of that body is determined by one of the following
+ (in order of precedence):
+
+ 1.Any response message which "MUST NOT" include a message-body (such
+ as the 1xx, 204, and 304 responses and any response to a HEAD
+ request) is always terminated by the first empty line after the
+ header fields, regardless of the entity-header fields present in
+ the message.
+
+ 2.If a Transfer-Encoding header field (section 14.41) is present and
+ has any value other than "identity", then the transfer-length is
+ defined by use of the "chunked" transfer-coding (section 3.6),
+ unless the message is terminated by closing the connection.
+
+ 3.If a Content-Length header field (section 14.13) is present, its
+ decimal value in OCTETs represents both the entity-length and the
+ transfer-length. The Content-Length header field MUST NOT be sent
+ if these two lengths are different (i.e., if a Transfer-Encoding
+
+ header field is present). If a message is received with both a
+ Transfer-Encoding header field and a Content-Length header field,
+ the latter MUST be ignored.
+
+ 4.If the message uses the media type "multipart/byteranges", and the
+ ransfer-length is not otherwise specified, then this self-
+ elimiting media type defines the transfer-length. This media type
+ UST NOT be used unless the sender knows that the recipient can arse
+ it; the presence in a request of a Range header with ultiple byte-
+ range specifiers from a 1.1 client implies that the lient can parse
+ multipart/byteranges responses.
+
+ A range header might be forwarded by a 1.0 proxy that does not
+ understand multipart/byteranges; in this case the server MUST
+ delimit the message using methods defined in items 1,3 or 5 of
+ this section.
+
+ 5.By the server closing the connection. (Closing the connection
+ cannot be used to indicate the end of a request body, since that
+ would leave no possibility for the server to send back a response.)
+
+ For compatibility with HTTP/1.0 applications, HTTP/1.1 requests
+ containing a message-body MUST include a valid Content-Length header
+ field unless the server is known to be HTTP/1.1 compliant. If a
+ request contains a message-body and a Content-Length is not given,
+ the server SHOULD respond with 400 (bad request) if it cannot
+ determine the length of the message, or with 411 (length required) if
+ it wishes to insist on receiving a valid Content-Length.
+
+ All HTTP/1.1 applications that receive entities MUST accept the
+ "chunked" transfer-coding (section 3.6), thus allowing this mechanism
+ to be used for messages when the message length cannot be determined
+ in advance.
+
+ Messages MUST NOT include both a Content-Length header field and a
+ non-identity transfer-coding. If the message does include a non-
+ identity transfer-coding, the Content-Length MUST be ignored.
+
+ When a Content-Length is given in a message where a message-body is
+ allowed, its field value MUST exactly match the number of OCTETs in
+ the message-body. HTTP/1.1 user agents MUST notify the user when an
+ invalid length is received and detected.
+
+4.5 General Header Fields
+
+ There are a few header fields which have general applicability for
+ both request and response messages, but which do not apply to the
+ entity being transferred. These header fields apply only to the
+
+ message being transmitted.
+
+ general-header = Cache-Control ; Section 14.9
+ | Connection ; Section 14.10
+ | Date ; Section 14.18
+ | Pragma ; Section 14.32
+ | Trailer ; Section 14.40
+ | Transfer-Encoding ; Section 14.41
+ | Upgrade ; Section 14.42
+ | Via ; Section 14.45
+ | Warning ; Section 14.46
+
+ General-header field names can be extended reliably only in
+ combination with a change in the protocol version. However, new or
+ experimental header fields may be given the semantics of general
+ header fields if all parties in the communication recognize them to
+ be general-header fields. Unrecognized header fields are treated as
+ entity-header fields.
+
+5 Request
+
+ A request message from a client to a server includes, within the
+ first line of that message, the method to be applied to the resource,
+ the identifier of the resource, and the protocol version in use.
+
+ Request = Request-Line ; Section 5.1
+ *(( general-header ; Section 4.5
+ | request-header ; Section 5.3
+ | entity-header ) CRLF) ; Section 7.1
+ CRLF
+ [ message-body ] ; Section 4.3
+
+5.1 Request-Line
+
+ The Request-Line begins with a method token, followed by the
+ Request-URI and the protocol version, and ending with CRLF. The
+ elements are separated by SP characters. No CR or LF is allowed
+ except in the final CRLF sequence.
+
+ Request-Line = Method SP Request-URI SP HTTP-Version CRLF
+
+5.1.1 Method
+
+ The Method token indicates the method to be performed on the
+ resource identified by the Request-URI. The method is case-sensitive.
+
+ Method = "OPTIONS" ; Section 9.2
+ | "GET" ; Section 9.3
+ | "HEAD" ; Section 9.4
+ | "POST" ; Section 9.5
+ | "PUT" ; Section 9.6
+ | "DELETE" ; Section 9.7
+ | "TRACE" ; Section 9.8
+ | "CONNECT" ; Section 9.9
+ | extension-method
+ extension-method = token
+
+ The list of methods allowed by a resource can be specified in an
+ Allow header field (section 14.7). The return code of the response
+ always notifies the client whether a method is currently allowed on a
+ resource, since the set of allowed methods can change dynamically. An
+ origin server SHOULD return the status code 405 (Method Not Allowed)
+ if the method is known by the origin server but not allowed for the
+ requested resource, and 501 (Not Implemented) if the method is
+ unrecognized or not implemented by the origin server. The methods GET
+ and HEAD MUST be supported by all general-purpose servers. All other
+ methods are OPTIONAL; however, if the above methods are implemented,
+ they MUST be implemented with the same semantics as those specified
+ in section 9.
+
+5.1.2 Request-URI
+
+ The Request-URI is a Uniform Resource Identifier (section 3.2) and
+ identifies the resource upon which to apply the request.
+
+ Request-URI = "*" | absoluteURI | abs_path | authority
+
+ The four options for Request-URI are dependent on the nature of the
+ request. The asterisk "*" means that the request does not apply to a
+ particular resource, but to the server itself, and is only allowed
+ when the method used does not necessarily apply to a resource. One
+ example would be
+
+ OPTIONS * HTTP/1.1
+
+ The absoluteURI form is REQUIRED when the request is being made to a
+ proxy. The proxy is requested to forward the request or service it
+ from a valid cache, and return the response. Note that the proxy MAY
+ forward the request on to another proxy or directly to the server
+
+ specified by the absoluteURI. In order to avoid request loops, a
+ proxy MUST be able to recognize all of its server names, including
+ any aliases, local variations, and the numeric IP address. An example
+ Request-Line would be:
+
+ GET <a href="http://www.w3.org/pub/WWW/TheProject.html">http://www.w3.org/pub/WWW/TheProject.html</a> HTTP/1.1
+
+ To allow for transition to absoluteURIs in all requests in future
+ versions of HTTP, all HTTP/1.1 servers MUST accept the absoluteURI
+ form in requests, even though HTTP/1.1 clients will only generate
+ them in requests to proxies.
+
+ The authority form is only used by the CONNECT method (section 9.9).
+
+ The most common form of Request-URI is that used to identify a
+ resource on an origin server or gateway. In this case the absolute
+ path of the URI MUST be transmitted (see section 3.2.1, abs_path) as
+ the Request-URI, and the network location of the URI (authority) MUST
+ be transmitted in a Host header field. For example, a client wishing
+ to retrieve the resource above directly from the origin server would
+ create a TCP connection to port 80 of the host "www.w3.org" and send
+ the lines:
+
+ GET /pub/WWW/TheProject.html HTTP/1.1
+ Host: www.w3.org
+
+ followed by the remainder of the Request. Note that the absolute path
+ cannot be empty; if none is present in the original URI, it MUST be
+ given as "/" (the server root).
+
+ The Request-URI is transmitted in the format specified in section
+ 3.2.1. If the Request-URI is encoded using the "% HEX HEX" encoding
+ [42], the origin server MUST decode the Request-URI in order to
+ properly interpret the request. Servers SHOULD respond to invalid
+ Request-URIs with an appropriate status code.
+
+ A transparent proxy MUST NOT rewrite the "abs_path" part of the
+ received Request-URI when forwarding it to the next inbound server,
+ except as noted above to replace a null abs_path with "/".
+
+ Note: The "no rewrite" rule prevents the proxy from changing the
+ meaning of the request when the origin server is improperly using
+ a non-reserved URI character for a reserved purpose. Implementors
+ should be aware that some pre-HTTP/1.1 proxies have been known to
+ rewrite the Request-URI.
+
+5.2 The Resource Identified by a Request
+
+ The exact resource identified by an Internet request is determined by
+ examining both the Request-URI and the Host header field.
+
+ An origin server that does not allow resources to differ by the
+ requested host MAY ignore the Host header field value when
+ determining the resource identified by an HTTP/1.1 request. (But see
+ section 19.6.1.1 for other requirements on Host support in HTTP/1.1.)
+
+ An origin server that does differentiate resources based on the host
+ requested (sometimes referred to as virtual hosts or vanity host
+ names) MUST use the following rules for determining the requested
+ resource on an HTTP/1.1 request:
+
+ 1. If Request-URI is an absoluteURI, the host is part of the
+ Request-URI. Any Host header field value in the request MUST be
+ ignored.
+
+ 2. If the Request-URI is not an absoluteURI, and the request includes
+ a Host header field, the host is determined by the Host header
+ field value.
+
+ 3. If the host as determined by rule 1 or 2 is not a valid host on
+ the server, the response MUST be a 400 (Bad Request) error message.
+
+ Recipients of an HTTP/1.0 request that lacks a Host header field MAY
+ attempt to use heuristics (e.g., examination of the URI path for
+ something unique to a particular host) in order to determine what
+ exact resource is being requested.
+
+5.3 Request Header Fields
+
+ The request-header fields allow the client to pass additional
+ information about the request, and about the client itself, to the
+ server. These fields act as request modifiers, with semantics
+ equivalent to the parameters on a programming language method
+ invocation.
+
+ request-header = Accept ; Section 14.1
+ | Accept-Charset ; Section 14.2
+ | Accept-Encoding ; Section 14.3
+ | Accept-Language ; Section 14.4
+ | Authorization ; Section 14.8
+ | Expect ; Section 14.20
+ | From ; Section 14.22
+ | Host ; Section 14.23
+ | If-Match ; Section 14.24
+
+ | If-Modified-Since ; Section 14.25
+ | If-None-Match ; Section 14.26
+ | If-Range ; Section 14.27
+ | If-Unmodified-Since ; Section 14.28
+ | Max-Forwards ; Section 14.31
+ | Proxy-Authorization ; Section 14.34
+ | Range ; Section 14.35
+ | Referer ; Section 14.36
+ | TE ; Section 14.39
+ | User-Agent ; Section 14.43
+
+ Request-header field names can be extended reliably only in
+ combination with a change in the protocol version. However, new or
+ experimental header fields MAY be given the semantics of request-
+ header fields if all parties in the communication recognize them to
+ be request-header fields. Unrecognized header fields are treated as
+ entity-header fields.
+
+6 Response
+
+ After receiving and interpreting a request message, a server responds
+ with an HTTP response message.
+
+ Response = Status-Line ; Section 6.1
+ *(( general-header ; Section 4.5
+ | response-header ; Section 6.2
+ | entity-header ) CRLF) ; Section 7.1
+ CRLF
+ [ message-body ] ; Section 7.2
+
+6.1 Status-Line
+
+ The first line of a Response message is the Status-Line, consisting
+ of the protocol version followed by a numeric status code and its
+ associated textual phrase, with each element separated by SP
+ characters. No CR or LF is allowed except in the final CRLF sequence.
+
+ Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
+
+6.1.1 Status Code and Reason Phrase
+
+ The Status-Code element is a 3-digit integer result code of the
+ attempt to understand and satisfy the request. These codes are fully
+ defined in section 10. The Reason-Phrase is intended to give a short
+ textual description of the Status-Code. The Status-Code is intended
+ for use by automata and the Reason-Phrase is intended for the human
+ user. The client is not required to examine or display the Reason-
+ Phrase.
+
+ The first digit of the Status-Code defines the class of response. The
+ last two digits do not have any categorization role. There are 5
+ values for the first digit:
+
+ - 1xx: Informational - Request received, continuing process
+
+ - 2xx: Success - The action was successfully received,
+ understood, and accepted
+
+ - 3xx: Redirection - Further action must be taken in order to
+ complete the request
+
+ - 4xx: Client Error - The request contains bad syntax or cannot
+ be fulfilled
+
+ - 5xx: Server Error - The server failed to fulfill an apparently
+ valid request
+
+ The individual values of the numeric status codes defined for
+ HTTP/1.1, and an example set of corresponding Reason-Phrase's, are
+ presented below. The reason phrases listed here are only
+ recommendations -- they MAY be replaced by local equivalents without
+ affecting the protocol.
+
+ Status-Code =
+ "100" ; Section 10.1.1: Continue
+ | "101" ; Section 10.1.2: Switching Protocols
+ | "200" ; Section 10.2.1: OK
+ | "201" ; Section 10.2.2: Created
+ | "202" ; Section 10.2.3: Accepted
+ | "203" ; Section 10.2.4: Non-Authoritative Information
+ | "204" ; Section 10.2.5: No Content
+ | "205" ; Section 10.2.6: Reset Content
+ | "206" ; Section 10.2.7: Partial Content
+ | "300" ; Section 10.3.1: Multiple Choices
+ | "301" ; Section 10.3.2: Moved Permanently
+ | "302" ; Section 10.3.3: Found
+ | "303" ; Section 10.3.4: See Other
+ | "304" ; Section 10.3.5: Not Modified
+ | "305" ; Section 10.3.6: Use Proxy
+ | "307" ; Section 10.3.8: Temporary Redirect
+ | "400" ; Section 10.4.1: Bad Request
+ | "401" ; Section 10.4.2: Unauthorized
+ | "402" ; Section 10.4.3: Payment Required
+ | "403" ; Section 10.4.4: Forbidden
+ | "404" ; Section 10.4.5: Not Found
+ | "405" ; Section 10.4.6: Method Not Allowed
+ | "406" ; Section 10.4.7: Not Acceptable
+
+ | "407" ; Section 10.4.8: Proxy Authentication Required
+ | "408" ; Section 10.4.9: Request Time-out
+ | "409" ; Section 10.4.10: Conflict
+ | "410" ; Section 10.4.11: Gone
+ | "411" ; Section 10.4.12: Length Required
+ | "412" ; Section 10.4.13: Precondition Failed
+ | "413" ; Section 10.4.14: Request Entity Too Large
+ | "414" ; Section 10.4.15: Request-URI Too Large
+ | "415" ; Section 10.4.16: Unsupported Media Type
+ | "416" ; Section 10.4.17: Requested range not satisfiable
+ | "417" ; Section 10.4.18: Expectation Failed
+ | "500" ; Section 10.5.1: Internal Server Error
+ | "501" ; Section 10.5.2: Not Implemented
+ | "502" ; Section 10.5.3: Bad Gateway
+ | "503" ; Section 10.5.4: Service Unavailable
+ | "504" ; Section 10.5.5: Gateway Time-out
+ | "505" ; Section 10.5.6: HTTP Version not supported
+ | extension-code
+
+ extension-code = 3DIGIT
+ Reason-Phrase = *&lt;TEXT, excluding CR, LF&gt;
+
+ HTTP status codes are extensible. HTTP applications are not required
+ to understand the meaning of all registered status codes, though such
+ understanding is obviously desirable. However, applications MUST
+ understand the class of any status code, as indicated by the first
+ digit, and treat any unrecognized response as being equivalent to the
+ x00 status code of that class, with the exception that an
+ unrecognized response MUST NOT be cached. For example, if an
+ unrecognized status code of 431 is received by the client, it can
+ safely assume that there was something wrong with its request and
+ treat the response as if it had received a 400 status code. In such
+ cases, user agents SHOULD present to the user the entity returned
+ with the response, since that entity is likely to include human-
+ readable information which will explain the unusual status.
+
+6.2 Response Header Fields
+
+ The response-header fields allow the server to pass additional
+ information about the response which cannot be placed in the Status-
+ Line. These header fields give information about the server and about
+ further access to the resource identified by the Request-URI.
+
+ response-header = Accept-Ranges ; Section 14.5
+ | Age ; Section 14.6
+ | ETag ; Section 14.19
+ | Location ; Section 14.30
+ | Proxy-Authenticate ; Section 14.33
+
+ | Retry-After ; Section 14.37
+ | Server ; Section 14.38
+ | Vary ; Section 14.44
+ | WWW-Authenticate ; Section 14.47
+
+ Response-header field names can be extended reliably only in
+ combination with a change in the protocol version. However, new or
+ experimental header fields MAY be given the semantics of response-
+ header fields if all parties in the communication recognize them to
+ be response-header fields. Unrecognized header fields are treated as
+ entity-header fields.
+
+7 Entity
+
+ Request and Response messages MAY transfer an entity if not otherwise
+ restricted by the request method or response status code. An entity
+ consists of entity-header fields and an entity-body, although some
+ responses will only include the entity-headers.
+
+ In this section, both sender and recipient refer to either the client
+ or the server, depending on who sends and who receives the entity.
+
+7.1 Entity Header Fields
+
+ Entity-header fields define metainformation about the entity-body or,
+ if no body is present, about the resource identified by the request.
+ Some of this metainformation is OPTIONAL; some might be REQUIRED by
+ portions of this specification.
+
+ entity-header = Allow ; Section 14.7
+ | Content-Encoding ; Section 14.11
+ | Content-Language ; Section 14.12
+ | Content-Length ; Section 14.13
+ | Content-Location ; Section 14.14
+ | Content-MD5 ; Section 14.15
+ | Content-Range ; Section 14.16
+ | Content-Type ; Section 14.17
+ | Expires ; Section 14.21
+ | Last-Modified ; Section 14.29
+ | extension-header
+
+ extension-header = message-header
+
+ The extension-header mechanism allows additional entity-header fields
+ to be defined without changing the protocol, but these fields cannot
+ be assumed to be recognizable by the recipient. Unrecognized header
+ fields SHOULD be ignored by the recipient and MUST be forwarded by
+ transparent proxies.
+
+7.2 Entity Body
+
+ The entity-body (if any) sent with an HTTP request or response is in
+ a format and encoding defined by the entity-header fields.
+
+ entity-body = *OCTET
+
+ An entity-body is only present in a message when a message-body is
+ present, as described in section 4.3. The entity-body is obtained
+ from the message-body by decoding any Transfer-Encoding that might
+ have been applied to ensure safe and proper transfer of the message.
+
+7.2.1 Type
+
+ When an entity-body is included with a message, the data type of that
+ body is determined via the header fields Content-Type and Content-
+ Encoding. These define a two-layer, ordered encoding model:
+
+ entity-body := Content-Encoding( Content-Type( data ) )
+
+ Content-Type specifies the media type of the underlying data.
+ Content-Encoding may be used to indicate any additional content
+ codings applied to the data, usually for the purpose of data
+ compression, that are a property of the requested resource. There is
+ no default encoding.
+
+ Any HTTP/1.1 message containing an entity-body SHOULD include a
+ Content-Type header field defining the media type of that body. If
+ and only if the media type is not given by a Content-Type field, the
+ recipient MAY attempt to guess the media type via inspection of its
+ content and/or the name extension(s) of the URI used to identify the
+ resource. If the media type remains unknown, the recipient SHOULD
+ treat it as type "application/octet-stream".
+
+7.2.2 Entity Length
+
+ The entity-length of a message is the length of the message-body
+ before any transfer-codings have been applied. Section 4.4 defines
+ how the transfer-length of a message-body is determined.
+
+8 Connections
+
+8.1 Persistent Connections
+
+8.1.1 Purpose
+
+ Prior to persistent connections, a separate TCP connection was
+ established to fetch each URL, increasing the load on HTTP servers
+ and causing congestion on the Internet. The use of inline images and
+ other associated data often require a client to make multiple
+ requests of the same server in a short amount of time. Analysis of
+ these performance problems and results from a prototype
+ implementation are available [26] [30]. Implementation experience and
+ measurements of actual HTTP/1.1 (<a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a>) implementations show good
+ results [39]. Alternatives have also been explored, for example,
+ T/TCP [27].
+
+ Persistent HTTP connections have a number of advantages:
+
+ - By opening and closing fewer TCP connections, CPU time is saved
+ in routers and hosts (clients, servers, proxies, gateways,
+ tunnels, or caches), and memory used for TCP protocol control
+ blocks can be saved in hosts.
+
+ - HTTP requests and responses can be pipelined on a connection.
+ Pipelining allows a client to make multiple requests without
+ waiting for each response, allowing a single TCP connection to
+ be used much more efficiently, with much lower elapsed time.
+
+ - Network congestion is reduced by reducing the number of packets
+ caused by TCP opens, and by allowing TCP sufficient time to
+ determine the congestion state of the network.
+
+ - Latency on subsequent requests is reduced since there is no time
+ spent in TCP's connection opening handshake.
+
+ - HTTP can evolve more gracefully, since errors can be reported
+ without the penalty of closing the TCP connection. Clients using
+ future versions of HTTP might optimistically try a new feature,
+ but if communicating with an older server, retry with old
+ semantics after an error is reported.
+
+ HTTP implementations SHOULD implement persistent connections.
+
+8.1.2 Overall Operation
+
+ A significant difference between HTTP/1.1 and earlier versions of
+ HTTP is that persistent connections are the default behavior of any
+ HTTP connection. That is, unless otherwise indicated, the client
+ SHOULD assume that the server will maintain a persistent connection,
+ even after error responses from the server.
+
+ Persistent connections provide a mechanism by which a client and a
+ server can signal the close of a TCP connection. This signaling takes
+ place using the Connection header field (section 14.10). Once a close
+ has been signaled, the client MUST NOT send any more requests on that
+ connection.
+
+8.1.2.1 Negotiation
+
+ An HTTP/1.1 server MAY assume that a HTTP/1.1 client intends to
+ maintain a persistent connection unless a Connection header including
+ the connection-token "close" was sent in the request. If the server
+ chooses to close the connection immediately after sending the
+ response, it SHOULD send a Connection header including the
+ connection-token close.
+
+ An HTTP/1.1 client MAY expect a connection to remain open, but would
+ decide to keep it open based on whether the response from a server
+ contains a Connection header with the connection-token close. In case
+ the client does not want to maintain a connection for more than that
+ request, it SHOULD send a Connection header including the
+ connection-token close.
+
+ If either the client or the server sends the close token in the
+ Connection header, that request becomes the last one for the
+ connection.
+
+ Clients and servers SHOULD NOT assume that a persistent connection is
+ maintained for HTTP versions less than 1.1 unless it is explicitly
+ signaled. See section 19.6.2 for more information on backward
+ compatibility with HTTP/1.0 clients.
+
+ In order to remain persistent, all messages on the connection MUST
+ have a self-defined message length (i.e., one not defined by closure
+ of the connection), as described in section 4.4.
+
+8.1.2.2 Pipelining
+
+ A client that supports persistent connections MAY "pipeline" its
+ requests (i.e., send multiple requests without waiting for each
+ response). A server MUST send its responses to those requests in the
+ same order that the requests were received.
+
+ Clients which assume persistent connections and pipeline immediately
+ after connection establishment SHOULD be prepared to retry their
+ connection if the first pipelined attempt fails. If a client does
+ such a retry, it MUST NOT pipeline before it knows the connection is
+ persistent. Clients MUST also be prepared to resend their requests if
+ the server closes the connection before sending all of the
+ corresponding responses.
+
+ Clients SHOULD NOT pipeline requests using non-idempotent methods or
+ non-idempotent sequences of methods (see section 9.1.2). Otherwise, a
+ premature termination of the transport connection could lead to
+ indeterminate results. A client wishing to send a non-idempotent
+ request SHOULD wait to send that request until it has received the
+ response status for the previous request.
+
+8.1.3 Proxy Servers
+
+ It is especially important that proxies correctly implement the
+ properties of the Connection header field as specified in section
+ 14.10.
+
+ The proxy server MUST signal persistent connections separately with
+ its clients and the origin servers (or other proxy servers) that it
+ connects to. Each persistent connection applies to only one transport
+ link.
+
+ A proxy server MUST NOT establish a HTTP/1.1 persistent connection
+ with an HTTP/1.0 client (but see <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> [33] for information and
+ discussion of the problems with the Keep-Alive header implemented by
+ many HTTP/1.0 clients).
+
+8.1.4 Practical Considerations
+
+ Servers will usually have some time-out value beyond which they will
+ no longer maintain an inactive connection. Proxy servers might make
+ this a higher value since it is likely that the client will be making
+ more connections through the same server. The use of persistent
+ connections places no requirements on the length (or existence) of
+ this time-out for either the client or the server.
+
+ When a client or server wishes to time-out it SHOULD issue a graceful
+ close on the transport connection. Clients and servers SHOULD both
+ constantly watch for the other side of the transport close, and
+ respond to it as appropriate. If a client or server does not detect
+ the other side's close promptly it could cause unnecessary resource
+ drain on the network.
+
+ A client, server, or proxy MAY close the transport connection at any
+ time. For example, a client might have started to send a new request
+ at the same time that the server has decided to close the "idle"
+ connection. From the server's point of view, the connection is being
+ closed while it was idle, but from the client's point of view, a
+ request is in progress.
+
+ This means that clients, servers, and proxies MUST be able to recover
+ from asynchronous close events. Client software SHOULD reopen the
+ transport connection and retransmit the aborted sequence of requests
+ without user interaction so long as the request sequence is
+ idempotent (see section 9.1.2). Non-idempotent methods or sequences
+ MUST NOT be automatically retried, although user agents MAY offer a
+ human operator the choice of retrying the request(s). Confirmation by
+ user-agent software with semantic understanding of the application
+ MAY substitute for user confirmation. The automatic retry SHOULD NOT
+ be repeated if the second sequence of requests fails.
+
+ Servers SHOULD always respond to at least one request per connection,
+ if at all possible. Servers SHOULD NOT close a connection in the
+ middle of transmitting a response, unless a network or client failure
+ is suspected.
+
+ Clients that use persistent connections SHOULD limit the number of
+ simultaneous connections that they maintain to a given server. A
+ single-user client SHOULD NOT maintain more than 2 connections with
+ any server or proxy. A proxy SHOULD use up to 2*N connections to
+ another server or proxy, where N is the number of simultaneously
+ active users. These guidelines are intended to improve HTTP response
+ times and avoid congestion.
+
+8.2 Message Transmission Requirements
+
+8.2.1 Persistent Connections and Flow Control
+
+ HTTP/1.1 servers SHOULD maintain persistent connections and use TCP's
+ flow control mechanisms to resolve temporary overloads, rather than
+ terminating connections with the expectation that clients will retry.
+ The latter technique can exacerbate network congestion.
+
+8.2.2 Monitoring Connections for Error Status Messages
+
+ An HTTP/1.1 (or later) client sending a message-body SHOULD monitor
+ the network connection for an error status while it is transmitting
+ the request. If the client sees an error status, it SHOULD
+ immediately cease transmitting the body. If the body is being sent
+ using a "chunked" encoding (section 3.6), a zero length chunk and
+ empty trailer MAY be used to prematurely mark the end of the message.
+ If the body was preceded by a Content-Length header, the client MUST
+ close the connection.
+
+8.2.3 Use of the 100 (Continue) Status
+
+ The purpose of the 100 (Continue) status (see section 10.1.1) is to
+ allow a client that is sending a request message with a request body
+ to determine if the origin server is willing to accept the request
+ (based on the request headers) before the client sends the request
+ body. In some cases, it might either be inappropriate or highly
+ inefficient for the client to send the body if the server will reject
+ the message without looking at the body.
+
+ Requirements for HTTP/1.1 clients:
+
+ - If a client will wait for a 100 (Continue) response before
+ sending the request body, it MUST send an Expect request-header
+ field (section 14.20) with the "100-continue" expectation.
+
+ - A client MUST NOT send an Expect request-header field (section
+ 14.20) with the "100-continue" expectation if it does not intend
+ to send a request body.
+
+ Because of the presence of older implementations, the protocol allows
+ ambiguous situations in which a client may send "Expect: 100-
+ continue" without receiving either a 417 (Expectation Failed) status
+ or a 100 (Continue) status. Therefore, when a client sends this
+ header field to an origin server (possibly via a proxy) from which it
+ has never seen a 100 (Continue) status, the client SHOULD NOT wait
+ for an indefinite period before sending the request body.
+
+ Requirements for HTTP/1.1 origin servers:
+
+ - Upon receiving a request which includes an Expect request-header
+ field with the "100-continue" expectation, an origin server MUST
+ either respond with 100 (Continue) status and continue to read
+ from the input stream, or respond with a final status code. The
+ origin server MUST NOT wait for the request body before sending
+ the 100 (Continue) response. If it responds with a final status
+ code, it MAY close the transport connection or it MAY continue
+
+ to read and discard the rest of the request. It MUST NOT
+ perform the requested method if it returns a final status code.
+
+ - An origin server SHOULD NOT send a 100 (Continue) response if
+ the request message does not include an Expect request-header
+ field with the "100-continue" expectation, and MUST NOT send a
+ 100 (Continue) response if such a request comes from an HTTP/1.0
+ (or earlier) client. There is an exception to this rule: for
+ compatibility with <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a>, a server MAY send a 100 (Continue)
+ status in response to an HTTP/1.1 PUT or POST request that does
+ not include an Expect request-header field with the "100-
+ continue" expectation. This exception, the purpose of which is
+ to minimize any client processing delays associated with an
+ undeclared wait for 100 (Continue) status, applies only to
+ HTTP/1.1 requests, and not to requests with any other HTTP-
+ version value.
+
+ - An origin server MAY omit a 100 (Continue) response if it has
+ already received some or all of the request body for the
+ corresponding request.
+
+ - An origin server that sends a 100 (Continue) response MUST
+ ultimately send a final status code, once the request body is
+ received and processed, unless it terminates the transport
+ connection prematurely.
+
+ - If an origin server receives a request that does not include an
+ Expect request-header field with the "100-continue" expectation,
+ the request includes a request body, and the server responds
+ with a final status code before reading the entire request body
+ from the transport connection, then the server SHOULD NOT close
+ the transport connection until it has read the entire request,
+ or until the client closes the connection. Otherwise, the client
+ might not reliably receive the response message. However, this
+ requirement is not be construed as preventing a server from
+ defending itself against denial-of-service attacks, or from
+ badly broken client implementations.
+
+ Requirements for HTTP/1.1 proxies:
+
+ - If a proxy receives a request that includes an Expect request-
+ header field with the "100-continue" expectation, and the proxy
+ either knows that the next-hop server complies with HTTP/1.1 or
+ higher, or does not know the HTTP version of the next-hop
+ server, it MUST forward the request, including the Expect header
+ field.
+
+ - If the proxy knows that the version of the next-hop server is
+ HTTP/1.0 or lower, it MUST NOT forward the request, and it MUST
+ respond with a 417 (Expectation Failed) status.
+
+ - Proxies SHOULD maintain a cache recording the HTTP version
+ numbers received from recently-referenced next-hop servers.
+
+ - A proxy MUST NOT forward a 100 (Continue) response if the
+ request message was received from an HTTP/1.0 (or earlier)
+ client and did not include an Expect request-header field with
+ the "100-continue" expectation. This requirement overrides the
+ general rule for forwarding of 1xx responses (see section 10.1).
+
+8.2.4 Client Behavior if Server Prematurely Closes Connection
+
+ If an HTTP/1.1 client sends a request which includes a request body,
+ but which does not include an Expect request-header field with the
+ "100-continue" expectation, and if the client is not directly
+ connected to an HTTP/1.1 origin server, and if the client sees the
+ connection close before receiving any status from the server, the
+ client SHOULD retry the request. If the client does retry this
+ request, it MAY use the following "binary exponential backoff"
+ algorithm to be assured of obtaining a reliable response:
+
+ 1. Initiate a new connection to the server
+
+ 2. Transmit the request-headers
+
+ 3. Initialize a variable R to the estimated round-trip time to the
+ server (e.g., based on the time it took to establish the
+ connection), or to a constant value of 5 seconds if the round-
+ trip time is not available.
+
+ 4. Compute T = R * (2**N), where N is the number of previous
+ retries of this request.
+
+ 5. Wait either for an error response from the server, or for T
+ seconds (whichever comes first)
+
+ 6. If no error response is received, after T seconds transmit the
+ body of the request.
+
+ 7. If client sees that the connection is closed prematurely,
+ repeat from step 1 until the request is accepted, an error
+ response is received, or the user becomes impatient and
+ terminates the retry process.
+
+ If at any point an error status is received, the client
+
+ - SHOULD NOT continue and
+
+ - SHOULD close the connection if it has not completed sending the
+ request message.
+
+9 Method Definitions
+
+ The set of common methods for HTTP/1.1 is defined below. Although
+ this set can be expanded, additional methods cannot be assumed to
+ share the same semantics for separately extended clients and servers.
+
+ The Host request-header field (section 14.23) MUST accompany all
+ HTTP/1.1 requests.
+
+9.1 Safe and Idempotent Methods
+
+9.1.1 Safe Methods
+
+ Implementors should be aware that the software represents the user in
+ their interactions over the Internet, and should be careful to allow
+ the user to be aware of any actions they might take which may have an
+ unexpected significance to themselves or others.
+
+ In particular, the convention has been established that the GET and
+ HEAD methods SHOULD NOT have the significance of taking an action
+ other than retrieval. These methods ought to be considered "safe".
+ This allows user agents to represent other methods, such as POST, PUT
+ and DELETE, in a special way, so that the user is made aware of the
+ fact that a possibly unsafe action is being requested.
+
+ Naturally, it is not possible to ensure that the server does not
+ generate side-effects as a result of performing a GET request; in
+ fact, some dynamic resources consider that a feature. The important
+ distinction here is that the user did not request the side-effects,
+ so therefore cannot be held accountable for them.
+
+9.1.2 Idempotent Methods
+
+ Methods can also have the property of "idempotence" in that (aside
+ from error or expiration issues) the side-effects of N &gt; 0 identical
+ requests is the same as for a single request. The methods GET, HEAD,
+ PUT and DELETE share this property. Also, the methods OPTIONS and
+ TRACE SHOULD NOT have side effects, and so are inherently idempotent.
+
+ However, it is possible that a sequence of several requests is non-
+ idempotent, even if all of the methods executed in that sequence are
+ idempotent. (A sequence is idempotent if a single execution of the
+ entire sequence always yields a result that is not changed by a
+ reexecution of all, or part, of that sequence.) For example, a
+ sequence is non-idempotent if its result depends on a value that is
+ later modified in the same sequence.
+
+ A sequence that never has side effects is idempotent, by definition
+ (provided that no concurrent operations are being executed on the
+ same set of resources).
+
+9.2 OPTIONS
+
+ The OPTIONS method represents a request for information about the
+ communication options available on the request/response chain
+ identified by the Request-URI. This method allows the client to
+ determine the options and/or requirements associated with a resource,
+ or the capabilities of a server, without implying a resource action
+ or initiating a resource retrieval.
+
+ Responses to this method are not cacheable.
+
+ If the OPTIONS request includes an entity-body (as indicated by the
+ presence of Content-Length or Transfer-Encoding), then the media type
+ MUST be indicated by a Content-Type field. Although this
+ specification does not define any use for such a body, future
+ extensions to HTTP might use the OPTIONS body to make more detailed
+ queries on the server. A server that does not support such an
+ extension MAY discard the request body.
+
+ If the Request-URI is an asterisk ("*"), the OPTIONS request is
+ intended to apply to the server in general rather than to a specific
+ resource. Since a server's communication options typically depend on
+ the resource, the "*" request is only useful as a "ping" or "no-op"
+ type of method; it does nothing beyond allowing the client to test
+ the capabilities of the server. For example, this can be used to test
+ a proxy for HTTP/1.1 compliance (or lack thereof).
+
+ If the Request-URI is not an asterisk, the OPTIONS request applies
+ only to the options that are available when communicating with that
+ resource.
+
+ A 200 response SHOULD include any header fields that indicate
+ optional features implemented by the server and applicable to that
+ resource (e.g., Allow), possibly including extensions not defined by
+ this specification. The response body, if any, SHOULD also include
+ information about the communication options. The format for such a
+
+ body is not defined by this specification, but might be defined by
+ future extensions to HTTP. Content negotiation MAY be used to select
+ the appropriate response format. If no response body is included, the
+ response MUST include a Content-Length field with a field-value of
+ "0".
+
+ The Max-Forwards request-header field MAY be used to target a
+ specific proxy in the request chain. When a proxy receives an OPTIONS
+ request on an absoluteURI for which request forwarding is permitted,
+ the proxy MUST check for a Max-Forwards field. If the Max-Forwards
+ field-value is zero ("0"), the proxy MUST NOT forward the message;
+ instead, the proxy SHOULD respond with its own communication options.
+ If the Max-Forwards field-value is an integer greater than zero, the
+ proxy MUST decrement the field-value when it forwards the request. If
+ no Max-Forwards field is present in the request, then the forwarded
+ request MUST NOT include a Max-Forwards field.
+
+9.3 GET
+
+ The GET method means retrieve whatever information (in the form of an
+ entity) is identified by the Request-URI. If the Request-URI refers
+ to a data-producing process, it is the produced data which shall be
+ returned as the entity in the response and not the source text of the
+ process, unless that text happens to be the output of the process.
+
+ The semantics of the GET method change to a "conditional GET" if the
+ request message includes an If-Modified-Since, If-Unmodified-Since,
+ If-Match, If-None-Match, or If-Range header field. A conditional GET
+ method requests that the entity be transferred only under the
+ circumstances described by the conditional header field(s). The
+ conditional GET method is intended to reduce unnecessary network
+ usage by allowing cached entities to be refreshed without requiring
+ multiple requests or transferring data already held by the client.
+
+ The semantics of the GET method change to a "partial GET" if the
+ request message includes a Range header field. A partial GET requests
+ that only part of the entity be transferred, as described in section
+ 14.35. The partial GET method is intended to reduce unnecessary
+ network usage by allowing partially-retrieved entities to be
+ completed without transferring data already held by the client.
+
+ The response to a GET request is cacheable if and only if it meets
+ the requirements for HTTP caching described in section 13.
+
+ See section 15.1.3 for security considerations when used for forms.
+
+9.4 HEAD
+
+ The HEAD method is identical to GET except that the server MUST NOT
+ return a message-body in the response. The metainformation contained
+ in the HTTP headers in response to a HEAD request SHOULD be identical
+ to the information sent in response to a GET request. This method can
+ be used for obtaining metainformation about the entity implied by the
+ request without transferring the entity-body itself. This method is
+ often used for testing hypertext links for validity, accessibility,
+ and recent modification.
+
+ The response to a HEAD request MAY be cacheable in the sense that the
+ information contained in the response MAY be used to update a
+ previously cached entity from that resource. If the new field values
+ indicate that the cached entity differs from the current entity (as
+ would be indicated by a change in Content-Length, Content-MD5, ETag
+ or Last-Modified), then the cache MUST treat the cache entry as
+ stale.
+
+9.5 POST
+
+ The POST method is used to request that the origin server accept the
+ entity enclosed in the request as a new subordinate of the resource
+ identified by the Request-URI in the Request-Line. POST is designed
+ to allow a uniform method to cover the following functions:
+
+ - Annotation of existing resources;
+
+ - Posting a message to a bulletin board, newsgroup, mailing list,
+ or similar group of articles;
+
+ - Providing a block of data, such as the result of submitting a
+ form, to a data-handling process;
+
+ - Extending a database through an append operation.
+
+ The actual function performed by the POST method is determined by the
+ server and is usually dependent on the Request-URI. The posted entity
+ is subordinate to that URI in the same way that a file is subordinate
+ to a directory containing it, a news article is subordinate to a
+ newsgroup to which it is posted, or a record is subordinate to a
+ database.
+
+ The action performed by the POST method might not result in a
+ resource that can be identified by a URI. In this case, either 200
+ (OK) or 204 (No Content) is the appropriate response status,
+ depending on whether or not the response includes an entity that
+ describes the result.
+
+ If a resource has been created on the origin server, the response
+ SHOULD be 201 (Created) and contain an entity which describes the
+ status of the request and refers to the new resource, and a Location
+ header (see section 14.30).
+
+ Responses to this method are not cacheable, unless the response
+ includes appropriate Cache-Control or Expires header fields. However,
+ the 303 (See Other) response can be used to direct the user agent to
+ retrieve a cacheable resource.
+
+ POST requests MUST obey the message transmission requirements set out
+ in section 8.2.
+
+ See section 15.1.3 for security considerations.
+
+9.6 PUT
+
+ The PUT method requests that the enclosed entity be stored under the
+ supplied Request-URI. If the Request-URI refers to an already
+ existing resource, the enclosed entity SHOULD be considered as a
+ modified version of the one residing on the origin server. If the
+ Request-URI does not point to an existing resource, and that URI is
+ capable of being defined as a new resource by the requesting user
+ agent, the origin server can create the resource with that URI. If a
+ new resource is created, the origin server MUST inform the user agent
+ via the 201 (Created) response. If an existing resource is modified,
+ either the 200 (OK) or 204 (No Content) response codes SHOULD be sent
+ to indicate successful completion of the request. If the resource
+ could not be created or modified with the Request-URI, an appropriate
+ error response SHOULD be given that reflects the nature of the
+ problem. The recipient of the entity MUST NOT ignore any Content-*
+ (e.g. Content-Range) headers that it does not understand or implement
+ and MUST return a 501 (Not Implemented) response in such cases.
+
+ If the request passes through a cache and the Request-URI identifies
+ one or more currently cached entities, those entries SHOULD be
+ treated as stale. Responses to this method are not cacheable.
+
+ The fundamental difference between the POST and PUT requests is
+ reflected in the different meaning of the Request-URI. The URI in a
+ POST request identifies the resource that will handle the enclosed
+ entity. That resource might be a data-accepting process, a gateway to
+ some other protocol, or a separate entity that accepts annotations.
+ In contrast, the URI in a PUT request identifies the entity enclosed
+ with the request -- the user agent knows what URI is intended and the
+ server MUST NOT attempt to apply the request to some other resource.
+ If the server desires that the request be applied to a different URI,
+
+ it MUST send a 301 (Moved Permanently) response; the user agent MAY
+ then make its own decision regarding whether or not to redirect the
+ request.
+
+ A single resource MAY be identified by many different URIs. For
+ example, an article might have a URI for identifying "the current
+ version" which is separate from the URI identifying each particular
+ version. In this case, a PUT request on a general URI might result in
+ several other URIs being defined by the origin server.
+
+ HTTP/1.1 does not define how a PUT method affects the state of an
+ origin server.
+
+ PUT requests MUST obey the message transmission requirements set out
+ in section 8.2.
+
+ Unless otherwise specified for a particular entity-header, the
+ entity-headers in the PUT request SHOULD be applied to the resource
+ created or modified by the PUT.
+
+9.7 DELETE
+
+ The DELETE method requests that the origin server delete the resource
+ identified by the Request-URI. This method MAY be overridden by human
+ intervention (or other means) on the origin server. The client cannot
+ be guaranteed that the operation has been carried out, even if the
+ status code returned from the origin server indicates that the action
+ has been completed successfully. However, the server SHOULD NOT
+ indicate success unless, at the time the response is given, it
+ intends to delete the resource or move it to an inaccessible
+ location.
+
+ A successful response SHOULD be 200 (OK) if the response includes an
+ entity describing the status, 202 (Accepted) if the action has not
+ yet been enacted, or 204 (No Content) if the action has been enacted
+ but the response does not include an entity.
+
+ If the request passes through a cache and the Request-URI identifies
+ one or more currently cached entities, those entries SHOULD be
+ treated as stale. Responses to this method are not cacheable.
+
+9.8 TRACE
+
+ The TRACE method is used to invoke a remote, application-layer loop-
+ back of the request message. The final recipient of the request
+ SHOULD reflect the message received back to the client as the
+ entity-body of a 200 (OK) response. The final recipient is either the
+
+ origin server or the first proxy or gateway to receive a Max-Forwards
+ value of zero (0) in the request (see section 14.31). A TRACE request
+ MUST NOT include an entity.
+
+ TRACE allows the client to see what is being received at the other
+ end of the request chain and use that data for testing or diagnostic
+ information. The value of the Via header field (section 14.45) is of
+ particular interest, since it acts as a trace of the request chain.
+ Use of the Max-Forwards header field allows the client to limit the
+ length of the request chain, which is useful for testing a chain of
+ proxies forwarding messages in an infinite loop.
+
+ If the request is valid, the response SHOULD contain the entire
+ request message in the entity-body, with a Content-Type of
+ "message/http". Responses to this method MUST NOT be cached.
+
+9.9 CONNECT
+
+ This specification reserves the method name CONNECT for use with a
+ proxy that can dynamically switch to being a tunnel (e.g. SSL
+ tunneling [44]).
+
+10 Status Code Definitions
+
+ Each Status-Code is described below, including a description of which
+ method(s) it can follow and any metainformation required in the
+ response.
+
+10.1 Informational 1xx
+
+ This class of status code indicates a provisional response,
+ consisting only of the Status-Line and optional headers, and is
+ terminated by an empty line. There are no required headers for this
+ class of status code. Since HTTP/1.0 did not define any 1xx status
+ codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client
+ except under experimental conditions.
+
+ A client MUST be prepared to accept one or more 1xx status responses
+ prior to a regular response, even if the client does not expect a 100
+ (Continue) status message. Unexpected 1xx status responses MAY be
+ ignored by a user agent.
+
+ Proxies MUST forward 1xx responses, unless the connection between the
+ proxy and its client has been closed, or unless the proxy itself
+ requested the generation of the 1xx response. (For example, if a
+
+ proxy adds a "Expect: 100-continue" field when it forwards a request,
+ then it need not forward the corresponding 100 (Continue)
+ response(s).)
+
+10.1.1 100 Continue
+
+ The client SHOULD continue with its request. This interim response is
+ used to inform the client that the initial part of the request has
+ been received and has not yet been rejected by the server. The client
+ SHOULD continue by sending the remainder of the request or, if the
+ request has already been completed, ignore this response. The server
+ MUST send a final response after the request has been completed. See
+ section 8.2.3 for detailed discussion of the use and handling of this
+ status code.
+
+10.1.2 101 Switching Protocols
+
+ The server understands and is willing to comply with the client's
+ request, via the Upgrade message header field (section 14.42), for a
+ change in the application protocol being used on this connection. The
+ server will switch protocols to those defined by the response's
+ Upgrade header field immediately after the empty line which
+ terminates the 101 response.
+
+ The protocol SHOULD be switched only when it is advantageous to do
+ so. For example, switching to a newer version of HTTP is advantageous
+ over older versions, and switching to a real-time, synchronous
+ protocol might be advantageous when delivering resources that use
+ such features.
+
+10.2 Successful 2xx
+
+ This class of status code indicates that the client's request was
+ successfully received, understood, and accepted.
+
+10.2.1 200 OK
+
+ The request has succeeded. The information returned with the response
+ is dependent on the method used in the request, for example:
+
+ GET an entity corresponding to the requested resource is sent in
+ the response;
+
+ HEAD the entity-header fields corresponding to the requested
+ resource are sent in the response without any message-body;
+
+ POST an entity describing or containing the result of the action;
+
+ TRACE an entity containing the request message as received by the
+ end server.
+
+10.2.2 201 Created
+
+ The request has been fulfilled and resulted in a new resource being
+ created. The newly created resource can be referenced by the URI(s)
+ returned in the entity of the response, with the most specific URI
+ for the resource given by a Location header field. The response
+ SHOULD include an entity containing a list of resource
+ characteristics and location(s) from which the user or user agent can
+ choose the one most appropriate. The entity format is specified by
+ the media type given in the Content-Type header field. The origin
+ server MUST create the resource before returning the 201 status code.
+ If the action cannot be carried out immediately, the server SHOULD
+ respond with 202 (Accepted) response instead.
+
+ A 201 response MAY contain an ETag response header field indicating
+ the current value of the entity tag for the requested variant just
+ created, see section 14.19.
+
+10.2.3 202 Accepted
+
+ The request has been accepted for processing, but the processing has
+ not been completed. The request might or might not eventually be
+ acted upon, as it might be disallowed when processing actually takes
+ place. There is no facility for re-sending a status code from an
+ asynchronous operation such as this.
+
+ The 202 response is intentionally non-committal. Its purpose is to
+ allow a server to accept a request for some other process (perhaps a
+ batch-oriented process that is only run once per day) without
+ requiring that the user agent's connection to the server persist
+ until the process is completed. The entity returned with this
+ response SHOULD include an indication of the request's current status
+ and either a pointer to a status monitor or some estimate of when the
+ user can expect the request to be fulfilled.
+
+10.2.4 203 Non-Authoritative Information
+
+ The returned metainformation in the entity-header is not the
+ definitive set as available from the origin server, but is gathered
+ from a local or a third-party copy. The set presented MAY be a subset
+ or superset of the original version. For example, including local
+ annotation information about the resource might result in a superset
+ of the metainformation known by the origin server. Use of this
+ response code is not required and is only appropriate when the
+ response would otherwise be 200 (OK).
+
+10.2.5 204 No Content
+
+ The server has fulfilled the request but does not need to return an
+ entity-body, and might want to return updated metainformation. The
+ response MAY include new or updated metainformation in the form of
+ entity-headers, which if present SHOULD be associated with the
+ requested variant.
+
+ If the client is a user agent, it SHOULD NOT change its document view
+ from that which caused the request to be sent. This response is
+ primarily intended to allow input for actions to take place without
+ causing a change to the user agent's active document view, although
+ any new or updated metainformation SHOULD be applied to the document
+ currently in the user agent's active view.
+
+ The 204 response MUST NOT include a message-body, and thus is always
+ terminated by the first empty line after the header fields.
+
+10.2.6 205 Reset Content
+
+ The server has fulfilled the request and the user agent SHOULD reset
+ the document view which caused the request to be sent. This response
+ is primarily intended to allow input for actions to take place via
+ user input, followed by a clearing of the form in which the input is
+ given so that the user can easily initiate another input action. The
+ response MUST NOT include an entity.
+
+10.2.7 206 Partial Content
+
+ The server has fulfilled the partial GET request for the resource.
+ The request MUST have included a Range header field (section 14.35)
+ indicating the desired range, and MAY have included an If-Range
+ header field (section 14.27) to make the request conditional.
+
+ The response MUST include the following header fields:
+
+ - Either a Content-Range header field (section 14.16) indicating
+ the range included with this response, or a multipart/byteranges
+ Content-Type including Content-Range fields for each part. If a
+ Content-Length header field is present in the response, its
+ value MUST match the actual number of OCTETs transmitted in the
+ message-body.
+
+ - Date
+
+ - ETag and/or Content-Location, if the header would have been sent
+ in a 200 response to the same request
+
+ - Expires, Cache-Control, and/or Vary, if the field-value might
+ differ from that sent in any previous response for the same
+ variant
+
+ If the 206 response is the result of an If-Range request that used a
+ strong cache validator (see section 13.3.3), the response SHOULD NOT
+ include other entity-headers. If the response is the result of an
+ If-Range request that used a weak validator, the response MUST NOT
+ include other entity-headers; this prevents inconsistencies between
+ cached entity-bodies and updated headers. Otherwise, the response
+ MUST include all of the entity-headers that would have been returned
+ with a 200 (OK) response to the same request.
+
+ A cache MUST NOT combine a 206 response with other previously cached
+ content if the ETag or Last-Modified headers do not match exactly,
+ see 13.5.4.
+
+ A cache that does not support the Range and Content-Range headers
+ MUST NOT cache 206 (Partial) responses.
+
+10.3 Redirection 3xx
+
+ This class of status code indicates that further action needs to be
+ taken by the user agent in order to fulfill the request. The action
+ required MAY be carried out by the user agent without interaction
+ with the user if and only if the method used in the second request is
+ GET or HEAD. A client SHOULD detect infinite redirection loops, since
+ such loops generate network traffic for each redirection.
+
+ Note: previous versions of this specification recommended a
+ maximum of five redirections. Content developers should be aware
+ that there might be clients that implement such a fixed
+ limitation.
+
+10.3.1 300 Multiple Choices
+
+ The requested resource corresponds to any one of a set of
+ representations, each with its own specific location, and agent-
+ driven negotiation information (section 12) is being provided so that
+ the user (or user agent) can select a preferred representation and
+ redirect its request to that location.
+
+ Unless it was a HEAD request, the response SHOULD include an entity
+ containing a list of resource characteristics and location(s) from
+ which the user or user agent can choose the one most appropriate. The
+ entity format is specified by the media type given in the Content-
+ Type header field. Depending upon the format and the capabilities of
+
+ the user agent, selection of the most appropriate choice MAY be
+ performed automatically. However, this specification does not define
+ any standard for such automatic selection.
+
+ If the server has a preferred choice of representation, it SHOULD
+ include the specific URI for that representation in the Location
+ field; user agents MAY use the Location field value for automatic
+ redirection. This response is cacheable unless indicated otherwise.
+
+10.3.2 301 Moved Permanently
+
+ The requested resource has been assigned a new permanent URI and any
+ future references to this resource SHOULD use one of the returned
+ URIs. Clients with link editing capabilities ought to automatically
+ re-link references to the Request-URI to one or more of the new
+ references returned by the server, where possible. This response is
+ cacheable unless indicated otherwise.
+
+ The new permanent URI SHOULD be given by the Location field in the
+ response. Unless the request method was HEAD, the entity of the
+ response SHOULD contain a short hypertext note with a hyperlink to
+ the new URI(s).
+
+ If the 301 status code is received in response to a request other
+ than GET or HEAD, the user agent MUST NOT automatically redirect the
+ request unless it can be confirmed by the user, since this might
+ change the conditions under which the request was issued.
+
+ Note: When automatically redirecting a POST request after
+ receiving a 301 status code, some existing HTTP/1.0 user agents
+ will erroneously change it into a GET request.
+
+10.3.3 302 Found
+
+ The requested resource resides temporarily under a different URI.
+ Since the redirection might be altered on occasion, the client SHOULD
+ continue to use the Request-URI for future requests. This response
+ is only cacheable if indicated by a Cache-Control or Expires header
+ field.
+
+ The temporary URI SHOULD be given by the Location field in the
+ response. Unless the request method was HEAD, the entity of the
+ response SHOULD contain a short hypertext note with a hyperlink to
+ the new URI(s).
+
+ If the 302 status code is received in response to a request other
+ than GET or HEAD, the user agent MUST NOT automatically redirect the
+ request unless it can be confirmed by the user, since this might
+ change the conditions under which the request was issued.
+
+ Note: <a href="http://firefly.troll.no/rfcs/rfc1945.html">RFC 1945</a> and <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> specify that the client is not allowed
+ to change the method on the redirected request. However, most
+ existing user agent implementations treat 302 as if it were a 303
+ response, performing a GET on the Location field-value regardless
+ of the original request method. The status codes 303 and 307 have
+ been added for servers that wish to make unambiguously clear which
+ kind of reaction is expected of the client.
+
+10.3.4 303 See Other
+
+ The response to the request can be found under a different URI and
+ SHOULD be retrieved using a GET method on that resource. This method
+ exists primarily to allow the output of a POST-activated script to
+ redirect the user agent to a selected resource. The new URI is not a
+ substitute reference for the originally requested resource. The 303
+ response MUST NOT be cached, but the response to the second
+ (redirected) request might be cacheable.
+
+ The different URI SHOULD be given by the Location field in the
+ response. Unless the request method was HEAD, the entity of the
+ response SHOULD contain a short hypertext note with a hyperlink to
+ the new URI(s).
+
+ Note: Many pre-HTTP/1.1 user agents do not understand the 303
+ status. When interoperability with such clients is a concern, the
+ 302 status code may be used instead, since most user agents react
+ to a 302 response as described here for 303.
+
+10.3.5 304 Not Modified
+
+ If the client has performed a conditional GET request and access is
+ allowed, but the document has not been modified, the server SHOULD
+ respond with this status code. The 304 response MUST NOT contain a
+ message-body, and thus is always terminated by the first empty line
+ after the header fields.
+
+ The response MUST include the following header fields:
+
+ - Date, unless its omission is required by section 14.18.1
+
+ If a clockless origin server obeys these rules, and proxies and
+ clients add their own Date to any response received without one (as
+ already specified by [<a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a>], section 14.19), caches will operate
+ correctly.
+
+ - ETag and/or Content-Location, if the header would have been sent
+ in a 200 response to the same request
+
+ - Expires, Cache-Control, and/or Vary, if the field-value might
+ differ from that sent in any previous response for the same
+ variant
+
+ If the conditional GET used a strong cache validator (see section
+ 13.3.3), the response SHOULD NOT include other entity-headers.
+ Otherwise (i.e., the conditional GET used a weak validator), the
+ response MUST NOT include other entity-headers; this prevents
+ inconsistencies between cached entity-bodies and updated headers.
+
+ If a 304 response indicates an entity not currently cached, then the
+ cache MUST disregard the response and repeat the request without the
+ conditional.
+
+ If a cache uses a received 304 response to update a cache entry, the
+ cache MUST update the entry to reflect any new field values given in
+ the response.
+
+10.3.6 305 Use Proxy
+
+ The requested resource MUST be accessed through the proxy given by
+ the Location field. The Location field gives the URI of the proxy.
+ The recipient is expected to repeat this single request via the
+ proxy. 305 responses MUST only be generated by origin servers.
+
+ Note: <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> was not clear that 305 was intended to redirect a
+ single request, and to be generated by origin servers only. Not
+ observing these limitations has significant security consequences.
+
+10.3.7 306 (Unused)
+
+ The 306 status code was used in a previous version of the
+ specification, is no longer used, and the code is reserved.
+
+10.3.8 307 Temporary Redirect
+
+ The requested resource resides temporarily under a different URI.
+ Since the redirection MAY be altered on occasion, the client SHOULD
+ continue to use the Request-URI for future requests. This response
+ is only cacheable if indicated by a Cache-Control or Expires header
+ field.
+
+ The temporary URI SHOULD be given by the Location field in the
+ response. Unless the request method was HEAD, the entity of the
+ response SHOULD contain a short hypertext note with a hyperlink to
+ the new URI(s) , since many pre-HTTP/1.1 user agents do not
+ understand the 307 status. Therefore, the note SHOULD contain the
+ information necessary for a user to repeat the original request on
+ the new URI.
+
+ If the 307 status code is received in response to a request other
+ than GET or HEAD, the user agent MUST NOT automatically redirect the
+ request unless it can be confirmed by the user, since this might
+ change the conditions under which the request was issued.
+
+10.4 Client Error 4xx
+
+ The 4xx class of status code is intended for cases in which the
+ client seems to have erred. Except when responding to a HEAD request,
+ the server SHOULD include an entity containing an explanation of the
+ error situation, and whether it is a temporary or permanent
+ condition. These status codes are applicable to any request method.
+ User agents SHOULD display any included entity to the user.
+
+ If the client is sending data, a server implementation using TCP
+ SHOULD be careful to ensure that the client acknowledges receipt of
+ the packet(s) containing the response, before the server closes the
+ input connection. If the client continues sending data to the server
+ after the close, the server's TCP stack will send a reset packet to
+ the client, which may erase the client's unacknowledged input buffers
+ before they can be read and interpreted by the HTTP application.
+
+10.4.1 400 Bad Request
+
+ The request could not be understood by the server due to malformed
+ syntax. The client SHOULD NOT repeat the request without
+ modifications.
+
+10.4.2 401 Unauthorized
+
+ The request requires user authentication. The response MUST include a
+ WWW-Authenticate header field (section 14.47) containing a challenge
+ applicable to the requested resource. The client MAY repeat the
+ request with a suitable Authorization header field (section 14.8). If
+ the request already included Authorization credentials, then the 401
+ response indicates that authorization has been refused for those
+ credentials. If the 401 response contains the same challenge as the
+ prior response, and the user agent has already attempted
+ authentication at least once, then the user SHOULD be presented the
+ entity that was given in the response, since that entity might
+ include relevant diagnostic information. HTTP access authentication
+ is explained in "HTTP Authentication: Basic and Digest Access
+ Authentication" [43].
+
+10.4.3 402 Payment Required
+
+ This code is reserved for future use.
+
+10.4.4 403 Forbidden
+
+ The server understood the request, but is refusing to fulfill it.
+ Authorization will not help and the request SHOULD NOT be repeated.
+ If the request method was not HEAD and the server wishes to make
+ public why the request has not been fulfilled, it SHOULD describe the
+ reason for the refusal in the entity. If the server does not wish to
+ make this information available to the client, the status code 404
+ (Not Found) can be used instead.
+
+10.4.5 404 Not Found
+
+ The server has not found anything matching the Request-URI. No
+ indication is given of whether the condition is temporary or
+ permanent. The 410 (Gone) status code SHOULD be used if the server
+ knows, through some internally configurable mechanism, that an old
+ resource is permanently unavailable and has no forwarding address.
+ This status code is commonly used when the server does not wish to
+ reveal exactly why the request has been refused, or when no other
+ response is applicable.
+
+10.4.6 405 Method Not Allowed
+
+ The method specified in the Request-Line is not allowed for the
+ resource identified by the Request-URI. The response MUST include an
+ Allow header containing a list of valid methods for the requested
+ resource.
+
+10.4.7 406 Not Acceptable
+
+ The resource identified by the request is only capable of generating
+ response entities which have content characteristics not acceptable
+ according to the accept headers sent in the request.
+
+ Unless it was a HEAD request, the response SHOULD include an entity
+ containing a list of available entity characteristics and location(s)
+ from which the user or user agent can choose the one most
+ appropriate. The entity format is specified by the media type given
+ in the Content-Type header field. Depending upon the format and the
+ capabilities of the user agent, selection of the most appropriate
+ choice MAY be performed automatically. However, this specification
+ does not define any standard for such automatic selection.
+
+ Note: HTTP/1.1 servers are allowed to return responses which are
+ not acceptable according to the accept headers sent in the
+ request. In some cases, this may even be preferable to sending a
+ 406 response. User agents are encouraged to inspect the headers of
+ an incoming response to determine if it is acceptable.
+
+ If the response could be unacceptable, a user agent SHOULD
+ temporarily stop receipt of more data and query the user for a
+ decision on further actions.
+
+10.4.8 407 Proxy Authentication Required
+
+ This code is similar to 401 (Unauthorized), but indicates that the
+ client must first authenticate itself with the proxy. The proxy MUST
+ return a Proxy-Authenticate header field (section 14.33) containing a
+ challenge applicable to the proxy for the requested resource. The
+ client MAY repeat the request with a suitable Proxy-Authorization
+ header field (section 14.34). HTTP access authentication is explained
+ in "HTTP Authentication: Basic and Digest Access Authentication"
+ [43].
+
+10.4.9 408 Request Timeout
+
+ The client did not produce a request within the time that the server
+ was prepared to wait. The client MAY repeat the request without
+ modifications at any later time.
+
+10.4.10 409 Conflict
+
+ The request could not be completed due to a conflict with the current
+ state of the resource. This code is only allowed in situations where
+ it is expected that the user might be able to resolve the conflict
+ and resubmit the request. The response body SHOULD include enough
+
+ information for the user to recognize the source of the conflict.
+ Ideally, the response entity would include enough information for the
+ user or user agent to fix the problem; however, that might not be
+ possible and is not required.
+
+ Conflicts are most likely to occur in response to a PUT request. For
+ example, if versioning were being used and the entity being PUT
+ included changes to a resource which conflict with those made by an
+ earlier (third-party) request, the server might use the 409 response
+ to indicate that it can't complete the request. In this case, the
+ response entity would likely contain a list of the differences
+ between the two versions in a format defined by the response
+ Content-Type.
+
+10.4.11 410 Gone
+
+ The requested resource is no longer available at the server and no
+ forwarding address is known. This condition is expected to be
+ considered permanent. Clients with link editing capabilities SHOULD
+ delete references to the Request-URI after user approval. If the
+ server does not know, or has no facility to determine, whether or not
+ the condition is permanent, the status code 404 (Not Found) SHOULD be
+ used instead. This response is cacheable unless indicated otherwise.
+
+ The 410 response is primarily intended to assist the task of web
+ maintenance by notifying the recipient that the resource is
+ intentionally unavailable and that the server owners desire that
+ remote links to that resource be removed. Such an event is common for
+ limited-time, promotional services and for resources belonging to
+ individuals no longer working at the server's site. It is not
+ necessary to mark all permanently unavailable resources as "gone" or
+ to keep the mark for any length of time -- that is left to the
+ discretion of the server owner.
+
+10.4.12 411 Length Required
+
+ The server refuses to accept the request without a defined Content-
+ Length. The client MAY repeat the request if it adds a valid
+ Content-Length header field containing the length of the message-body
+ in the request message.
+
+10.4.13 412 Precondition Failed
+
+ The precondition given in one or more of the request-header fields
+ evaluated to false when it was tested on the server. This response
+ code allows the client to place preconditions on the current resource
+ metainformation (header field data) and thus prevent the requested
+ method from being applied to a resource other than the one intended.
+
+10.4.14 413 Request Entity Too Large
+
+ The server is refusing to process a request because the request
+ entity is larger than the server is willing or able to process. The
+ server MAY close the connection to prevent the client from continuing
+ the request.
+
+ If the condition is temporary, the server SHOULD include a Retry-
+ After header field to indicate that it is temporary and after what
+ time the client MAY try again.
+
+10.4.15 414 Request-URI Too Long
+
+ The server is refusing to service the request because the Request-URI
+ is longer than the server is willing to interpret. This rare
+ condition is only likely to occur when a client has improperly
+ converted a POST request to a GET request with long query
+ information, when the client has descended into a URI "black hole" of
+ redirection (e.g., a redirected URI prefix that points to a suffix of
+ itself), or when the server is under attack by a client attempting to
+ exploit security holes present in some servers using fixed-length
+ buffers for reading or manipulating the Request-URI.
+
+10.4.16 415 Unsupported Media Type
+
+ The server is refusing to service the request because the entity of
+ the request is in a format not supported by the requested resource
+ for the requested method.
+
+10.4.17 416 Requested Range Not Satisfiable
+
+ A server SHOULD return a response with this status code if a request
+ included a Range request-header field (section 14.35), and none of
+ the range-specifier values in this field overlap the current extent
+ of the selected resource, and the request did not include an If-Range
+ request-header field. (For byte-ranges, this means that the first-
+ byte-pos of all of the byte-range-spec values were greater than the
+ current length of the selected resource.)
+
+ When this status code is returned for a byte-range request, the
+ response SHOULD include a Content-Range entity-header field
+ specifying the current length of the selected resource (see section
+ 14.16). This response MUST NOT use the multipart/byteranges content-
+ type.
+
+10.4.18 417 Expectation Failed
+
+ The expectation given in an Expect request-header field (see section
+ 14.20) could not be met by this server, or, if the server is a proxy,
+ the server has unambiguous evidence that the request could not be met
+ by the next-hop server.
+
+10.5 Server Error 5xx
+
+ Response status codes beginning with the digit "5" indicate cases in
+ which the server is aware that it has erred or is incapable of
+ performing the request. Except when responding to a HEAD request, the
+ server SHOULD include an entity containing an explanation of the
+ error situation, and whether it is a temporary or permanent
+ condition. User agents SHOULD display any included entity to the
+ user. These response codes are applicable to any request method.
+
+10.5.1 500 Internal Server Error
+
+ The server encountered an unexpected condition which prevented it
+ from fulfilling the request.
+
+10.5.2 501 Not Implemented
+
+ The server does not support the functionality required to fulfill the
+ request. This is the appropriate response when the server does not
+ recognize the request method and is not capable of supporting it for
+ any resource.
+
+10.5.3 502 Bad Gateway
+
+ The server, while acting as a gateway or proxy, received an invalid
+ response from the upstream server it accessed in attempting to
+ fulfill the request.
+
+10.5.4 503 Service Unavailable
+
+ The server is currently unable to handle the request due to a
+ temporary overloading or maintenance of the server. The implication
+ is that this is a temporary condition which will be alleviated after
+ some delay. If known, the length of the delay MAY be indicated in a
+ Retry-After header. If no Retry-After is given, the client SHOULD
+ handle the response as it would for a 500 response.
+
+ Note: The existence of the 503 status code does not imply that a
+ server must use it when becoming overloaded. Some servers may wish
+ to simply refuse the connection.
+
+10.5.5 504 Gateway Timeout
+
+ The server, while acting as a gateway or proxy, did not receive a
+ timely response from the upstream server specified by the URI (e.g.
+ HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed
+ to access in attempting to complete the request.
+
+ Note: Note to implementors: some deployed proxies are known to
+ return 400 or 500 when DNS lookups time out.
+
+10.5.6 505 HTTP Version Not Supported
+
+ The server does not support, or refuses to support, the HTTP protocol
+ version that was used in the request message. The server is
+ indicating that it is unable or unwilling to complete the request
+ using the same major version as the client, as described in section
+ 3.1, other than with this error message. The response SHOULD contain
+ an entity describing why that version is not supported and what other
+ protocols are supported by that server.
+
+11 Access Authentication
+
+ HTTP provides several OPTIONAL challenge-response authentication
+ mechanisms which can be used by a server to challenge a client
+ request and by a client to provide authentication information. The
+ general framework for access authentication, and the specification of
+ "basic" and "digest" authentication, are specified in "HTTP
+ Authentication: Basic and Digest Access Authentication" [43]. This
+ specification adopts the definitions of "challenge" and "credentials"
+ from that specification.
+
+12 Content Negotiation
+
+ Most HTTP responses include an entity which contains information for
+ interpretation by a human user. Naturally, it is desirable to supply
+ the user with the "best available" entity corresponding to the
+ request. Unfortunately for servers and caches, not all users have the
+ same preferences for what is "best," and not all user agents are
+ equally capable of rendering all entity types. For that reason, HTTP
+ has provisions for several mechanisms for "content negotiation" --
+ the process of selecting the best representation for a given response
+ when there are multiple representations available.
+
+ Note: This is not called "format negotiation" because the
+ alternate representations may be of the same media type, but use
+ different capabilities of that type, be in different languages,
+ etc.
+
+ Any response containing an entity-body MAY be subject to negotiation,
+ including error responses.
+
+ There are two kinds of content negotiation which are possible in
+ HTTP: server-driven and agent-driven negotiation. These two kinds of
+ negotiation are orthogonal and thus may be used separately or in
+ combination. One method of combination, referred to as transparent
+ negotiation, occurs when a cache uses the agent-driven negotiation
+ information provided by the origin server in order to provide
+ server-driven negotiation for subsequent requests.
+
+12.1 Server-driven Negotiation
+
+ If the selection of the best representation for a response is made by
+ an algorithm located at the server, it is called server-driven
+ negotiation. Selection is based on the available representations of
+ the response (the dimensions over which it can vary; e.g. language,
+ content-coding, etc.) and the contents of particular header fields in
+ the request message or on other information pertaining to the request
+ (such as the network address of the client).
+
+ Server-driven negotiation is advantageous when the algorithm for
+ selecting from among the available representations is difficult to
+ describe to the user agent, or when the server desires to send its
+ "best guess" to the client along with the first response (hoping to
+ avoid the round-trip delay of a subsequent request if the "best
+ guess" is good enough for the user). In order to improve the server's
+ guess, the user agent MAY include request header fields (Accept,
+ Accept-Language, Accept-Encoding, etc.) which describe its
+ preferences for such a response.
+
+ Server-driven negotiation has disadvantages:
+
+ 1. It is impossible for the server to accurately determine what
+ might be "best" for any given user, since that would require
+ complete knowledge of both the capabilities of the user agent
+ and the intended use for the response (e.g., does the user want
+ to view it on screen or print it on paper?).
+
+ 2. Having the user agent describe its capabilities in every
+ request can be both very inefficient (given that only a small
+ percentage of responses have multiple representations) and a
+ potential violation of the user's privacy.
+
+ 3. It complicates the implementation of an origin server and the
+ algorithms for generating responses to a request.
+
+ 4. It may limit a public cache's ability to use the same response
+ for multiple user's requests.
+
+ HTTP/1.1 includes the following request-header fields for enabling
+ server-driven negotiation through description of user agent
+ capabilities and user preferences: Accept (section 14.1), Accept-
+ Charset (section 14.2), Accept-Encoding (section 14.3), Accept-
+ Language (section 14.4), and User-Agent (section 14.43). However, an
+ origin server is not limited to these dimensions and MAY vary the
+ response based on any aspect of the request, including information
+ outside the request-header fields or within extension header fields
+ not defined by this specification.
+
+ The Vary header field can be used to express the parameters the
+ server uses to select a representation that is subject to server-
+ driven negotiation. See section 13.6 for use of the Vary header field
+ by caches and section 14.44 for use of the Vary header field by
+ servers.
+
+12.2 Agent-driven Negotiation
+
+ With agent-driven negotiation, selection of the best representation
+ for a response is performed by the user agent after receiving an
+ initial response from the origin server. Selection is based on a list
+ of the available representations of the response included within the
+ header fields or entity-body of the initial response, with each
+ representation identified by its own URI. Selection from among the
+ representations may be performed automatically (if the user agent is
+ capable of doing so) or manually by the user selecting from a
+ generated (possibly hypertext) menu.
+
+ Agent-driven negotiation is advantageous when the response would vary
+ over commonly-used dimensions (such as type, language, or encoding),
+ when the origin server is unable to determine a user agent's
+ capabilities from examining the request, and generally when public
+ caches are used to distribute server load and reduce network usage.
+
+ Agent-driven negotiation suffers from the disadvantage of needing a
+ second request to obtain the best alternate representation. This
+ second request is only efficient when caching is used. In addition,
+ this specification does not define any mechanism for supporting
+ automatic selection, though it also does not prevent any such
+ mechanism from being developed as an extension and used within
+ HTTP/1.1.
+
+ HTTP/1.1 defines the 300 (Multiple Choices) and 406 (Not Acceptable)
+ status codes for enabling agent-driven negotiation when the server is
+ unwilling or unable to provide a varying response using server-driven
+ negotiation.
+
+12.3 Transparent Negotiation
+
+ Transparent negotiation is a combination of both server-driven and
+ agent-driven negotiation. When a cache is supplied with a form of the
+ list of available representations of the response (as in agent-driven
+ negotiation) and the dimensions of variance are completely understood
+ by the cache, then the cache becomes capable of performing server-
+ driven negotiation on behalf of the origin server for subsequent
+ requests on that resource.
+
+ Transparent negotiation has the advantage of distributing the
+ negotiation work that would otherwise be required of the origin
+ server and also removing the second request delay of agent-driven
+ negotiation when the cache is able to correctly guess the right
+ response.
+
+ This specification does not define any mechanism for transparent
+ negotiation, though it also does not prevent any such mechanism from
+ being developed as an extension that could be used within HTTP/1.1.
+
+13 Caching in HTTP
+
+ HTTP is typically used for distributed information systems, where
+ performance can be improved by the use of response caches. The
+ HTTP/1.1 protocol includes a number of elements intended to make
+ caching work as well as possible. Because these elements are
+ inextricable from other aspects of the protocol, and because they
+ interact with each other, it is useful to describe the basic caching
+ design of HTTP separately from the detailed descriptions of methods,
+ headers, response codes, etc.
+
+ Caching would be useless if it did not significantly improve
+ performance. The goal of caching in HTTP/1.1 is to eliminate the need
+ to send requests in many cases, and to eliminate the need to send
+ full responses in many other cases. The former reduces the number of
+ network round-trips required for many operations; we use an
+ "expiration" mechanism for this purpose (see section 13.2). The
+ latter reduces network bandwidth requirements; we use a "validation"
+ mechanism for this purpose (see section 13.3).
+
+ Requirements for performance, availability, and disconnected
+ operation require us to be able to relax the goal of semantic
+ transparency. The HTTP/1.1 protocol allows origin servers, caches,
+
+ and clients to explicitly reduce transparency when necessary.
+ However, because non-transparent operation may confuse non-expert
+ users, and might be incompatible with certain server applications
+ (such as those for ordering merchandise), the protocol requires that
+ transparency be relaxed
+
+ - only by an explicit protocol-level request when relaxed by
+ client or origin server
+
+ - only with an explicit warning to the end user when relaxed by
+ cache or client
+
+ Therefore, the HTTP/1.1 protocol provides these important elements:
+
+ 1. Protocol features that provide full semantic transparency when
+ this is required by all parties.
+
+ 2. Protocol features that allow an origin server or user agent to
+ explicitly request and control non-transparent operation.
+
+ 3. Protocol features that allow a cache to attach warnings to
+ responses that do not preserve the requested approximation of
+ semantic transparency.
+
+ A basic principle is that it must be possible for the clients to
+ detect any potential relaxation of semantic transparency.
+
+ Note: The server, cache, or client implementor might be faced with
+ design decisions not explicitly discussed in this specification.
+ If a decision might affect semantic transparency, the implementor
+ ought to err on the side of maintaining transparency unless a
+ careful and complete analysis shows significant benefits in
+ breaking transparency.
+
+13.1.1 Cache Correctness
+
+ A correct cache MUST respond to a request with the most up-to-date
+ response held by the cache that is appropriate to the request (see
+ sections 13.2.5, 13.2.6, and 13.12) which meets one of the following
+ conditions:
+
+ 1. It has been checked for equivalence with what the origin server
+ would have returned by revalidating the response with the
+ origin server (section 13.3);
+
+ 2. It is "fresh enough" (see section 13.2). In the default case,
+ this means it meets the least restrictive freshness requirement
+ of the client, origin server, and cache (see section 14.9); if
+ the origin server so specifies, it is the freshness requirement
+ of the origin server alone.
+
+ If a stored response is not "fresh enough" by the most
+ restrictive freshness requirement of both the client and the
+ origin server, in carefully considered circumstances the cache
+ MAY still return the response with the appropriate Warning
+ header (see section 13.1.5 and 14.46), unless such a response
+ is prohibited (e.g., by a "no-store" cache-directive, or by a
+ "no-cache" cache-request-directive; see section 14.9).
+
+ 3. It is an appropriate 304 (Not Modified), 305 (Proxy Redirect),
+ or error (4xx or 5xx) response message.
+
+ If the cache can not communicate with the origin server, then a
+ correct cache SHOULD respond as above if the response can be
+ correctly served from the cache; if not it MUST return an error or
+ warning indicating that there was a communication failure.
+
+ If a cache receives a response (either an entire response, or a 304
+ (Not Modified) response) that it would normally forward to the
+ requesting client, and the received response is no longer fresh, the
+ cache SHOULD forward it to the requesting client without adding a new
+ Warning (but without removing any existing Warning headers). A cache
+ SHOULD NOT attempt to revalidate a response simply because that
+ response became stale in transit; this might lead to an infinite
+ loop. A user agent that receives a stale response without a Warning
+ MAY display a warning indication to the user.
+
+13.1.2 Warnings
+
+ Whenever a cache returns a response that is neither first-hand nor
+ "fresh enough" (in the sense of condition 2 in section 13.1.1), it
+ MUST attach a warning to that effect, using a Warning general-header.
+ The Warning header and the currently defined warnings are described
+ in section 14.46. The warning allows clients to take appropriate
+ action.
+
+ Warnings MAY be used for other purposes, both cache-related and
+ otherwise. The use of a warning, rather than an error status code,
+ distinguish these responses from true failures.
+
+ Warnings are assigned three digit warn-codes. The first digit
+ indicates whether the Warning MUST or MUST NOT be deleted from a
+ stored cache entry after a successful revalidation:
+
+ 1xx Warnings that describe the freshness or revalidation status of
+ the response, and so MUST be deleted after a successful
+ revalidation. 1XX warn-codes MAY be generated by a cache only when
+ validating a cached entry. It MUST NOT be generated by clients.
+
+ 2xx Warnings that describe some aspect of the entity body or entity
+ headers that is not rectified by a revalidation (for example, a
+ lossy compression of the entity bodies) and which MUST NOT be
+ deleted after a successful revalidation.
+
+ See section 14.46 for the definitions of the codes themselves.
+
+ HTTP/1.0 caches will cache all Warnings in responses, without
+ deleting the ones in the first category. Warnings in responses that
+ are passed to HTTP/1.0 caches carry an extra warning-date field,
+ which prevents a future HTTP/1.1 recipient from believing an
+ erroneously cached Warning.
+
+ Warnings also carry a warning text. The text MAY be in any
+ appropriate natural language (perhaps based on the client's Accept
+ headers), and include an OPTIONAL indication of what character set is
+ used.
+
+ Multiple warnings MAY be attached to a response (either by the origin
+ server or by a cache), including multiple warnings with the same code
+ number. For example, a server might provide the same warning with
+ texts in both English and Basque.
+
+ When multiple warnings are attached to a response, it might not be
+ practical or reasonable to display all of them to the user. This
+ version of HTTP does not specify strict priority rules for deciding
+ which warnings to display and in what order, but does suggest some
+ heuristics.
+
+13.1.3 Cache-control Mechanisms
+
+ The basic cache mechanisms in HTTP/1.1 (server-specified expiration
+ times and validators) are implicit directives to caches. In some
+ cases, a server or client might need to provide explicit directives
+ to the HTTP caches. We use the Cache-Control header for this purpose.
+
+ The Cache-Control header allows a client or server to transmit a
+ variety of directives in either requests or responses. These
+ directives typically override the default caching algorithms. As a
+ general rule, if there is any apparent conflict between header
+ values, the most restrictive interpretation is applied (that is, the
+ one that is most likely to preserve semantic transparency). However,
+
+ in some cases, cache-control directives are explicitly specified as
+ weakening the approximation of semantic transparency (for example,
+ "max-stale" or "public").
+
+ The cache-control directives are described in detail in section 14.9.
+
+13.1.4 Explicit User Agent Warnings
+
+ Many user agents make it possible for users to override the basic
+ caching mechanisms. For example, the user agent might allow the user
+ to specify that cached entities (even explicitly stale ones) are
+ never validated. Or the user agent might habitually add "Cache-
+ Control: max-stale=3600" to every request. The user agent SHOULD NOT
+ default to either non-transparent behavior, or behavior that results
+ in abnormally ineffective caching, but MAY be explicitly configured
+ to do so by an explicit action of the user.
+
+ If the user has overridden the basic caching mechanisms, the user
+ agent SHOULD explicitly indicate to the user whenever this results in
+ the display of information that might not meet the server's
+ transparency requirements (in particular, if the displayed entity is
+ known to be stale). Since the protocol normally allows the user agent
+ to determine if responses are stale or not, this indication need only
+ be displayed when this actually happens. The indication need not be a
+ dialog box; it could be an icon (for example, a picture of a rotting
+ fish) or some other indicator.
+
+ If the user has overridden the caching mechanisms in a way that would
+ abnormally reduce the effectiveness of caches, the user agent SHOULD
+ continually indicate this state to the user (for example, by a
+ display of a picture of currency in flames) so that the user does not
+ inadvertently consume excess resources or suffer from excessive
+ latency.
+
+13.1.5 Exceptions to the Rules and Warnings
+
+ In some cases, the operator of a cache MAY choose to configure it to
+ return stale responses even when not requested by clients. This
+ decision ought not be made lightly, but may be necessary for reasons
+ of availability or performance, especially when the cache is poorly
+ connected to the origin server. Whenever a cache returns a stale
+ response, it MUST mark it as such (using a Warning header) enabling
+ the client software to alert the user that there might be a potential
+ problem.
+
+ It also allows the user agent to take steps to obtain a first-hand or
+ fresh response. For this reason, a cache SHOULD NOT return a stale
+ response if the client explicitly requests a first-hand or fresh one,
+ unless it is impossible to comply for technical or policy reasons.
+
+13.1.6 Client-controlled Behavior
+
+ While the origin server (and to a lesser extent, intermediate caches,
+ by their contribution to the age of a response) are the primary
+ source of expiration information, in some cases the client might need
+ to control a cache's decision about whether to return a cached
+ response without validating it. Clients do this using several
+ directives of the Cache-Control header.
+
+ A client's request MAY specify the maximum age it is willing to
+ accept of an unvalidated response; specifying a value of zero forces
+ the cache(s) to revalidate all responses. A client MAY also specify
+ the minimum time remaining before a response expires. Both of these
+ options increase constraints on the behavior of caches, and so cannot
+ further relax the cache's approximation of semantic transparency.
+
+ A client MAY also specify that it will accept stale responses, up to
+ some maximum amount of staleness. This loosens the constraints on the
+ caches, and so might violate the origin server's specified
+ constraints on semantic transparency, but might be necessary to
+ support disconnected operation, or high availability in the face of
+ poor connectivity.
+
+13.2 Expiration Model
+
+13.2.1 Server-Specified Expiration
+
+ HTTP caching works best when caches can entirely avoid making
+ requests to the origin server. The primary mechanism for avoiding
+ requests is for an origin server to provide an explicit expiration
+ time in the future, indicating that a response MAY be used to satisfy
+ subsequent requests. In other words, a cache can return a fresh
+ response without first contacting the server.
+
+ Our expectation is that servers will assign future explicit
+ expiration times to responses in the belief that the entity is not
+ likely to change, in a semantically significant way, before the
+ expiration time is reached. This normally preserves semantic
+ transparency, as long as the server's expiration times are carefully
+ chosen.
+
+ The expiration mechanism applies only to responses taken from a cache
+ and not to first-hand responses forwarded immediately to the
+ requesting client.
+
+ If an origin server wishes to force a semantically transparent cache
+ to validate every request, it MAY assign an explicit expiration time
+ in the past. This means that the response is always stale, and so the
+ cache SHOULD validate it before using it for subsequent requests. See
+ section 14.9.4 for a more restrictive way to force revalidation.
+
+ If an origin server wishes to force any HTTP/1.1 cache, no matter how
+ it is configured, to validate every request, it SHOULD use the "must-
+ revalidate" cache-control directive (see section 14.9).
+
+ Servers specify explicit expiration times using either the Expires
+ header, or the max-age directive of the Cache-Control header.
+
+ An expiration time cannot be used to force a user agent to refresh
+ its display or reload a resource; its semantics apply only to caching
+ mechanisms, and such mechanisms need only check a resource's
+ expiration status when a new request for that resource is initiated.
+ See section 13.13 for an explanation of the difference between caches
+ and history mechanisms.
+
+13.2.2 Heuristic Expiration
+
+ Since origin servers do not always provide explicit expiration times,
+ HTTP caches typically assign heuristic expiration times, employing
+ algorithms that use other header values (such as the Last-Modified
+ time) to estimate a plausible expiration time. The HTTP/1.1
+ specification does not provide specific algorithms, but does impose
+ worst-case constraints on their results. Since heuristic expiration
+ times might compromise semantic transparency, they ought to used
+ cautiously, and we encourage origin servers to provide explicit
+ expiration times as much as possible.
+
+13.2.3 Age Calculations
+
+ In order to know if a cached entry is fresh, a cache needs to know if
+ its age exceeds its freshness lifetime. We discuss how to calculate
+ the latter in section 13.2.4; this section describes how to calculate
+ the age of a response or cache entry.
+
+ In this discussion, we use the term "now" to mean "the current value
+ of the clock at the host performing the calculation." Hosts that use
+ HTTP, but especially hosts running origin servers and caches, SHOULD
+ use NTP [28] or some similar protocol to synchronize their clocks to
+ a globally accurate time standard.
+
+ HTTP/1.1 requires origin servers to send a Date header, if possible,
+ with every response, giving the time at which the response was
+ generated (see section 14.18). We use the term "date_value" to denote
+ the value of the Date header, in a form appropriate for arithmetic
+ operations.
+
+ HTTP/1.1 uses the Age response-header to convey the estimated age of
+ the response message when obtained from a cache. The Age field value
+ is the cache's estimate of the amount of time since the response was
+ generated or revalidated by the origin server.
+
+ In essence, the Age value is the sum of the time that the response
+ has been resident in each of the caches along the path from the
+ origin server, plus the amount of time it has been in transit along
+ network paths.
+
+ We use the term "age_value" to denote the value of the Age header, in
+ a form appropriate for arithmetic operations.
+
+ A response's age can be calculated in two entirely independent ways:
+
+ 1. now minus date_value, if the local clock is reasonably well
+ synchronized to the origin server's clock. If the result is
+ negative, the result is replaced by zero.
+
+ 2. age_value, if all of the caches along the response path
+ implement HTTP/1.1.
+
+ Given that we have two independent ways to compute the age of a
+ response when it is received, we can combine these as
+
+ corrected_received_age = max(now - date_value, age_value)
+
+ and as long as we have either nearly synchronized clocks or all-
+ HTTP/1.1 paths, one gets a reliable (conservative) result.
+
+ Because of network-imposed delays, some significant interval might
+ pass between the time that a server generates a response and the time
+ it is received at the next outbound cache or client. If uncorrected,
+ this delay could result in improperly low ages.
+
+ Because the request that resulted in the returned Age value must have
+ been initiated prior to that Age value's generation, we can correct
+ for delays imposed by the network by recording the time at which the
+ request was initiated. Then, when an Age value is received, it MUST
+ be interpreted relative to the time the request was initiated, not
+
+ the time that the response was received. This algorithm results in
+ conservative behavior no matter how much delay is experienced. So, we
+ compute:
+
+ corrected_initial_age = corrected_received_age
+ + (now - request_time)
+
+ where "request_time" is the time (according to the local clock) when
+ the request that elicited this response was sent.
+
+ Summary of age calculation algorithm, when a cache receives a
+ response:
+
+ /*
+ * age_value
+ * is the value of Age: header received by the cache with
+ * this response.
+ * date_value
+ * is the value of the origin server's Date: header
+ * request_time
+ * is the (local) time when the cache made the request
+ * that resulted in this cached response
+ * response_time
+ * is the (local) time when the cache received the
+ * response
+ * now
+ * is the current (local) time
+ */
+
+ apparent_age = max(0, response_time - date_value);
+ corrected_received_age = max(apparent_age, age_value);
+ response_delay = response_time - request_time;
+ corrected_initial_age = corrected_received_age + response_delay;
+ resident_time = now - response_time;
+ current_age = corrected_initial_age + resident_time;
+
+ The current_age of a cache entry is calculated by adding the amount
+ of time (in seconds) since the cache entry was last validated by the
+ origin server to the corrected_initial_age. When a response is
+ generated from a cache entry, the cache MUST include a single Age
+ header field in the response with a value equal to the cache entry's
+ current_age.
+
+ The presence of an Age header field in a response implies that a
+ response is not first-hand. However, the converse is not true, since
+ the lack of an Age header field in a response does not imply that the
+
+ response is first-hand unless all caches along the request path are
+ compliant with HTTP/1.1 (i.e., older HTTP caches did not implement
+ the Age header field).
+
+13.2.4 Expiration Calculations
+
+ In order to decide whether a response is fresh or stale, we need to
+ compare its freshness lifetime to its age. The age is calculated as
+ described in section 13.2.3; this section describes how to calculate
+ the freshness lifetime, and to determine if a response has expired.
+ In the discussion below, the values can be represented in any form
+ appropriate for arithmetic operations.
+
+ We use the term "expires_value" to denote the value of the Expires
+ header. We use the term "max_age_value" to denote an appropriate
+ value of the number of seconds carried by the "max-age" directive of
+ the Cache-Control header in a response (see section 14.9.3).
+
+ The max-age directive takes priority over Expires, so if max-age is
+ present in a response, the calculation is simply:
+
+ freshness_lifetime = max_age_value
+
+ Otherwise, if Expires is present in the response, the calculation is:
+
+ freshness_lifetime = expires_value - date_value
+
+ Note that neither of these calculations is vulnerable to clock skew,
+ since all of the information comes from the origin server.
+
+ If none of Expires, Cache-Control: max-age, or Cache-Control: s-
+ maxage (see section 14.9.3) appears in the response, and the response
+ does not include other restrictions on caching, the cache MAY compute
+ a freshness lifetime using a heuristic. The cache MUST attach Warning
+ 113 to any response whose age is more than 24 hours if such warning
+ has not already been added.
+
+ Also, if the response does have a Last-Modified time, the heuristic
+ expiration value SHOULD be no more than some fraction of the interval
+ since that time. A typical setting of this fraction might be 10%.
+
+ The calculation to determine if a response has expired is quite
+ simple:
+
+ response_is_fresh = (freshness_lifetime &gt; current_age)
+
+13.2.5 Disambiguating Expiration Values
+
+ Because expiration values are assigned optimistically, it is possible
+ for two caches to contain fresh values for the same resource that are
+ different.
+
+ If a client performing a retrieval receives a non-first-hand response
+ for a request that was already fresh in its own cache, and the Date
+ header in its existing cache entry is newer than the Date on the new
+ response, then the client MAY ignore the response. If so, it MAY
+ retry the request with a "Cache-Control: max-age=0" directive (see
+ section 14.9), to force a check with the origin server.
+
+ If a cache has two fresh responses for the same representation with
+ different validators, it MUST use the one with the more recent Date
+ header. This situation might arise because the cache is pooling
+ responses from other caches, or because a client has asked for a
+ reload or a revalidation of an apparently fresh cache entry.
+
+13.2.6 Disambiguating Multiple Responses
+
+ Because a client might be receiving responses via multiple paths, so
+ that some responses flow through one set of caches and other
+ responses flow through a different set of caches, a client might
+ receive responses in an order different from that in which the origin
+ server sent them. We would like the client to use the most recently
+ generated response, even if older responses are still apparently
+ fresh.
+
+ Neither the entity tag nor the expiration value can impose an
+ ordering on responses, since it is possible that a later response
+ intentionally carries an earlier expiration time. The Date values are
+ ordered to a granularity of one second.
+
+ When a client tries to revalidate a cache entry, and the response it
+ receives contains a Date header that appears to be older than the one
+ for the existing entry, then the client SHOULD repeat the request
+ unconditionally, and include
+
+ Cache-Control: max-age=0
+
+ to force any intermediate caches to validate their copies directly
+ with the origin server, or
+
+ Cache-Control: no-cache
+
+ to force any intermediate caches to obtain a new copy from the origin
+ server.
+
+ If the Date values are equal, then the client MAY use either response
+ (or MAY, if it is being extremely prudent, request a new response).
+ Servers MUST NOT depend on clients being able to choose
+ deterministically between responses generated during the same second,
+ if their expiration times overlap.
+
+13.3 Validation Model
+
+ When a cache has a stale entry that it would like to use as a
+ response to a client's request, it first has to check with the origin
+ server (or possibly an intermediate cache with a fresh response) to
+ see if its cached entry is still usable. We call this "validating"
+ the cache entry. Since we do not want to have to pay the overhead of
+ retransmitting the full response if the cached entry is good, and we
+ do not want to pay the overhead of an extra round trip if the cached
+ entry is invalid, the HTTP/1.1 protocol supports the use of
+ conditional methods.
+
+ The key protocol features for supporting conditional methods are
+ those concerned with "cache validators." When an origin server
+ generates a full response, it attaches some sort of validator to it,
+ which is kept with the cache entry. When a client (user agent or
+ proxy cache) makes a conditional request for a resource for which it
+ has a cache entry, it includes the associated validator in the
+ request.
+
+ The server then checks that validator against the current validator
+ for the entity, and, if they match (see section 13.3.3), it responds
+ with a special status code (usually, 304 (Not Modified)) and no
+ entity-body. Otherwise, it returns a full response (including
+ entity-body). Thus, we avoid transmitting the full response if the
+ validator matches, and we avoid an extra round trip if it does not
+ match.
+
+ In HTTP/1.1, a conditional request looks exactly the same as a normal
+ request for the same resource, except that it carries a special
+ header (which includes the validator) that implicitly turns the
+ method (usually, GET) into a conditional.
+
+ The protocol includes both positive and negative senses of cache-
+ validating conditions. That is, it is possible to request either that
+ a method be performed if and only if a validator matches or if and
+ only if no validators match.
+
+ Note: a response that lacks a validator may still be cached, and
+ served from cache until it expires, unless this is explicitly
+ prohibited by a cache-control directive. However, a cache cannot
+ do a conditional retrieval if it does not have a validator for the
+ entity, which means it will not be refreshable after it expires.
+
+13.3.1 Last-Modified Dates
+
+ The Last-Modified entity-header field value is often used as a cache
+ validator. In simple terms, a cache entry is considered to be valid
+ if the entity has not been modified since the Last-Modified value.
+
+13.3.2 Entity Tag Cache Validators
+
+ The ETag response-header field value, an entity tag, provides for an
+ "opaque" cache validator. This might allow more reliable validation
+ in situations where it is inconvenient to store modification dates,
+ where the one-second resolution of HTTP date values is not
+ sufficient, or where the origin server wishes to avoid certain
+ paradoxes that might arise from the use of modification dates.
+
+ Entity Tags are described in section 3.11. The headers used with
+ entity tags are described in sections 14.19, 14.24, 14.26 and 14.44.
+
+13.3.3 Weak and Strong Validators
+
+ Since both origin servers and caches will compare two validators to
+ decide if they represent the same or different entities, one normally
+ would expect that if the entity (the entity-body or any entity-
+ headers) changes in any way, then the associated validator would
+ change as well. If this is true, then we call this validator a
+ "strong validator."
+
+ However, there might be cases when a server prefers to change the
+ validator only on semantically significant changes, and not when
+ insignificant aspects of the entity change. A validator that does not
+ always change when the resource changes is a "weak validator."
+
+ Entity tags are normally "strong validators," but the protocol
+ provides a mechanism to tag an entity tag as "weak." One can think of
+ a strong validator as one that changes whenever the bits of an entity
+ changes, while a weak value changes whenever the meaning of an entity
+ changes. Alternatively, one can think of a strong validator as part
+ of an identifier for a specific entity, while a weak validator is
+ part of an identifier for a set of semantically equivalent entities.
+
+ Note: One example of a strong validator is an integer that is
+ incremented in stable storage every time an entity is changed.
+
+ An entity's modification time, if represented with one-second
+ resolution, could be a weak validator, since it is possible that
+ the resource might be modified twice during a single second.
+
+ Support for weak validators is optional. However, weak validators
+ allow for more efficient caching of equivalent objects; for
+ example, a hit counter on a site is probably good enough if it is
+ updated every few days or weeks, and any value during that period
+ is likely "good enough" to be equivalent.
+
+ A "use" of a validator is either when a client generates a request
+ and includes the validator in a validating header field, or when a
+ server compares two validators.
+
+ Strong validators are usable in any context. Weak validators are only
+ usable in contexts that do not depend on exact equality of an entity.
+ For example, either kind is usable for a conditional GET of a full
+ entity. However, only a strong validator is usable for a sub-range
+ retrieval, since otherwise the client might end up with an internally
+ inconsistent entity.
+
+ Clients MAY issue simple (non-subrange) GET requests with either weak
+ validators or strong validators. Clients MUST NOT use weak validators
+ in other forms of request.
+
+ The only function that the HTTP/1.1 protocol defines on validators is
+ comparison. There are two validator comparison functions, depending
+ on whether the comparison context allows the use of weak validators
+ or not:
+
+ - The strong comparison function: in order to be considered equal,
+ both validators MUST be identical in every way, and both MUST
+ NOT be weak.
+
+ - The weak comparison function: in order to be considered equal,
+ both validators MUST be identical in every way, but either or
+ both of them MAY be tagged as "weak" without affecting the
+ result.
+
+ An entity tag is strong unless it is explicitly tagged as weak.
+ Section 3.11 gives the syntax for entity tags.
+
+ A Last-Modified time, when used as a validator in a request, is
+ implicitly weak unless it is possible to deduce that it is strong,
+ using the following rules:
+
+ - The validator is being compared by an origin server to the
+ actual current validator for the entity and,
+
+ - That origin server reliably knows that the associated entity did
+ not change twice during the second covered by the presented
+ validator.
+
+ or
+
+ - The validator is about to be used by a client in an If-
+ Modified-Since or If-Unmodified-Since header, because the client
+ has a cache entry for the associated entity, and
+
+ - That cache entry includes a Date value, which gives the time
+ when the origin server sent the original response, and
+
+ - The presented Last-Modified time is at least 60 seconds before
+ the Date value.
+
+ or
+
+ - The validator is being compared by an intermediate cache to the
+ validator stored in its cache entry for the entity, and
+
+ - That cache entry includes a Date value, which gives the time
+ when the origin server sent the original response, and
+
+ - The presented Last-Modified time is at least 60 seconds before
+ the Date value.
+
+ This method relies on the fact that if two different responses were
+ sent by the origin server during the same second, but both had the
+ same Last-Modified time, then at least one of those responses would
+ have a Date value equal to its Last-Modified time. The arbitrary 60-
+ second limit guards against the possibility that the Date and Last-
+ Modified values are generated from different clocks, or at somewhat
+ different times during the preparation of the response. An
+ implementation MAY use a value larger than 60 seconds, if it is
+ believed that 60 seconds is too short.
+
+ If a client wishes to perform a sub-range retrieval on a value for
+ which it has only a Last-Modified time and no opaque validator, it
+ MAY do this only if the Last-Modified time is strong in the sense
+ described here.
+
+ A cache or origin server receiving a conditional request, other than
+ a full-body GET request, MUST use the strong comparison function to
+ evaluate the condition.
+
+ These rules allow HTTP/1.1 caches and clients to safely perform sub-
+ range retrievals on values that have been obtained from HTTP/1.0
+
+ servers.
+
+13.3.4 Rules for When to Use Entity Tags and Last-Modified Dates
+
+ We adopt a set of rules and recommendations for origin servers,
+ clients, and caches regarding when various validator types ought to
+ be used, and for what purposes.
+
+ HTTP/1.1 origin servers:
+
+ - SHOULD send an entity tag validator unless it is not feasible to
+ generate one.
+
+ - MAY send a weak entity tag instead of a strong entity tag, if
+ performance considerations support the use of weak entity tags,
+ or if it is unfeasible to send a strong entity tag.
+
+ - SHOULD send a Last-Modified value if it is feasible to send one,
+ unless the risk of a breakdown in semantic transparency that
+ could result from using this date in an If-Modified-Since header
+ would lead to serious problems.
+
+ In other words, the preferred behavior for an HTTP/1.1 origin server
+ is to send both a strong entity tag and a Last-Modified value.
+
+ In order to be legal, a strong entity tag MUST change whenever the
+ associated entity value changes in any way. A weak entity tag SHOULD
+ change whenever the associated entity changes in a semantically
+ significant way.
+
+ Note: in order to provide semantically transparent caching, an
+ origin server must avoid reusing a specific strong entity tag
+ value for two different entities, or reusing a specific weak
+ entity tag value for two semantically different entities. Cache
+ entries might persist for arbitrarily long periods, regardless of
+ expiration times, so it might be inappropriate to expect that a
+ cache will never again attempt to validate an entry using a
+ validator that it obtained at some point in the past.
+
+ HTTP/1.1 clients:
+
+ - If an entity tag has been provided by the origin server, MUST
+ use that entity tag in any cache-conditional request (using If-
+ Match or If-None-Match).
+
+ - If only a Last-Modified value has been provided by the origin
+ server, SHOULD use that value in non-subrange cache-conditional
+ requests (using If-Modified-Since).
+
+ - If only a Last-Modified value has been provided by an HTTP/1.0
+ origin server, MAY use that value in subrange cache-conditional
+ requests (using If-Unmodified-Since:). The user agent SHOULD
+ provide a way to disable this, in case of difficulty.
+
+ - If both an entity tag and a Last-Modified value have been
+ provided by the origin server, SHOULD use both validators in
+ cache-conditional requests. This allows both HTTP/1.0 and
+ HTTP/1.1 caches to respond appropriately.
+
+ An HTTP/1.1 origin server, upon receiving a conditional request that
+ includes both a Last-Modified date (e.g., in an If-Modified-Since or
+ If-Unmodified-Since header field) and one or more entity tags (e.g.,
+ in an If-Match, If-None-Match, or If-Range header field) as cache
+ validators, MUST NOT return a response status of 304 (Not Modified)
+ unless doing so is consistent with all of the conditional header
+ fields in the request.
+
+ An HTTP/1.1 caching proxy, upon receiving a conditional request that
+ includes both a Last-Modified date and one or more entity tags as
+ cache validators, MUST NOT return a locally cached response to the
+ client unless that cached response is consistent with all of the
+ conditional header fields in the request.
+
+ Note: The general principle behind these rules is that HTTP/1.1
+ servers and clients should transmit as much non-redundant
+ information as is available in their responses and requests.
+ HTTP/1.1 systems receiving this information will make the most
+ conservative assumptions about the validators they receive.
+
+ HTTP/1.0 clients and caches will ignore entity tags. Generally,
+ last-modified values received or used by these systems will
+ support transparent and efficient caching, and so HTTP/1.1 origin
+ servers should provide Last-Modified values. In those rare cases
+ where the use of a Last-Modified value as a validator by an
+ HTTP/1.0 system could result in a serious problem, then HTTP/1.1
+ origin servers should not provide one.
+
+13.3.5 Non-validating Conditionals
+
+ The principle behind entity tags is that only the service author
+ knows the semantics of a resource well enough to select an
+ appropriate cache validation mechanism, and the specification of any
+ validator comparison function more complex than byte-equality would
+ open up a can of worms. Thus, comparisons of any other headers
+ (except Last-Modified, for compatibility with HTTP/1.0) are never
+ used for purposes of validating a cache entry.
+
+13.4 Response Cacheability
+
+ Unless specifically constrained by a cache-control (section 14.9)
+ directive, a caching system MAY always store a successful response
+ (see section 13.8) as a cache entry, MAY return it without validation
+ if it is fresh, and MAY return it after successful validation. If
+ there is neither a cache validator nor an explicit expiration time
+ associated with a response, we do not expect it to be cached, but
+ certain caches MAY violate this expectation (for example, when little
+ or no network connectivity is available). A client can usually detect
+ that such a response was taken from a cache by comparing the Date
+ header to the current time.
+
+ Note: some HTTP/1.0 caches are known to violate this expectation
+ without providing any Warning.
+
+ However, in some cases it might be inappropriate for a cache to
+ retain an entity, or to return it in response to a subsequent
+ request. This might be because absolute semantic transparency is
+ deemed necessary by the service author, or because of security or
+ privacy considerations. Certain cache-control directives are
+ therefore provided so that the server can indicate that certain
+ resource entities, or portions thereof, are not to be cached
+ regardless of other considerations.
+
+ Note that section 14.8 normally prevents a shared cache from saving
+ and returning a response to a previous request if that request
+ included an Authorization header.
+
+ A response received with a status code of 200, 203, 206, 300, 301 or
+ 410 MAY be stored by a cache and used in reply to a subsequent
+ request, subject to the expiration mechanism, unless a cache-control
+ directive prohibits caching. However, a cache that does not support
+ the Range and Content-Range headers MUST NOT cache 206 (Partial
+ Content) responses.
+
+ A response received with any other status code (e.g. status codes 302
+ and 307) MUST NOT be returned in a reply to a subsequent request
+ unless there are cache-control directives or another header(s) that
+ explicitly allow it. For example, these include the following: an
+ Expires header (section 14.21); a "max-age", "s-maxage", "must-
+ revalidate", "proxy-revalidate", "public" or "private" cache-control
+ directive (section 14.9).
+
+13.5 Constructing Responses From Caches
+
+ The purpose of an HTTP cache is to store information received in
+ response to requests for use in responding to future requests. In
+ many cases, a cache simply returns the appropriate parts of a
+ response to the requester. However, if the cache holds a cache entry
+ based on a previous response, it might have to combine parts of a new
+ response with what is held in the cache entry.
+
+13.5.1 End-to-end and Hop-by-hop Headers
+
+ For the purpose of defining the behavior of caches and non-caching
+ proxies, we divide HTTP headers into two categories:
+
+ - End-to-end headers, which are transmitted to the ultimate
+ recipient of a request or response. End-to-end headers in
+ responses MUST be stored as part of a cache entry and MUST be
+ transmitted in any response formed from a cache entry.
+
+ - Hop-by-hop headers, which are meaningful only for a single
+ transport-level connection, and are not stored by caches or
+ forwarded by proxies.
+
+ The following HTTP/1.1 headers are hop-by-hop headers:
+
+ - Connection
+ - Keep-Alive
+ - Proxy-Authenticate
+ - Proxy-Authorization
+ - TE
+ - Trailers
+ - Transfer-Encoding
+ - Upgrade
+
+ All other headers defined by HTTP/1.1 are end-to-end headers.
+
+ Other hop-by-hop headers MUST be listed in a Connection header,
+ (section 14.10) to be introduced into HTTP/1.1 (or later).
+
+13.5.2 Non-modifiable Headers
+
+ Some features of the HTTP/1.1 protocol, such as Digest
+ Authentication, depend on the value of certain end-to-end headers. A
+ transparent proxy SHOULD NOT modify an end-to-end header unless the
+ definition of that header requires or specifically allows that.
+
+ A transparent proxy MUST NOT modify any of the following fields in a
+ request or response, and it MUST NOT add any of these fields if not
+ already present:
+
+ - Content-Location
+
+ - Content-MD5
+
+ - ETag
+
+ - Last-Modified
+
+ A transparent proxy MUST NOT modify any of the following fields in a
+ response:
+
+ - Expires
+
+ but it MAY add any of these fields if not already present. If an
+ Expires header is added, it MUST be given a field-value identical to
+ that of the Date header in that response.
+
+ A proxy MUST NOT modify or add any of the following fields in a
+ message that contains the no-transform cache-control directive, or in
+ any request:
+
+ - Content-Encoding
+
+ - Content-Range
+
+ - Content-Type
+
+ A non-transparent proxy MAY modify or add these fields to a message
+ that does not include no-transform, but if it does so, it MUST add a
+ Warning 214 (Transformation applied) if one does not already appear
+ in the message (see section 14.46).
+
+ Warning: unnecessary modification of end-to-end headers might
+ cause authentication failures if stronger authentication
+ mechanisms are introduced in later versions of HTTP. Such
+ authentication mechanisms MAY rely on the values of header fields
+ not listed here.
+
+ The Content-Length field of a request or response is added or deleted
+ according to the rules in section 4.4. A transparent proxy MUST
+ preserve the entity-length (section 7.2.2) of the entity-body,
+ although it MAY change the transfer-length (section 4.4).
+
+13.5.3 Combining Headers
+
+ When a cache makes a validating request to a server, and the server
+ provides a 304 (Not Modified) response or a 206 (Partial Content)
+ response, the cache then constructs a response to send to the
+ requesting client.
+
+ If the status code is 304 (Not Modified), the cache uses the entity-
+ body stored in the cache entry as the entity-body of this outgoing
+ response. If the status code is 206 (Partial Content) and the ETag or
+ Last-Modified headers match exactly, the cache MAY combine the
+ contents stored in the cache entry with the new contents received in
+ the response and use the result as the entity-body of this outgoing
+ response, (see 13.5.4).
+
+ The end-to-end headers stored in the cache entry are used for the
+ constructed response, except that
+
+ - any stored Warning headers with warn-code 1xx (see section
+ 14.46) MUST be deleted from the cache entry and the forwarded
+ response.
+
+ - any stored Warning headers with warn-code 2xx MUST be retained
+ in the cache entry and the forwarded response.
+
+ - any end-to-end headers provided in the 304 or 206 response MUST
+ replace the corresponding headers from the cache entry.
+
+ Unless the cache decides to remove the cache entry, it MUST also
+ replace the end-to-end headers stored with the cache entry with
+ corresponding headers received in the incoming response, except for
+ Warning headers as described immediately above. If a header field-
+ name in the incoming response matches more than one header in the
+ cache entry, all such old headers MUST be replaced.
+
+ In other words, the set of end-to-end headers received in the
+ incoming response overrides all corresponding end-to-end headers
+ stored with the cache entry (except for stored Warning headers with
+ warn-code 1xx, which are deleted even if not overridden).
+
+ Note: this rule allows an origin server to use a 304 (Not
+ Modified) or a 206 (Partial Content) response to update any header
+ associated with a previous response for the same entity or sub-
+ ranges thereof, although it might not always be meaningful or
+ correct to do so. This rule does not allow an origin server to use
+ a 304 (Not Modified) or a 206 (Partial Content) response to
+ entirely delete a header that it had provided with a previous
+ response.
+
+13.5.4 Combining Byte Ranges
+
+ A response might transfer only a subrange of the bytes of an entity-
+ body, either because the request included one or more Range
+ specifications, or because a connection was broken prematurely. After
+ several such transfers, a cache might have received several ranges of
+ the same entity-body.
+
+ If a cache has a stored non-empty set of subranges for an entity, and
+ an incoming response transfers another subrange, the cache MAY
+ combine the new subrange with the existing set if both the following
+ conditions are met:
+
+ - Both the incoming response and the cache entry have a cache
+ validator.
+
+ - The two cache validators match using the strong comparison
+ function (see section 13.3.3).
+
+ If either requirement is not met, the cache MUST use only the most
+ recent partial response (based on the Date values transmitted with
+ every response, and using the incoming response if these values are
+ equal or missing), and MUST discard the other partial information.
+
+13.6 Caching Negotiated Responses
+
+ Use of server-driven content negotiation (section 12.1), as indicated
+ by the presence of a Vary header field in a response, alters the
+ conditions and procedure by which a cache can use the response for
+ subsequent requests. See section 14.44 for use of the Vary header
+ field by servers.
+
+ A server SHOULD use the Vary header field to inform a cache of what
+ request-header fields were used to select among multiple
+ representations of a cacheable response subject to server-driven
+ negotiation. The set of header fields named by the Vary field value
+ is known as the "selecting" request-headers.
+
+ When the cache receives a subsequent request whose Request-URI
+ specifies one or more cache entries including a Vary header field,
+ the cache MUST NOT use such a cache entry to construct a response to
+ the new request unless all of the selecting request-headers present
+ in the new request match the corresponding stored request-headers in
+ the original request.
+
+ The selecting request-headers from two requests are defined to match
+ if and only if the selecting request-headers in the first request can
+ be transformed to the selecting request-headers in the second request
+
+ by adding or removing linear white space (LWS) at places where this
+ is allowed by the corresponding BNF, and/or combining multiple
+ message-header fields with the same field name following the rules
+ about message headers in section 4.2.
+
+ A Vary header field-value of "*" always fails to match and subsequent
+ requests on that resource can only be properly interpreted by the
+ origin server.
+
+ If the selecting request header fields for the cached entry do not
+ match the selecting request header fields of the new request, then
+ the cache MUST NOT use a cached entry to satisfy the request unless
+ it first relays the new request to the origin server in a conditional
+ request and the server responds with 304 (Not Modified), including an
+ entity tag or Content-Location that indicates the entity to be used.
+
+ If an entity tag was assigned to a cached representation, the
+ forwarded request SHOULD be conditional and include the entity tags
+ in an If-None-Match header field from all its cache entries for the
+ resource. This conveys to the server the set of entities currently
+ held by the cache, so that if any one of these entities matches the
+ requested entity, the server can use the ETag header field in its 304
+ (Not Modified) response to tell the cache which entry is appropriate.
+ If the entity-tag of the new response matches that of an existing
+ entry, the new response SHOULD be used to update the header fields of
+ the existing entry, and the result MUST be returned to the client.
+
+ If any of the existing cache entries contains only partial content
+ for the associated entity, its entity-tag SHOULD NOT be included in
+ the If-None-Match header field unless the request is for a range that
+ would be fully satisfied by that entry.
+
+ If a cache receives a successful response whose Content-Location
+ field matches that of an existing cache entry for the same Request-
+ ]URI, whose entity-tag differs from that of the existing entry, and
+ whose Date is more recent than that of the existing entry, the
+ existing entry SHOULD NOT be returned in response to future requests
+ and SHOULD be deleted from the cache.
+
+13.7 Shared and Non-Shared Caches
+
+ For reasons of security and privacy, it is necessary to make a
+ distinction between "shared" and "non-shared" caches. A non-shared
+ cache is one that is accessible only to a single user. Accessibility
+ in this case SHOULD be enforced by appropriate security mechanisms.
+ All other caches are considered to be "shared." Other sections of
+
+ this specification place certain constraints on the operation of
+ shared caches in order to prevent loss of privacy or failure of
+ access controls.
+
+13.8 Errors or Incomplete Response Cache Behavior
+
+ A cache that receives an incomplete response (for example, with fewer
+ bytes of data than specified in a Content-Length header) MAY store
+ the response. However, the cache MUST treat this as a partial
+ response. Partial responses MAY be combined as described in section
+ 13.5.4; the result might be a full response or might still be
+ partial. A cache MUST NOT return a partial response to a client
+ without explicitly marking it as such, using the 206 (Partial
+ Content) status code. A cache MUST NOT return a partial response
+ using a status code of 200 (OK).
+
+ If a cache receives a 5xx response while attempting to revalidate an
+ entry, it MAY either forward this response to the requesting client,
+ or act as if the server failed to respond. In the latter case, it MAY
+ return a previously received response unless the cached entry
+ includes the "must-revalidate" cache-control directive (see section
+ 14.9).
+
+13.9 Side Effects of GET and HEAD
+
+ Unless the origin server explicitly prohibits the caching of their
+ responses, the application of GET and HEAD methods to any resources
+ SHOULD NOT have side effects that would lead to erroneous behavior if
+ these responses are taken from a cache. They MAY still have side
+ effects, but a cache is not required to consider such side effects in
+ its caching decisions. Caches are always expected to observe an
+ origin server's explicit restrictions on caching.
+
+ We note one exception to this rule: since some applications have
+ traditionally used GETs and HEADs with query URLs (those containing a
+ "?" in the rel_path part) to perform operations with significant side
+ effects, caches MUST NOT treat responses to such URIs as fresh unless
+ the server provides an explicit expiration time. This specifically
+ means that responses from HTTP/1.0 servers for such URIs SHOULD NOT
+ be taken from a cache. See section 9.1.1 for related information.
+
+13.10 Invalidation After Updates or Deletions
+
+ The effect of certain methods performed on a resource at the origin
+ server might cause one or more existing cache entries to become non-
+ transparently invalid. That is, although they might continue to be
+ "fresh," they do not accurately reflect what the origin server would
+ return for a new request on that resource.
+
+ There is no way for the HTTP protocol to guarantee that all such
+ cache entries are marked invalid. For example, the request that
+ caused the change at the origin server might not have gone through
+ the proxy where a cache entry is stored. However, several rules help
+ reduce the likelihood of erroneous behavior.
+
+ In this section, the phrase "invalidate an entity" means that the
+ cache will either remove all instances of that entity from its
+ storage, or will mark these as "invalid" and in need of a mandatory
+ revalidation before they can be returned in response to a subsequent
+ request.
+
+ Some HTTP methods MUST cause a cache to invalidate an entity. This is
+ either the entity referred to by the Request-URI, or by the Location
+ or Content-Location headers (if present). These methods are:
+
+ - PUT
+
+ - DELETE
+
+ - POST
+
+ In order to prevent denial of service attacks, an invalidation based
+ on the URI in a Location or Content-Location header MUST only be
+ performed if the host part is the same as in the Request-URI.
+
+ A cache that passes through requests for methods it does not
+ understand SHOULD invalidate any entities referred to by the
+ Request-URI.
+
+13.11 Write-Through Mandatory
+
+ All methods that might be expected to cause modifications to the
+ origin server's resources MUST be written through to the origin
+ server. This currently includes all methods except for GET and HEAD.
+ A cache MUST NOT reply to such a request from a client before having
+ transmitted the request to the inbound server, and having received a
+ corresponding response from the inbound server. This does not prevent
+ a proxy cache from sending a 100 (Continue) response before the
+ inbound server has sent its final reply.
+
+ The alternative (known as "write-back" or "copy-back" caching) is not
+ allowed in HTTP/1.1, due to the difficulty of providing consistent
+ updates and the problems arising from server, cache, or network
+ failure prior to write-back.
+
+13.12 Cache Replacement
+
+ If a new cacheable (see sections 14.9.2, 13.2.5, 13.2.6 and 13.8)
+ response is received from a resource while any existing responses for
+ the same resource are cached, the cache SHOULD use the new response
+ to reply to the current request. It MAY insert it into cache storage
+ and MAY, if it meets all other requirements, use it to respond to any
+ future requests that would previously have caused the old response to
+ be returned. If it inserts the new response into cache storage the
+ rules in section 13.5.3 apply.
+
+ Note: a new response that has an older Date header value than
+ existing cached responses is not cacheable.
+
+13.13 History Lists
+
+ User agents often have history mechanisms, such as "Back" buttons and
+ history lists, which can be used to redisplay an entity retrieved
+ earlier in a session.
+
+ History mechanisms and caches are different. In particular history
+ mechanisms SHOULD NOT try to show a semantically transparent view of
+ the current state of a resource. Rather, a history mechanism is meant
+ to show exactly what the user saw at the time when the resource was
+ retrieved.
+
+ By default, an expiration time does not apply to history mechanisms.
+ If the entity is still in storage, a history mechanism SHOULD display
+ it even if the entity has expired, unless the user has specifically
+ configured the agent to refresh expired history documents.
+
+ This is not to be construed to prohibit the history mechanism from
+ telling the user that a view might be stale.
+
+ Note: if history list mechanisms unnecessarily prevent users from
+ viewing stale resources, this will tend to force service authors
+ to avoid using HTTP expiration controls and cache controls when
+ they would otherwise like to. Service authors may consider it
+ important that users not be presented with error messages or
+ warning messages when they use navigation controls (such as BACK)
+ to view previously fetched resources. Even though sometimes such
+ resources ought not to cached, or ought to expire quickly, user
+ interface considerations may force service authors to resort to
+ other means of preventing caching (e.g. "once-only" URLs) in order
+ not to suffer the effects of improperly functioning history
+ mechanisms.
+
+14 Header Field Definitions
+
+ This section defines the syntax and semantics of all standard
+ HTTP/1.1 header fields. For entity-header fields, both sender and
+ recipient refer to either the client or the server, depending on who
+ sends and who receives the entity.
+
+14.1 Accept
+
+ The Accept request-header field can be used to specify certain media
+ types which are acceptable for the response. Accept headers can be
+ used to indicate that the request is specifically limited to a small
+ set of desired types, as in the case of a request for an in-line
+ image.
+
+ Accept = "Accept" ":"
+ #( media-range [ accept-params ] )
+
+ media-range = ( "*/*"
+ | ( type "/" "*" )
+ | ( type "/" subtype )
+ ) *( ";" parameter )
+ accept-params = ";" "q" "=" qvalue *( accept-extension )
+ accept-extension = ";" token [ "=" ( token | quoted-string ) ]
+
+ The asterisk "*" character is used to group media types into ranges,
+ with "*/*" indicating all media types and "type/*" indicating all
+ subtypes of that type. The media-range MAY include media type
+ parameters that are applicable to that range.
+
+ Each media-range MAY be followed by one or more accept-params,
+ beginning with the "q" parameter for indicating a relative quality
+ factor. The first "q" parameter (if any) separates the media-range
+ parameter(s) from the accept-params. Quality factors allow the user
+ or user agent to indicate the relative degree of preference for that
+ media-range, using the qvalue scale from 0 to 1 (section 3.9). The
+ default value is q=1.
+
+ Note: Use of the "q" parameter name to separate media type
+ parameters from Accept extension parameters is due to historical
+ practice. Although this prevents any media type parameter named
+ "q" from being used with a media range, such an event is believed
+ to be unlikely given the lack of any "q" parameters in the IANA
+ media type registry and the rare usage of any media type
+ parameters in Accept. Future media types are discouraged from
+ registering any parameter named "q".
+
+ The example
+
+ Accept: audio/*; q=0.2, audio/basic
+
+ SHOULD be interpreted as "I prefer audio/basic, but send me any audio
+ type if it is the best available after an 80% mark-down in quality."
+
+ If no Accept header field is present, then it is assumed that the
+ client accepts all media types. If an Accept header field is present,
+ and if the server cannot send a response which is acceptable
+ according to the combined Accept field value, then the server SHOULD
+ send a 406 (not acceptable) response.
+
+ A more elaborate example is
+
+ Accept: text/plain; q=0.5, text/html,
+ text/x-dvi; q=0.8, text/x-c
+
+ Verbally, this would be interpreted as "text/html and text/x-c are
+ the preferred media types, but if they do not exist, then send the
+ text/x-dvi entity, and if that does not exist, send the text/plain
+ entity."
+
+ Media ranges can be overridden by more specific media ranges or
+ specific media types. If more than one media range applies to a given
+ type, the most specific reference has precedence. For example,
+
+ Accept: text/*, text/html, text/html;level=1, */*
+
+ have the following precedence:
+
+ 1) text/html;level=1
+ 2) text/html
+ 3) text/*
+ 4) */*
+
+ The media type quality factor associated with a given type is
+ determined by finding the media range with the highest precedence
+ which matches that type. For example,
+
+ Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1,
+ text/html;level=2;q=0.4, */*;q=0.5
+
+ would cause the following values to be associated:
+
+ text/html;level=1 = 1
+ text/html = 0.7
+ text/plain = 0.3
+
+ image/jpeg = 0.5
+ text/html;level=2 = 0.4
+ text/html;level=3 = 0.7
+
+ Note: A user agent might be provided with a default set of quality
+ values for certain media ranges. However, unless the user agent is
+ a closed system which cannot interact with other rendering agents,
+ this default set ought to be configurable by the user.
+
+14.2 Accept-Charset
+
+ The Accept-Charset request-header field can be used to indicate what
+ character sets are acceptable for the response. This field allows
+ clients capable of understanding more comprehensive or special-
+ purpose character sets to signal that capability to a server which is
+ capable of representing documents in those character sets.
+
+ Accept-Charset = "Accept-Charset" ":"
+ 1#( ( charset | "*" )[ ";" "q" "=" qvalue ] )
+
+ Character set values are described in section 3.4. Each charset MAY
+ be given an associated quality value which represents the user's
+ preference for that charset. The default value is q=1. An example is
+
+ Accept-Charset: iso-8859-5, unicode-1-1;q=0.8
+
+ The special value "*", if present in the Accept-Charset field,
+ matches every character set (including ISO-8859-1) which is not
+ mentioned elsewhere in the Accept-Charset field. If no "*" is present
+ in an Accept-Charset field, then all character sets not explicitly
+ mentioned get a quality value of 0, except for ISO-8859-1, which gets
+ a quality value of 1 if not explicitly mentioned.
+
+ If no Accept-Charset header is present, the default is that any
+ character set is acceptable. If an Accept-Charset header is present,
+ and if the server cannot send a response which is acceptable
+ according to the Accept-Charset header, then the server SHOULD send
+ an error response with the 406 (not acceptable) status code, though
+ the sending of an unacceptable response is also allowed.
+
+14.3 Accept-Encoding
+
+ The Accept-Encoding request-header field is similar to Accept, but
+ restricts the content-codings (section 3.5) that are acceptable in
+ the response.
+
+ Accept-Encoding = "Accept-Encoding" ":"
+
+ 1#( codings [ ";" "q" "=" qvalue ] )
+ codings = ( content-coding | "*" )
+
+ Examples of its use are:
+
+ Accept-Encoding: compress, gzip
+ Accept-Encoding:
+ Accept-Encoding: *
+ Accept-Encoding: compress;q=0.5, gzip;q=1.0
+ Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0
+
+ A server tests whether a content-coding is acceptable, according to
+ an Accept-Encoding field, using these rules:
+
+ 1. If the content-coding is one of the content-codings listed in
+ the Accept-Encoding field, then it is acceptable, unless it is
+ accompanied by a qvalue of 0. (As defined in section 3.9, a
+ qvalue of 0 means "not acceptable.")
+
+ 2. The special "*" symbol in an Accept-Encoding field matches any
+ available content-coding not explicitly listed in the header
+ field.
+
+ 3. If multiple content-codings are acceptable, then the acceptable
+ content-coding with the highest non-zero qvalue is preferred.
+
+ 4. The "identity" content-coding is always acceptable, unless
+ specifically refused because the Accept-Encoding field includes
+ "identity;q=0", or because the field includes "*;q=0" and does
+ not explicitly include the "identity" content-coding. If the
+ Accept-Encoding field-value is empty, then only the "identity"
+ encoding is acceptable.
+
+ If an Accept-Encoding field is present in a request, and if the
+ server cannot send a response which is acceptable according to the
+ Accept-Encoding header, then the server SHOULD send an error response
+ with the 406 (Not Acceptable) status code.
+
+ If no Accept-Encoding field is present in a request, the server MAY
+ assume that the client will accept any content coding. In this case,
+ if "identity" is one of the available content-codings, then the
+ server SHOULD use the "identity" content-coding, unless it has
+ additional information that a different content-coding is meaningful
+ to the client.
+
+ Note: If the request does not include an Accept-Encoding field,
+ and if the "identity" content-coding is unavailable, then
+ content-codings commonly understood by HTTP/1.0 clients (i.e.,
+
+ "gzip" and "compress") are preferred; some older clients
+ improperly display messages sent with other content-codings. The
+ server might also make this decision based on information about
+ the particular user-agent or client.
+
+ Note: Most HTTP/1.0 applications do not recognize or obey qvalues
+ associated with content-codings. This means that qvalues will not
+ work and are not permitted with x-gzip or x-compress.
+
+14.4 Accept-Language
+
+ The Accept-Language request-header field is similar to Accept, but
+ restricts the set of natural languages that are preferred as a
+ response to the request. Language tags are defined in section 3.10.
+
+ Accept-Language = "Accept-Language" ":"
+ 1#( language-range [ ";" "q" "=" qvalue ] )
+ language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
+
+ Each language-range MAY be given an associated quality value which
+ represents an estimate of the user's preference for the languages
+ specified by that range. The quality value defaults to "q=1". For
+ example,
+
+ Accept-Language: da, en-gb;q=0.8, en;q=0.7
+
+ would mean: "I prefer Danish, but will accept British English and
+ other types of English." A language-range matches a language-tag if
+ it exactly equals the tag, or if it exactly equals a prefix of the
+ tag such that the first tag character following the prefix is "-".
+ The special range "*", if present in the Accept-Language field,
+ matches every tag not matched by any other range present in the
+ Accept-Language field.
+
+ Note: This use of a prefix matching rule does not imply that
+ language tags are assigned to languages in such a way that it is
+ always true that if a user understands a language with a certain
+ tag, then this user will also understand all languages with tags
+ for which this tag is a prefix. The prefix rule simply allows the
+ use of prefix tags if this is the case.
+
+ The language quality factor assigned to a language-tag by the
+ Accept-Language field is the quality value of the longest language-
+ range in the field that matches the language-tag. If no language-
+ range in the field matches the tag, the language quality factor
+ assigned is 0. If no Accept-Language header is present in the
+ request, the server
+
+ SHOULD assume that all languages are equally acceptable. If an
+ Accept-Language header is present, then all languages which are
+ assigned a quality factor greater than 0 are acceptable.
+
+ It might be contrary to the privacy expectations of the user to send
+ an Accept-Language header with the complete linguistic preferences of
+ the user in every request. For a discussion of this issue, see
+ section 15.1.4.
+
+ As intelligibility is highly dependent on the individual user, it is
+ recommended that client applications make the choice of linguistic
+ preference available to the user. If the choice is not made
+ available, then the Accept-Language header field MUST NOT be given in
+ the request.
+
+ Note: When making the choice of linguistic preference available to
+ the user, we remind implementors of the fact that users are not
+ familiar with the details of language matching as described above,
+ and should provide appropriate guidance. As an example, users
+ might assume that on selecting "en-gb", they will be served any
+ kind of English document if British English is not available. A
+ user agent might suggest in such a case to add "en" to get the
+ best matching behavior.
+
+14.5 Accept-Ranges
+
+ The Accept-Ranges response-header field allows the server to
+ indicate its acceptance of range requests for a resource:
+
+ Accept-Ranges = "Accept-Ranges" ":" acceptable-ranges
+ acceptable-ranges = 1#range-unit | "none"
+
+ Origin servers that accept byte-range requests MAY send
+
+ Accept-Ranges: bytes
+
+ but are not required to do so. Clients MAY generate byte-range
+ requests without having received this header for the resource
+ involved. Range units are defined in section 3.12.
+
+ Servers that do not accept any kind of range request for a
+ resource MAY send
+
+ Accept-Ranges: none
+
+ to advise the client not to attempt a range request.
+
+14.6 Age
+
+ The Age response-header field conveys the sender's estimate of the
+ amount of time since the response (or its revalidation) was
+ generated at the origin server. A cached response is "fresh" if
+ its age does not exceed its freshness lifetime. Age values are
+ calculated as specified in section 13.2.3.
+
+ Age = "Age" ":" age-value
+ age-value = delta-seconds
+
+ Age values are non-negative decimal integers, representing time in
+ seconds.
+
+ If a cache receives a value larger than the largest positive
+ integer it can represent, or if any of its age calculations
+ overflows, it MUST transmit an Age header with a value of
+ 2147483648 (2^31). An HTTP/1.1 server that includes a cache MUST
+ include an Age header field in every response generated from its
+ own cache. Caches SHOULD use an arithmetic type of at least 31
+ bits of range.
+
+14.7 Allow
+
+ The Allow entity-header field lists the set of methods supported
+ by the resource identified by the Request-URI. The purpose of this
+ field is strictly to inform the recipient of valid methods
+ associated with the resource. An Allow header field MUST be
+ present in a 405 (Method Not Allowed) response.
+
+ Allow = "Allow" ":" #Method
+
+ Example of use:
+
+ Allow: GET, HEAD, PUT
+
+ This field cannot prevent a client from trying other methods.
+ However, the indications given by the Allow header field value
+ SHOULD be followed. The actual set of allowed methods is defined
+ by the origin server at the time of each request.
+
+ The Allow header field MAY be provided with a PUT request to
+ recommend the methods to be supported by the new or modified
+ resource. The server is not required to support these methods and
+ SHOULD include an Allow header in the response giving the actual
+ supported methods.
+
+ A proxy MUST NOT modify the Allow header field even if it does not
+ understand all the methods specified, since the user agent might
+ have other means of communicating with the origin server.
+
+14.8 Authorization
+
+ A user agent that wishes to authenticate itself with a server--
+ usually, but not necessarily, after receiving a 401 response--does
+ so by including an Authorization request-header field with the
+ request. The Authorization field value consists of credentials
+ containing the authentication information of the user agent for
+ the realm of the resource being requested.
+
+ Authorization = "Authorization" ":" credentials
+
+ HTTP access authentication is described in "HTTP Authentication:
+ Basic and Digest Access Authentication" [43]. If a request is
+ authenticated and a realm specified, the same credentials SHOULD
+ be valid for all other requests within this realm (assuming that
+ the authentication scheme itself does not require otherwise, such
+ as credentials that vary according to a challenge value or using
+ synchronized clocks).
+
+ When a shared cache (see section 13.7) receives a request
+ containing an Authorization field, it MUST NOT return the
+ corresponding response as a reply to any other request, unless one
+ of the following specific exceptions holds:
+
+ 1. If the response includes the "s-maxage" cache-control
+ directive, the cache MAY use that response in replying to a
+ subsequent request. But (if the specified maximum age has
+ passed) a proxy cache MUST first revalidate it with the origin
+ server, using the request-headers from the new request to allow
+ the origin server to authenticate the new request. (This is the
+ defined behavior for s-maxage.) If the response includes "s-
+ maxage=0", the proxy MUST always revalidate it before re-using
+ it.
+
+ 2. If the response includes the "must-revalidate" cache-control
+ directive, the cache MAY use that response in replying to a
+ subsequent request. But if the response is stale, all caches
+ MUST first revalidate it with the origin server, using the
+ request-headers from the new request to allow the origin server
+ to authenticate the new request.
+
+ 3. If the response includes the "public" cache-control directive,
+ it MAY be returned in reply to any subsequent request.
+
+14.9 Cache-Control
+
+ The Cache-Control general-header field is used to specify directives
+ that MUST be obeyed by all caching mechanisms along the
+ request/response chain. The directives specify behavior intended to
+ prevent caches from adversely interfering with the request or
+ response. These directives typically override the default caching
+ algorithms. Cache directives are unidirectional in that the presence
+ of a directive in a request does not imply that the same directive is
+ to be given in the response.
+
+ Note that HTTP/1.0 caches might not implement Cache-Control and
+ might only implement Pragma: no-cache (see section 14.32).
+
+ Cache directives MUST be passed through by a proxy or gateway
+ application, regardless of their significance to that application,
+ since the directives might be applicable to all recipients along the
+ request/response chain. It is not possible to specify a cache-
+ directive for a specific cache.
+
+ Cache-Control = "Cache-Control" ":" 1#cache-directive
+
+ cache-directive = cache-request-directive
+ | cache-response-directive
+
+ cache-request-directive =
+ "no-cache" ; Section 14.9.1
+ | "no-store" ; Section 14.9.2
+ | "max-age" "=" delta-seconds ; Section 14.9.3, 14.9.4
+ | "max-stale" [ "=" delta-seconds ] ; Section 14.9.3
+ | "min-fresh" "=" delta-seconds ; Section 14.9.3
+ | "no-transform" ; Section 14.9.5
+ | "only-if-cached" ; Section 14.9.4
+ | cache-extension ; Section 14.9.6
+
+ cache-response-directive =
+ "public" ; Section 14.9.1
+ | "private" [ "=" &lt;"&gt; 1#field-name &lt;"&gt; ] ; Section 14.9.1
+ | "no-cache" [ "=" &lt;"&gt; 1#field-name &lt;"&gt; ]; Section 14.9.1
+ | "no-store" ; Section 14.9.2
+ | "no-transform" ; Section 14.9.5
+ | "must-revalidate" ; Section 14.9.4
+ | "proxy-revalidate" ; Section 14.9.4
+ | "max-age" "=" delta-seconds ; Section 14.9.3
+ | "s-maxage" "=" delta-seconds ; Section 14.9.3
+ | cache-extension ; Section 14.9.6
+
+ cache-extension = token [ "=" ( token | quoted-string ) ]
+
+ When a directive appears without any 1#field-name parameter, the
+ directive applies to the entire request or response. When such a
+ directive appears with a 1#field-name parameter, it applies only to
+ the named field or fields, and not to the rest of the request or
+ response. This mechanism supports extensibility; implementations of
+ future versions of the HTTP protocol might apply these directives to
+ header fields not defined in HTTP/1.1.
+
+ The cache-control directives can be broken down into these general
+ categories:
+
+ - Restrictions on what are cacheable; these may only be imposed by
+ the origin server.
+
+ - Restrictions on what may be stored by a cache; these may be
+ imposed by either the origin server or the user agent.
+
+ - Modifications of the basic expiration mechanism; these may be
+ imposed by either the origin server or the user agent.
+
+ - Controls over cache revalidation and reload; these may only be
+ imposed by a user agent.
+
+ - Control over transformation of entities.
+
+ - Extensions to the caching system.
+
+14.9.1 What is Cacheable
+
+ By default, a response is cacheable if the requirements of the
+ request method, request header fields, and the response status
+ indicate that it is cacheable. Section 13.4 summarizes these defaults
+ for cacheability. The following Cache-Control response directives
+ allow an origin server to override the default cacheability of a
+ response:
+
+ public
+ Indicates that the response MAY be cached by any cache, even if it
+ would normally be non-cacheable or cacheable only within a non-
+ shared cache. (See also Authorization, section 14.8, for
+ additional details.)
+
+ private
+ Indicates that all or part of the response message is intended for
+ a single user and MUST NOT be cached by a shared cache. This
+ allows an origin server to state that the specified parts of the
+
+ response are intended for only one user and are not a valid
+ response for requests by other users. A private (non-shared) cache
+ MAY cache the response.
+
+ Note: This usage of the word private only controls where the
+ response may be cached, and cannot ensure the privacy of the
+ message content.
+
+ no-cache
+ If the no-cache directive does not specify a field-name, then a
+ cache MUST NOT use the response to satisfy a subsequent request
+ without successful revalidation with the origin server. This
+ allows an origin server to prevent caching even by caches that
+ have been configured to return stale responses to client requests.
+
+ If the no-cache directive does specify one or more field-names,
+ then a cache MAY use the response to satisfy a subsequent request,
+ subject to any other restrictions on caching. However, the
+ specified field-name(s) MUST NOT be sent in the response to a
+ subsequent request without successful revalidation with the origin
+ server. This allows an origin server to prevent the re-use of
+ certain header fields in a response, while still allowing caching
+ of the rest of the response.
+
+ Note: Most HTTP/1.0 caches will not recognize or obey this
+ directive.
+
+14.9.2 What May be Stored by Caches
+
+ no-store
+ The purpose of the no-store directive is to prevent the
+ inadvertent release or retention of sensitive information (for
+ example, on backup tapes). The no-store directive applies to the
+ entire message, and MAY be sent either in a response or in a
+ request. If sent in a request, a cache MUST NOT store any part of
+ either this request or any response to it. If sent in a response,
+ a cache MUST NOT store any part of either this response or the
+ request that elicited it. This directive applies to both non-
+ shared and shared caches. "MUST NOT store" in this context means
+ that the cache MUST NOT intentionally store the information in
+ non-volatile storage, and MUST make a best-effort attempt to
+ remove the information from volatile storage as promptly as
+ possible after forwarding it.
+
+ Even when this directive is associated with a response, users
+ might explicitly store such a response outside of the caching
+ system (e.g., with a "Save As" dialog). History buffers MAY store
+ such responses as part of their normal operation.
+
+ The purpose of this directive is to meet the stated requirements
+ of certain users and service authors who are concerned about
+ accidental releases of information via unanticipated accesses to
+ cache data structures. While the use of this directive might
+ improve privacy in some cases, we caution that it is NOT in any
+ way a reliable or sufficient mechanism for ensuring privacy. In
+ particular, malicious or compromised caches might not recognize or
+ obey this directive, and communications networks might be
+ vulnerable to eavesdropping.
+
+14.9.3 Modifications of the Basic Expiration Mechanism
+
+ The expiration time of an entity MAY be specified by the origin
+ server using the Expires header (see section 14.21). Alternatively,
+ it MAY be specified using the max-age directive in a response. When
+ the max-age cache-control directive is present in a cached response,
+ the response is stale if its current age is greater than the age
+ value given (in seconds) at the time of a new request for that
+ resource. The max-age directive on a response implies that the
+ response is cacheable (i.e., "public") unless some other, more
+ restrictive cache directive is also present.
+
+ If a response includes both an Expires header and a max-age
+ directive, the max-age directive overrides the Expires header, even
+ if the Expires header is more restrictive. This rule allows an origin
+ server to provide, for a given response, a longer expiration time to
+ an HTTP/1.1 (or later) cache than to an HTTP/1.0 cache. This might be
+ useful if certain HTTP/1.0 caches improperly calculate ages or
+ expiration times, perhaps due to desynchronized clocks.
+
+ Many HTTP/1.0 cache implementations will treat an Expires value that
+ is less than or equal to the response Date value as being equivalent
+ to the Cache-Control response directive "no-cache". If an HTTP/1.1
+ cache receives such a response, and the response does not include a
+ Cache-Control header field, it SHOULD consider the response to be
+ non-cacheable in order to retain compatibility with HTTP/1.0 servers.
+
+ Note: An origin server might wish to use a relatively new HTTP
+ cache control feature, such as the "private" directive, on a
+ network including older caches that do not understand that
+ feature. The origin server will need to combine the new feature
+ with an Expires field whose value is less than or equal to the
+ Date value. This will prevent older caches from improperly
+ caching the response.
+
+ s-maxage
+ If a response includes an s-maxage directive, then for a shared
+ cache (but not for a private cache), the maximum age specified by
+ this directive overrides the maximum age specified by either the
+ max-age directive or the Expires header. The s-maxage directive
+ also implies the semantics of the proxy-revalidate directive (see
+ section 14.9.4), i.e., that the shared cache must not use the
+ entry after it becomes stale to respond to a subsequent request
+ without first revalidating it with the origin server. The s-
+ maxage directive is always ignored by a private cache.
+
+ Note that most older caches, not compliant with this specification,
+ do not implement any cache-control directives. An origin server
+ wishing to use a cache-control directive that restricts, but does not
+ prevent, caching by an HTTP/1.1-compliant cache MAY exploit the
+ requirement that the max-age directive overrides the Expires header,
+ and the fact that pre-HTTP/1.1-compliant caches do not observe the
+ max-age directive.
+
+ Other directives allow a user agent to modify the basic expiration
+ mechanism. These directives MAY be specified on a request:
+
+ max-age
+ Indicates that the client is willing to accept a response whose
+ age is no greater than the specified time in seconds. Unless max-
+ stale directive is also included, the client is not willing to
+ accept a stale response.
+
+ min-fresh
+ Indicates that the client is willing to accept a response whose
+ freshness lifetime is no less than its current age plus the
+ specified time in seconds. That is, the client wants a response
+ that will still be fresh for at least the specified number of
+ seconds.
+
+ max-stale
+ Indicates that the client is willing to accept a response that has
+ exceeded its expiration time. If max-stale is assigned a value,
+ then the client is willing to accept a response that has exceeded
+ its expiration time by no more than the specified number of
+ seconds. If no value is assigned to max-stale, then the client is
+ willing to accept a stale response of any age.
+
+ If a cache returns a stale response, either because of a max-stale
+ directive on a request, or because the cache is configured to
+ override the expiration time of a response, the cache MUST attach a
+ Warning header to the stale response, using Warning 110 (Response is
+ stale).
+
+ A cache MAY be configured to return stale responses without
+ validation, but only if this does not conflict with any "MUST"-level
+ requirements concerning cache validation (e.g., a "must-revalidate"
+ cache-control directive).
+
+ If both the new request and the cached entry include "max-age"
+ directives, then the lesser of the two values is used for determining
+ the freshness of the cached entry for that request.
+
+14.9.4 Cache Revalidation and Reload Controls
+
+ Sometimes a user agent might want or need to insist that a cache
+ revalidate its cache entry with the origin server (and not just with
+ the next cache along the path to the origin server), or to reload its
+ cache entry from the origin server. End-to-end revalidation might be
+ necessary if either the cache or the origin server has overestimated
+ the expiration time of the cached response. End-to-end reload may be
+ necessary if the cache entry has become corrupted for some reason.
+
+ End-to-end revalidation may be requested either when the client does
+ not have its own local cached copy, in which case we call it
+ "unspecified end-to-end revalidation", or when the client does have a
+ local cached copy, in which case we call it "specific end-to-end
+ revalidation."
+
+ The client can specify these three kinds of action using Cache-
+ Control request directives:
+
+ End-to-end reload
+ The request includes a "no-cache" cache-control directive or, for
+ compatibility with HTTP/1.0 clients, "Pragma: no-cache". Field
+ names MUST NOT be included with the no-cache directive in a
+ request. The server MUST NOT use a cached copy when responding to
+ such a request.
+
+ Specific end-to-end revalidation
+ The request includes a "max-age=0" cache-control directive, which
+ forces each cache along the path to the origin server to
+ revalidate its own entry, if any, with the next cache or server.
+ The initial request includes a cache-validating conditional with
+ the client's current validator.
+
+ Unspecified end-to-end revalidation
+ The request includes "max-age=0" cache-control directive, which
+ forces each cache along the path to the origin server to
+ revalidate its own entry, if any, with the next cache or server.
+ The initial request does not include a cache-validating
+
+ conditional; the first cache along the path (if any) that holds a
+ cache entry for this resource includes a cache-validating
+ conditional with its current validator.
+
+ max-age
+ When an intermediate cache is forced, by means of a max-age=0
+ directive, to revalidate its own cache entry, and the client has
+ supplied its own validator in the request, the supplied validator
+ might differ from the validator currently stored with the cache
+ entry. In this case, the cache MAY use either validator in making
+ its own request without affecting semantic transparency.
+
+ However, the choice of validator might affect performance. The
+ best approach is for the intermediate cache to use its own
+ validator when making its request. If the server replies with 304
+ (Not Modified), then the cache can return its now validated copy
+ to the client with a 200 (OK) response. If the server replies with
+ a new entity and cache validator, however, the intermediate cache
+ can compare the returned validator with the one provided in the
+ client's request, using the strong comparison function. If the
+ client's validator is equal to the origin server's, then the
+ intermediate cache simply returns 304 (Not Modified). Otherwise,
+ it returns the new entity with a 200 (OK) response.
+
+ If a request includes the no-cache directive, it SHOULD NOT
+ include min-fresh, max-stale, or max-age.
+
+ only-if-cached
+ In some cases, such as times of extremely poor network
+ connectivity, a client may want a cache to return only those
+ responses that it currently has stored, and not to reload or
+ revalidate with the origin server. To do this, the client may
+ include the only-if-cached directive in a request. If it receives
+ this directive, a cache SHOULD either respond using a cached entry
+ that is consistent with the other constraints of the request, or
+ respond with a 504 (Gateway Timeout) status. However, if a group
+ of caches is being operated as a unified system with good internal
+ connectivity, such a request MAY be forwarded within that group of
+ caches.
+
+ must-revalidate
+ Because a cache MAY be configured to ignore a server's specified
+ expiration time, and because a client request MAY include a max-
+ stale directive (which has a similar effect), the protocol also
+ includes a mechanism for the origin server to require revalidation
+ of a cache entry on any subsequent use. When the must-revalidate
+ directive is present in a response received by a cache, that cache
+ MUST NOT use the entry after it becomes stale to respond to a
+
+ subsequent request without first revalidating it with the origin
+ server. (I.e., the cache MUST do an end-to-end revalidation every
+ time, if, based solely on the origin server's Expires or max-age
+ value, the cached response is stale.)
+
+ The must-revalidate directive is necessary to support reliable
+ operation for certain protocol features. In all circumstances an
+ HTTP/1.1 cache MUST obey the must-revalidate directive; in
+ particular, if the cache cannot reach the origin server for any
+ reason, it MUST generate a 504 (Gateway Timeout) response.
+
+ Servers SHOULD send the must-revalidate directive if and only if
+ failure to revalidate a request on the entity could result in
+ incorrect operation, such as a silently unexecuted financial
+ transaction. Recipients MUST NOT take any automated action that
+ violates this directive, and MUST NOT automatically provide an
+ unvalidated copy of the entity if revalidation fails.
+
+ Although this is not recommended, user agents operating under
+ severe connectivity constraints MAY violate this directive but, if
+ so, MUST explicitly warn the user that an unvalidated response has
+ been provided. The warning MUST be provided on each unvalidated
+ access, and SHOULD require explicit user confirmation.
+
+ proxy-revalidate
+ The proxy-revalidate directive has the same meaning as the must-
+ revalidate directive, except that it does not apply to non-shared
+ user agent caches. It can be used on a response to an
+ authenticated request to permit the user's cache to store and
+ later return the response without needing to revalidate it (since
+ it has already been authenticated once by that user), while still
+ requiring proxies that service many users to revalidate each time
+ (in order to make sure that each user has been authenticated).
+ Note that such authenticated responses also need the public cache
+ control directive in order to allow them to be cached at all.
+
+14.9.5 No-Transform Directive
+
+ no-transform
+ Implementors of intermediate caches (proxies) have found it useful
+ to convert the media type of certain entity bodies. A non-
+ transparent proxy might, for example, convert between image
+ formats in order to save cache space or to reduce the amount of
+ traffic on a slow link.
+
+ Serious operational problems occur, however, when these
+ transformations are applied to entity bodies intended for certain
+ kinds of applications. For example, applications for medical
+
+ imaging, scientific data analysis and those using end-to-end
+ authentication, all depend on receiving an entity body that is bit
+ for bit identical to the original entity-body.
+
+ Therefore, if a message includes the no-transform directive, an
+ intermediate cache or proxy MUST NOT change those headers that are
+ listed in section 13.5.2 as being subject to the no-transform
+ directive. This implies that the cache or proxy MUST NOT change
+ any aspect of the entity-body that is specified by these headers,
+ including the value of the entity-body itself.
+
+14.9.6 Cache Control Extensions
+
+ The Cache-Control header field can be extended through the use of one
+ or more cache-extension tokens, each with an optional assigned value.
+ Informational extensions (those which do not require a change in
+ cache behavior) MAY be added without changing the semantics of other
+ directives. Behavioral extensions are designed to work by acting as
+ modifiers to the existing base of cache directives. Both the new
+ directive and the standard directive are supplied, such that
+ applications which do not understand the new directive will default
+ to the behavior specified by the standard directive, and those that
+ understand the new directive will recognize it as modifying the
+ requirements associated with the standard directive. In this way,
+ extensions to the cache-control directives can be made without
+ requiring changes to the base protocol.
+
+ This extension mechanism depends on an HTTP cache obeying all of the
+ cache-control directives defined for its native HTTP-version, obeying
+ certain extensions, and ignoring all directives that it does not
+ understand.
+
+ For example, consider a hypothetical new response directive called
+ community which acts as a modifier to the private directive. We
+ define this new directive to mean that, in addition to any non-shared
+ cache, any cache which is shared only by members of the community
+ named within its value may cache the response. An origin server
+ wishing to allow the UCI community to use an otherwise private
+ response in their shared cache(s) could do so by including
+
+ Cache-Control: private, community="UCI"
+
+ A cache seeing this header field will act correctly even if the cache
+ does not understand the community cache-extension, since it will also
+ see and understand the private directive and thus default to the safe
+ behavior.
+
+ Unrecognized cache-directives MUST be ignored; it is assumed that any
+ cache-directive likely to be unrecognized by an HTTP/1.1 cache will
+ be combined with standard directives (or the response's default
+ cacheability) such that the cache behavior will remain minimally
+ correct even if the cache does not understand the extension(s).
+
+14.10 Connection
+
+ The Connection general-header field allows the sender to specify
+ options that are desired for that particular connection and MUST NOT
+ be communicated by proxies over further connections.
+
+ The Connection header has the following grammar:
+
+ Connection = "Connection" ":" 1#(connection-token)
+ connection-token = token
+
+ HTTP/1.1 proxies MUST parse the Connection header field before a
+ message is forwarded and, for each connection-token in this field,
+ remove any header field(s) from the message with the same name as the
+ connection-token. Connection options are signaled by the presence of
+ a connection-token in the Connection header field, not by any
+ corresponding additional header field(s), since the additional header
+ field may not be sent if there are no parameters associated with that
+ connection option.
+
+ Message headers listed in the Connection header MUST NOT include
+ end-to-end headers, such as Cache-Control.
+
+ HTTP/1.1 defines the "close" connection option for the sender to
+ signal that the connection will be closed after completion of the
+ response. For example,
+
+ Connection: close
+
+ in either the request or the response header fields indicates that
+ the connection SHOULD NOT be considered `persistent' (section 8.1)
+ after the current request/response is complete.
+
+ HTTP/1.1 applications that do not support persistent connections MUST
+ include the "close" connection option in every message.
+
+ A system receiving an HTTP/1.0 (or lower-version) message that
+ includes a Connection header MUST, for each connection-token in this
+ field, remove and ignore any header field(s) from the message with
+ the same name as the connection-token. This protects against mistaken
+ forwarding of such header fields by pre-HTTP/1.1 proxies. See section
+ 19.6.2.
+
+14.11 Content-Encoding
+
+ The Content-Encoding entity-header field is used as a modifier to the
+ media-type. When present, its value indicates what additional content
+ codings have been applied to the entity-body, and thus what decoding
+ mechanisms must be applied in order to obtain the media-type
+ referenced by the Content-Type header field. Content-Encoding is
+ primarily used to allow a document to be compressed without losing
+ the identity of its underlying media type.
+
+ Content-Encoding = "Content-Encoding" ":" 1#content-coding
+
+ Content codings are defined in section 3.5. An example of its use is
+
+ Content-Encoding: gzip
+
+ The content-coding is a characteristic of the entity identified by
+ the Request-URI. Typically, the entity-body is stored with this
+ encoding and is only decoded before rendering or analogous usage.
+ However, a non-transparent proxy MAY modify the content-coding if the
+ new coding is known to be acceptable to the recipient, unless the
+ "no-transform" cache-control directive is present in the message.
+
+ If the content-coding of an entity is not "identity", then the
+ response MUST include a Content-Encoding entity-header (section
+ 14.11) that lists the non-identity content-coding(s) used.
+
+ If the content-coding of an entity in a request message is not
+ acceptable to the origin server, the server SHOULD respond with a
+ status code of 415 (Unsupported Media Type).
+
+ If multiple encodings have been applied to an entity, the content
+ codings MUST be listed in the order in which they were applied.
+ Additional information about the encoding parameters MAY be provided
+ by other entity-header fields not defined by this specification.
+
+14.12 Content-Language
+
+ The Content-Language entity-header field describes the natural
+ language(s) of the intended audience for the enclosed entity. Note
+ that this might not be equivalent to all the languages used within
+ the entity-body.
+
+ Content-Language = "Content-Language" ":" 1#language-tag
+
+ Language tags are defined in section 3.10. The primary purpose of
+ Content-Language is to allow a user to identify and differentiate
+ entities according to the user's own preferred language. Thus, if the
+ body content is intended only for a Danish-literate audience, the
+ appropriate field is
+
+ Content-Language: da
+
+ If no Content-Language is specified, the default is that the content
+ is intended for all language audiences. This might mean that the
+ sender does not consider it to be specific to any natural language,
+ or that the sender does not know for which language it is intended.
+
+ Multiple languages MAY be listed for content that is intended for
+ multiple audiences. For example, a rendition of the "Treaty of
+ Waitangi," presented simultaneously in the original Maori and English
+ versions, would call for
+
+ Content-Language: mi, en
+
+ However, just because multiple languages are present within an entity
+ does not mean that it is intended for multiple linguistic audiences.
+ An example would be a beginner's language primer, such as "A First
+ Lesson in Latin," which is clearly intended to be used by an
+ English-literate audience. In this case, the Content-Language would
+ properly only include "en".
+
+ Content-Language MAY be applied to any media type -- it is not
+ limited to textual documents.
+
+14.13 Content-Length
+
+ The Content-Length entity-header field indicates the size of the
+ entity-body, in decimal number of OCTETs, sent to the recipient or,
+ in the case of the HEAD method, the size of the entity-body that
+ would have been sent had the request been a GET.
+
+ Content-Length = "Content-Length" ":" 1*DIGIT
+
+ An example is
+
+ Content-Length: 3495
+
+ Applications SHOULD use this field to indicate the transfer-length of
+ the message-body, unless this is prohibited by the rules in section
+ 4.4.
+
+ Any Content-Length greater than or equal to zero is a valid value.
+ Section 4.4 describes how to determine the length of a message-body
+ if a Content-Length is not given.
+
+ Note that the meaning of this field is significantly different from
+ the corresponding definition in MIME, where it is an optional field
+ used within the "message/external-body" content-type. In HTTP, it
+ SHOULD be sent whenever the message's length can be determined prior
+ to being transferred, unless this is prohibited by the rules in
+ section 4.4.
+
+14.14 Content-Location
+
+ The Content-Location entity-header field MAY be used to supply the
+ resource location for the entity enclosed in the message when that
+ entity is accessible from a location separate from the requested
+ resource's URI. A server SHOULD provide a Content-Location for the
+ variant corresponding to the response entity; especially in the case
+ where a resource has multiple entities associated with it, and those
+ entities actually have separate locations by which they might be
+ individually accessed, the server SHOULD provide a Content-Location
+ for the particular variant which is returned.
+
+ Content-Location = "Content-Location" ":"
+ ( absoluteURI | relativeURI )
+
+ The value of Content-Location also defines the base URI for the
+ entity.
+
+ The Content-Location value is not a replacement for the original
+ requested URI; it is only a statement of the location of the resource
+ corresponding to this particular entity at the time of the request.
+ Future requests MAY specify the Content-Location URI as the request-
+ URI if the desire is to identify the source of that particular
+ entity.
+
+ A cache cannot assume that an entity with a Content-Location
+ different from the URI used to retrieve it can be used to respond to
+ later requests on that Content-Location URI. However, the Content-
+ Location can be used to differentiate between multiple entities
+ retrieved from a single requested resource, as described in section
+ 13.6.
+
+ If the Content-Location is a relative URI, the relative URI is
+ interpreted relative to the Request-URI.
+
+ The meaning of the Content-Location header in PUT or POST requests is
+ undefined; servers are free to ignore it in those cases.
+
+14.15 Content-MD5
+
+ The Content-MD5 entity-header field, as defined in <a href="http://firefly.troll.no/rfcs/rfc1864.html">RFC 1864</a> [23], is
+ an MD5 digest of the entity-body for the purpose of providing an
+ end-to-end message integrity check (MIC) of the entity-body. (Note: a
+ MIC is good for detecting accidental modification of the entity-body
+ in transit, but is not proof against malicious attacks.)
+
+ Content-MD5 = "Content-MD5" ":" md5-digest
+ md5-digest = &lt;base64 of 128 bit MD5 digest as per <a href="http://firefly.troll.no/rfcs/rfc1864.html">RFC 1864</a>&gt;
+
+ The Content-MD5 header field MAY be generated by an origin server or
+ client to function as an integrity check of the entity-body. Only
+ origin servers or clients MAY generate the Content-MD5 header field;
+ proxies and gateways MUST NOT generate it, as this would defeat its
+ value as an end-to-end integrity check. Any recipient of the entity-
+ body, including gateways and proxies, MAY check that the digest value
+ in this header field matches that of the entity-body as received.
+
+ The MD5 digest is computed based on the content of the entity-body,
+ including any content-coding that has been applied, but not including
+ any transfer-encoding applied to the message-body. If the message is
+ received with a transfer-encoding, that encoding MUST be removed
+ prior to checking the Content-MD5 value against the received entity.
+
+ This has the result that the digest is computed on the octets of the
+ entity-body exactly as, and in the order that, they would be sent if
+ no transfer-encoding were being applied.
+
+ HTTP extends <a href="http://firefly.troll.no/rfcs/rfc1864.html">RFC 1864</a> to permit the digest to be computed for MIME
+ composite media-types (e.g., multipart/* and message/rfc822), but
+ this does not change how the digest is computed as defined in the
+ preceding paragraph.
+
+ There are several consequences of this. The entity-body for composite
+ types MAY contain many body-parts, each with its own MIME and HTTP
+ headers (including Content-MD5, Content-Transfer-Encoding, and
+ Content-Encoding headers). If a body-part has a Content-Transfer-
+ Encoding or Content-Encoding header, it is assumed that the content
+ of the body-part has had the encoding applied, and the body-part is
+ included in the Content-MD5 digest as is -- i.e., after the
+ application. The Transfer-Encoding header field is not allowed within
+ body-parts.
+
+ Conversion of all line breaks to CRLF MUST NOT be done before
+ computing or checking the digest: the line break convention used in
+ the text actually transmitted MUST be left unaltered when computing
+ the digest.
+
+ Note: while the definition of Content-MD5 is exactly the same for
+ HTTP as in <a href="http://firefly.troll.no/rfcs/rfc1864.html">RFC 1864</a> for MIME entity-bodies, there are several ways
+ in which the application of Content-MD5 to HTTP entity-bodies
+ differs from its application to MIME entity-bodies. One is that
+ HTTP, unlike MIME, does not use Content-Transfer-Encoding, and
+ does use Transfer-Encoding and Content-Encoding. Another is that
+ HTTP more frequently uses binary content types than MIME, so it is
+ worth noting that, in such cases, the byte order used to compute
+ the digest is the transmission byte order defined for the type.
+ Lastly, HTTP allows transmission of text types with any of several
+ line break conventions and not just the canonical form using CRLF.
+
+14.16 Content-Range
+
+ The Content-Range entity-header is sent with a partial entity-body to
+ specify where in the full entity-body the partial body should be
+ applied. Range units are defined in section 3.12.
+
+ Content-Range = "Content-Range" ":" content-range-spec
+
+ content-range-spec = byte-content-range-spec
+ byte-content-range-spec = bytes-unit SP
+ byte-range-resp-spec "/"
+ ( instance-length | "*" )
+
+ byte-range-resp-spec = (first-byte-pos "-" last-byte-pos)
+ | "*"
+ instance-length = 1*DIGIT
+
+ The header SHOULD indicate the total length of the full entity-body,
+ unless this length is unknown or difficult to determine. The asterisk
+ "*" character means that the instance-length is unknown at the time
+ when the response was generated.
+
+ Unlike byte-ranges-specifier values (see section 14.35.1), a byte-
+ range-resp-spec MUST only specify one range, and MUST contain
+ absolute byte positions for both the first and last byte of the
+ range.
+
+ A byte-content-range-spec with a byte-range-resp-spec whose last-
+ byte-pos value is less than its first-byte-pos value, or whose
+ instance-length value is less than or equal to its last-byte-pos
+ value, is invalid. The recipient of an invalid byte-content-range-
+ spec MUST ignore it and any content transferred along with it.
+
+ A server sending a response with status code 416 (Requested range not
+ satisfiable) SHOULD include a Content-Range field with a byte-range-
+ resp-spec of "*". The instance-length specifies the current length of
+
+ the selected resource. A response with status code 206 (Partial
+ Content) MUST NOT include a Content-Range field with a byte-range-
+ resp-spec of "*".
+
+ Examples of byte-content-range-spec values, assuming that the entity
+ contains a total of 1234 bytes:
+
+ . The first 500 bytes:
+ bytes 0-499/1234
+
+ . The second 500 bytes:
+ bytes 500-999/1234
+
+ . All except for the first 500 bytes:
+ bytes 500-1233/1234
+
+ . The last 500 bytes:
+ bytes 734-1233/1234
+
+ When an HTTP message includes the content of a single range (for
+ example, a response to a request for a single range, or to a request
+ for a set of ranges that overlap without any holes), this content is
+ transmitted with a Content-Range header, and a Content-Length header
+ showing the number of bytes actually transferred. For example,
+
+ HTTP/1.1 206 Partial content
+ Date: Wed, 15 Nov 1995 06:25:24 GMT
+ Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
+ Content-Range: bytes 21010-47021/47022
+ Content-Length: 26012
+ Content-Type: image/gif
+
+ When an HTTP message includes the content of multiple ranges (for
+ example, a response to a request for multiple non-overlapping
+ ranges), these are transmitted as a multipart message. The multipart
+ media type used for this purpose is "multipart/byteranges" as defined
+ in appendix 19.2. See appendix 19.6.3 for a compatibility issue.
+
+ A response to a request for a single range MUST NOT be sent using the
+ multipart/byteranges media type. A response to a request for
+ multiple ranges, whose result is a single range, MAY be sent as a
+ multipart/byteranges media type with one part. A client that cannot
+ decode a multipart/byteranges message MUST NOT ask for multiple
+ byte-ranges in a single request.
+
+ When a client requests multiple byte-ranges in one request, the
+ server SHOULD return them in the order that they appeared in the
+ request.
+
+ If the server ignores a byte-range-spec because it is syntactically
+ invalid, the server SHOULD treat the request as if the invalid Range
+ header field did not exist. (Normally, this means return a 200
+ response containing the full entity).
+
+ If the server receives a request (other than one including an If-
+ Range request-header field) with an unsatisfiable Range request-
+ header field (that is, all of whose byte-range-spec values have a
+ first-byte-pos value greater than the current length of the selected
+ resource), it SHOULD return a response code of 416 (Requested range
+ not satisfiable) (section 10.4.17).
+
+ Note: clients cannot depend on servers to send a 416 (Requested
+ range not satisfiable) response instead of a 200 (OK) response for
+ an unsatisfiable Range request-header, since not all servers
+ implement this request-header.
+
+14.17 Content-Type
+
+ The Content-Type entity-header field indicates the media type of the
+ entity-body sent to the recipient or, in the case of the HEAD method,
+ the media type that would have been sent had the request been a GET.
+
+ Content-Type = "Content-Type" ":" media-type
+
+ Media types are defined in section 3.7. An example of the field is
+
+ Content-Type: text/html; charset=ISO-8859-4
+
+ Further discussion of methods for identifying the media type of an
+ entity is provided in section 7.2.1.
+
+14.18 Date
+
+ The Date general-header field represents the date and time at which
+ the message was originated, having the same semantics as orig-date in
+ <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a>. The field value is an HTTP-date, as described in section
+ 3.3.1; it MUST be sent in <a href="http://firefly.troll.no/rfcs/rfc1123.html">RFC 1123</a> [8]-date format.
+
+ Date = "Date" ":" HTTP-date
+
+ An example is
+
+ Date: Tue, 15 Nov 1994 08:12:31 GMT
+
+ Origin servers MUST include a Date header field in all responses,
+ except in these cases:
+
+ 1. If the response status code is 100 (Continue) or 101 (Switching
+ Protocols), the response MAY include a Date header field, at
+ the server's option.
+
+ 2. If the response status code conveys a server error, e.g. 500
+ (Internal Server Error) or 503 (Service Unavailable), and it is
+ inconvenient or impossible to generate a valid Date.
+
+ 3. If the server does not have a clock that can provide a
+ reasonable approximation of the current time, its responses
+ MUST NOT include a Date header field. In this case, the rules
+ in section 14.18.1 MUST be followed.
+
+ A received message that does not have a Date header field MUST be
+ assigned one by the recipient if the message will be cached by that
+ recipient or gatewayed via a protocol which requires a Date. An HTTP
+ implementation without a clock MUST NOT cache responses without
+ revalidating them on every use. An HTTP cache, especially a shared
+ cache, SHOULD use a mechanism, such as NTP [28], to synchronize its
+ clock with a reliable external standard.
+
+ Clients SHOULD only send a Date header field in messages that include
+ an entity-body, as in the case of the PUT and POST requests, and even
+ then it is optional. A client without a clock MUST NOT send a Date
+ header field in a request.
+
+ The HTTP-date sent in a Date header SHOULD NOT represent a date and
+ time subsequent to the generation of the message. It SHOULD represent
+ the best available approximation of the date and time of message
+ generation, unless the implementation has no means of generating a
+ reasonably accurate date and time. In theory, the date ought to
+ represent the moment just before the entity is generated. In
+ practice, the date can be generated at any time during the message
+ origination without affecting its semantic value.
+
+14.18.1 Clockless Origin Server Operation
+
+ Some origin server implementations might not have a clock available.
+ An origin server without a clock MUST NOT assign Expires or Last-
+ Modified values to a response, unless these values were associated
+ with the resource by a system or user with a reliable clock. It MAY
+ assign an Expires value that is known, at or before server
+ configuration time, to be in the past (this allows "pre-expiration"
+ of responses without storing separate Expires values for each
+ resource).
+
+14.19 ETag
+
+ The ETag response-header field provides the current value of the
+ entity tag for the requested variant. The headers used with entity
+ tags are described in sections 14.24, 14.26 and 14.44. The entity tag
+ MAY be used for comparison with other entities from the same resource
+ (see section 13.3.3).
+
+ ETag = "ETag" ":" entity-tag
+
+ Examples:
+
+ ETag: "xyzzy"
+ ETag: W/"xyzzy"
+ ETag: ""
+
+14.20 Expect
+
+ The Expect request-header field is used to indicate that particular
+ server behaviors are required by the client.
+
+ Expect = "Expect" ":" 1#expectation
+
+ expectation = "100-continue" | expectation-extension
+ expectation-extension = token [ "=" ( token | quoted-string )
+ *expect-params ]
+ expect-params = ";" token [ "=" ( token | quoted-string ) ]
+
+ A server that does not understand or is unable to comply with any of
+ the expectation values in the Expect field of a request MUST respond
+ with appropriate error status. The server MUST respond with a 417
+ (Expectation Failed) status if any of the expectations cannot be met
+ or, if there are other problems with the request, some other 4xx
+ status.
+
+ This header field is defined with extensible syntax to allow for
+ future extensions. If a server receives a request containing an
+ Expect field that includes an expectation-extension that it does not
+ support, it MUST respond with a 417 (Expectation Failed) status.
+
+ Comparison of expectation values is case-insensitive for unquoted
+ tokens (including the 100-continue token), and is case-sensitive for
+ quoted-string expectation-extensions.
+
+ The Expect mechanism is hop-by-hop: that is, an HTTP/1.1 proxy MUST
+ return a 417 (Expectation Failed) status if it receives a request
+ with an expectation that it cannot meet. However, the Expect
+ request-header itself is end-to-end; it MUST be forwarded if the
+ request is forwarded.
+
+ Many older HTTP/1.0 and HTTP/1.1 applications do not understand the
+ Expect header.
+
+ See section 8.2.3 for the use of the 100 (continue) status.
+
+14.21 Expires
+
+ The Expires entity-header field gives the date/time after which the
+ response is considered stale. A stale cache entry may not normally be
+ returned by a cache (either a proxy cache or a user agent cache)
+ unless it is first validated with the origin server (or with an
+ intermediate cache that has a fresh copy of the entity). See section
+ 13.2 for further discussion of the expiration model.
+
+ The presence of an Expires field does not imply that the original
+ resource will change or cease to exist at, before, or after that
+ time.
+
+ The format is an absolute date and time as defined by HTTP-date in
+ section 3.3.1; it MUST be in <a href="http://firefly.troll.no/rfcs/rfc1123.html">RFC 1123</a> date format:
+
+ Expires = "Expires" ":" HTTP-date
+
+ An example of its use is
+
+ Expires: Thu, 01 Dec 1994 16:00:00 GMT
+
+ Note: if a response includes a Cache-Control field with the max-
+ age directive (see section 14.9.3), that directive overrides the
+ Expires field.
+
+ HTTP/1.1 clients and caches MUST treat other invalid date formats,
+ especially including the value "0", as in the past (i.e., "already
+ expired").
+
+ To mark a response as "already expired," an origin server sends an
+ Expires date that is equal to the Date header value. (See the rules
+ for expiration calculations in section 13.2.4.)
+
+ To mark a response as "never expires," an origin server sends an
+ Expires date approximately one year from the time the response is
+ sent. HTTP/1.1 servers SHOULD NOT send Expires dates more than one
+ year in the future.
+
+ The presence of an Expires header field with a date value of some
+ time in the future on a response that otherwise would by default be
+ non-cacheable indicates that the response is cacheable, unless
+ indicated otherwise by a Cache-Control header field (section 14.9).
+
+14.22 From
+
+ The From request-header field, if given, SHOULD contain an Internet
+ e-mail address for the human user who controls the requesting user
+ agent. The address SHOULD be machine-usable, as defined by "mailbox"
+ in <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a> [9] as updated by <a href="http://firefly.troll.no/rfcs/rfc1123.html">RFC 1123</a> [8]:
+
+ From = "From" ":" mailbox
+
+ An example is:
+
+ From: <a href="mailto:webmaster@w3.org">webmaster@w3.org</a>
+
+ This header field MAY be used for logging purposes and as a means for
+ identifying the source of invalid or unwanted requests. It SHOULD NOT
+ be used as an insecure form of access protection. The interpretation
+ of this field is that the request is being performed on behalf of the
+ person given, who accepts responsibility for the method performed. In
+ particular, robot agents SHOULD include this header so that the
+ person responsible for running the robot can be contacted if problems
+ occur on the receiving end.
+
+ The Internet e-mail address in this field MAY be separate from the
+ Internet host which issued the request. For example, when a request
+ is passed through a proxy the original issuer's address SHOULD be
+ used.
+
+ The client SHOULD NOT send the From header field without the user's
+ approval, as it might conflict with the user's privacy interests or
+ their site's security policy. It is strongly recommended that the
+ user be able to disable, enable, and modify the value of this field
+ at any time prior to a request.
+
+14.23 Host
+
+ The Host request-header field specifies the Internet host and port
+ number of the resource being requested, as obtained from the original
+ URI given by the user or referring resource (generally an HTTP URL,
+
+ as described in section 3.2.2). The Host field value MUST represent
+ the naming authority of the origin server or gateway given by the
+ original URL. This allows the origin server or gateway to
+ differentiate between internally-ambiguous URLs, such as the root "/"
+ URL of a server for multiple host names on a single IP address.
+
+ Host = "Host" ":" host [ ":" port ] ; Section 3.2.2
+
+ A "host" without any trailing port information implies the default
+ port for the service requested (e.g., "80" for an HTTP URL). For
+ example, a request on the origin server for
+ &lt;<a href="http://www.w3.org/pub/WWW/">http://www.w3.org/pub/WWW/</a>&gt; would properly include:
+
+ GET /pub/WWW/ HTTP/1.1
+ Host: www.w3.org
+
+ A client MUST include a Host header field in all HTTP/1.1 request
+ messages . If the requested URI does not include an Internet host
+ name for the service being requested, then the Host header field MUST
+ be given with an empty value. An HTTP/1.1 proxy MUST ensure that any
+ request message it forwards does contain an appropriate Host header
+ field that identifies the service being requested by the proxy. All
+ Internet-based HTTP/1.1 servers MUST respond with a 400 (Bad Request)
+ status code to any HTTP/1.1 request message which lacks a Host header
+ field.
+
+ See sections 5.2 and 19.6.1.1 for other requirements relating to
+ Host.
+
+14.24 If-Match
+
+ The If-Match request-header field is used with a method to make it
+ conditional. A client that has one or more entities previously
+ obtained from the resource can verify that one of those entities is
+ current by including a list of their associated entity tags in the
+ If-Match header field. Entity tags are defined in section 3.11. The
+ purpose of this feature is to allow efficient updates of cached
+ information with a minimum amount of transaction overhead. It is also
+ used, on updating requests, to prevent inadvertent modification of
+ the wrong version of a resource. As a special case, the value "*"
+ matches any current entity of the resource.
+
+ If-Match = "If-Match" ":" ( "*" | 1#entity-tag )
+
+ If any of the entity tags match the entity tag of the entity that
+ would have been returned in the response to a similar GET request
+ (without the If-Match header) on that resource, or if "*" is given
+
+ and any current entity exists for that resource, then the server MAY
+ perform the requested method as if the If-Match header field did not
+ exist.
+
+ A server MUST use the strong comparison function (see section 13.3.3)
+ to compare the entity tags in If-Match.
+
+ If none of the entity tags match, or if "*" is given and no current
+ entity exists, the server MUST NOT perform the requested method, and
+ MUST return a 412 (Precondition Failed) response. This behavior is
+ most useful when the client wants to prevent an updating method, such
+ as PUT, from modifying a resource that has changed since the client
+ last retrieved it.
+
+ If the request would, without the If-Match header field, result in
+ anything other than a 2xx or 412 status, then the If-Match header
+ MUST be ignored.
+
+ The meaning of "If-Match: *" is that the method SHOULD be performed
+ if the representation selected by the origin server (or by a cache,
+ possibly using the Vary mechanism, see section 14.44) exists, and
+ MUST NOT be performed if the representation does not exist.
+
+ A request intended to update a resource (e.g., a PUT) MAY include an
+ If-Match header field to signal that the request method MUST NOT be
+ applied if the entity corresponding to the If-Match value (a single
+ entity tag) is no longer a representation of that resource. This
+ allows the user to indicate that they do not wish the request to be
+ successful if the resource has been changed without their knowledge.
+ Examples:
+
+ If-Match: "xyzzy"
+ If-Match: "xyzzy", "r2d2xxxx", "c3piozzzz"
+ If-Match: *
+
+ The result of a request having both an If-Match header field and
+ either an If-None-Match or an If-Modified-Since header fields is
+ undefined by this specification.
+
+14.25 If-Modified-Since
+
+ The If-Modified-Since request-header field is used with a method to
+ make it conditional: if the requested variant has not been modified
+ since the time specified in this field, an entity will not be
+ returned from the server; instead, a 304 (not modified) response will
+ be returned without any message-body.
+
+ If-Modified-Since = "If-Modified-Since" ":" HTTP-date
+
+ An example of the field is:
+
+ If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
+
+ A GET method with an If-Modified-Since header and no Range header
+ requests that the identified entity be transferred only if it has
+ been modified since the date given by the If-Modified-Since header.
+ The algorithm for determining this includes the following cases:
+
+ a) If the request would normally result in anything other than a
+ 200 (OK) status, or if the passed If-Modified-Since date is
+ invalid, the response is exactly the same as for a normal GET.
+ A date which is later than the server's current time is
+ invalid.
+
+ b) If the variant has been modified since the If-Modified-Since
+ date, the response is exactly the same as for a normal GET.
+
+ c) If the variant has not been modified since a valid If-
+ Modified-Since date, the server SHOULD return a 304 (Not
+ Modified) response.
+
+ The purpose of this feature is to allow efficient updates of cached
+ information with a minimum amount of transaction overhead.
+
+ Note: The Range request-header field modifies the meaning of If-
+ Modified-Since; see section 14.35 for full details.
+
+ Note: If-Modified-Since times are interpreted by the server, whose
+ clock might not be synchronized with the client.
+
+ Note: When handling an If-Modified-Since header field, some
+ servers will use an exact date comparison function, rather than a
+ less-than function, for deciding whether to send a 304 (Not
+ Modified) response. To get best results when sending an If-
+ Modified-Since header field for cache validation, clients are
+ advised to use the exact date string received in a previous Last-
+ Modified header field whenever possible.
+
+ Note: If a client uses an arbitrary date in the If-Modified-Since
+ header instead of a date taken from the Last-Modified header for
+ the same request, the client should be aware of the fact that this
+ date is interpreted in the server's understanding of time. The
+ client should consider unsynchronized clocks and rounding problems
+ due to the different encodings of time between the client and
+ server. This includes the possibility of race conditions if the
+ document has changed between the time it was first requested and
+ the If-Modified-Since date of a subsequent request, and the
+
+ possibility of clock-skew-related problems if the If-Modified-
+ Since date is derived from the client's clock without correction
+ to the server's clock. Corrections for different time bases
+ between client and server are at best approximate due to network
+ latency.
+
+ The result of a request having both an If-Modified-Since header field
+ and either an If-Match or an If-Unmodified-Since header fields is
+ undefined by this specification.
+
+14.26 If-None-Match
+
+ The If-None-Match request-header field is used with a method to make
+ it conditional. A client that has one or more entities previously
+ obtained from the resource can verify that none of those entities is
+ current by including a list of their associated entity tags in the
+ If-None-Match header field. The purpose of this feature is to allow
+ efficient updates of cached information with a minimum amount of
+ transaction overhead. It is also used to prevent a method (e.g. PUT)
+ from inadvertently modifying an existing resource when the client
+ believes that the resource does not exist.
+
+ As a special case, the value "*" matches any current entity of the
+ resource.
+
+ If-None-Match = "If-None-Match" ":" ( "*" | 1#entity-tag )
+
+ If any of the entity tags match the entity tag of the entity that
+ would have been returned in the response to a similar GET request
+ (without the If-None-Match header) on that resource, or if "*" is
+ given and any current entity exists for that resource, then the
+ server MUST NOT perform the requested method, unless required to do
+ so because the resource's modification date fails to match that
+ supplied in an If-Modified-Since header field in the request.
+ Instead, if the request method was GET or HEAD, the server SHOULD
+ respond with a 304 (Not Modified) response, including the cache-
+ related header fields (particularly ETag) of one of the entities that
+ matched. For all other request methods, the server MUST respond with
+ a status of 412 (Precondition Failed).
+
+ See section 13.3.3 for rules on how to determine if two entities tags
+ match. The weak comparison function can only be used with GET or HEAD
+ requests.
+
+ If none of the entity tags match, then the server MAY perform the
+ requested method as if the If-None-Match header field did not exist,
+ but MUST also ignore any If-Modified-Since header field(s) in the
+ request. That is, if no entity tags match, then the server MUST NOT
+ return a 304 (Not Modified) response.
+
+ If the request would, without the If-None-Match header field, result
+ in anything other than a 2xx or 304 status, then the If-None-Match
+ header MUST be ignored. (See section 13.3.4 for a discussion of
+ server behavior when both If-Modified-Since and If-None-Match appear
+ in the same request.)
+
+ The meaning of "If-None-Match: *" is that the method MUST NOT be
+ performed if the representation selected by the origin server (or by
+ a cache, possibly using the Vary mechanism, see section 14.44)
+ exists, and SHOULD be performed if the representation does not exist.
+ This feature is intended to be useful in preventing races between PUT
+ operations.
+
+ Examples:
+
+ If-None-Match: "xyzzy"
+ If-None-Match: W/"xyzzy"
+ If-None-Match: "xyzzy", "r2d2xxxx", "c3piozzzz"
+ If-None-Match: W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz"
+ If-None-Match: *
+
+ The result of a request having both an If-None-Match header field and
+ either an If-Match or an If-Unmodified-Since header fields is
+ undefined by this specification.
+
+14.27 If-Range
+
+ If a client has a partial copy of an entity in its cache, and wishes
+ to have an up-to-date copy of the entire entity in its cache, it
+ could use the Range request-header with a conditional GET (using
+ either or both of If-Unmodified-Since and If-Match.) However, if the
+ condition fails because the entity has been modified, the client
+ would then have to make a second request to obtain the entire current
+ entity-body.
+
+ The If-Range header allows a client to "short-circuit" the second
+ request. Informally, its meaning is `if the entity is unchanged, send
+ me the part(s) that I am missing; otherwise, send me the entire new
+ entity'.
+
+ If-Range = "If-Range" ":" ( entity-tag | HTTP-date )
+
+ If the client has no entity tag for an entity, but does have a Last-
+ Modified date, it MAY use that date in an If-Range header. (The
+ server can distinguish between a valid HTTP-date and any form of
+ entity-tag by examining no more than two characters.) The If-Range
+ header SHOULD only be used together with a Range header, and MUST be
+ ignored if the request does not include a Range header, or if the
+ server does not support the sub-range operation.
+
+ If the entity tag given in the If-Range header matches the current
+ entity tag for the entity, then the server SHOULD provide the
+ specified sub-range of the entity using a 206 (Partial content)
+ response. If the entity tag does not match, then the server SHOULD
+ return the entire entity using a 200 (OK) response.
+
+14.28 If-Unmodified-Since
+
+ The If-Unmodified-Since request-header field is used with a method to
+ make it conditional. If the requested resource has not been modified
+ since the time specified in this field, the server SHOULD perform the
+ requested operation as if the If-Unmodified-Since header were not
+ present.
+
+ If the requested variant has been modified since the specified time,
+ the server MUST NOT perform the requested operation, and MUST return
+ a 412 (Precondition Failed).
+
+ If-Unmodified-Since = "If-Unmodified-Since" ":" HTTP-date
+
+ An example of the field is:
+
+ If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT
+
+ If the request normally (i.e., without the If-Unmodified-Since
+ header) would result in anything other than a 2xx or 412 status, the
+ If-Unmodified-Since header SHOULD be ignored.
+
+ If the specified date is invalid, the header is ignored.
+
+ The result of a request having both an If-Unmodified-Since header
+ field and either an If-None-Match or an If-Modified-Since header
+ fields is undefined by this specification.
+
+14.29 Last-Modified
+
+ The Last-Modified entity-header field indicates the date and time at
+ which the origin server believes the variant was last modified.
+
+ Last-Modified = "Last-Modified" ":" HTTP-date
+
+ An example of its use is
+
+ Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT
+
+ The exact meaning of this header field depends on the implementation
+ of the origin server and the nature of the original resource. For
+ files, it may be just the file system last-modified time. For
+ entities with dynamically included parts, it may be the most recent
+ of the set of last-modify times for its component parts. For database
+ gateways, it may be the last-update time stamp of the record. For
+ virtual objects, it may be the last time the internal state changed.
+
+ An origin server MUST NOT send a Last-Modified date which is later
+ than the server's time of message origination. In such cases, where
+ the resource's last modification would indicate some time in the
+ future, the server MUST replace that date with the message
+ origination date.
+
+ An origin server SHOULD obtain the Last-Modified value of the entity
+ as close as possible to the time that it generates the Date value of
+ its response. This allows a recipient to make an accurate assessment
+ of the entity's modification time, especially if the entity changes
+ near the time that the response is generated.
+
+ HTTP/1.1 servers SHOULD send Last-Modified whenever feasible.
+
+14.30 Location
+
+ The Location response-header field is used to redirect the recipient
+ to a location other than the Request-URI for completion of the
+ request or identification of a new resource. For 201 (Created)
+ responses, the Location is that of the new resource which was created
+ by the request. For 3xx responses, the location SHOULD indicate the
+ server's preferred URI for automatic redirection to the resource. The
+ field value consists of a single absolute URI.
+
+ Location = "Location" ":" absoluteURI
+
+ An example is:
+
+ Location: <a href="http://www.w3.org/pub/WWW/People.html">http://www.w3.org/pub/WWW/People.html</a>
+
+ Note: The Content-Location header field (section 14.14) differs
+ from Location in that the Content-Location identifies the original
+ location of the entity enclosed in the request. It is therefore
+ possible for a response to contain header fields for both Location
+ and Content-Location. Also see section 13.10 for cache
+ requirements of some methods.
+
+14.31 Max-Forwards
+
+ The Max-Forwards request-header field provides a mechanism with the
+ TRACE (section 9.8) and OPTIONS (section 9.2) methods to limit the
+ number of proxies or gateways that can forward the request to the
+ next inbound server. This can be useful when the client is attempting
+ to trace a request chain which appears to be failing or looping in
+ mid-chain.
+
+ Max-Forwards = "Max-Forwards" ":" 1*DIGIT
+
+ The Max-Forwards value is a decimal integer indicating the remaining
+ number of times this request message may be forwarded.
+
+ Each proxy or gateway recipient of a TRACE or OPTIONS request
+ containing a Max-Forwards header field MUST check and update its
+ value prior to forwarding the request. If the received value is zero
+ (0), the recipient MUST NOT forward the request; instead, it MUST
+ respond as the final recipient. If the received Max-Forwards value is
+ greater than zero, then the forwarded message MUST contain an updated
+ Max-Forwards field with a value decremented by one (1).
+
+ The Max-Forwards header field MAY be ignored for all other methods
+ defined by this specification and for any extension methods for which
+ it is not explicitly referred to as part of that method definition.
+
+14.32 Pragma
+
+ The Pragma general-header field is used to include implementation-
+ specific directives that might apply to any recipient along the
+ request/response chain. All pragma directives specify optional
+ behavior from the viewpoint of the protocol; however, some systems
+ MAY require that behavior be consistent with the directives.
+
+ Pragma = "Pragma" ":" 1#pragma-directive
+ pragma-directive = "no-cache" | extension-pragma
+ extension-pragma = token [ "=" ( token | quoted-string ) ]
+
+ When the no-cache directive is present in a request message, an
+ application SHOULD forward the request toward the origin server even
+ if it has a cached copy of what is being requested. This pragma
+ directive has the same semantics as the no-cache cache-directive (see
+ section 14.9) and is defined here for backward compatibility with
+ HTTP/1.0. Clients SHOULD include both header fields when a no-cache
+ request is sent to a server not known to be HTTP/1.1 compliant.
+
+ Pragma directives MUST be passed through by a proxy or gateway
+ application, regardless of their significance to that application,
+ since the directives might be applicable to all recipients along the
+ request/response chain. It is not possible to specify a pragma for a
+ specific recipient; however, any pragma directive not relevant to a
+ recipient SHOULD be ignored by that recipient.
+
+ HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had
+ sent "Cache-Control: no-cache". No new Pragma directives will be
+ defined in HTTP.
+
+ Note: because the meaning of "Pragma: no-cache as a response
+ header field is not actually specified, it does not provide a
+ reliable replacement for "Cache-Control: no-cache" in a response
+
+14.33 Proxy-Authenticate
+
+ The Proxy-Authenticate response-header field MUST be included as part
+ of a 407 (Proxy Authentication Required) response. The field value
+ consists of a challenge that indicates the authentication scheme and
+ parameters applicable to the proxy for this Request-URI.
+
+ Proxy-Authenticate = "Proxy-Authenticate" ":" 1#challenge
+
+ The HTTP access authentication process is described in "HTTP
+ Authentication: Basic and Digest Access Authentication" [43]. Unlike
+ WWW-Authenticate, the Proxy-Authenticate header field applies only to
+ the current connection and SHOULD NOT be passed on to downstream
+ clients. However, an intermediate proxy might need to obtain its own
+ credentials by requesting them from the downstream client, which in
+ some circumstances will appear as if the proxy is forwarding the
+ Proxy-Authenticate header field.
+
+14.34 Proxy-Authorization
+
+ The Proxy-Authorization request-header field allows the client to
+ identify itself (or its user) to a proxy which requires
+ authentication. The Proxy-Authorization field value consists of
+ credentials containing the authentication information of the user
+ agent for the proxy and/or realm of the resource being requested.
+
+ Proxy-Authorization = "Proxy-Authorization" ":" credentials
+
+ The HTTP access authentication process is described in "HTTP
+ Authentication: Basic and Digest Access Authentication" [43] . Unlike
+ Authorization, the Proxy-Authorization header field applies only to
+ the next outbound proxy that demanded authentication using the Proxy-
+ Authenticate field. When multiple proxies are used in a chain, the
+
+ Proxy-Authorization header field is consumed by the first outbound
+ proxy that was expecting to receive credentials. A proxy MAY relay
+ the credentials from the client request to the next proxy if that is
+ the mechanism by which the proxies cooperatively authenticate a given
+ request.
+
+14.35 Range
+
+14.35.1 Byte Ranges
+
+ Since all HTTP entities are represented in HTTP messages as sequences
+ of bytes, the concept of a byte range is meaningful for any HTTP
+ entity. (However, not all clients and servers need to support byte-
+ range operations.)
+
+ Byte range specifications in HTTP apply to the sequence of bytes in
+ the entity-body (not necessarily the same as the message-body).
+
+ A byte range operation MAY specify a single range of bytes, or a set
+ of ranges within a single entity.
+
+ ranges-specifier = byte-ranges-specifier
+ byte-ranges-specifier = bytes-unit "=" byte-range-set
+ byte-range-set = 1#( byte-range-spec | suffix-byte-range-spec )
+ byte-range-spec = first-byte-pos "-" [last-byte-pos]
+ first-byte-pos = 1*DIGIT
+ last-byte-pos = 1*DIGIT
+
+ The first-byte-pos value in a byte-range-spec gives the byte-offset
+ of the first byte in a range. The last-byte-pos value gives the
+ byte-offset of the last byte in the range; that is, the byte
+ positions specified are inclusive. Byte offsets start at zero.
+
+ If the last-byte-pos value is present, it MUST be greater than or
+ equal to the first-byte-pos in that byte-range-spec, or the byte-
+ range-spec is syntactically invalid. The recipient of a byte-range-
+ set that includes one or more syntactically invalid byte-range-spec
+ values MUST ignore the header field that includes that byte-range-
+ set.
+
+ If the last-byte-pos value is absent, or if the value is greater than
+ or equal to the current length of the entity-body, last-byte-pos is
+ taken to be equal to one less than the current length of the entity-
+ body in bytes.
+
+ By its choice of last-byte-pos, a client can limit the number of
+ bytes retrieved without knowing the size of the entity.
+
+ suffix-byte-range-spec = "-" suffix-length
+ suffix-length = 1*DIGIT
+
+ A suffix-byte-range-spec is used to specify the suffix of the
+ entity-body, of a length given by the suffix-length value. (That is,
+ this form specifies the last N bytes of an entity-body.) If the
+ entity is shorter than the specified suffix-length, the entire
+ entity-body is used.
+
+ If a syntactically valid byte-range-set includes at least one byte-
+ range-spec whose first-byte-pos is less than the current length of
+ the entity-body, or at least one suffix-byte-range-spec with a non-
+ zero suffix-length, then the byte-range-set is satisfiable.
+ Otherwise, the byte-range-set is unsatisfiable. If the byte-range-set
+ is unsatisfiable, the server SHOULD return a response with a status
+ of 416 (Requested range not satisfiable). Otherwise, the server
+ SHOULD return a response with a status of 206 (Partial Content)
+ containing the satisfiable ranges of the entity-body.
+
+ Examples of byte-ranges-specifier values (assuming an entity-body of
+ length 10000):
+
+ - The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-
+ 499
+
+ - The second 500 bytes (byte offsets 500-999, inclusive):
+ bytes=500-999
+
+ - The final 500 bytes (byte offsets 9500-9999, inclusive):
+ bytes=-500
+
+ - Or bytes=9500-
+
+ - The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1
+
+ - Several legal but not canonical specifications of the second 500
+ bytes (byte offsets 500-999, inclusive):
+ bytes=500-600,601-999
+ bytes=500-700,601-999
+
+14.35.2 Range Retrieval Requests
+
+ HTTP retrieval requests using conditional or unconditional GET
+ methods MAY request one or more sub-ranges of the entity, instead of
+ the entire entity, using the Range request header, which applies to
+ the entity returned as the result of the request:
+
+ Range = "Range" ":" ranges-specifier
+
+ A server MAY ignore the Range header. However, HTTP/1.1 origin
+ servers and intermediate caches ought to support byte ranges when
+ possible, since Range supports efficient recovery from partially
+ failed transfers, and supports efficient partial retrieval of large
+ entities.
+
+ If the server supports the Range header and the specified range or
+ ranges are appropriate for the entity:
+
+ - The presence of a Range header in an unconditional GET modifies
+ what is returned if the GET is otherwise successful. In other
+ words, the response carries a status code of 206 (Partial
+ Content) instead of 200 (OK).
+
+ - The presence of a Range header in a conditional GET (a request
+ using one or both of If-Modified-Since and If-None-Match, or
+ one or both of If-Unmodified-Since and If-Match) modifies what
+ is returned if the GET is otherwise successful and the
+ condition is true. It does not affect the 304 (Not Modified)
+ response returned if the conditional is false.
+
+ In some cases, it might be more appropriate to use the If-Range
+ header (see section 14.27) in addition to the Range header.
+
+ If a proxy that supports ranges receives a Range request, forwards
+ the request to an inbound server, and receives an entire entity in
+ reply, it SHOULD only return the requested range to its client. It
+ SHOULD store the entire received response in its cache if that is
+ consistent with its cache allocation policies.
+
+14.36 Referer
+
+ The Referer[sic] request-header field allows the client to specify,
+ for the server's benefit, the address (URI) of the resource from
+ which the Request-URI was obtained (the "referrer", although the
+ header field is misspelled.) The Referer request-header allows a
+ server to generate lists of back-links to resources for interest,
+ logging, optimized caching, etc. It also allows obsolete or mistyped
+ links to be traced for maintenance. The Referer field MUST NOT be
+ sent if the Request-URI was obtained from a source that does not have
+ its own URI, such as input from the user keyboard.
+
+ Referer = "Referer" ":" ( absoluteURI | relativeURI )
+
+ Example:
+
+ Referer: <a href="http://www.w3.org/hypertext/DataSources/Overview.html">http://www.w3.org/hypertext/DataSources/Overview.html</a>
+
+ If the field value is a relative URI, it SHOULD be interpreted
+ relative to the Request-URI. The URI MUST NOT include a fragment. See
+ section 15.1.3 for security considerations.
+
+14.37 Retry-After
+
+ The Retry-After response-header field can be used with a 503 (Service
+ Unavailable) response to indicate how long the service is expected to
+ be unavailable to the requesting client. This field MAY also be used
+ with any 3xx (Redirection) response to indicate the minimum time the
+ user-agent is asked wait before issuing the redirected request. The
+ value of this field can be either an HTTP-date or an integer number
+ of seconds (in decimal) after the time of the response.
+
+ Retry-After = "Retry-After" ":" ( HTTP-date | delta-seconds )
+
+ Two examples of its use are
+
+ Retry-After: Fri, 31 Dec 1999 23:59:59 GMT
+ Retry-After: 120
+
+ In the latter example, the delay is 2 minutes.
+
+14.38 Server
+
+ The Server response-header field contains information about the
+ software used by the origin server to handle the request. The field
+ can contain multiple product tokens (section 3.8) and comments
+ identifying the server and any significant subproducts. The product
+ tokens are listed in order of their significance for identifying the
+ application.
+
+ Server = "Server" ":" 1*( product | comment )
+
+ Example:
+
+ Server: CERN/3.0 libwww/2.17
+
+ If the response is being forwarded through a proxy, the proxy
+ application MUST NOT modify the Server response-header. Instead, it
+ SHOULD include a Via field (as described in section 14.45).
+
+ Note: Revealing the specific software version of the server might
+ allow the server machine to become more vulnerable to attacks
+ against software that is known to contain security holes. Server
+ implementors are encouraged to make this field a configurable
+ option.
+
+14.39 TE
+
+ The TE request-header field indicates what extension transfer-codings
+ it is willing to accept in the response and whether or not it is
+ willing to accept trailer fields in a chunked transfer-coding. Its
+ value may consist of the keyword "trailers" and/or a comma-separated
+ list of extension transfer-coding names with optional accept
+ parameters (as described in section 3.6).
+
+ TE = "TE" ":" #( t-codings )
+ t-codings = "trailers" | ( transfer-extension [ accept-params ] )
+
+ The presence of the keyword "trailers" indicates that the client is
+ willing to accept trailer fields in a chunked transfer-coding, as
+ defined in section 3.6.1. This keyword is reserved for use with
+ transfer-coding values even though it does not itself represent a
+ transfer-coding.
+
+ Examples of its use are:
+
+ TE: deflate
+ TE:
+ TE: trailers, deflate;q=0.5
+
+ The TE header field only applies to the immediate connection.
+ Therefore, the keyword MUST be supplied within a Connection header
+ field (section 14.10) whenever TE is present in an HTTP/1.1 message.
+
+ A server tests whether a transfer-coding is acceptable, according to
+ a TE field, using these rules:
+
+ 1. The "chunked" transfer-coding is always acceptable. If the
+ keyword "trailers" is listed, the client indicates that it is
+ willing to accept trailer fields in the chunked response on
+ behalf of itself and any downstream clients. The implication is
+ that, if given, the client is stating that either all
+ downstream clients are willing to accept trailer fields in the
+ forwarded response, or that it will attempt to buffer the
+ response on behalf of downstream recipients.
+
+ Note: HTTP/1.1 does not define any means to limit the size of a
+ chunked response such that a client can be assured of buffering
+ the entire response.
+
+ 2. If the transfer-coding being tested is one of the transfer-
+ codings listed in the TE field, then it is acceptable unless it
+ is accompanied by a qvalue of 0. (As defined in section 3.9, a
+ qvalue of 0 means "not acceptable.")
+
+ 3. If multiple transfer-codings are acceptable, then the
+ acceptable transfer-coding with the highest non-zero qvalue is
+ preferred. The "chunked" transfer-coding always has a qvalue
+ of 1.
+
+ If the TE field-value is empty or if no TE field is present, the only
+ transfer-coding is "chunked". A message with no transfer-coding is
+ always acceptable.
+
+14.40 Trailer
+
+ The Trailer general field value indicates that the given set of
+ header fields is present in the trailer of a message encoded with
+ chunked transfer-coding.
+
+ Trailer = "Trailer" ":" 1#field-name
+
+ An HTTP/1.1 message SHOULD include a Trailer header field in a
+ message using chunked transfer-coding with a non-empty trailer. Doing
+ so allows the recipient to know which header fields to expect in the
+ trailer.
+
+ If no Trailer header field is present, the trailer SHOULD NOT include
+ any header fields. See section 3.6.1 for restrictions on the use of
+ trailer fields in a "chunked" transfer-coding.
+
+ Message header fields listed in the Trailer header field MUST NOT
+ include the following header fields:
+
+ . Transfer-Encoding
+
+ . Content-Length
+
+ . Trailer
+
+14.41 Transfer-Encoding
+
+ The Transfer-Encoding general-header field indicates what (if any)
+ type of transformation has been applied to the message body in order
+ to safely transfer it between the sender and the recipient. This
+ differs from the content-coding in that the transfer-coding is a
+ property of the message, not of the entity.
+
+ Transfer-Encoding = "Transfer-Encoding" ":" 1#transfer-coding
+
+ Transfer-codings are defined in section 3.6. An example is:
+
+ Transfer-Encoding: chunked
+
+ If multiple encodings have been applied to an entity, the transfer-
+ codings MUST be listed in the order in which they were applied.
+ Additional information about the encoding parameters MAY be provided
+ by other entity-header fields not defined by this specification.
+
+ Many older HTTP/1.0 applications do not understand the Transfer-
+ Encoding header.
+
+14.42 Upgrade
+
+ The Upgrade general-header allows the client to specify what
+ additional communication protocols it supports and would like to use
+ if the server finds it appropriate to switch protocols. The server
+ MUST use the Upgrade header field within a 101 (Switching Protocols)
+ response to indicate which protocol(s) are being switched.
+
+ Upgrade = "Upgrade" ":" 1#product
+
+ For example,
+
+ Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
+
+ The Upgrade header field is intended to provide a simple mechanism
+ for transition from HTTP/1.1 to some other, incompatible protocol. It
+ does so by allowing the client to advertise its desire to use another
+ protocol, such as a later version of HTTP with a higher major version
+ number, even though the current request has been made using HTTP/1.1.
+ This eases the difficult transition between incompatible protocols by
+ allowing the client to initiate a request in the more commonly
+ supported protocol while indicating to the server that it would like
+ to use a "better" protocol if available (where "better" is determined
+ by the server, possibly according to the nature of the method and/or
+ resource being requested).
+
+ The Upgrade header field only applies to switching application-layer
+ protocols upon the existing transport-layer connection. Upgrade
+ cannot be used to insist on a protocol change; its acceptance and use
+ by the server is optional. The capabilities and nature of the
+ application-layer communication after the protocol change is entirely
+ dependent upon the new protocol chosen, although the first action
+ after changing the protocol MUST be a response to the initial HTTP
+ request containing the Upgrade header field.
+
+ The Upgrade header field only applies to the immediate connection.
+ Therefore, the upgrade keyword MUST be supplied within a Connection
+ header field (section 14.10) whenever Upgrade is present in an
+ HTTP/1.1 message.
+
+ The Upgrade header field cannot be used to indicate a switch to a
+ protocol on a different connection. For that purpose, it is more
+ appropriate to use a 301, 302, 303, or 305 redirection response.
+
+ This specification only defines the protocol name "HTTP" for use by
+ the family of Hypertext Transfer Protocols, as defined by the HTTP
+ version rules of section 3.1 and future updates to this
+ specification. Any token can be used as a protocol name; however, it
+ will only be useful if both the client and server associate the name
+ with the same protocol.
+
+14.43 User-Agent
+
+ The User-Agent request-header field contains information about the
+ user agent originating the request. This is for statistical purposes,
+ the tracing of protocol violations, and automated recognition of user
+ agents for the sake of tailoring responses to avoid particular user
+ agent limitations. User agents SHOULD include this field with
+ requests. The field can contain multiple product tokens (section 3.8)
+ and comments identifying the agent and any subproducts which form a
+ significant part of the user agent. By convention, the product tokens
+ are listed in order of their significance for identifying the
+ application.
+
+ User-Agent = "User-Agent" ":" 1*( product | comment )
+
+ Example:
+
+ User-Agent: CERN-LineMode/2.15 libwww/2.17b3
+
+14.44 Vary
+
+ The Vary field value indicates the set of request-header fields that
+ fully determines, while the response is fresh, whether a cache is
+ permitted to use the response to reply to a subsequent request
+ without revalidation. For uncacheable or stale responses, the Vary
+ field value advises the user agent about the criteria that were used
+ to select the representation. A Vary field value of "*" implies that
+ a cache cannot determine from the request headers of a subsequent
+ request whether this response is the appropriate representation. See
+ section 13.6 for use of the Vary header field by caches.
+
+ Vary = "Vary" ":" ( "*" | 1#field-name )
+
+ An HTTP/1.1 server SHOULD include a Vary header field with any
+ cacheable response that is subject to server-driven negotiation.
+ Doing so allows a cache to properly interpret future requests on that
+ resource and informs the user agent about the presence of negotiation
+
+ on that resource. A server MAY include a Vary header field with a
+ non-cacheable response that is subject to server-driven negotiation,
+ since this might provide the user agent with useful information about
+ the dimensions over which the response varies at the time of the
+ response.
+
+ A Vary field value consisting of a list of field-names signals that
+ the representation selected for the response is based on a selection
+ algorithm which considers ONLY the listed request-header field values
+ in selecting the most appropriate representation. A cache MAY assume
+ that the same selection will be made for future requests with the
+ same values for the listed field names, for the duration of time for
+ which the response is fresh.
+
+ The field-names given are not limited to the set of standard
+ request-header fields defined by this specification. Field names are
+ case-insensitive.
+
+ A Vary field value of "*" signals that unspecified parameters not
+ limited to the request-headers (e.g., the network address of the
+ client), play a role in the selection of the response representation.
+ The "*" value MUST NOT be generated by a proxy server; it may only be
+ generated by an origin server.
+
+14.45 Via
+
+ The Via general-header field MUST be used by gateways and proxies to
+ indicate the intermediate protocols and recipients between the user
+ agent and the server on requests, and between the origin server and
+ the client on responses. It is analogous to the "Received" field of
+ <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a> [9] and is intended to be used for tracking message forwards,
+ avoiding request loops, and identifying the protocol capabilities of
+ all senders along the request/response chain.
+
+ Via = "Via" ":" 1#( received-protocol received-by [ comment ] )
+ received-protocol = [ protocol-name "/" ] protocol-version
+ protocol-name = token
+ protocol-version = token
+ received-by = ( host [ ":" port ] ) | pseudonym
+ pseudonym = token
+
+ The received-protocol indicates the protocol version of the message
+ received by the server or client along each segment of the
+ request/response chain. The received-protocol version is appended to
+ the Via field value when the message is forwarded so that information
+ about the protocol capabilities of upstream applications remains
+ visible to all recipients.
+
+ The protocol-name is optional if and only if it would be "HTTP". The
+ received-by field is normally the host and optional port number of a
+ recipient server or client that subsequently forwarded the message.
+ However, if the real host is considered to be sensitive information,
+ it MAY be replaced by a pseudonym. If the port is not given, it MAY
+ be assumed to be the default port of the received-protocol.
+
+ Multiple Via field values represents each proxy or gateway that has
+ forwarded the message. Each recipient MUST append its information
+ such that the end result is ordered according to the sequence of
+ forwarding applications.
+
+ Comments MAY be used in the Via header field to identify the software
+ of the recipient proxy or gateway, analogous to the User-Agent and
+ Server header fields. However, all comments in the Via field are
+ optional and MAY be removed by any recipient prior to forwarding the
+ message.
+
+ For example, a request message could be sent from an HTTP/1.0 user
+ agent to an internal proxy code-named "fred", which uses HTTP/1.1 to
+ forward the request to a public proxy at nowhere.com, which completes
+ the request by forwarding it to the origin server at www.ics.uci.edu.
+ The request received by www.ics.uci.edu would then have the following
+ Via header field:
+
+ Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
+
+ Proxies and gateways used as a portal through a network firewall
+ SHOULD NOT, by default, forward the names and ports of hosts within
+ the firewall region. This information SHOULD only be propagated if
+ explicitly enabled. If not enabled, the received-by host of any host
+ behind the firewall SHOULD be replaced by an appropriate pseudonym
+ for that host.
+
+ For organizations that have strong privacy requirements for hiding
+ internal structures, a proxy MAY combine an ordered subsequence of
+ Via header field entries with identical received-protocol values into
+ a single such entry. For example,
+
+ Via: 1.0 ricky, 1.1 ethel, 1.1 fred, 1.0 lucy
+
+ could be collapsed to
+
+ Via: 1.0 ricky, 1.1 mertz, 1.0 lucy
+
+ Applications SHOULD NOT combine multiple entries unless they are all
+ under the same organizational control and the hosts have already been
+ replaced by pseudonyms. Applications MUST NOT combine entries which
+ have different received-protocol values.
+
+14.46 Warning
+
+ The Warning general-header field is used to carry additional
+ information about the status or transformation of a message which
+ might not be reflected in the message. This information is typically
+ used to warn about a possible lack of semantic transparency from
+ caching operations or transformations applied to the entity body of
+ the message.
+
+ Warning headers are sent with responses using:
+
+ Warning = "Warning" ":" 1#warning-value
+
+ warning-value = warn-code SP warn-agent SP warn-text
+ [SP warn-date]
+
+ warn-code = 3DIGIT
+ warn-agent = ( host [ ":" port ] ) | pseudonym
+ ; the name or pseudonym of the server adding
+ ; the Warning header, for use in debugging
+ warn-text = quoted-string
+ warn-date = &lt;"&gt; HTTP-date &lt;"&gt;
+
+ A response MAY carry more than one Warning header.
+
+ The warn-text SHOULD be in a natural language and character set that
+ is most likely to be intelligible to the human user receiving the
+ response. This decision MAY be based on any available knowledge, such
+ as the location of the cache or user, the Accept-Language field in a
+ request, the Content-Language field in a response, etc. The default
+ language is English and the default character set is ISO-8859-1.
+
+ If a character set other than ISO-8859-1 is used, it MUST be encoded
+ in the warn-text using the method described in <a href="http://firefly.troll.no/rfcs/rfc2047.html">RFC 2047</a> [14].
+
+ Warning headers can in general be applied to any message, however
+ some specific warn-codes are specific to caches and can only be
+ applied to response messages. New Warning headers SHOULD be added
+ after any existing Warning headers. A cache MUST NOT delete any
+ Warning header that it received with a message. However, if a cache
+ successfully validates a cache entry, it SHOULD remove any Warning
+ headers previously attached to that entry except as specified for
+
+ specific Warning codes. It MUST then add any Warning headers received
+ in the validating response. In other words, Warning headers are those
+ that would be attached to the most recent relevant response.
+
+ When multiple Warning headers are attached to a response, the user
+ agent ought to inform the user of as many of them as possible, in the
+ order that they appear in the response. If it is not possible to
+ inform the user of all of the warnings, the user agent SHOULD follow
+ these heuristics:
+
+ - Warnings that appear early in the response take priority over
+ those appearing later in the response.
+
+ - Warnings in the user's preferred character set take priority
+ over warnings in other character sets but with identical warn-
+ codes and warn-agents.
+
+ Systems that generate multiple Warning headers SHOULD order them with
+ this user agent behavior in mind.
+
+ Requirements for the behavior of caches with respect to Warnings are
+ stated in section 13.1.2.
+
+ This is a list of the currently-defined warn-codes, each with a
+ recommended warn-text in English, and a description of its meaning.
+
+ 110 Response is stale
+ MUST be included whenever the returned response is stale.
+
+ 111 Revalidation failed
+ MUST be included if a cache returns a stale response because an
+ attempt to revalidate the response failed, due to an inability to
+ reach the server.
+
+ 112 Disconnected operation
+ SHOULD be included if the cache is intentionally disconnected from
+ the rest of the network for a period of time.
+
+ 113 Heuristic expiration
+ MUST be included if the cache heuristically chose a freshness
+ lifetime greater than 24 hours and the response's age is greater
+ than 24 hours.
+
+ 199 Miscellaneous warning
+ The warning text MAY include arbitrary information to be presented
+ to a human user, or logged. A system receiving this warning MUST
+ NOT take any automated action, besides presenting the warning to
+ the user.
+
+ 214 Transformation applied
+ MUST be added by an intermediate cache or proxy if it applies any
+ transformation changing the content-coding (as specified in the
+ Content-Encoding header) or media-type (as specified in the
+ Content-Type header) of the response, or the entity-body of the
+ response, unless this Warning code already appears in the response.
+
+ 299 Miscellaneous persistent warning
+ The warning text MAY include arbitrary information to be presented
+ to a human user, or logged. A system receiving this warning MUST
+ NOT take any automated action.
+
+ If an implementation sends a message with one or more Warning headers
+ whose version is HTTP/1.0 or lower, then the sender MUST include in
+ each warning-value a warn-date that matches the date in the response.
+
+ If an implementation receives a message with a warning-value that
+ includes a warn-date, and that warn-date is different from the Date
+ value in the response, then that warning-value MUST be deleted from
+ the message before storing, forwarding, or using it. (This prevents
+ bad consequences of naive caching of Warning header fields.) If all
+ of the warning-values are deleted for this reason, the Warning header
+ MUST be deleted as well.
+
+14.47 WWW-Authenticate
+
+ The WWW-Authenticate response-header field MUST be included in 401
+ (Unauthorized) response messages. The field value consists of at
+ least one challenge that indicates the authentication scheme(s) and
+ parameters applicable to the Request-URI.
+
+ WWW-Authenticate = "WWW-Authenticate" ":" 1#challenge
+
+ The HTTP access authentication process is described in "HTTP
+ Authentication: Basic and Digest Access Authentication" [43]. User
+ agents are advised to take special care in parsing the WWW-
+ Authenticate field value as it might contain more than one challenge,
+ or if more than one WWW-Authenticate header field is provided, the
+ contents of a challenge itself can contain a comma-separated list of
+ authentication parameters.
+
+15 Security Considerations
+
+ This section is meant to inform application developers, information
+ providers, and users of the security limitations in HTTP/1.1 as
+ described by this document. The discussion does not include
+ definitive solutions to the problems revealed, though it does make
+ some suggestions for reducing security risks.
+
+15.1 Personal Information
+
+ HTTP clients are often privy to large amounts of personal information
+ (e.g. the user's name, location, mail address, passwords, encryption
+ keys, etc.), and SHOULD be very careful to prevent unintentional
+ leakage of this information via the HTTP protocol to other sources.
+ We very strongly recommend that a convenient interface be provided
+ for the user to control dissemination of such information, and that
+ designers and implementors be particularly careful in this area.
+ History shows that errors in this area often create serious security
+ and/or privacy problems and generate highly adverse publicity for the
+ implementor's company.
+
+15.1.1 Abuse of Server Log Information
+
+ A server is in the position to save personal data about a user's
+ requests which might identify their reading patterns or subjects of
+ interest. This information is clearly confidential in nature and its
+ handling can be constrained by law in certain countries. People using
+ the HTTP protocol to provide data are responsible for ensuring that
+ such material is not distributed without the permission of any
+ individuals that are identifiable by the published results.
+
+15.1.2 Transfer of Sensitive Information
+
+ Like any generic data transfer protocol, HTTP cannot regulate the
+ content of the data that is transferred, nor is there any a priori
+ method of determining the sensitivity of any particular piece of
+ information within the context of any given request. Therefore,
+ applications SHOULD supply as much control over this information as
+ possible to the provider of that information. Four header fields are
+ worth special mention in this context: Server, Via, Referer and From.
+
+ Revealing the specific software version of the server might allow the
+ server machine to become more vulnerable to attacks against software
+ that is known to contain security holes. Implementors SHOULD make the
+ Server header field a configurable option.
+
+ Proxies which serve as a portal through a network firewall SHOULD
+ take special precautions regarding the transfer of header information
+ that identifies the hosts behind the firewall. In particular, they
+ SHOULD remove, or replace with sanitized versions, any Via fields
+ generated behind the firewall.
+
+ The Referer header allows reading patterns to be studied and reverse
+ links drawn. Although it can be very useful, its power can be abused
+ if user details are not separated from the information contained in
+
+ the Referer. Even when the personal information has been removed, the
+ Referer header might indicate a private document's URI whose
+ publication would be inappropriate.
+
+ The information sent in the From field might conflict with the user's
+ privacy interests or their site's security policy, and hence it
+ SHOULD NOT be transmitted without the user being able to disable,
+ enable, and modify the contents of the field. The user MUST be able
+ to set the contents of this field within a user preference or
+ application defaults configuration.
+
+ We suggest, though do not require, that a convenient toggle interface
+ be provided for the user to enable or disable the sending of From and
+ Referer information.
+
+ The User-Agent (section 14.43) or Server (section 14.38) header
+ fields can sometimes be used to determine that a specific client or
+ server have a particular security hole which might be exploited.
+ Unfortunately, this same information is often used for other valuable
+ purposes for which HTTP currently has no better mechanism.
+
+15.1.3 Encoding Sensitive Information in URI's
+
+ Because the source of a link might be private information or might
+ reveal an otherwise private information source, it is strongly
+ recommended that the user be able to select whether or not the
+ Referer field is sent. For example, a browser client could have a
+ toggle switch for browsing openly/anonymously, which would
+ respectively enable/disable the sending of Referer and From
+ information.
+
+ Clients SHOULD NOT include a Referer header field in a (non-secure)
+ HTTP request if the referring page was transferred with a secure
+ protocol.
+
+ Authors of services which use the HTTP protocol SHOULD NOT use GET
+ based forms for the submission of sensitive data, because this will
+ cause this data to be encoded in the Request-URI. Many existing
+ servers, proxies, and user agents will log the request URI in some
+ place where it might be visible to third parties. Servers can use
+ POST-based form submission instead
+
+15.1.4 Privacy Issues Connected to Accept Headers
+
+ Accept request-headers can reveal information about the user to all
+ servers which are accessed. The Accept-Language header in particular
+ can reveal information the user would consider to be of a private
+ nature, because the understanding of particular languages is often
+
+ strongly correlated to the membership of a particular ethnic group.
+ User agents which offer the option to configure the contents of an
+ Accept-Language header to be sent in every request are strongly
+ encouraged to let the configuration process include a message which
+ makes the user aware of the loss of privacy involved.
+
+ An approach that limits the loss of privacy would be for a user agent
+ to omit the sending of Accept-Language headers by default, and to ask
+ the user whether or not to start sending Accept-Language headers to a
+ server if it detects, by looking for any Vary response-header fields
+ generated by the server, that such sending could improve the quality
+ of service.
+
+ Elaborate user-customized accept header fields sent in every request,
+ in particular if these include quality values, can be used by servers
+ as relatively reliable and long-lived user identifiers. Such user
+ identifiers would allow content providers to do click-trail tracking,
+ and would allow collaborating content providers to match cross-server
+ click-trails or form submissions of individual users. Note that for
+ many users not behind a proxy, the network address of the host
+ running the user agent will also serve as a long-lived user
+ identifier. In environments where proxies are used to enhance
+ privacy, user agents ought to be conservative in offering accept
+ header configuration options to end users. As an extreme privacy
+ measure, proxies could filter the accept headers in relayed requests.
+ General purpose user agents which provide a high degree of header
+ configurability SHOULD warn users about the loss of privacy which can
+ be involved.
+
+15.2 Attacks Based On File and Path Names
+
+ Implementations of HTTP origin servers SHOULD be careful to restrict
+ the documents returned by HTTP requests to be only those that were
+ intended by the server administrators. If an HTTP server translates
+ HTTP URIs directly into file system calls, the server MUST take
+ special care not to serve files that were not intended to be
+ delivered to HTTP clients. For example, UNIX, Microsoft Windows, and
+ other operating systems use ".." as a path component to indicate a
+ directory level above the current one. On such a system, an HTTP
+ server MUST disallow any such construct in the Request-URI if it
+ would otherwise allow access to a resource outside those intended to
+ be accessible via the HTTP server. Similarly, files intended for
+ reference only internally to the server (such as access control
+ files, configuration files, and script code) MUST be protected from
+ inappropriate retrieval, since they might contain sensitive
+ information. Experience has shown that minor bugs in such HTTP server
+ implementations have turned into security risks.
+
+15.3 DNS Spoofing
+
+ Clients using HTTP rely heavily on the Domain Name Service, and are
+ thus generally prone to security attacks based on the deliberate
+ mis-association of IP addresses and DNS names. Clients need to be
+ cautious in assuming the continuing validity of an IP number/DNS name
+ association.
+
+ In particular, HTTP clients SHOULD rely on their name resolver for
+ confirmation of an IP number/DNS name association, rather than
+ caching the result of previous host name lookups. Many platforms
+ already can cache host name lookups locally when appropriate, and
+ they SHOULD be configured to do so. It is proper for these lookups to
+ be cached, however, only when the TTL (Time To Live) information
+ reported by the name server makes it likely that the cached
+ information will remain useful.
+
+ If HTTP clients cache the results of host name lookups in order to
+ achieve a performance improvement, they MUST observe the TTL
+ information reported by DNS.
+
+ If HTTP clients do not observe this rule, they could be spoofed when
+ a previously-accessed server's IP address changes. As network
+ renumbering is expected to become increasingly common [24], the
+ possibility of this form of attack will grow. Observing this
+ requirement thus reduces this potential security vulnerability.
+
+ This requirement also improves the load-balancing behavior of clients
+ for replicated servers using the same DNS name and reduces the
+ likelihood of a user's experiencing failure in accessing sites which
+ use that strategy.
+
+15.4 Location Headers and Spoofing
+
+ If a single server supports multiple organizations that do not trust
+ one another, then it MUST check the values of Location and Content-
+ Location headers in responses that are generated under control of
+ said organizations to make sure that they do not attempt to
+ invalidate resources over which they have no authority.
+
+15.5 Content-Disposition Issues
+
+ <a href="http://firefly.troll.no/rfcs/rfc1806.html">RFC 1806</a> [35], from which the often implemented Content-Disposition
+ (see section 19.5.1) header in HTTP is derived, has a number of very
+ serious security considerations. Content-Disposition is not part of
+ the HTTP standard, but since it is widely implemented, we are
+ documenting its use and risks for implementors. See <a href="http://firefly.troll.no/rfcs/rfc2183.html">RFC 2183</a> [49]
+ (which updates <a href="http://firefly.troll.no/rfcs/rfc1806.html">RFC 1806</a>) for details.
+
+15.6 Authentication Credentials and Idle Clients
+
+ Existing HTTP clients and user agents typically retain authentication
+ information indefinitely. HTTP/1.1. does not provide a method for a
+ server to direct clients to discard these cached credentials. This is
+ a significant defect that requires further extensions to HTTP.
+ Circumstances under which credential caching can interfere with the
+ application's security model include but are not limited to:
+
+ - Clients which have been idle for an extended period following
+ which the server might wish to cause the client to reprompt the
+ user for credentials.
+
+ - Applications which include a session termination indication
+ (such as a `logout' or `commit' button on a page) after which
+ the server side of the application `knows' that there is no
+ further reason for the client to retain the credentials.
+
+ This is currently under separate study. There are a number of work-
+ arounds to parts of this problem, and we encourage the use of
+ password protection in screen savers, idle time-outs, and other
+ methods which mitigate the security problems inherent in this
+ problem. In particular, user agents which cache credentials are
+ encouraged to provide a readily accessible mechanism for discarding
+ cached credentials under user control.
+
+15.7 Proxies and Caching
+
+ By their very nature, HTTP proxies are men-in-the-middle, and
+ represent an opportunity for man-in-the-middle attacks. Compromise of
+ the systems on which the proxies run can result in serious security
+ and privacy problems. Proxies have access to security-related
+ information, personal information about individual users and
+ organizations, and proprietary information belonging to users and
+ content providers. A compromised proxy, or a proxy implemented or
+ configured without regard to security and privacy considerations,
+ might be used in the commission of a wide range of potential attacks.
+
+ Proxy operators should protect the systems on which proxies run as
+ they would protect any system that contains or transports sensitive
+ information. In particular, log information gathered at proxies often
+ contains highly sensitive personal information, and/or information
+ about organizations. Log information should be carefully guarded, and
+ appropriate guidelines for use developed and followed. (Section
+ 15.1.1).
+
+ Caching proxies provide additional potential vulnerabilities, since
+ the contents of the cache represent an attractive target for
+ malicious exploitation. Because cache contents persist after an HTTP
+ request is complete, an attack on the cache can reveal information
+ long after a user believes that the information has been removed from
+ the network. Therefore, cache contents should be protected as
+ sensitive information.
+
+ Proxy implementors should consider the privacy and security
+ implications of their design and coding decisions, and of the
+ configuration options they provide to proxy operators (especially the
+ default configuration).
+
+ Users of a proxy need to be aware that they are no trustworthier than
+ the people who run the proxy; HTTP itself cannot solve this problem.
+
+ The judicious use of cryptography, when appropriate, may suffice to
+ protect against a broad range of security and privacy attacks. Such
+ cryptography is beyond the scope of the HTTP/1.1 specification.
+
+15.7.1 Denial of Service Attacks on Proxies
+
+ They exist. They are hard to defend against. Research continues.
+ Beware.
+
+16 Acknowledgments
+
+ This specification makes heavy use of the augmented BNF and generic
+ constructs defined by David H. Crocker for <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a> [9]. Similarly, it
+ reuses many of the definitions provided by Nathaniel Borenstein and
+ Ned Freed for MIME [7]. We hope that their inclusion in this
+ specification will help reduce past confusion over the relationship
+ between HTTP and Internet mail message formats.
+
+ The HTTP protocol has evolved considerably over the years. It has
+ benefited from a large and active developer community--the many
+ people who have participated on the www-talk mailing list--and it is
+ that community which has been most responsible for the success of
+ HTTP and of the World-Wide Web in general. Marc Andreessen, Robert
+ Cailliau, Daniel W. Connolly, Bob Denny, John Franks, Jean-Francois
+ Groff, Phillip M. Hallam-Baker, Hakon W. Lie, Ari Luotonen, Rob
+ McCool, Lou Montulli, Dave Raggett, Tony Sanders, and Marc
+ VanHeyningen deserve special recognition for their efforts in
+ defining early aspects of the protocol.
+
+ This document has benefited greatly from the comments of all those
+ participating in the HTTP-WG. In addition to those already mentioned,
+ the following individuals have contributed to this specification:
+
+ Gary Adams Ross Patterson
+ Harald Tveit Alvestrand Albert Lunde
+ Keith Ball John C. Mallery
+ Brian Behlendorf Jean-Philippe Martin-Flatin
+ Paul Burchard Mitra
+ Maurizio Codogno David Morris
+ Mike Cowlishaw Gavin Nicol
+ Roman Czyborra Bill Perry
+ Michael A. Dolan Jeffrey Perry
+ David J. Fiander Scott Powers
+ Alan Freier Owen Rees
+ Marc Hedlund Luigi Rizzo
+ Greg Herlihy David Robinson
+ Koen Holtman Marc Salomon
+ Alex Hopmann Rich Salz
+ Bob Jernigan Allan M. Schiffman
+ Shel Kaphan Jim Seidman
+ Rohit Khare Chuck Shotton
+ John Klensin Eric W. Sink
+ Martijn Koster Simon E. Spero
+ Alexei Kosut Richard N. Taylor
+ David M. Kristol Robert S. Thau
+ Daniel LaLiberte Bill (BearHeart) Weinman
+ Ben Laurie Francois Yergeau
+ Paul J. Leach Mary Ellen Zurko
+ Daniel DuBois Josh Cohen
+
+ Much of the content and presentation of the caching design is due to
+ suggestions and comments from individuals including: Shel Kaphan,
+ Paul Leach, Koen Holtman, David Morris, and Larry Masinter.
+
+ Most of the specification of ranges is based on work originally done
+ by Ari Luotonen and John Franks, with additional input from Steve
+ Zilles.
+
+ Thanks to the "cave men" of Palo Alto. You know who you are.
+
+ Jim Gettys (the current editor of this document) wishes particularly
+ to thank Roy Fielding, the previous editor of this document, along
+ with John Klensin, Jeff Mogul, Paul Leach, Dave Kristol, Koen
+ Holtman, John Franks, Josh Cohen, Alex Hopmann, Scott Lawrence, and
+ Larry Masinter for their help. And thanks go particularly to Jeff
+ Mogul and Scott Lawrence for performing the "MUST/MAY/SHOULD" audit.
+
+ The Apache Group, Anselm Baird-Smith, author of Jigsaw, and Henrik
+ Frystyk implemented <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> early, and we wish to thank them for the
+ discovery of many of the problems that this document attempts to
+ rectify.
+
+17 References
+
+ [1] Alvestrand, H., "Tags for the Identification of Languages", RFC
+ 1766, March 1995.
+
+ [2] Anklesaria, F., McCahill, M., Lindner, P., Johnson, D., Torrey,
+ D. and B. Alberti, "The Internet Gopher Protocol (a distributed
+ document search and retrieval protocol)", <a href="http://firefly.troll.no/rfcs/rfc1436.html">RFC 1436</a>, March 1993.
+
+ [3] Berners-Lee, T., "Universal Resource Identifiers in WWW", RFC
+ 1630, June 1994.
+
+ [4] Berners-Lee, T., Masinter, L. and M. McCahill, "Uniform Resource
+ Locators (URL)", <a href="http://firefly.troll.no/rfcs/rfc1738.html">RFC 1738</a>, December 1994.
+
+ [5] Berners-Lee, T. and D. Connolly, "Hypertext Markup Language -
+ 2.0", <a href="http://firefly.troll.no/rfcs/rfc1866.html">RFC 1866</a>, November 1995.
+
+ [6] Berners-Lee, T., Fielding, R. and H. Frystyk, "Hypertext Transfer
+ Protocol -- HTTP/1.0", <a href="http://firefly.troll.no/rfcs/rfc1945.html">RFC 1945</a>, May 1996.
+
+ [7] Freed, N. and N. Borenstein, "Multipurpose Internet Mail
+ Extensions (MIME) Part One: Format of Internet Message Bodies",
+ <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a>, November 1996.
+
+ [8] Braden, R., "Requirements for Internet Hosts -- Communication
+ Layers", STD 3, <a href="http://firefly.troll.no/rfcs/rfc1123.html">RFC 1123</a>, October 1989.
+
+ [9] Crocker, D., "Standard for The Format of ARPA Internet Text
+ Messages", STD 11, <a href="http://firefly.troll.no/rfcs/rfc822.html">RFC 822</a>, August 1982.
+
+ [10] Davis, F., Kahle, B., Morris, H., Salem, J., Shen, T., Wang, R.,
+ Sui, J., and M. Grinbaum, "WAIS Interface Protocol Prototype
+ Functional Specification," (v1.5), Thinking Machines
+ Corporation, April 1990.
+
+ [11] Fielding, R., "Relative Uniform Resource Locators", <a href="http://firefly.troll.no/rfcs/rfc1808.html">RFC 1808</a>,
+ June 1995.
+
+ [12] Horton, M. and R. Adams, "Standard for Interchange of USENET
+ Messages", <a href="http://firefly.troll.no/rfcs/rfc1036.html">RFC 1036</a>, December 1987.
+
+ [13] Kantor, B. and P. Lapsley, "Network News Transfer Protocol", RFC
+ 977, February 1986.
+
+ [14] Moore, K., "MIME (Multipurpose Internet Mail Extensions) Part
+ Three: Message Header Extensions for Non-ASCII Text", <a href="http://firefly.troll.no/rfcs/rfc2047.html">RFC 2047</a>,
+ November 1996.
+
+ [15] Nebel, E. and L. Masinter, "Form-based File Upload in HTML", RFC
+ 1867, November 1995.
+
+ [16] Postel, J., "Simple Mail Transfer Protocol", STD 10, <a href="http://firefly.troll.no/rfcs/rfc821.html">RFC 821</a>,
+ August 1982.
+
+ [17] Postel, J., "Media Type Registration Procedure", <a href="http://firefly.troll.no/rfcs/rfc1590.html">RFC 1590</a>,
+ November 1996.
+
+ [18] Postel, J. and J. Reynolds, "File Transfer Protocol", STD 9, RFC
+ 959, October 1985.
+
+ [19] Reynolds, J. and J. Postel, "Assigned Numbers", STD 2, <a href="http://firefly.troll.no/rfcs/rfc1700.html">RFC 1700</a>,
+ October 1994.
+
+ [20] Sollins, K. and L. Masinter, "Functional Requirements for
+ Uniform Resource Names", <a href="http://firefly.troll.no/rfcs/rfc1737.html">RFC 1737</a>, December 1994.
+
+ [21] US-ASCII. Coded Character Set - 7-Bit American Standard Code for
+ Information Interchange. Standard ANSI X3.4-1986, ANSI, 1986.
+
+ [22] ISO-8859. International Standard -- Information Processing --
+ 8-bit Single-Byte Coded Graphic Character Sets --
+ Part 1: Latin alphabet No. 1, ISO-8859-1:1987.
+ Part 2: Latin alphabet No. 2, ISO-8859-2, 1987.
+ Part 3: Latin alphabet No. 3, ISO-8859-3, 1988.
+ Part 4: Latin alphabet No. 4, ISO-8859-4, 1988.
+ Part 5: Latin/Cyrillic alphabet, ISO-8859-5, 1988.
+ Part 6: Latin/Arabic alphabet, ISO-8859-6, 1987.
+ Part 7: Latin/Greek alphabet, ISO-8859-7, 1987.
+ Part 8: Latin/Hebrew alphabet, ISO-8859-8, 1988.
+ Part 9: Latin alphabet No. 5, ISO-8859-9, 1990.
+
+ [23] Meyers, J. and M. Rose, "The Content-MD5 Header Field", RFC
+ 1864, October 1995.
+
+ [24] Carpenter, B. and Y. Rekhter, "Renumbering Needs Work", RFC
+ 1900, February 1996.
+
+ [25] Deutsch, P., "GZIP file format specification version 4.3", RFC
+ 1952, May 1996.
+
+ [26] Venkata N. Padmanabhan, and Jeffrey C. Mogul. "Improving HTTP
+ Latency", Computer Networks and ISDN Systems, v. 28, pp. 25-35,
+ Dec. 1995. Slightly revised version of paper in Proc. 2nd
+ International WWW Conference '94: Mosaic and the Web, Oct. 1994,
+ which is available at
+ <a href="http://www.ncsa.uiuc.edu/SDG/IT94/Proceedings/DDay/mogul/HTTPLat">http://www.ncsa.uiuc.edu/SDG/IT94/Proceedings/DDay/mogul/HTTPLat</a>
+ ency.html.
+
+ [27] Joe Touch, John Heidemann, and Katia Obraczka. "Analysis of HTTP
+ Performance", &lt;URL: <a href="http://www.isi.edu/touch/pubs/http-perf96/">http://www.isi.edu/touch/pubs/http-perf96/</a>&gt;,
+ ISI Research Report ISI/RR-98-463, (original report dated Aug.
+ 1996), USC/Information Sciences Institute, August 1998.
+
+ [28] Mills, D., "Network Time Protocol (Version 3) Specification,
+ Implementation and Analysis", <a href="http://firefly.troll.no/rfcs/rfc1305.html">RFC 1305</a>, March 1992.
+
+ [29] Deutsch, P., "DEFLATE Compressed Data Format Specification
+ version 1.3", <a href="http://firefly.troll.no/rfcs/rfc1951.html">RFC 1951</a>, May 1996.
+
+ [30] S. Spero, "Analysis of HTTP Performance Problems,"
+ <a href="http://sunsite.unc.edu/mdma-release/http-prob.html">http://sunsite.unc.edu/mdma-release/http-prob.html</a>.
+
+ [31] Deutsch, P. and J. Gailly, "ZLIB Compressed Data Format
+ Specification version 3.3", <a href="http://firefly.troll.no/rfcs/rfc1950.html">RFC 1950</a>, May 1996.
+
+ [32] Franks, J., Hallam-Baker, P., Hostetler, J., Leach, P.,
+ Luotonen, A., Sink, E. and L. Stewart, "An Extension to HTTP:
+ Digest Access Authentication", <a href="http://firefly.troll.no/rfcs/rfc2069.html">RFC 2069</a>, January 1997.
+
+ [33] Fielding, R., Gettys, J., Mogul, J., Frystyk, H. and T.
+ Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", RFC
+ 2068, January 1997.
+
+ [34] Bradner, S., "Key words for use in RFCs to Indicate Requirement
+ Levels", BCP 14, <a href="http://firefly.troll.no/rfcs/rfc2119.html">RFC 2119</a>, March 1997.
+
+ [35] Troost, R. and Dorner, S., "Communicating Presentation
+ Information in Internet Messages: The Content-Disposition
+ Header", <a href="http://firefly.troll.no/rfcs/rfc1806.html">RFC 1806</a>, June 1995.
+
+ [36] Mogul, J., Fielding, R., Gettys, J. and H. Frystyk, "Use and
+ Interpretation of HTTP Version Numbers", <a href="http://firefly.troll.no/rfcs/rfc2145.html">RFC 2145</a>, May 1997.
+ [jg639]
+
+ [37] Palme, J., "Common Internet Message Headers", <a href="http://firefly.troll.no/rfcs/rfc2076.html">RFC 2076</a>, February
+ 1997. [jg640]
+
+ [38] Yergeau, F., "UTF-8, a transformation format of Unicode and
+ ISO-10646", <a href="http://firefly.troll.no/rfcs/rfc2279.html">RFC 2279</a>, January 1998. [jg641]
+
+ [39] Nielsen, H.F., Gettys, J., Baird-Smith, A., Prud'hommeaux, E.,
+ Lie, H., and C. Lilley. "Network Performance Effects of
+ HTTP/1.1, CSS1, and PNG," Proceedings of ACM SIGCOMM '97, Cannes
+ France, September 1997.[jg642]
+
+ [40] Freed, N. and N. Borenstein, "Multipurpose Internet Mail
+ Extensions (MIME) Part Two: Media Types", <a href="http://firefly.troll.no/rfcs/rfc2046.html">RFC 2046</a>, November
+ 1996. [jg643]
+
+ [41] Alvestrand, H., "IETF Policy on Character Sets and Languages",
+ BCP 18, <a href="http://firefly.troll.no/rfcs/rfc2277.html">RFC 2277</a>, January 1998. [jg644]
+
+ [42] Berners-Lee, T., Fielding, R. and L. Masinter, "Uniform Resource
+ Identifiers (URI): Generic Syntax and Semantics", <a href="http://firefly.troll.no/rfcs/rfc2396.html">RFC 2396</a>,
+ August 1998. [jg645]
+
+ [43] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S.,
+ Leach, P., Luotonen, A., Sink, E. and L. Stewart, "HTTP
+ Authentication: Basic and Digest Access Authentication", RFC
+ 2617, June 1999. [jg646]
+
+ [44] Luotonen, A., "Tunneling TCP based protocols through Web proxy
+ servers," Work in Progress. [jg647]
+
+ [45] Palme, J. and A. Hopmann, "MIME E-mail Encapsulation of
+ Aggregate Documents, such as HTML (MHTML)", <a href="http://firefly.troll.no/rfcs/rfc2110.html">RFC 2110</a>, March
+ 1997.
+
+ [46] Bradner, S., "The Internet Standards Process -- Revision 3", BCP
+ 9, <a href="http://firefly.troll.no/rfcs/rfc2026.html">RFC 2026</a>, October 1996.
+
+ [47] Masinter, L., "Hyper Text Coffee Pot Control Protocol
+ (HTCPCP/1.0)", <a href="http://firefly.troll.no/rfcs/rfc2324.html">RFC 2324</a>, 1 April 1998.
+
+ [48] Freed, N. and N. Borenstein, "Multipurpose Internet Mail
+ Extensions (MIME) Part Five: Conformance Criteria and Examples",
+ <a href="http://firefly.troll.no/rfcs/rfc2049.html">RFC 2049</a>, November 1996.
+
+ [49] Troost, R., Dorner, S. and K. Moore, "Communicating Presentation
+ Information in Internet Messages: The Content-Disposition Header
+ Field", <a href="http://firefly.troll.no/rfcs/rfc2183.html">RFC 2183</a>, August 1997.
+
+18 Authors' Addresses
+
+ Roy T. Fielding
+ Information and Computer Science
+ University of California, Irvine
+ Irvine, CA 92697-3425, USA
+
+ Fax: +1 (949) 824-1715
+ EMail: <a href="mailto:fielding@ics.uci.edu">fielding@ics.uci.edu</a>
+
+ James Gettys
+ World Wide Web Consortium
+ MIT Laboratory for Computer Science
+ 545 Technology Square
+ Cambridge, MA 02139, USA
+
+ Fax: +1 (617) 258 8682
+ EMail: <a href="mailto:jg@w3.org">jg@w3.org</a>
+
+ Jeffrey C. Mogul
+ Western Research Laboratory
+ Compaq Computer Corporation
+ 250 University Avenue
+ Palo Alto, California, 94305, USA
+
+ EMail: <a href="mailto:mogul@wrl.dec.com">mogul@wrl.dec.com</a>
+
+ Henrik Frystyk Nielsen
+ World Wide Web Consortium
+ MIT Laboratory for Computer Science
+ 545 Technology Square
+ Cambridge, MA 02139, USA
+
+ Fax: +1 (617) 258 8682
+ EMail: <a href="mailto:frystyk@w3.org">frystyk@w3.org</a>
+
+ Larry Masinter
+ Xerox Corporation
+ 3333 Coyote Hill Road
+ Palo Alto, CA 94034, USA
+
+ EMail: <a href="mailto:masinter@parc.xerox.com">masinter@parc.xerox.com</a>
+
+ Paul J. Leach
+ Microsoft Corporation
+ 1 Microsoft Way
+ Redmond, WA 98052, USA
+
+ EMail: <a href="mailto:paulle@microsoft.com">paulle@microsoft.com</a>
+
+ Tim Berners-Lee
+ Director, World Wide Web Consortium
+ MIT Laboratory for Computer Science
+ 545 Technology Square
+ Cambridge, MA 02139, USA
+
+ Fax: +1 (617) 258 8682
+ EMail: <a href="mailto:timbl@w3.org">timbl@w3.org</a>
+
+19 Appendices
+
+19.1 Internet Media Type message/http and application/http
+
+ In addition to defining the HTTP/1.1 protocol, this document serves
+ as the specification for the Internet media type "message/http" and
+ "application/http". The message/http type can be used to enclose a
+ single HTTP request or response message, provided that it obeys the
+ MIME restrictions for all "message" types regarding line length and
+ encodings. The application/http type can be used to enclose a
+ pipeline of one or more HTTP request or response messages (not
+ intermixed). The following is to be registered with IANA [17].
+
+ Media Type name: message
+ Media subtype name: http
+ Required parameters: none
+ Optional parameters: version, msgtype
+ version: The HTTP-Version number of the enclosed message
+ (e.g., "1.1"). If not present, the version can be
+ determined from the first line of the body.
+ msgtype: The message type -- "request" or "response". If not
+ present, the type can be determined from the first
+ line of the body.
+ Encoding considerations: only "7bit", "8bit", or "binary" are
+ permitted
+ Security considerations: none
+
+ Media Type name: application
+ Media subtype name: http
+ Required parameters: none
+ Optional parameters: version, msgtype
+ version: The HTTP-Version number of the enclosed messages
+ (e.g., "1.1"). If not present, the version can be
+ determined from the first line of the body.
+ msgtype: The message type -- "request" or "response". If not
+ present, the type can be determined from the first
+ line of the body.
+ Encoding considerations: HTTP messages enclosed by this type
+ are in "binary" format; use of an appropriate
+ Content-Transfer-Encoding is required when
+ transmitted via E-mail.
+ Security considerations: none
+
+19.2 Internet Media Type multipart/byteranges
+
+ When an HTTP 206 (Partial Content) response message includes the
+ content of multiple ranges (a response to a request for multiple
+ non-overlapping ranges), these are transmitted as a multipart
+ message-body. The media type for this purpose is called
+ "multipart/byteranges".
+
+ The multipart/byteranges media type includes two or more parts, each
+ with its own Content-Type and Content-Range fields. The required
+ boundary parameter specifies the boundary string used to separate
+ each body-part.
+
+ Media Type name: multipart
+ Media subtype name: byteranges
+ Required parameters: boundary
+ Optional parameters: none
+ Encoding considerations: only "7bit", "8bit", or "binary" are
+ permitted
+ Security considerations: none
+
+ For example:
+
+ HTTP/1.1 206 Partial Content
+ Date: Wed, 15 Nov 1995 06:25:24 GMT
+ Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
+ Content-type: multipart/byteranges; boundary=THIS_STRING_SEPARATES
+
+ --THIS_STRING_SEPARATES
+ Content-type: application/pdf
+ Content-range: bytes 500-999/8000
+
+ ...the first range...
+ --THIS_STRING_SEPARATES
+ Content-type: application/pdf
+ Content-range: bytes 7000-7999/8000
+
+ ...the second range
+ --THIS_STRING_SEPARATES--
+
+ Notes:
+
+ 1) Additional CRLFs may precede the first boundary string in the
+ entity.
+
+ 2) Although <a href="http://firefly.troll.no/rfcs/rfc2046.html">RFC 2046</a> [40] permits the boundary string to be
+ quoted, some existing implementations handle a quoted boundary
+ string incorrectly.
+
+ 3) A number of browsers and servers were coded to an early draft
+ of the byteranges specification to use a media type of
+ multipart/x-byteranges, which is almost, but not quite
+ compatible with the version documented in HTTP/1.1.
+
+19.3 Tolerant Applications
+
+ Although this document specifies the requirements for the generation
+ of HTTP/1.1 messages, not all applications will be correct in their
+ implementation. We therefore recommend that operational applications
+ be tolerant of deviations whenever those deviations can be
+ interpreted unambiguously.
+
+ Clients SHOULD be tolerant in parsing the Status-Line and servers
+ tolerant when parsing the Request-Line. In particular, they SHOULD
+ accept any amount of SP or HT characters between fields, even though
+ only a single SP is required.
+
+ The line terminator for message-header fields is the sequence CRLF.
+ However, we recommend that applications, when parsing such headers,
+ recognize a single LF as a line terminator and ignore the leading CR.
+
+ The character set of an entity-body SHOULD be labeled as the lowest
+ common denominator of the character codes used within that body, with
+ the exception that not labeling the entity is preferred over labeling
+ the entity with the labels US-ASCII or ISO-8859-1. See section 3.7.1
+ and 3.4.1.
+
+ Additional rules for requirements on parsing and encoding of dates
+ and other potential problems with date encodings include:
+
+ - HTTP/1.1 clients and caches SHOULD assume that an <a href="http://firefly.troll.no/rfcs/rfc850.html">RFC-850</a> date
+ which appears to be more than 50 years in the future is in fact
+ in the past (this helps solve the "year 2000" problem).
+
+ - An HTTP/1.1 implementation MAY internally represent a parsed
+ Expires date as earlier than the proper value, but MUST NOT
+ internally represent a parsed Expires date as later than the
+ proper value.
+
+ - All expiration-related calculations MUST be done in GMT. The
+ local time zone MUST NOT influence the calculation or comparison
+ of an age or expiration time.
+
+ - If an HTTP header incorrectly carries a date value with a time
+ zone other than GMT, it MUST be converted into GMT using the
+ most conservative possible conversion.
+
+19.4 Differences Between HTTP Entities and <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a> Entities
+
+ HTTP/1.1 uses many of the constructs defined for Internet Mail (RFC
+ 822 [9]) and the Multipurpose Internet Mail Extensions (MIME [7]) to
+ allow entities to be transmitted in an open variety of
+ representations and with extensible mechanisms. However, <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a>
+ discusses mail, and HTTP has a few features that are different from
+ those described in <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a>. These differences were carefully chosen
+ to optimize performance over binary connections, to allow greater
+ freedom in the use of new media types, to make date comparisons
+ easier, and to acknowledge the practice of some early HTTP servers
+ and clients.
+
+ This appendix describes specific areas where HTTP differs from RFC
+ 2045. Proxies and gateways to strict MIME environments SHOULD be
+ aware of these differences and provide the appropriate conversions
+ where necessary. Proxies and gateways from MIME environments to HTTP
+ also need to be aware of the differences because some conversions
+ might be required.
+
+19.4.1 MIME-Version
+
+ HTTP is not a MIME-compliant protocol. However, HTTP/1.1 messages MAY
+ include a single MIME-Version general-header field to indicate what
+ version of the MIME protocol was used to construct the message. Use
+ of the MIME-Version header field indicates that the message is in
+ full compliance with the MIME protocol (as defined in <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a>[7]).
+ Proxies/gateways are responsible for ensuring full compliance (where
+ possible) when exporting HTTP messages to strict MIME environments.
+
+ MIME-Version = "MIME-Version" ":" 1*DIGIT "." 1*DIGIT
+
+ MIME version "1.0" is the default for use in HTTP/1.1. However,
+ HTTP/1.1 message parsing and semantics are defined by this document
+ and not the MIME specification.
+
+19.4.2 Conversion to Canonical Form
+
+ <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a> [7] requires that an Internet mail entity be converted to
+ canonical form prior to being transferred, as described in section 4
+ of <a href="http://firefly.troll.no/rfcs/rfc2049.html">RFC 2049</a> [48]. Section 3.7.1 of this document describes the forms
+ allowed for subtypes of the "text" media type when transmitted over
+ HTTP. <a href="http://firefly.troll.no/rfcs/rfc2046.html">RFC 2046</a> requires that content with a type of "text" represent
+ line breaks as CRLF and forbids the use of CR or LF outside of line
+
+ break sequences. HTTP allows CRLF, bare CR, and bare LF to indicate a
+ line break within text content when a message is transmitted over
+ HTTP.
+
+ Where it is possible, a proxy or gateway from HTTP to a strict MIME
+ environment SHOULD translate all line breaks within the text media
+ types described in section 3.7.1 of this document to the <a href="http://firefly.troll.no/rfcs/rfc2049.html">RFC 2049</a>
+ canonical form of CRLF. Note, however, that this might be complicated
+ by the presence of a Content-Encoding and by the fact that HTTP
+ allows the use of some character sets which do not use octets 13 and
+ 10 to represent CR and LF, as is the case for some multi-byte
+ character sets.
+
+ Implementors should note that conversion will break any cryptographic
+ checksums applied to the original content unless the original content
+ is already in canonical form. Therefore, the canonical form is
+ recommended for any content that uses such checksums in HTTP.
+
+19.4.3 Conversion of Date Formats
+
+ HTTP/1.1 uses a restricted set of date formats (section 3.3.1) to
+ simplify the process of date comparison. Proxies and gateways from
+ other protocols SHOULD ensure that any Date header field present in a
+ message conforms to one of the HTTP/1.1 formats and rewrite the date
+ if necessary.
+
+19.4.4 Introduction of Content-Encoding
+
+ <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a> does not include any concept equivalent to HTTP/1.1's
+ Content-Encoding header field. Since this acts as a modifier on the
+ media type, proxies and gateways from HTTP to MIME-compliant
+ protocols MUST either change the value of the Content-Type header
+ field or decode the entity-body before forwarding the message. (Some
+ experimental applications of Content-Type for Internet mail have used
+ a media-type parameter of ";conversions=&lt;content-coding&gt;" to perform
+ a function equivalent to Content-Encoding. However, this parameter is
+ not part of <a href="http://firefly.troll.no/rfcs/rfc2045.html">RFC 2045</a>.)
+
+19.4.5 No Content-Transfer-Encoding
+
+ HTTP does not use the Content-Transfer-Encoding (CTE) field of RFC
+ 2045. Proxies and gateways from MIME-compliant protocols to HTTP MUST
+ remove any non-identity CTE ("quoted-printable" or "base64") encoding
+ prior to delivering the response message to an HTTP client.
+
+ Proxies and gateways from HTTP to MIME-compliant protocols are
+ responsible for ensuring that the message is in the correct format
+ and encoding for safe transport on that protocol, where "safe
+
+ transport" is defined by the limitations of the protocol being used.
+ Such a proxy or gateway SHOULD label the data with an appropriate
+ Content-Transfer-Encoding if doing so will improve the likelihood of
+ safe transport over the destination protocol.
+
+19.4.6 Introduction of Transfer-Encoding
+
+ HTTP/1.1 introduces the Transfer-Encoding header field (section
+ 14.41). Proxies/gateways MUST remove any transfer-coding prior to
+ forwarding a message via a MIME-compliant protocol.
+
+ A process for decoding the "chunked" transfer-coding (section 3.6)
+ can be represented in pseudo-code as:
+
+ length := 0
+ read chunk-size, chunk-extension (if any) and CRLF
+ while (chunk-size &gt; 0) {
+ read chunk-data and CRLF
+ append chunk-data to entity-body
+ length := length + chunk-size
+ read chunk-size and CRLF
+ }
+ read entity-header
+ while (entity-header not empty) {
+ append entity-header to existing header fields
+ read entity-header
+ }
+ Content-Length := length
+ Remove "chunked" from Transfer-Encoding
+
+19.4.7 MHTML and Line Length Limitations
+
+ HTTP implementations which share code with MHTML [45] implementations
+ need to be aware of MIME line length limitations. Since HTTP does not
+ have this limitation, HTTP does not fold long lines. MHTML messages
+ being transported by HTTP follow all conventions of MHTML, including
+ line length limitations and folding, canonicalization, etc., since
+ HTTP transports all message-bodies as payload (see section 3.7.2) and
+ does not interpret the content or any MIME header lines that might be
+ contained therein.
+
+19.5 Additional Features
+
+ <a href="http://firefly.troll.no/rfcs/rfc1945.html">RFC 1945</a> and <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> document protocol elements used by some
+ existing HTTP implementations, but not consistently and correctly
+ across most HTTP/1.1 applications. Implementors are advised to be
+ aware of these features, but cannot rely upon their presence in, or
+ interoperability with, other HTTP/1.1 applications. Some of these
+
+ describe proposed experimental features, and some describe features
+ that experimental deployment found lacking that are now addressed in
+ the base HTTP/1.1 specification.
+
+ A number of other headers, such as Content-Disposition and Title,
+ from SMTP and MIME are also often implemented (see <a href="http://firefly.troll.no/rfcs/rfc2076.html">RFC 2076</a> [37]).
+
+19.5.1 Content-Disposition
+
+ The Content-Disposition response-header field has been proposed as a
+ means for the origin server to suggest a default filename if the user
+ requests that the content is saved to a file. This usage is derived
+ from the definition of Content-Disposition in <a href="http://firefly.troll.no/rfcs/rfc1806.html">RFC 1806</a> [35].
+
+ content-disposition = "Content-Disposition" ":"
+ disposition-type *( ";" disposition-parm )
+ disposition-type = "attachment" | disp-extension-token
+ disposition-parm = filename-parm | disp-extension-parm
+ filename-parm = "filename" "=" quoted-string
+ disp-extension-token = token
+ disp-extension-parm = token "=" ( token | quoted-string )
+
+ An example is
+
+ Content-Disposition: attachment; filename="fname.ext"
+
+ The receiving user agent SHOULD NOT respect any directory path
+ information present in the filename-parm parameter, which is the only
+ parameter believed to apply to HTTP implementations at this time. The
+ filename SHOULD be treated as a terminal component only.
+
+ If this header is used in a response with the application/octet-
+ stream content-type, the implied suggestion is that the user agent
+ should not display the response, but directly enter a `save response
+ as...' dialog.
+
+ See section 15.5 for Content-Disposition security issues.
+
+19.6 Compatibility with Previous Versions
+
+ It is beyond the scope of a protocol specification to mandate
+ compliance with previous versions. HTTP/1.1 was deliberately
+ designed, however, to make supporting previous versions easy. It is
+ worth noting that, at the time of composing this specification
+ (1996), we would expect commercial HTTP/1.1 servers to:
+
+ - recognize the format of the Request-Line for HTTP/0.9, 1.0, and
+ 1.1 requests;
+
+ - understand any valid request in the format of HTTP/0.9, 1.0, or
+ 1.1;
+
+ - respond appropriately with a message in the same major version
+ used by the client.
+
+ And we would expect HTTP/1.1 clients to:
+
+ - recognize the format of the Status-Line for HTTP/1.0 and 1.1
+ responses;
+
+ - understand any valid response in the format of HTTP/0.9, 1.0, or
+ 1.1.
+
+ For most implementations of HTTP/1.0, each connection is established
+ by the client prior to the request and closed by the server after
+ sending the response. Some implementations implement the Keep-Alive
+ version of persistent connections described in section 19.7.1 of RFC
+ 2068 [33].
+
+19.6.1 Changes from HTTP/1.0
+
+ This section summarizes major differences between versions HTTP/1.0
+ and HTTP/1.1.
+
+19.6.1.1 Changes to Simplify Multi-homed Web Servers and Conserve IP
+ Addresses
+
+ The requirements that clients and servers support the Host request-
+ header, report an error if the Host request-header (section 14.23) is
+ missing from an HTTP/1.1 request, and accept absolute URIs (section
+ 5.1.2) are among the most important changes defined by this
+ specification.
+
+ Older HTTP/1.0 clients assumed a one-to-one relationship of IP
+ addresses and servers; there was no other established mechanism for
+ distinguishing the intended server of a request than the IP address
+ to which that request was directed. The changes outlined above will
+ allow the Internet, once older HTTP clients are no longer common, to
+ support multiple Web sites from a single IP address, greatly
+ simplifying large operational Web servers, where allocation of many
+ IP addresses to a single host has created serious problems. The
+ Internet will also be able to recover the IP addresses that have been
+ allocated for the sole purpose of allowing special-purpose domain
+ names to be used in root-level HTTP URLs. Given the rate of growth of
+ the Web, and the number of servers already deployed, it is extremely
+
+ important that all implementations of HTTP (including updates to
+ existing HTTP/1.0 applications) correctly implement these
+ requirements:
+
+ - Both clients and servers MUST support the Host request-header.
+
+ - A client that sends an HTTP/1.1 request MUST send a Host header.
+
+ - Servers MUST report a 400 (Bad Request) error if an HTTP/1.1
+ request does not include a Host request-header.
+
+ - Servers MUST accept absolute URIs.
+
+19.6.2 Compatibility with HTTP/1.0 Persistent Connections
+
+ Some clients and servers might wish to be compatible with some
+ previous implementations of persistent connections in HTTP/1.0
+ clients and servers. Persistent connections in HTTP/1.0 are
+ explicitly negotiated as they are not the default behavior. HTTP/1.0
+ experimental implementations of persistent connections are faulty,
+ and the new facilities in HTTP/1.1 are designed to rectify these
+ problems. The problem was that some existing 1.0 clients may be
+ sending Keep-Alive to a proxy server that doesn't understand
+ Connection, which would then erroneously forward it to the next
+ inbound server, which would establish the Keep-Alive connection and
+ result in a hung HTTP/1.0 proxy waiting for the close on the
+ response. The result is that HTTP/1.0 clients must be prevented from
+ using Keep-Alive when talking to proxies.
+
+ However, talking to proxies is the most important use of persistent
+ connections, so that prohibition is clearly unacceptable. Therefore,
+ we need some other mechanism for indicating a persistent connection
+ is desired, which is safe to use even when talking to an old proxy
+ that ignores Connection. Persistent connections are the default for
+ HTTP/1.1 messages; we introduce a new keyword (Connection: close) for
+ declaring non-persistence. See section 14.10.
+
+ The original HTTP/1.0 form of persistent connections (the Connection:
+ Keep-Alive and Keep-Alive header) is documented in <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a>. [33]
+
+19.6.3 Changes from <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a>
+
+ This specification has been carefully audited to correct and
+ disambiguate key word usage; <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> had many problems in respect to
+ the conventions laid out in <a href="http://firefly.troll.no/rfcs/rfc2119.html">RFC 2119</a> [34].
+
+ Clarified which error code should be used for inbound server failures
+ (e.g. DNS failures). (Section 10.5.5).
+
+ CREATE had a race that required an Etag be sent when a resource is
+ first created. (Section 10.2.2).
+
+ Content-Base was deleted from the specification: it was not
+ implemented widely, and there is no simple, safe way to introduce it
+ without a robust extension mechanism. In addition, it is used in a
+ similar, but not identical fashion in MHTML [45].
+
+ Transfer-coding and message lengths all interact in ways that
+ required fixing exactly when chunked encoding is used (to allow for
+ transfer encoding that may not be self delimiting); it was important
+ to straighten out exactly how message lengths are computed. (Sections
+ 3.6, 4.4, 7.2.2, 13.5.2, 14.13, 14.16)
+
+ A content-coding of "identity" was introduced, to solve problems
+ discovered in caching. (section 3.5)
+
+ Quality Values of zero should indicate that "I don't want something"
+ to allow clients to refuse a representation. (Section 3.9)
+
+ The use and interpretation of HTTP version numbers has been clarified
+ by <a href="http://firefly.troll.no/rfcs/rfc2145.html">RFC 2145</a>. Require proxies to upgrade requests to highest protocol
+ version they support to deal with problems discovered in HTTP/1.0
+ implementations (Section 3.1)
+
+ Charset wildcarding is introduced to avoid explosion of character set
+ names in accept headers. (Section 14.2)
+
+ A case was missed in the Cache-Control model of HTTP/1.1; s-maxage
+ was introduced to add this missing case. (Sections 13.4, 14.8, 14.9,
+ 14.9.3)
+
+ The Cache-Control: max-age directive was not properly defined for
+ responses. (Section 14.9.3)
+
+ There are situations where a server (especially a proxy) does not
+ know the full length of a response but is capable of serving a
+ byterange request. We therefore need a mechanism to allow byteranges
+ with a content-range not indicating the full length of the message.
+ (Section 14.16)
+
+ Range request responses would become very verbose if all meta-data
+ were always returned; by allowing the server to only send needed
+ headers in a 206 response, this problem can be avoided. (Section
+ 10.2.7, 13.5.3, and 14.27)
+
+ Fix problem with unsatisfiable range requests; there are two cases:
+ syntactic problems, and range doesn't exist in the document. The 416
+ status code was needed to resolve this ambiguity needed to indicate
+ an error for a byte range request that falls outside of the actual
+ contents of a document. (Section 10.4.17, 14.16)
+
+ Rewrite of message transmission requirements to make it much harder
+ for implementors to get it wrong, as the consequences of errors here
+ can have significant impact on the Internet, and to deal with the
+ following problems:
+
+ 1. Changing "HTTP/1.1 or later" to "HTTP/1.1", in contexts where
+ this was incorrectly placing a requirement on the behavior of
+ an implementation of a future version of HTTP/1.x
+
+ 2. Made it clear that user-agents should retry requests, not
+ "clients" in general.
+
+ 3. Converted requirements for clients to ignore unexpected 100
+ (Continue) responses, and for proxies to forward 100 responses,
+ into a general requirement for 1xx responses.
+
+ 4. Modified some TCP-specific language, to make it clearer that
+ non-TCP transports are possible for HTTP.
+
+ 5. Require that the origin server MUST NOT wait for the request
+ body before it sends a required 100 (Continue) response.
+
+ 6. Allow, rather than require, a server to omit 100 (Continue) if
+ it has already seen some of the request body.
+
+ 7. Allow servers to defend against denial-of-service attacks and
+ broken clients.
+
+ This change adds the Expect header and 417 status code. The message
+ transmission requirements fixes are in sections 8.2, 10.4.18,
+ 8.1.2.2, 13.11, and 14.20.
+
+ Proxies should be able to add Content-Length when appropriate.
+ (Section 13.5.2)
+
+ Clean up confusion between 403 and 404 responses. (Section 10.4.4,
+ 10.4.5, and 10.4.11)
+
+ Warnings could be cached incorrectly, or not updated appropriately.
+ (Section 13.1.2, 13.2.4, 13.5.2, 13.5.3, 14.9.3, and 14.46) Warning
+ also needed to be a general header, as PUT or other methods may have
+ need for it in requests.
+
+ Transfer-coding had significant problems, particularly with
+ interactions with chunked encoding. The solution is that transfer-
+ codings become as full fledged as content-codings. This involves
+ adding an IANA registry for transfer-codings (separate from content
+ codings), a new header field (TE) and enabling trailer headers in the
+ future. Transfer encoding is a major performance benefit, so it was
+ worth fixing [39]. TE also solves another, obscure, downward
+ interoperability problem that could have occurred due to interactions
+ between authentication trailers, chunked encoding and HTTP/1.0
+ clients.(Section 3.6, 3.6.1, and 14.39)
+
+ The PATCH, LINK, UNLINK methods were defined but not commonly
+ implemented in previous versions of this specification. See <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a>
+ [33].
+
+ The Alternates, Content-Version, Derived-From, Link, URI, Public and
+ Content-Base header fields were defined in previous versions of this
+ specification, but not commonly implemented. See <a href="http://firefly.troll.no/rfcs/rfc2068.html">RFC 2068</a> [33].
+
+20 Index
+
+ Please see the PostScript version of this RFC for the INDEX.
+
+21. Full Copyright Statement
+
+ Copyright (C) The Internet Society (1999). All Rights Reserved.
+
+ This document and translations of it may be copied and furnished to
+ others, and derivative works that comment on or otherwise explain it
+ or assist in its implementation may be prepared, copied, published
+ and distributed, in whole or in part, without restriction of any
+ kind, provided that the above copyright notice and this paragraph are
+ included on all such copies and derivative works. However, this
+ document itself may not be modified in any way, such as by removing
+ the copyright notice or references to the Internet Society or other
+ Internet organizations, except as needed for the purpose of
+ developing Internet standards in which case the procedures for
+ copyrights defined in the Internet Standards process must be
+ followed, or as required to translate it into languages other than
+ English.
+
+ The limited permissions granted above are perpetual and will not be
+ revoked by the Internet Society or its successors or assigns.
+
+ This document and the information contained herein is provided on an
+ "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+ TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
+ BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
+ HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+ MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+Acknowledgement
+
+ Funding for the RFC Editor function is currently provided by the
+ Internet Society.
+
+</pre>
+<p align="center"><script language="JavaScript"><!--
+erfc("2616");
+// --></script><a href="http://firefly.troll.no/rfccomment.php?rfcnum=2616" target="_blank" onclick="window.open('/rfccomment.php?rfcnum=2616','Popup','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=680,height=530,left=30,top=43'); return false;" )="">Comment on RFC 2616</a>
+</p>
+&nbsp;<br>
+<div align="center">
+<center>
+<table border="0" cellpadding="4" cellspacing="4" width="100%">
+<tbody><tr><td bgcolor="#d6d6c0" width="100%">
+<p><font face="Arial">Comments about this RFC:</font></p>
+<ul>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-869.html">RFC 2616: Very basic HTTP Server written in Emacs Lisp: http://www.chez.com/emarsden/downl...</a> by Alex Schröder (5/12/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-539.html">RFC 2616: If someone has got sample code for a basic HTTP/1.1 Server please let me know......</a> by Mike (2/4/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-486.html">RFC 2616: I am seeking ladies for nothing but sex that is all i want from the lady sorry...</a> by treblav (1/16/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-2360.html">RFC 2616: Hello.
+
+ I have realized that point 8.1.4 of the RFC 2616 is a big threat to...</a> by Doolyo (8/20/2005)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-1522.html">RFC 2616: êêêöïïäììóì::::::@::@"""@:&gt;c
+ :::@"$$%^^*^^*((((99(
+ &lt;&lt;&gt;:"? </a> by óäöóöóöóö (12/16/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-2147.html">RFC 2616: Man Such a big and boring doc.. thats why ppl shy away from RFC stuff. Make it...</a> by AnurgaM (6/15/2005)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-2277.html">RFC 2616: igeve uo 100 dolars
+
+ iwant password
+
+ farh51@hotmail.com </a> by farh (7/24/2005)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-2349.html">RFC 2616: I have realized that point 8.1.4 of this RFC is a big threat to the load speed...</a> by Doolyo (8/15/2005)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-1230.html">RFC 2616: Would it possible to extend the
+ protocol to allow another GET,
+ HEAD, POST,...</a> by CCaldwell (9/15/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-692.html">RFC 2616: Wonder if he got his lady? </a> by SinJax (3/26/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-2056.html">RFC 2616: it's for shareaza that the program go fasther </a> by sylle (5/24/2005)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-2526.html">RFC 2616: Only 2 simultaneous connections is a big threat to the load speed of HTML...</a> by Doolyo (9/30/2005)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-736.html">RFC 2616: yo to the southampton uni coursework massive </a> by anon (4/6/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-1574.html">RFC 2616: If you know everything about HTTP this rfc will be helpful to you (as a recap...</a> by just a developer (1/5/2005)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-1111.html">RFC 2616: Please note that section 3.6.2, referenced in section 3.5 (page 25)
+ may most...</a> by Patrick Powell (8/12/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-1354.html">RFC 2616: gtu87t 86t8o;koip]0-n df bhvfjkhfgfter6ecvgjlhhjuhjioy uftyei vn bk.jljpoi
+ =- ...</a> by jkl (10/20/2004)</font></li>
+<li><font face="Arial"><a href="http://firefly.troll.no/qa/rfcc-1973.html">RFC 2616: I HOPE KNOW MANY OF SOME RFC </a> by MARRY (5/5/2005)</font></li>
+</ul>
+</td></tr></tbody></table> <br></center></div>
+<div align="center">
+<table border="0" cellpadding="3" cellspacing="3" width="100%">
+<tbody><tr><td width="45%">
+<p align="left">Previous: <a href="http://firefly.troll.no/rfcs/rfc2615.html">RFC 2615 - PPP over SONET/SDH</a>
+</p></td><td width="10%">&nbsp;</td><td width="45%">
+<p align="right">Next: <a href="http://firefly.troll.no/rfcs/rfc2617.html">RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication</a>
+</p></td></tr></tbody></table></div><p align="right">&nbsp;</p>
+<hr noshade="noshade" size="2">
+<div align="center">[ <a href="http://firefly.troll.no/rfcs/">RFC Index</a> | <a href="http://firefly.troll.no/rfcs/rfcsearch.html">RFC Search</a> | <a href="http://firefly.troll.no/faqs/">Usenet FAQs</a> | <a href="http://firefly.troll.no/contrib/">Web FAQs</a> | <a href="http://firefly.troll.no/docs/">Documents</a> | <a href="http://www.city-data.com/">Cities</a> ]
+<p>
+</p></div>
+ <a href="http://firefly.troll.no/ftp/rfc/rfc2616.pdf">rfc2616.pdf</a>
+<small>
+<address>
+<p align="center">
+
+</p>
+</address>
+</small>
+</body></html> \ No newline at end of file
diff --git a/tests/testserver/cyrus/cyrus.sh b/tests/testserver/cyrus/cyrus.sh
new file mode 100755
index 0000000000..bd09acffc8
--- /dev/null
+++ b/tests/testserver/cyrus/cyrus.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+
+#############################################################################
+##
+## Copyright (C) 2019 The Qt Company Ltd.
+## Contact: https://www.qt.io/licensing/
+##
+## This file is part of the test suite of the Qt Toolkit.
+##
+## $QT_BEGIN_LICENSE:GPL$
+## Commercial License Usage
+## Licensees holding valid commercial Qt licenses may use this file in
+## accordance with the commercial license agreement provided with the
+## Software or, alternatively, in accordance with the terms contained in
+## a written agreement between you and The Qt Company. For licensing terms
+## and conditions see https://www.qt.io/terms-conditions. For further
+## information use the contact form at https://www.qt.io/contact-us.
+##
+## GNU General Public License Usage
+## Alternatively, this file may be used under the terms of the GNU
+## General Public License version 3 or (at your option) any later version
+## approved by the KDE Free Qt Foundation. The licenses are as published by
+## the Free Software Foundation and appearing in the file LICENSE.GPL3
+## included in the packaging of this file. Please review the following
+## information to ensure the GNU General Public License requirements will
+## be met: https://www.gnu.org/licenses/gpl-3.0.html.
+##
+## $QT_END_LICENSE$
+##
+#############################################################################
+
+set -ex
+
+service cyrus-imapd start
diff --git a/tests/testserver/docker-compose.yml b/tests/testserver/docker-compose.yml
index be65e5a26a..4286c88211 100644
--- a/tests/testserver/docker-compose.yml
+++ b/tests/testserver/docker-compose.yml
@@ -31,6 +31,9 @@ services:
- apache2
external_links:
- apache2:apache2.${TEST_DOMAIN}
+ - cyrus:cyrus.${TEST_DOMAIN}
+ - iptables:iptables.${TEST_DOMAIN}
+ - vsftpd:vsftpd.${TEST_DOMAIN}
volumes:
- ./common:/common:ro
- ./squid:/service:ro
@@ -76,8 +79,34 @@ services:
- apache2:apache2.${TEST_DOMAIN}
- vsftpd:vsftpd.${TEST_DOMAIN}
- ftp-proxy:ftp-proxy.${TEST_DOMAIN}
+ - cyrus:cyrus.${TEST_DOMAIN}
volumes:
- ./common:/common:ro
- ./danted:/service:ro
entrypoint: common/startup.sh
command: service/danted.sh
+
+ cyrus:
+ image: qt-test-server-cyrus:c8d72754abc0e501afd624ce838e4df35505abc9
+ container_name: qt-test-server-cyrus
+ domainname: ${TEST_DOMAIN}
+ hostname: cyrus
+ volumes:
+ - ./common:/common:ro
+ - ./cyrus:/service:ro
+ entrypoint: common/startup.sh
+ command: service/cyrus.sh
+
+ iptables:
+ image: qt-test-server-iptables:cb7a8bd6d28602085a88c8ced7d67e28e75781e2
+ container_name: qt-test-server-iptables
+ domainname: ${TEST_DOMAIN}
+ hostname: iptables
+ volumes:
+ - ./common:/common:ro
+ - ./iptables:/service:ro
+ entrypoint: common/startup.sh
+ command: service/iptables.sh
+ cap_add:
+ - NET_ADMIN
+ - NET_RAW
diff --git a/tests/testserver/iptables/iptables.sh b/tests/testserver/iptables/iptables.sh
new file mode 100755
index 0000000000..9a48686d8b
--- /dev/null
+++ b/tests/testserver/iptables/iptables.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+
+#############################################################################
+##
+## Copyright (C) 2019 The Qt Company Ltd.
+## Contact: https://www.qt.io/licensing/
+##
+## This file is part of the test suite of the Qt Toolkit.
+##
+## $QT_BEGIN_LICENSE:GPL$
+## Commercial License Usage
+## Licensees holding valid commercial Qt licenses may use this file in
+## accordance with the commercial license agreement provided with the
+## Software or, alternatively, in accordance with the terms contained in
+## a written agreement between you and The Qt Company. For licensing terms
+## and conditions see https://www.qt.io/terms-conditions. For further
+## information use the contact form at https://www.qt.io/contact-us.
+##
+## GNU General Public License Usage
+## Alternatively, this file may be used under the terms of the GNU
+## General Public License version 3 or (at your option) any later version
+## approved by the KDE Free Qt Foundation. The licenses are as published by
+## the Free Software Foundation and appearing in the file LICENSE.GPL3
+## included in the packaging of this file. Please review the following
+## information to ensure the GNU General Public License requirements will
+## be met: https://www.gnu.org/licenses/gpl-3.0.html.
+##
+## $QT_END_LICENSE$
+##
+#############################################################################
+
+set -ex
+
+iptables -A INPUT -p tcp --destination-port 1357 -j DROP