diff options
author | Qt Continuous Integration System <qt-info@nokia.com> | 2011-04-18 06:31:10 (GMT) |
---|---|---|
committer | Qt Continuous Integration System <qt-info@nokia.com> | 2011-04-18 06:31:10 (GMT) |
commit | a4d33d8c3cd206b982962014323abb673f5c64e3 (patch) | |
tree | 2bd6a5e2b3dba061cdbb610c46789f78696063b3 /tests | |
parent | 45e3500d8a34bee9893eff95b494497d29f7a61b (diff) | |
parent | 6e74302238fbac8783eab36f7553eb30dc5ca352 (diff) | |
download | Qt-a4d33d8c3cd206b982962014323abb673f5c64e3.zip Qt-a4d33d8c3cd206b982962014323abb673f5c64e3.tar.gz Qt-a4d33d8c3cd206b982962014323abb673f5c64e3.tar.bz2 |
Merge branch 'master' of scm.dev.nokia.troll.no:qt/qt-earth-staging into master-integration
* 'master' of scm.dev.nokia.troll.no:qt/qt-earth-staging: (163 commits)
QLocale: Fixed double to currency string conversion on Mac.
Fix qstringbuilder4 test on mac
Compile on Mac.
Revert "HTTP caching internals: fix logic for PreferNetwork and PreferCache"
Use the qt_static_metacall in QueuedConnection
Fix crash after merge of the native symbian thread branch.
Fix bad merge
Re-apply part of ba8e5eedf5f40091eb67dd391a7dcaf9299db2f5
Removed useless comment
SSL code: introduce new error value for blacklisted certificates
Disable DEF files by default for symbian-gcce.
HTTP caching internals: fix logic for PreferNetwork and PreferCache
Added a consistency check for number of missing symbols in elf2e32.
Updated def file after symbol removal.
QLocalSocket: fix abort on Windows.
QStringBuilder: add operator += for QString and QByteArray
Dummy commit to trigger pulse.
Fix QMetaObject::indexOfSlot
Fix compilation
Documentation for the initilize_list constructor
...
Diffstat (limited to 'tests')
66 files changed, 3353 insertions, 833 deletions
diff --git a/tests/auto/collections/tst_collections.cpp b/tests/auto/collections/tst_collections.cpp index 9b24660..b1ea326 100644 --- a/tests/auto/collections/tst_collections.cpp +++ b/tests/auto/collections/tst_collections.cpp @@ -104,13 +104,6 @@ void foo() #include "q3cleanuphandler.h" #endif -// Do not test initialization of pods on msvc6 and msvc 2002 -// This is a known issue -#if defined Q_CC_MSVC && _MSC_VER < 1310 -# define NOPODINITIALIZATION -#endif - - template class QList<int>; //TESTED_FILES= @@ -198,10 +191,6 @@ QT_END_NAMESPACE struct Pod { int i1, i2; - -#if defined NOPODINITIALIZATION - Pod() : i1(0), i2(0) { } -#endif }; tst_Collections::tst_Collections() diff --git a/tests/auto/declarative/declarative.pro b/tests/auto/declarative/declarative.pro index 08f0b9e..98e15e8 100644 --- a/tests/auto/declarative/declarative.pro +++ b/tests/auto/declarative/declarative.pro @@ -76,11 +76,6 @@ contains(QT_CONFIG, private_tests) { qdeclarativeworkerscript \ qdeclarativexmllistmodel \ qpacketprotocol - -contains(QT_CONFIG, webkit) { - SUBDIRS += \ - qdeclarativewebview -} } # Tests which should run in Pulse diff --git a/tests/auto/declarative/qdeclarativewebview/data/basic.html b/tests/auto/declarative/qdeclarativewebview/data/basic.html deleted file mode 100644 index 22e3e24..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/basic.html +++ /dev/null @@ -1,17 +0,0 @@ -<html> -<head><title>Basic</title> -<link rel="icon" sizes="48x48" href="basic.png"> -<script type="text/javascript"> -<!-- -window.onload = function(){ window.status = "status here"; } -// --> -</script> -</head> -<body leftmargin="0" marginwidth="0"> -<table width="123"> -<tbody> -<tr><td>This is a basic test.</td></tr> -</tbody> -</table> -</body> -</html> diff --git a/tests/auto/declarative/qdeclarativewebview/data/basic.ico b/tests/auto/declarative/qdeclarativewebview/data/basic.ico Binary files differdeleted file mode 100644 index 8f3d05e..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/basic.ico +++ /dev/null diff --git a/tests/auto/declarative/qdeclarativewebview/data/basic.png b/tests/auto/declarative/qdeclarativewebview/data/basic.png Binary files differdeleted file mode 100644 index 35717cc..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/basic.png +++ /dev/null diff --git a/tests/auto/declarative/qdeclarativewebview/data/basic.qml b/tests/auto/declarative/qdeclarativewebview/data/basic.qml deleted file mode 100644 index 73330cd..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/basic.qml +++ /dev/null @@ -1,6 +0,0 @@ -import QtQuick 1.0 -import QtWebKit 1.0 - -WebView { - url: "basic.html" -} diff --git a/tests/auto/declarative/qdeclarativewebview/data/elements.html b/tests/auto/declarative/qdeclarativewebview/data/elements.html deleted file mode 100644 index 9236867..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/elements.html +++ /dev/null @@ -1,14 +0,0 @@ -<body leftmargin=0 topmargin=0> -<table width="300px" border=1 cellpadding=0 cellspacing=0> -<tr> -<td align=center width=25%%><p>A</p></td> -<td width=75% height=50px> - <table width=100% border=1 cellpadding=0 cellspacing=0> - <tr> - <td align=center width=50% height=50px><p>B</p></td> - <td align=center width=50% height=50px><p>C</p></td> - </tr> - </table> -</td> -</tr> -</table> diff --git a/tests/auto/declarative/qdeclarativewebview/data/elements.qml b/tests/auto/declarative/qdeclarativewebview/data/elements.qml deleted file mode 100644 index b86dd9d..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/elements.qml +++ /dev/null @@ -1,8 +0,0 @@ -import QtQuick 1.0 -import QtWebKit 1.0 - -WebView { - url: "elements.html" - width: 310 - height: 100 -} diff --git a/tests/auto/declarative/qdeclarativewebview/data/forward.html b/tests/auto/declarative/qdeclarativewebview/data/forward.html deleted file mode 100644 index 62ab62d..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/forward.html +++ /dev/null @@ -1,12 +0,0 @@ -<html> -<head><title>Forward</title> -<link rel="icon" sizes="32x32" href="forward.png"> -</head> -<body leftmargin="0" marginwidth="0"> -<table width="123"> -<tbody> -<tr><td>This is more.</td></tr> -</tbody> -</table> -</body> -</html> diff --git a/tests/auto/declarative/qdeclarativewebview/data/forward.png b/tests/auto/declarative/qdeclarativewebview/data/forward.png Binary files differdeleted file mode 100644 index a82533e..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/forward.png +++ /dev/null diff --git a/tests/auto/declarative/qdeclarativewebview/data/javaScript.html b/tests/auto/declarative/qdeclarativewebview/data/javaScript.html deleted file mode 100644 index 35270bc..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/javaScript.html +++ /dev/null @@ -1,11 +0,0 @@ -<html> -<head><title>JavaScript</title> -<link rel="icon" sizes="48x48" href="basic.png"> -<script type="text/javascript"> -<!-- -window.onload = function(){ window.status = "status here"; } -// --> -</script> -</head> -<body> -This is a JS test. diff --git a/tests/auto/declarative/qdeclarativewebview/data/javaScript.qml b/tests/auto/declarative/qdeclarativewebview/data/javaScript.qml deleted file mode 100644 index 527e3b9..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/javaScript.qml +++ /dev/null @@ -1,12 +0,0 @@ -import QtQuick 1.0 -import QtWebKit 1.0 - -WebView { - url: "javaScript.html" - javaScriptWindowObjects: [ - QtObject { - property string qmlprop: "qmlvalue" - WebView.windowObjectName: "myjsname" - } - ] -} diff --git a/tests/auto/declarative/qdeclarativewebview/data/loadError.qml b/tests/auto/declarative/qdeclarativewebview/data/loadError.qml deleted file mode 100644 index baab1a0..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/loadError.qml +++ /dev/null @@ -1,6 +0,0 @@ -import QtQuick 1.0 -import QtWebKit 1.0 - -WebView { - url: "does-not-exist.html" -} diff --git a/tests/auto/declarative/qdeclarativewebview/data/newwindows.html b/tests/auto/declarative/qdeclarativewebview/data/newwindows.html deleted file mode 100644 index dd541f9..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/newwindows.html +++ /dev/null @@ -1,16 +0,0 @@ -<html> -<head> -<script type="text/javascript"> -<!-- -function clickTheLink() -{ - var ev = document.createEvent('MouseEvents'); - ev.initEvent( "click", true, false ); - document.getElementById('thelink').dispatchEvent(ev); -} -// --> -</script> -</head> -<h1>Multiple windows...</h1> - -<a id=thelink target="_blank" href="newwindows.html">Popup!</a> diff --git a/tests/auto/declarative/qdeclarativewebview/data/newwindows.qml b/tests/auto/declarative/qdeclarativewebview/data/newwindows.qml deleted file mode 100644 index e66631d..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/newwindows.qml +++ /dev/null @@ -1,34 +0,0 @@ -// Demonstrates opening new WebViews from HTML - -import QtQuick 1.0 -import QtWebKit 1.0 - -Grid { - columns: 3 - id: pages - height: 300; width: 600 - property int total: 0 - - Component { - id: webViewPage - Rectangle { - width: webView.width - height: webView.height - border.color: "gray" - - WebView { - id: webView - width: 150 // force predictable for test - newWindowComponent: webViewPage - newWindowParent: pages - url: "newwindows.html" - Timer { - interval: 10; running: total<4; repeat: false; - onTriggered: { if (webView.status==WebView.Ready) { total++; webView.evaluateJavaScript("clickTheLink()") } } - } - } - } - } - - Loader { sourceComponent: webViewPage } -} diff --git a/tests/auto/declarative/qdeclarativewebview/data/pixelCache.html b/tests/auto/declarative/qdeclarativewebview/data/pixelCache.html deleted file mode 100644 index 9412674..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/pixelCache.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> -<body topmargin=0 leftmargin=0> -<table width=120 cellpadding=0 cellspacing=0> -<tr><td> -<h1>Pixel Cache</h1> -This test is for the pixel cache. Because this is a long document, -as it scrolls, more of the document will need to be rendered. -If the pixelCacheSize is small, the first parts of the document will -no longer be in the cache when it returns. -</table> diff --git a/tests/auto/declarative/qdeclarativewebview/data/pixelCache.qml b/tests/auto/declarative/qdeclarativewebview/data/pixelCache.qml deleted file mode 100644 index 08e4d65..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/pixelCache.qml +++ /dev/null @@ -1,6 +0,0 @@ -import Test 1.0 - -MyWebView { - anchors.fill: parent - url: "pixelCache.html" -} diff --git a/tests/auto/declarative/qdeclarativewebview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativewebview/data/propertychanges.qml deleted file mode 100644 index db06887..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/propertychanges.qml +++ /dev/null @@ -1,34 +0,0 @@ -import QtQuick 1.0 -import QtWebKit 1.0 - -Item { - width: 240 - height: 160 - Grid { - anchors.fill: parent - objectName: "newWindowParent" - id: newWindowParent - } - - Row { - anchors.fill: parent - id: oldWindowParent - objectName: "oldWindowParent" - } - - Loader { - sourceComponent: webViewComponent - } - Component { - id: webViewComponent - WebView { - id: webView - objectName: "webView" - newWindowComponent: webViewComponent - newWindowParent: oldWindowParent - url: "basic.html" - renderingEnabled: true - pressGrabTime: 200 - } - } -} diff --git a/tests/auto/declarative/qdeclarativewebview/data/sethtml.qml b/tests/auto/declarative/qdeclarativewebview/data/sethtml.qml deleted file mode 100644 index 7889704..0000000 --- a/tests/auto/declarative/qdeclarativewebview/data/sethtml.qml +++ /dev/null @@ -1,6 +0,0 @@ -import QtQuick 1.0 -import QtWebKit 1.0 - -WebView { - html: "<p>This is a <b>string</b> set on the WebView" -} diff --git a/tests/auto/declarative/qdeclarativewebview/qdeclarativewebview.pro b/tests/auto/declarative/qdeclarativewebview/qdeclarativewebview.pro deleted file mode 100644 index af13d33..0000000 --- a/tests/auto/declarative/qdeclarativewebview/qdeclarativewebview.pro +++ /dev/null @@ -1,16 +0,0 @@ -load(qttest_p4) -contains(QT_CONFIG,declarative): QT += declarative -contains(QT_CONFIG,webkit): QT += webkit -macx:CONFIG -= app_bundle - -SOURCES += tst_qdeclarativewebview.cpp - -symbian: { - importFiles.files = data - importFiles.path = . - DEPLOYMENT += importFiles -} else { - DEFINES += SRCDIR=\\\"$$PWD\\\" -} - -CONFIG += parallel_test diff --git a/tests/auto/declarative/qdeclarativewebview/tst_qdeclarativewebview.cpp b/tests/auto/declarative/qdeclarativewebview/tst_qdeclarativewebview.cpp deleted file mode 100644 index 9f99e83..0000000 --- a/tests/auto/declarative/qdeclarativewebview/tst_qdeclarativewebview.cpp +++ /dev/null @@ -1,520 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#include <qtest.h> -#include <QtTest/QSignalSpy> -#include "../../../shared/util.h" -#include <QtDeclarative/qdeclarativeengine.h> -#include <QtDeclarative/qdeclarativecomponent.h> -#include <private/qdeclarativepositioners_p.h> -#include <QtWebKit/qwebpage.h> -#include <QtWebKit/qwebframe.h> -#include <QtCore/qdir.h> -#include <QtCore/qfile.h> -#include <QtGui/qpainter.h> - -#ifdef Q_OS_SYMBIAN -// In Symbian OS test data is located in applications private dir -#define SRCDIR "." -#endif - -class tst_qdeclarativewebview : public QObject -{ - Q_OBJECT -public: - tst_qdeclarativewebview() {} - -private slots: - void initTestCase(); - void basicProperties(); - void settings(); - void historyNav(); - void multipleWindows(); - void elementAreaAt(); - void loadError(); - void setHtml(); - void javaScript(); - void cleanupTestCase(); - //void pixelCache(); - void newWindowParent(); - void newWindowComponent(); - void renderingEnabled(); - void pressGrabTime(); - -private: - void checkNoErrors(const QDeclarativeComponent& component); - QDeclarativeEngine engine; - QString tmpDir() const - { - static QString tmpd = QDir::tempPath()+"/tst_qdeclarativewebview-" - + QDateTime::currentDateTime().toString(QLatin1String("yyyyMMddhhmmss")); - return tmpd; - } -}; - -void tst_qdeclarativewebview::initTestCase() -{ -} - -static QString strippedHtml(QString html) -{ - html.replace(QRegExp("\\s+"),""); - return html; -} - -static QString fileContents(const QString& filename) -{ - QFile file(filename); - file.open(QIODevice::ReadOnly); - return QString::fromUtf8(file.readAll()); -} - - -static void removeRecursive(const QString& dirname) -{ - QDir dir(dirname); - QFileInfoList entries(dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot)); - for (int i = 0; i < entries.count(); ++i) - if (entries[i].isDir()) - removeRecursive(entries[i].filePath()); - else - dir.remove(entries[i].fileName()); - QDir().rmdir(dirname); -} - -void tst_qdeclarativewebview::cleanupTestCase() -{ - removeRecursive(tmpDir()); -} - -void tst_qdeclarativewebview::checkNoErrors(const QDeclarativeComponent& component) -{ - // Wait until the component is ready - QTRY_VERIFY(component.isReady() || component.isError()); - - if (component.isError()) { - QList<QDeclarativeError> errors = component.errors(); - for (int ii = 0; ii < errors.count(); ++ii) { - const QDeclarativeError &error = errors.at(ii); - QByteArray errorStr = QByteArray::number(error.line()) + ":" + - QByteArray::number(error.column()) + ":" + - error.description().toUtf8(); - qWarning() << errorStr; - } - } - QVERIFY(!component.isError()); -} - -void tst_qdeclarativewebview::basicProperties() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/basic.qml")); - checkNoErrors(component); - QWebSettings::enablePersistentStorage(tmpDir()); - - QObject *wv = component.create(); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QCOMPARE(wv->property("title").toString(),QString("Basic")); - QTRY_COMPARE(qvariant_cast<QPixmap>(wv->property("icon")).width(), 48); - QCOMPARE(qvariant_cast<QPixmap>(wv->property("icon")),QPixmap(SRCDIR "/data/basic.png")); - QCOMPARE(wv->property("statusText").toString(),QString("status here")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->property("html").toString())); - QCOMPARE(wv->property("preferredWidth").toInt(), 0); - QCOMPARE(wv->property("preferredHeight").toInt(), 0); - QCOMPARE(wv->property("url").toUrl(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); - QCOMPARE(wv->property("status").toInt(), 1 /*QDeclarativeWebView::Ready*/); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("back"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("back"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("forward"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("forward"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("stop"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("stop"))->isEnabled()); - - wv->setProperty("pixelCacheSize", 0); // mainly testing that it doesn't crash or anything! - QCOMPARE(wv->property("pixelCacheSize").toInt(),0); - qvariant_cast<QAction*>(wv->property("reload"))->trigger(); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); -} - -void tst_qdeclarativewebview::settings() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/basic.qml")); - checkNoErrors(component); - QObject *wv = component.create(); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - - QObject *s = QDeclarativeProperty(wv,"settings").object(); - QVERIFY(s != 0); - - // merely tests that setting gets stored (in QWebSettings) - // behavioural tests are in WebKit. - for (int b=0; b<=1; ++b) { - bool on = !!b; - - s->setProperty("autoLoadImages", on); - s->setProperty("developerExtrasEnabled", on); - s->setProperty("javaEnabled", on); - s->setProperty("javascriptCanAccessClipboard", on); - s->setProperty("javascriptCanOpenWindows", on); - s->setProperty("javascriptEnabled", on); - s->setProperty("linksIncludedInFocusChain", on); - s->setProperty("localContentCanAccessRemoteUrls", on); - s->setProperty("localStorageDatabaseEnabled", on); - s->setProperty("offlineStorageDatabaseEnabled", on); - s->setProperty("offlineWebApplicationCacheEnabled", on); - s->setProperty("pluginsEnabled", on); - s->setProperty("printElementBackgrounds", on); - s->setProperty("privateBrowsingEnabled", on); - s->setProperty("zoomTextOnly", on); - - QVERIFY(s->property("autoLoadImages") == on); - QVERIFY(s->property("developerExtrasEnabled") == on); - QVERIFY(s->property("javaEnabled") == on); - QVERIFY(s->property("javascriptCanAccessClipboard") == on); - QVERIFY(s->property("javascriptCanOpenWindows") == on); - QVERIFY(s->property("javascriptEnabled") == on); - QVERIFY(s->property("linksIncludedInFocusChain") == on); - QVERIFY(s->property("localContentCanAccessRemoteUrls") == on); - QVERIFY(s->property("localStorageDatabaseEnabled") == on); - QVERIFY(s->property("offlineStorageDatabaseEnabled") == on); - QVERIFY(s->property("offlineWebApplicationCacheEnabled") == on); - QVERIFY(s->property("pluginsEnabled") == on); - QVERIFY(s->property("printElementBackgrounds") == on); - QVERIFY(s->property("privateBrowsingEnabled") == on); - QVERIFY(s->property("zoomTextOnly") == on); - - QVERIFY(s->property("autoLoadImages") == on); - QVERIFY(s->property("developerExtrasEnabled") == on); - QVERIFY(s->property("javaEnabled") == on); - QVERIFY(s->property("javascriptCanAccessClipboard") == on); - QVERIFY(s->property("javascriptCanOpenWindows") == on); - QVERIFY(s->property("javascriptEnabled") == on); - QVERIFY(s->property("linksIncludedInFocusChain") == on); - QVERIFY(s->property("localContentCanAccessRemoteUrls") == on); - QVERIFY(s->property("localStorageDatabaseEnabled") == on); - QVERIFY(s->property("offlineStorageDatabaseEnabled") == on); - QVERIFY(s->property("offlineWebApplicationCacheEnabled") == on); - QVERIFY(s->property("pluginsEnabled") == on); - QVERIFY(s->property("printElementBackgrounds") == on); - QVERIFY(s->property("privateBrowsingEnabled") == on); - QVERIFY(s->property("zoomTextOnly") == on); - } -} - -void tst_qdeclarativewebview::historyNav() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/basic.qml")); - checkNoErrors(component); - QWebSettings::enablePersistentStorage(tmpDir()); - - QObject *wv = component.create(); - QVERIFY(wv != 0); - for (int i=1; i<=2; ++i) { - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QCOMPARE(wv->property("title").toString(),QString("Basic")); - QTRY_COMPARE(qvariant_cast<QPixmap>(wv->property("icon")).width(), 48); - QCOMPARE(qvariant_cast<QPixmap>(wv->property("icon")),QPixmap(SRCDIR "/data/basic.png")); - QCOMPARE(wv->property("statusText").toString(),QString("status here")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->property("html").toString())); - QCOMPARE(wv->property("preferredWidth").toDouble(), 0.0); - QCOMPARE(wv->property("url").toUrl(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); - QCOMPARE(wv->property("status").toInt(), 1 /*QDeclarativeWebView::Ready*/); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("back"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("back"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("forward"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("forward"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("stop"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("stop"))->isEnabled()); - - qvariant_cast<QAction*>(wv->property("reload"))->trigger(); - } - - wv->setProperty("url", QUrl::fromLocalFile(SRCDIR "/data/forward.html")); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QCOMPARE(wv->property("title").toString(),QString("Forward")); - QTRY_COMPARE(qvariant_cast<QPixmap>(wv->property("icon")).width(), 32); - QCOMPARE(qvariant_cast<QPixmap>(wv->property("icon")),QPixmap(SRCDIR "/data/forward.png")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/forward.html")), strippedHtml(wv->property("html").toString())); - QCOMPARE(wv->property("url").toUrl(), QUrl::fromLocalFile(SRCDIR "/data/forward.html")); - QCOMPARE(wv->property("status").toInt(), 1 /*QDeclarativeWebView::Ready*/); - QCOMPARE(wv->property("statusText").toString(),QString("")); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("back"))); - QVERIFY(qvariant_cast<QAction*>(wv->property("back"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("forward"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("forward"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("stop"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("stop"))->isEnabled()); - - qvariant_cast<QAction*>(wv->property("back"))->trigger(); - - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QCOMPARE(wv->property("title").toString(),QString("Basic")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->property("html").toString())); - QCOMPARE(wv->property("url").toUrl(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); - QCOMPARE(wv->property("status").toInt(), 1 /*QDeclarativeWebView::Ready*/); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))); - QVERIFY(qvariant_cast<QAction*>(wv->property("reload"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("back"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("back"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("forward"))); - QVERIFY(qvariant_cast<QAction*>(wv->property("forward"))->isEnabled()); - QVERIFY(qvariant_cast<QAction*>(wv->property("stop"))); - QVERIFY(!qvariant_cast<QAction*>(wv->property("stop"))->isEnabled()); -} - -void tst_qdeclarativewebview::multipleWindows() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/newwindows.qml")); - checkNoErrors(component); - - QDeclarativeGrid *grid = qobject_cast<QDeclarativeGrid*>(component.create()); - QVERIFY(grid != 0); - QTRY_COMPARE(grid->children().count(), 2+4); // Component, Loader (with 1 WebView), 4 new-window WebViews - QDeclarativeItem* popup = qobject_cast<QDeclarativeItem*>(grid->children().at(2)); // first popup after Component and Loader. - QVERIFY(popup != 0); - QTRY_COMPARE(popup->x(), 150.0); -} - -void tst_qdeclarativewebview::loadError() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/loadError.qml")); - checkNoErrors(component); - QWebSettings::enablePersistentStorage(tmpDir()); - - QObject *wv = component.create(); - QVERIFY(wv != 0); - for (int i=1; i<=2; ++i) { - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QCOMPARE(wv->property("title").toString(),QString("")); - QCOMPARE(wv->property("statusText").toString(),QString("")); // HTML 'status bar' text, not error message - QCOMPARE(wv->property("url").toUrl(), QUrl::fromLocalFile(SRCDIR "/data/does-not-exist.html")); // Unlike QWebPage, which loses url - QCOMPARE(wv->property("status").toInt(), 3 /*QDeclarativeWebView::Error*/); - - qvariant_cast<QAction*>(wv->property("reload"))->trigger(); - } -} - -void tst_qdeclarativewebview::setHtml() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/sethtml.qml")); - checkNoErrors(component); - QObject *wv = component.create(); - QVERIFY(wv != 0); - QCOMPARE(wv->property("html").toString(),QString("<html><head></head><body><p>This is a <b>string</b> set on the WebView</p></body></html>")); - - QSignalSpy spy(wv, SIGNAL(htmlChanged())); - wv->setProperty("html", QString("<html><head><title>Basic</title></head><body><p>text</p></body></html>")); - QCOMPARE(spy.count(),1); -} - -void tst_qdeclarativewebview::elementAreaAt() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/elements.qml")); - checkNoErrors(component); - QObject *wv = component.create(); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - - /* not now it's a plugin... - QCOMPARE(wv->elementAreaAt(40,30,100,100),QRect(1,1,75,54)); // Area A in data/elements.html - QCOMPARE(wv->elementAreaAt(130,30,200,100),QRect(78,3,110,50)); // Area B - QCOMPARE(wv->elementAreaAt(40,30,400,400),QRect(0,0,310,100)); // Whole view - QCOMPARE(wv->elementAreaAt(130,30,280,280),QRect(76,1,223,54)); // Area BC - QCOMPARE(wv->elementAreaAt(130,30,400,400),QRect(0,0,310,100)); // Whole view - */ -} - -void tst_qdeclarativewebview::javaScript() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/javaScript.qml")); - checkNoErrors(component); - QObject *wv = component.create(); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - /* not now it's a plugin... - QCOMPARE(wv->evaluateJavaScript("123").toInt(), 123); - QCOMPARE(wv->evaluateJavaScript("window.status").toString(), QString("status here")); - QCOMPARE(wv->evaluateJavaScript("window.myjsname.qmlprop").toString(), QString("qmlvalue")); - */ -} - -/* -Cannot be done now that webkit is a plugin - -void tst_qdeclarativewebview::pixelCache() -{ - - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/pixelCache.qml")); - checkNoErrors(component); - MyWebView *wv = qobject_cast<MyWebView*>(component.create()); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress"), 1.0); - QPixmap pm(150,150); - QPainter p(&pm); - wv->paint(&p,0,0); - const int expected = 120*(150+128); // 120 = width of HTML page, 150=pixmap height, 128=cache extra area - QCOMPARE(wv->property("pixelsPainted"), expected); - wv->paint(&p,0,0); - QCOMPARE(wv->property("pixelsPainted"), expected); // nothing new needed to be painted - wv->setProperty("pixelCacheSize", 0); // clears the cache - wv->paint(&p,0,0); - QCOMPARE(wv->property("pixelsPainted"), expected*2); // everything needed to be painted - // Note that painted things always go into the cache (even if they don't "fit"), - // just that they will be removed if anything else needs to be painted. - wv->setProperty("pixelCacheSize", expected); // won't clear the cache - wv->paint(&p,0,0); - QCOMPARE(wv->property("pixelsPainted"), expected*2); // still there - wv->setProperty("pixelCacheSize", expected-1); // too small - will clear the cache - wv->paint(&p,0,0); - QCOMPARE(wv->property("pixelsPainted"), expected*3); // repainted -} -*/ - -void tst_qdeclarativewebview::newWindowParent() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); - checkNoErrors(component); - QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(component.create()); - QObject *wv = rootItem->findChild<QObject*>("webView"); - QVERIFY(rootItem != 0); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - - QDeclarativeItem* oldWindowParent = rootItem->findChild<QDeclarativeItem*>("oldWindowParent"); - QCOMPARE(qvariant_cast<QDeclarativeItem*>(wv->property("newWindowParent")), oldWindowParent); - QSignalSpy newWindowParentSpy(wv, SIGNAL(newWindowParentChanged())); - - QDeclarativeItem* newWindowParent = rootItem->findChild<QDeclarativeItem*>("newWindowParent"); - wv->setProperty("newWindowParent", QVariant::fromValue(newWindowParent)); - QVERIFY(newWindowParent); - QVERIFY(oldWindowParent); - QVERIFY(oldWindowParent->childItems().count() == 0); - QCOMPARE(wv->property("newWindowParent"), QVariant::fromValue(newWindowParent)); - QCOMPARE(newWindowParentSpy.count(),1); - - wv->setProperty("newWindowParent", QVariant::fromValue(newWindowParent)); - QCOMPARE(newWindowParentSpy.count(),1); - - wv->setProperty("newWindowParent", QVariant::fromValue((QDeclarativeItem*)0)); - QCOMPARE(newWindowParentSpy.count(),2); -} - -void tst_qdeclarativewebview::newWindowComponent() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); - checkNoErrors(component); - QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(component.create()); - QObject *wv = rootItem->findChild<QObject*>("webView"); - QVERIFY(rootItem != 0); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - - QDeclarativeComponent substituteComponent(&engine); - substituteComponent.setData("import QtQuick 1.0; WebView { objectName: 'newWebView'; url: 'basic.html'; }", QUrl::fromLocalFile("")); - QSignalSpy newWindowComponentSpy(wv, SIGNAL(newWindowComponentChanged())); - - wv->setProperty("newWindowComponent", QVariant::fromValue(&substituteComponent)); - QCOMPARE(wv->property("newWindowComponent"), QVariant::fromValue(&substituteComponent)); - QCOMPARE(newWindowComponentSpy.count(),1); - - wv->setProperty("newWindowComponent", QVariant::fromValue(&substituteComponent)); - QCOMPARE(newWindowComponentSpy.count(),1); - - wv->setProperty("newWindowComponent", QVariant::fromValue((QDeclarativeComponent*)0)); - QCOMPARE(newWindowComponentSpy.count(),2); -} - -void tst_qdeclarativewebview::renderingEnabled() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); - checkNoErrors(component); - QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(component.create()); - QObject *wv = rootItem->findChild<QObject*>("webView"); - QVERIFY(rootItem != 0); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - - QVERIFY(wv->property("renderingEnabled").toBool()); - QSignalSpy renderingEnabledSpy(wv, SIGNAL(renderingEnabledChanged())); - - wv->setProperty("renderingEnabled", false); - QVERIFY(!wv->property("renderingEnabled").toBool()); - QCOMPARE(renderingEnabledSpy.count(),1); - - wv->setProperty("renderingEnabled", false); - QCOMPARE(renderingEnabledSpy.count(),1); - - wv->setProperty("renderingEnabled", true); - QCOMPARE(renderingEnabledSpy.count(),2); -} - -void tst_qdeclarativewebview::pressGrabTime() -{ - QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); - checkNoErrors(component); - QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(component.create()); - QObject *wv = rootItem->findChild<QObject*>("webView"); - QVERIFY(rootItem != 0); - QVERIFY(wv != 0); - QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QCOMPARE(wv->property("pressGrabTime").toInt(), 200); - QSignalSpy pressGrabTimeSpy(wv, SIGNAL(pressGrabTimeChanged())); - - wv->setProperty("pressGrabTime", 100); - QCOMPARE(wv->property("pressGrabTime").toInt(), 100); - QCOMPARE(pressGrabTimeSpy.count(),1); - - wv->setProperty("pressGrabTime", 100); - QCOMPARE(pressGrabTimeSpy.count(),1); - - wv->setProperty("pressGrabTime", 0); - QCOMPARE(pressGrabTimeSpy.count(),2); -} - -QTEST_MAIN(tst_qdeclarativewebview) - -#include "tst_qdeclarativewebview.moc" diff --git a/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp b/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp index 06baed8..1b9831c 100644 --- a/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp +++ b/tests/auto/declarative/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp @@ -140,9 +140,9 @@ void tst_QMetaObjectBuilder::mocVersionCheck() // whenenver moc changes. Once QMetaObjectBuilder has been // updated, this test can be changed to check for the next version. int version = int(QObject::staticMetaObject.d.data[0]); - QVERIFY(version == 4 || version == 5); + QVERIFY(version == 4 || version == 5 || version == 6); version = int(staticMetaObject.d.data[0]); - QVERIFY(version == 4 || version == 5); + QVERIFY(version == 4 || version == 5 || version == 6); } void tst_QMetaObjectBuilder::create() @@ -920,9 +920,9 @@ void tst_QMetaObjectBuilder::relatedMetaObject() QVERIFY(checkForSideEffects(builder, QMetaObjectBuilder::RelatedMetaObjects)); } -static int smetacall(QMetaObject::Call, int, void **) +static void smetacall(QObject *, QMetaObject::Call, int, void **) { - return 0; + return; } void tst_QMetaObjectBuilder::staticMetacall() diff --git a/tests/auto/moc/tst_moc.cpp b/tests/auto/moc/tst_moc.cpp index 203f0ae..7a8f958 100644 --- a/tests/auto/moc/tst_moc.cpp +++ b/tests/auto/moc/tst_moc.cpp @@ -497,7 +497,7 @@ private slots: void revisions(); void warnings_data(); void warnings(); - + void privateClass(); signals: void sigWithUnsignedArg(unsigned foo); @@ -517,6 +517,7 @@ private: private: QString qtIncludePath; + class PrivateClass; }; void tst_Moc::initTestCase() @@ -1648,6 +1649,25 @@ void tst_Moc::warnings() } +class tst_Moc::PrivateClass : public QObject { + Q_PROPERTY(int someProperty READ someSlot WRITE someSlot2) +Q_OBJECT +Q_SIGNALS: + void someSignal(); +public Q_SLOTS: + int someSlot() { return 1; } + void someSlot2(int) {} +public: + Q_INVOKABLE PrivateClass() {} +}; + +void tst_Moc::privateClass() +{ + QVERIFY(PrivateClass::staticMetaObject.indexOfConstructor("PrivateClass()") == 0); + QVERIFY(PrivateClass::staticMetaObject.indexOfSignal("someSignal()") > 0); +} + + QTEST_APPLESS_MAIN(tst_Moc) #include "tst_moc.moc" diff --git a/tests/auto/qbytearray/tst_qbytearray.cpp b/tests/auto/qbytearray/tst_qbytearray.cpp index 5fff22a..0dea9be 100644 --- a/tests/auto/qbytearray/tst_qbytearray.cpp +++ b/tests/auto/qbytearray/tst_qbytearray.cpp @@ -898,12 +898,12 @@ void tst_QByteArray::indexOf_data() QByteArray veryBigHaystack(500, 'a'); veryBigHaystack += 'B'; QTest::newRow("BoyerMooreStressTest") << veryBigHaystack << veryBigHaystack << 0 << 0; - QTest::newRow("BoyerMooreStressTest2") << veryBigHaystack + 'c' << veryBigHaystack << 0 << 0; - QTest::newRow("BoyerMooreStressTest3") << 'c' + veryBigHaystack << veryBigHaystack << 0 << 1; - QTest::newRow("BoyerMooreStressTest4") << veryBigHaystack << veryBigHaystack + 'c' << 0 << -1; - QTest::newRow("BoyerMooreStressTest5") << veryBigHaystack << 'c' + veryBigHaystack << 0 << -1; - QTest::newRow("BoyerMooreStressTest6") << 'd' + veryBigHaystack << 'c' + veryBigHaystack << 0 << -1; - QTest::newRow("BoyerMooreStressTest6") << veryBigHaystack + 'c' << 'c' + veryBigHaystack << 0 << -1; + QTest::newRow("BoyerMooreStressTest2") << QByteArray(veryBigHaystack + 'c') << QByteArray(veryBigHaystack) << 0 << 0; + QTest::newRow("BoyerMooreStressTest3") << QByteArray('c' + veryBigHaystack) << QByteArray(veryBigHaystack) << 0 << 1; + QTest::newRow("BoyerMooreStressTest4") << QByteArray(veryBigHaystack) << QByteArray(veryBigHaystack + 'c') << 0 << -1; + QTest::newRow("BoyerMooreStressTest5") << QByteArray(veryBigHaystack) << QByteArray('c' + veryBigHaystack) << 0 << -1; + QTest::newRow("BoyerMooreStressTest6") << QByteArray('d' + veryBigHaystack) << QByteArray('c' + veryBigHaystack) << 0 << -1; + QTest::newRow("BoyerMooreStressTest6") << QByteArray(veryBigHaystack + 'c') << QByteArray('c' + veryBigHaystack) << 0 << -1; } void tst_QByteArray::indexOf() diff --git a/tests/auto/qdatetime/tst_qdatetime.cpp b/tests/auto/qdatetime/tst_qdatetime.cpp index fa9c70b..f8836a6 100644 --- a/tests/auto/qdatetime/tst_qdatetime.cpp +++ b/tests/auto/qdatetime/tst_qdatetime.cpp @@ -198,8 +198,8 @@ void tst_QDateTime::ctor() QDateTime dt3(QDate(2004, 1, 2), QTime(1, 2, 3), Qt::UTC); QVERIFY(dt1 == dt2); - QVERIFY(dt1 != dt3); if (europeanTimeZone) { + QVERIFY(dt1 != dt3); QVERIFY(dt1 < dt3); QVERIFY(dt1.addSecs(3600).toUTC() == dt3); } diff --git a/tests/auto/qfuture/tst_qfuture.cpp b/tests/auto/qfuture/tst_qfuture.cpp index fa4ccb5..8afdf48 100644 --- a/tests/auto/qfuture/tst_qfuture.cpp +++ b/tests/auto/qfuture/tst_qfuture.cpp @@ -81,6 +81,7 @@ private slots: void voidConversions(); #ifndef QT_NO_EXCEPTIONS void exceptions(); + void exceptions_QTBUG18149(); #endif }; @@ -1431,6 +1432,33 @@ void tst_QFuture::exceptions() } + +void tst_QFuture::exceptions_QTBUG18149() +{ + class MyClass + { + public: + ~MyClass() + { + QFuture<void> f = createExceptionFuture(); + bool caught = false; + try { + f.waitForFinished(); + } catch (Exception &) { + caught = true; + } + QVERIFY(caught); + } + }; + + try { + MyClass m; + throw 0; + } catch (int) {} + +} + + #endif // QT_NO_EXCEPTIONS #include "tst_qfuture.moc" diff --git a/tests/auto/qhostinfo/tst_qhostinfo.cpp b/tests/auto/qhostinfo/tst_qhostinfo.cpp index ee2fe0d..8be8dcb 100644 --- a/tests/auto/qhostinfo/tst_qhostinfo.cpp +++ b/tests/auto/qhostinfo/tst_qhostinfo.cpp @@ -291,6 +291,7 @@ void tst_QHostInfo::lookupIPv6_data() QTest::addColumn<int>("err"); QTest::newRow("ip6") << "www.ipv6-net.org" << "62.93.217.177 2001:618:1401:0:0:0:0:4" << int(QHostInfo::NoError); + QTest::newRow("ip6") << "ipv6.google.com" << "2A00:1450:8007:0:0:0:0:63" << int(QHostInfo::NoError); // avoid using real IPv6 addresses here because this will do a DNS query // real addresses are between 2000:: and 3fff:ffff:ffff:ffff:ffff:ffff:ffff @@ -337,7 +338,7 @@ void tst_QHostInfo::reverseLookup_data() // ### Use internal DNS instead. Discussed with Andreas. //QTest::newRow("classical.hexago.com") << QString("2001:5c0:0:2::24") << QStringList(QString("classical.hexago.com")) << 0; - QTest::newRow("origin.cisco.com") << QString("12.159.148.94") << QStringList(QString("origin.cisco.com")) << 0; + QTest::newRow("gitorious.org") << QString("87.238.52.168") << QStringList(QString("gitorious.org")) << 0; QTest::newRow("bogus-name") << QString("1::2::3::4") << QStringList() << 1; } diff --git a/tests/auto/qlocale/tst_qlocale.cpp b/tests/auto/qlocale/tst_qlocale.cpp index 3b62d64..2b7eaae 100644 --- a/tests/auto/qlocale/tst_qlocale.cpp +++ b/tests/auto/qlocale/tst_qlocale.cpp @@ -140,6 +140,11 @@ private slots: #endif void ampm(); + void currency(); + void quoteString(); + void uiLanguages(); + void weekendDays(); + void listPatterns(); private: QString m_decimal, m_thousand, m_sdate, m_ldate, m_time; @@ -181,6 +186,7 @@ void tst_QLocale::ctor() QCOMPARE(l.language(), QLocale::C); QCOMPARE(l.country(), QLocale::AnyCountry); } + TEST_CTOR(AnyLanguage, AnyCountry, default_lang, default_country) TEST_CTOR(C, AnyCountry, QLocale::C, QLocale::AnyCountry) TEST_CTOR(Aymara, AnyCountry, default_lang, default_country) TEST_CTOR(Aymara, France, default_lang, default_country) @@ -306,6 +312,7 @@ void tst_QLocale::ctor() TEST_CTOR("en@", English, UnitedStates) TEST_CTOR("en.@", English, UnitedStates) TEST_CTOR("en_", English, UnitedStates) + TEST_CTOR("en_U", English, UnitedStates) TEST_CTOR("en_.", English, UnitedStates) TEST_CTOR("en_.@", English, UnitedStates) TEST_CTOR("en.bla", English, UnitedStates) @@ -316,6 +323,8 @@ void tst_QLocale::ctor() TEST_CTOR("en_GB.bla", English, UnitedKingdom) TEST_CTOR("en_GB@.bla", English, UnitedKingdom) TEST_CTOR("en_GB@bla", English, UnitedKingdom) + TEST_CTOR("en-GB", English, UnitedKingdom) + TEST_CTOR("en-GB@bla", English, UnitedKingdom) Q_ASSERT(QLocale::Norwegian == QLocale::NorwegianBokmal); TEST_CTOR("no", Norwegian, Norway) @@ -326,13 +335,38 @@ void tst_QLocale::ctor() TEST_CTOR("nn_NO", NorwegianNynorsk, Norway) TEST_CTOR("es_ES", Spanish, Spain) TEST_CTOR("es_419", Spanish, LatinAmericaAndTheCaribbean) + TEST_CTOR("es-419", Spanish, LatinAmericaAndTheCaribbean) // test default countries for languages + TEST_CTOR("zh", Chinese, China) + TEST_CTOR("zh-Hans", Chinese, China) TEST_CTOR("mn", Mongolian, Mongolia) TEST_CTOR("ne", Nepali, Nepal) #undef TEST_CTOR +#define TEST_CTOR(req_lc, exp_lang, exp_script, exp_country) \ + { \ + QLocale l(req_lc); \ + QVERIFY2(l.language() == QLocale::exp_lang \ + && l.script() == QLocale::exp_script \ + && l.country() == QLocale::exp_country, \ + QString("requested: \"" + QString(req_lc) + "\", got: " \ + + QLocale::languageToString(l.language()) \ + + "/" + QLocale::scriptToString(l.script()) \ + + "/" + QLocale::countryToString(l.country())).toLatin1().constData()); \ + } + + TEST_CTOR("zh_CN", Chinese, AnyScript, China) + TEST_CTOR("zh_Hans_CN", Chinese, SimplifiedHanScript, China) + TEST_CTOR("zh_Hans", Chinese, SimplifiedHanScript, China) + TEST_CTOR("zh_Hant", Chinese, TraditionalHanScript, HongKong) + TEST_CTOR("zh_Hans_MO", Chinese, SimplifiedHanScript, Macau) + TEST_CTOR("zh_Hant_MO", Chinese, TraditionalHanScript, Macau) + TEST_CTOR("az_Latn_AZ", Azerbaijani, LatinScript, Azerbaijan) + TEST_CTOR("ha_Arab_NG", Hausa, ArabicScript, Nigeria) + TEST_CTOR("ha_Latn_NG", Hausa, LatinScript, Nigeria) +#undef TEST_CTOR } void tst_QLocale::emptyCtor() @@ -405,11 +439,12 @@ void tst_QLocale::emptyCtor() TEST_CTOR("nb_NO", "nb_NO") TEST_CTOR("nn_NO", "nn_NO") + TEST_CTOR("DE", "de_DE"); + TEST_CTOR("EN", "en_US"); + TEST_CTOR("en/", defaultLoc) - TEST_CTOR("DE", defaultLoc); TEST_CTOR("asdfghj", defaultLoc); TEST_CTOR("123456", defaultLoc); - TEST_CTOR("EN", defaultLoc); #undef TEST_CTOR #endif @@ -1095,6 +1130,11 @@ void tst_QLocale::macDefaultLocale() const QString timeString = locale.toString(QTime(1,2,3), QLocale::LongFormat); QVERIFY(timeString.contains(QString("1:02:03"))); + QCOMPARE(locale.toCurrencyString(qulonglong(1234)), QString("$1,234.00")); + QCOMPARE(locale.toCurrencyString(qlonglong(-1234)), QString("($1,234.00)")); + QCOMPARE(locale.toCurrencyString(double(1234.56)), QString("$1,234.56")); + QCOMPARE(locale.toCurrencyString(double(-1234.56)), QString("($1,234.56)")); + // Depending on the configured time zone, the time string might not // contain a GMT specifier. (Sometimes it just names the zone, like "CEST") if (timeString.contains(QString("GMT"))) { @@ -1117,6 +1157,13 @@ void tst_QLocale::macDefaultLocale() QCOMPARE(locale.dayName(7), QString("Sunday")); QCOMPARE(locale.monthName(1), QString("January")); QCOMPARE(locale.monthName(12), QString("December")); + QCOMPARE(locale.firstDayOfWeek(), Qt::Sunday); + QCOMPARE(locale.quoteString("string"), QString::fromUtf8("\xe2\x80\x9c" "string" "\xe2\x80\x9d")); + QCOMPARE(locale.quoteString("string", QLocale::AlternateQuotation), QString::fromUtf8("\xe2\x80\x98" "string" "\xe2\x80\x99")); + + QList<Qt::DayOfWeek> days; + days << Qt::Monday << Qt::Tuesday << Qt::Wednesday << Qt::Thursday << Qt::Friday; + QCOMPARE(locale.weekdays(), days); } @@ -1772,6 +1819,7 @@ void tst_QLocale::measurementSystems_data() void tst_QLocale::measurementSystems() { + QSKIP("Meh, skip the test as we do not reread the environment variables anymore", SkipAll); QFETCH(QString, localeName); QFETCH(int, mSystem); @@ -1833,6 +1881,7 @@ void tst_QLocale::systemMeasurementSystems_data() void tst_QLocale::systemMeasurementSystems() { + QSKIP("Meh, skip the test as we do not reread the environment variables anymore", SkipAll); // Theoretically, we could include HPUX in this test, but its setenv implementation // stinks. It's called putenv, and it requires you to keep the variable you pass // to it around forever. @@ -1955,6 +2004,7 @@ void tst_QLocale::queryMeasureSystem_data() void tst_QLocale::queryMeasureSystem() { + QSKIP("Meh, skip the test as we do not reread the environment variables anymore", SkipAll); // Theoretically, we could include HPUX in this test, but its setenv implementation // stinks. It's called putenv, and it requires you to keep the variable you pass // to it around forever. @@ -2070,6 +2120,10 @@ void tst_QLocale::monthName() QCOMPARE(ru.monthName(1, QLocale::LongFormat), QString::fromUtf8("\321\217\320\275\320\262\320\260\321\200\321\217")); QCOMPARE(ru.monthName(1, QLocale::ShortFormat), QString::fromUtf8("\321\217\320\275\320\262\56")); QCOMPARE(ru.monthName(1, QLocale::NarrowFormat), QString::fromUtf8("\320\257")); + + // check that our CLDR scripts handle surrogate pairs correctly + QLocale dsrt("en-Dsrt-US"); + QCOMPARE(dsrt.monthName(1, QLocale::LongFormat), QString::fromUtf8("\xf0\x90\x90\x96\xf0\x90\x90\xb0\xf0\x90\x91\x8c\xf0\x90\x90\xb7\xf0\x90\x90\xad\xf0\x90\x90\xaf\xf0\x90\x91\x89\xf0\x90\x90\xa8")); } void tst_QLocale::standaloneMonthName() @@ -2127,5 +2181,102 @@ void tst_QLocale::symbianSystemLocale() } #endif +void tst_QLocale::currency() +{ + const QLocale c(QLocale::C); + QCOMPARE(c.toCurrencyString(qulonglong(1234)), QString("1234")); + QCOMPARE(c.toCurrencyString(qlonglong(-1234)), QString("-1234")); + QCOMPARE(c.toCurrencyString(double(1234.56)), QString("1234.56")); + QCOMPARE(c.toCurrencyString(double(-1234.56)), QString("-1234.56")); + + const QLocale ru_RU("ru_RU"); + QCOMPARE(ru_RU.toCurrencyString(qulonglong(1234)), QString::fromUtf8("1234\xc2\xa0\xd1\x80\xd1\x83\xd0\xb1.")); + QCOMPARE(ru_RU.toCurrencyString(qlonglong(-1234)), QString::fromUtf8("-1234\xc2\xa0\xd1\x80\xd1\x83\xd0\xb1.")); + QCOMPARE(ru_RU.toCurrencyString(double(1234.56)), QString::fromUtf8("1234,56\xc2\xa0\xd1\x80\xd1\x83\xd0\xb1.")); + QCOMPARE(ru_RU.toCurrencyString(double(-1234.56)), QString::fromUtf8("-1234,56\xc2\xa0\xd1\x80\xd1\x83\xd0\xb1.")); + + const QLocale de_DE("de_DE"); + QCOMPARE(de_DE.toCurrencyString(qulonglong(1234)), QString::fromUtf8("1234\xc2\xa0\xe2\x82\xac")); + QCOMPARE(de_DE.toCurrencyString(qulonglong(1234), QLatin1String("BAZ")), QString::fromUtf8("1234\xc2\xa0" "BAZ")); + QCOMPARE(de_DE.toCurrencyString(qlonglong(-1234)), QString::fromUtf8("-1234\xc2\xa0\xe2\x82\xac")); + QCOMPARE(de_DE.toCurrencyString(qlonglong(-1234), QLatin1String("BAZ")), QString::fromUtf8("-1234\xc2\xa0" "BAZ")); + QCOMPARE(de_DE.toCurrencyString(double(1234.56)), QString::fromUtf8("1234,56\xc2\xa0\xe2\x82\xac")); + QCOMPARE(de_DE.toCurrencyString(double(-1234.56)), QString::fromUtf8("-1234,56\xc2\xa0\xe2\x82\xac")); + QCOMPARE(de_DE.toCurrencyString(double(-1234.56), QLatin1String("BAZ")), QString::fromUtf8("-1234,56\xc2\xa0" "BAZ")); + + const QLocale system = QLocale::system(); + QVERIFY(system.toCurrencyString(1, QLatin1String("FOO")).contains(QLatin1String("FOO"))); +} + +void tst_QLocale::quoteString() +{ + const QString someText("text"); + const QLocale c(QLocale::C); + QCOMPARE(c.quoteString(someText), QString::fromUtf8("\x22" "text" "\x22")); + QCOMPARE(c.quoteString(someText, QLocale::AlternateQuotation), QString::fromUtf8("\x27" "text" "\x27")); + + const QLocale de_CH("de_CH"); + QCOMPARE(de_CH.quoteString(someText), QString::fromUtf8("\xc2\xab" "text" "\xc2\xbb")); + QCOMPARE(de_CH.quoteString(someText, QLocale::AlternateQuotation), QString::fromUtf8("\xe2\x80\xb9" "text" "\xe2\x80\xba")); + +} + +void tst_QLocale::uiLanguages() +{ + const QLocale c(QLocale::C); + QCOMPARE(c.uiLanguages().size(), 1); + QCOMPARE(c.uiLanguages().at(0), QLatin1String("C")); + + const QLocale en_US("en_US"); + QCOMPARE(en_US.uiLanguages().size(), 1); + QCOMPARE(en_US.uiLanguages().at(0), QLatin1String("en-US")); + + const QLocale ru_RU("ru_RU"); + QCOMPARE(ru_RU.uiLanguages().size(), 1); + QCOMPARE(ru_RU.uiLanguages().at(0), QLatin1String("ru-RU")); +} + +void tst_QLocale::weekendDays() +{ + const QLocale c(QLocale::C); + QList<Qt::DayOfWeek> days; + days << Qt::Monday << Qt::Tuesday << Qt::Wednesday << Qt::Thursday << Qt::Friday; + QCOMPARE(c.weekdays(), days); +} + +void tst_QLocale::listPatterns() +{ + QStringList sl1; + QStringList sl2; + sl2 << "aaa"; + QStringList sl3; + sl3 << "aaa" << "bbb"; + QStringList sl4; + sl4 << "aaa" << "bbb" << "ccc"; + QStringList sl5; + sl5 << "aaa" << "bbb" << "ccc" << "ddd"; + + const QLocale c(QLocale::C); + QCOMPARE(c.createSeparatedList(sl1), QString("")); + QCOMPARE(c.createSeparatedList(sl2), QString("aaa")); + QCOMPARE(c.createSeparatedList(sl3), QString("aaa, bbb")); + QCOMPARE(c.createSeparatedList(sl4), QString("aaa, bbb, ccc")); + QCOMPARE(c.createSeparatedList(sl5), QString("aaa, bbb, ccc, ddd")); + + const QLocale en_US("en_US"); + QCOMPARE(en_US.createSeparatedList(sl1), QString("")); + QCOMPARE(en_US.createSeparatedList(sl2), QString("aaa")); + QCOMPARE(en_US.createSeparatedList(sl3), QString("aaa and bbb")); + QCOMPARE(en_US.createSeparatedList(sl4), QString("aaa, bbb, and ccc")); + QCOMPARE(en_US.createSeparatedList(sl5), QString("aaa, bbb, ccc, and ddd")); + + const QLocale zh_CN("zh_CN"); + QCOMPARE(zh_CN.createSeparatedList(sl1), QString("")); + QCOMPARE(zh_CN.createSeparatedList(sl2), QString("aaa")); + QCOMPARE(zh_CN.createSeparatedList(sl3), QString::fromUtf8("aaa" "\xe5\x92\x8c" "bbb")); + QCOMPARE(zh_CN.createSeparatedList(sl4), QString::fromUtf8("aaa" "\xe3\x80\x81" "bbb" "\xe5\x92\x8c" "ccc")); + QCOMPARE(zh_CN.createSeparatedList(sl5), QString::fromUtf8("aaa" "\xe3\x80\x81" "bbb" "\xe3\x80\x81" "ccc" "\xe5\x92\x8c" "ddd")); +} + QTEST_APPLESS_MAIN(tst_QLocale) #include "tst_qlocale.moc" diff --git a/tests/auto/qmetaobject/tst_qmetaobject.cpp b/tests/auto/qmetaobject/tst_qmetaobject.cpp index d496c56..13e3bcd 100644 --- a/tests/auto/qmetaobject/tst_qmetaobject.cpp +++ b/tests/auto/qmetaobject/tst_qmetaobject.cpp @@ -175,6 +175,9 @@ private slots: void metaMethod(); + void indexOfMethod_data(); + void indexOfMethod(); + signals: void value6Changed(); void value7Changed(const QString &); @@ -1077,5 +1080,31 @@ void tst_QMetaObject::metaMethod() QCOMPARE(obj.slotResult, QString("sl13")); } +void tst_QMetaObject::indexOfMethod_data() +{ + QTest::addColumn<QObject *>("object"); + QTest::addColumn<QByteArray>("name"); + QTest::addColumn<bool>("isSignal"); + QTest::newRow("indexOfMethod_data") << (QObject*)this << QByteArray("indexOfMethod_data()") << false; + QTest::newRow("deleteLater") << (QObject*)this << QByteArray("deleteLater()") << false; + QTest::newRow("value6changed") << (QObject*)this << QByteArray("value6Changed()") << true; + QTest::newRow("value7changed") << (QObject*)this << QByteArray("value7Changed(QString)") << true; + QTest::newRow("destroyed") << (QObject*)this << QByteArray("destroyed()") << true; + QTest::newRow("destroyed2") << (QObject*)this << QByteArray("destroyed(QObject*)") << true; +} + +void tst_QMetaObject::indexOfMethod() +{ + QFETCH(QObject *, object); + QFETCH(QByteArray, name); + QFETCH(bool, isSignal); + int idx = object->metaObject()->indexOfMethod(name); + QVERIFY(idx >= 0); + QCOMPARE(object->metaObject()->method(idx).signature(), name.constData()); + QCOMPARE(object->metaObject()->indexOfSlot(name), isSignal ? -1 : idx); + QCOMPARE(object->metaObject()->indexOfSignal(name), !isSignal ? -1 : idx); +} + + QTEST_MAIN(tst_QMetaObject) #include "tst_qmetaobject.moc" diff --git a/tests/auto/qnetworkaccessmanager_and_qprogressdialog/tst_qnetworkaccessmanager_and_qprogressdialog.cpp b/tests/auto/qnetworkaccessmanager_and_qprogressdialog/tst_qnetworkaccessmanager_and_qprogressdialog.cpp index 42bb069..f7c5ca1 100644 --- a/tests/auto/qnetworkaccessmanager_and_qprogressdialog/tst_qnetworkaccessmanager_and_qprogressdialog.cpp +++ b/tests/auto/qnetworkaccessmanager_and_qprogressdialog/tst_qnetworkaccessmanager_and_qprogressdialog.cpp @@ -58,6 +58,7 @@ public: tst_QNetworkAccessManager_And_QProgressDialog(); private slots: void downloadCheck(); + void downloadCheck_data(); }; class DownloadCheckWidget : public QWidget @@ -72,9 +73,14 @@ public: QMetaObject::invokeMethod(this, "go", Qt::QueuedConnection); } bool lateReadyRead; + bool zeroCopy; public slots: void go() { + QNetworkRequest request(QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/bigfile")); + if (zeroCopy) + request.setAttribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute, 10*1024*1024); + QNetworkReply *reply = netmanager.get( QNetworkRequest( QUrl("http://" + QtNetworkSettings::serverName() + "/qtest/bigfile") @@ -106,20 +112,30 @@ public slots: QTestEventLoop::instance().exitLoop(); } - private: QProgressDialog progressDlg; QNetworkAccessManager netmanager; }; + tst_QNetworkAccessManager_And_QProgressDialog::tst_QNetworkAccessManager_And_QProgressDialog() { Q_SET_DEFAULT_IAP } +void tst_QNetworkAccessManager_And_QProgressDialog::downloadCheck_data() +{ + QTest::addColumn<bool>("useZeroCopy"); + QTest::newRow("with-zeroCopy") << true; + QTest::newRow("without-zeroCopy") << false; +} + void tst_QNetworkAccessManager_And_QProgressDialog::downloadCheck() { + QFETCH(bool, useZeroCopy); + DownloadCheckWidget widget; + widget.zeroCopy = useZeroCopy; widget.show(); // run and exit on finished() QTestEventLoop::instance().enterLoop(10); diff --git a/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp b/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp index e974fcc..28c6027 100644 --- a/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp +++ b/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp @@ -46,6 +46,8 @@ #include "../../shared/util.h" #define EXAMPLE_URL "http://user:pass@www.example.com/#foo" +//cached objects are organized into these many subdirs +#define NUM_SUBDIRECTORIES 16 class tst_QNetworkDiskCache : public QObject { @@ -176,10 +178,10 @@ void tst_QNetworkDiskCache::initTestCase() cache.clear(); QString s = QDir::tempPath() + "/diskCache/"; QDir dir; - dir.rmdir(s + "http"); - dir.rmdir(s + "https"); + dir.rmdir(s + "data7"); // the number is the internal cache version dir.rmdir(s + "prepared"); dir.rmdir(s); + dir.rmdir(s + "http"); // delete directory used by 4.7 and earlier (would make the tests fail) } // This will be called after the last test function is executed. @@ -277,16 +279,16 @@ void tst_QNetworkDiskCache::clear() QVERIFY(cache.cacheSize() > qint64(0)); QString cacheDirectory = cache.cacheDirectory(); - QCOMPARE(countFiles(cacheDirectory).count(), 3); + QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3); cache.clear(); - QCOMPARE(countFiles(cacheDirectory).count(), 2); + QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 2); // don't delete files that it didn't create - QTemporaryFile file(cacheDirectory + "/cache_XXXXXX"); + QTemporaryFile file(cacheDirectory + "/XXXXXX"); if (file.open()) { - QCOMPARE(countFiles(cacheDirectory).count(), 3); + QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3); cache.clear(); - QCOMPARE(countFiles(cacheDirectory).count(), 3); + QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3); } } @@ -317,12 +319,6 @@ void tst_QNetworkDiskCache::data() QUrl url(EXAMPLE_URL); cache.setupWithOne(url, data); - // flush the cache - QTemporaryFile file(cache.cacheDirectory() + "/cache_XXXXXX.cache"); - if (file.open()) { - cache.call_fileMetaData(file.fileName()); - } - for (int i = 0; i < 3; ++i) { QIODevice *d = cache.data(url); QVERIFY(d); @@ -362,9 +358,9 @@ void tst_QNetworkDiskCache::remove() QUrl url(EXAMPLE_URL); cache.setupWithOne(url); QString cacheDirectory = cache.cacheDirectory(); - QCOMPARE(countFiles(cacheDirectory).count(), 3); + QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3); cache.remove(url); - QCOMPARE(countFiles(cacheDirectory).count(), 2); + QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 2); } void tst_QNetworkDiskCache::setCacheDirectory_data() @@ -414,7 +410,7 @@ void tst_QNetworkDiskCache::fileMetaData() QString cacheDirectory = cache.cacheDirectory(); QStringList list = countFiles(cacheDirectory); - QCOMPARE(list.count(), 3); + QCOMPARE(list.count(), NUM_SUBDIRECTORIES + 3); foreach(QString fileName, list) { QFileInfo info(fileName); if (info.isFile()) { @@ -491,7 +487,7 @@ void tst_QNetworkDiskCache::oldCacheVersionFile() if (pass == 0) { QString name; { - QTemporaryFile file(cache.cacheDirectory() + "/cache_XXXXXX.cache"); + QTemporaryFile file(cache.cacheDirectory() + "/XXXXXX.d"); file.setAutoRemove(false); QVERIFY(file.open()); QDataStream out(&file); @@ -507,7 +503,7 @@ void tst_QNetworkDiskCache::oldCacheVersionFile() QVERIFY(!QFile::exists(name)); } else { QStringList files = countFiles(cache.cacheDirectory()); - QCOMPARE(files.count(), 3); + QCOMPARE(files.count(), NUM_SUBDIRECTORIES + 3); // find the file QString cacheFile; foreach (QString file, files) { diff --git a/tests/auto/qnetworkreply/image1.jpg b/tests/auto/qnetworkreply/image1.jpg Binary files differnew file mode 100644 index 0000000..dba31c1 --- /dev/null +++ b/tests/auto/qnetworkreply/image1.jpg diff --git a/tests/auto/qnetworkreply/image2.jpg b/tests/auto/qnetworkreply/image2.jpg Binary files differnew file mode 100644 index 0000000..72936e2 --- /dev/null +++ b/tests/auto/qnetworkreply/image2.jpg diff --git a/tests/auto/qnetworkreply/image3.jpg b/tests/auto/qnetworkreply/image3.jpg Binary files differnew file mode 100644 index 0000000..cede519 --- /dev/null +++ b/tests/auto/qnetworkreply/image3.jpg diff --git a/tests/auto/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/qnetworkreply/tst_qnetworkreply.cpp index 2c79951..d8b6dc4 100644 --- a/tests/auto/qnetworkreply/tst_qnetworkreply.cpp +++ b/tests/auto/qnetworkreply/tst_qnetworkreply.cpp @@ -60,6 +60,8 @@ #include <QtNetwork/qnetworkrequest.h> #include <QtNetwork/qnetworkreply.h> #include <QtNetwork/qnetworkcookie.h> +#include <QtNetwork/QHttpPart> +#include <QtNetwork/QHttpMultiPart> #ifndef QT_NO_OPENSSL #include <QtNetwork/qsslerror.h> #include <QtNetwork/qsslconfiguration.h> @@ -83,6 +85,9 @@ Q_DECLARE_METATYPE(QNetworkProxyQuery) Q_DECLARE_METATYPE(QList<QNetworkProxy>) Q_DECLARE_METATYPE(QNetworkReply::NetworkError) Q_DECLARE_METATYPE(QBuffer*) +Q_DECLARE_METATYPE(QHttpMultiPart *) +Q_DECLARE_METATYPE(QList<QFile*>) // for multiparts +Q_DECLARE_METATYPE(QSslConfiguration) class QNetworkReplyPtr: public QSharedPointer<QNetworkReply> { @@ -139,6 +144,8 @@ public: ~tst_QNetworkReply(); QString runSimpleRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QNetworkReplyPtr &reply, const QByteArray &data = QByteArray()); + QString runMultipartRequest(const QNetworkRequest &request, QNetworkReplyPtr &reply, + QHttpMultiPart *multiPart, const QByteArray &verb); QString runCustomRequest(const QNetworkRequest &request, QNetworkReplyPtr &reply, const QByteArray &verb, QIODevice *data); @@ -185,10 +192,14 @@ private Q_SLOTS: void putToHttp(); void putToHttpSynchronous_data(); void putToHttpSynchronous(); + void putToHttpMultipart_data(); + void putToHttpMultipart(); void postToHttp_data(); void postToHttp(); void postToHttpSynchronous_data(); void postToHttpSynchronous(); + void postToHttpMultipart_data(); + void postToHttpMultipart(); void deleteFromHttp_data(); void deleteFromHttp(); void putGetDeleteGetFromHttp_data(); @@ -309,6 +320,8 @@ private Q_SLOTS: void ignoreSslErrorsList(); void ignoreSslErrorsListWithSlot_data(); void ignoreSslErrorsListWithSlot(); + void sslConfiguration_data(); + void sslConfiguration(); #endif void getAndThenDeleteObject_data(); @@ -337,6 +350,8 @@ private Q_SLOTS: void qtbug15311doubleContentLength(); + void qtbug18232gzipContentLengthZero(); + void synchronousRequest_data(); void synchronousRequest(); #ifndef QT_NO_OPENSSL @@ -1090,6 +1105,38 @@ void tst_QNetworkReply::storeSslConfiguration() } #endif +QString tst_QNetworkReply::runMultipartRequest(const QNetworkRequest &request, + QNetworkReplyPtr &reply, + QHttpMultiPart *multiPart, + const QByteArray &verb) +{ + if (verb == "POST") + reply = manager.post(request, multiPart); + else + reply = manager.put(request, multiPart); + + // the code below is copied from tst_QNetworkReply::runSimpleRequest, see below + reply->setParent(this); + connect(reply, SIGNAL(finished()), SLOT(finished())); + connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(gotError())); + multiPart->setParent(reply); + + returnCode = Timeout; + loop = new QEventLoop; + QTimer::singleShot(25000, loop, SLOT(quit())); + int code = returnCode == Timeout ? loop->exec() : returnCode; + delete loop; + loop = 0; + + switch (code) { + case Failure: + return "Request failed: " + reply->errorString(); + case Timeout: + return "Network timeout"; + } + return QString(); +} + QString tst_QNetworkReply::runSimpleRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QNetworkReplyPtr &reply, @@ -1835,6 +1882,307 @@ void tst_QNetworkReply::postToHttpSynchronous() QCOMPARE(uploadedData, md5sum.toHex()); } +void tst_QNetworkReply::postToHttpMultipart_data() +{ + QTest::addColumn<QUrl>("url"); + QTest::addColumn<QHttpMultiPart *>("multiPart"); + QTest::addColumn<QByteArray>("expectedReplyData"); + QTest::addColumn<QByteArray>("contentType"); + + QUrl url("http://" + QtNetworkSettings::serverName() + "/qtest/cgi-bin/multipart.cgi"); + QByteArray expectedData; + + + // empty parts + + QHttpMultiPart *emptyMultiPart = new QHttpMultiPart; + QTest::newRow("empty") << url << emptyMultiPart << expectedData << QByteArray("mixed"); + + QHttpMultiPart *emptyRelatedMultiPart = new QHttpMultiPart; + emptyRelatedMultiPart->setContentType(QHttpMultiPart::RelatedType); + QTest::newRow("empty-related") << url << emptyRelatedMultiPart << expectedData << QByteArray("related"); + + QHttpMultiPart *emptyAlternativeMultiPart = new QHttpMultiPart; + emptyAlternativeMultiPart->setContentType(QHttpMultiPart::AlternativeType); + QTest::newRow("empty-alternative") << url << emptyAlternativeMultiPart << expectedData << QByteArray("alternative"); + + + // text-only parts + + QHttpPart textPart; + textPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); + textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text\"")); + textPart.setBody("7 bytes"); + QHttpMultiPart *multiPart1 = new QHttpMultiPart; + multiPart1->setContentType(QHttpMultiPart::FormDataType); + multiPart1->append(textPart); + expectedData = "key: text, value: 7 bytes\n"; + QTest::newRow("text") << url << multiPart1 << expectedData << QByteArray("form-data"); + + QHttpMultiPart *customMultiPart = new QHttpMultiPart; + customMultiPart->append(textPart); + expectedData = "header: Content-Type, value: 'text/plain'\n" + "header: Content-Disposition, value: 'form-data; name=\"text\"'\n" + "content: 7 bytes\n" + "\n"; + QTest::newRow("text-custom") << url << customMultiPart << expectedData << QByteArray("custom"); + + QHttpPart textPart2; + textPart2.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); + textPart2.setRawHeader("myRawHeader", "myValue"); + textPart2.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text2\"")); + textPart2.setBody("some more bytes"); + textPart2.setBodyDevice((QIODevice *) 1); // test whether setting and unsetting of the device works + textPart2.setBodyDevice(0); + QHttpMultiPart *multiPart2 = new QHttpMultiPart; + multiPart2->setContentType(QHttpMultiPart::FormDataType); + multiPart2->append(textPart); + multiPart2->append(textPart2); + expectedData = "key: text2, value: some more bytes\n" + "key: text, value: 7 bytes\n"; + QTest::newRow("text-text") << url << multiPart2 << expectedData << QByteArray("form-data"); + + + QHttpPart textPart3; + textPart3.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); + textPart3.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text3\"")); + textPart3.setRawHeader("Content-Location", "http://my.test.location.tld"); + textPart3.setBody("even more bytes"); + QHttpMultiPart *multiPart3 = new QHttpMultiPart; + multiPart3->setContentType(QHttpMultiPart::AlternativeType); + multiPart3->append(textPart); + multiPart3->append(textPart2); + multiPart3->append(textPart3); + expectedData = "header: Content-Type, value: 'text/plain'\n" + "header: Content-Disposition, value: 'form-data; name=\"text\"'\n" + "content: 7 bytes\n" + "\n" + "header: Content-Type, value: 'text/plain'\n" + "header: myRawHeader, value: 'myValue'\n" + "header: Content-Disposition, value: 'form-data; name=\"text2\"'\n" + "content: some more bytes\n" + "\n" + "header: Content-Type, value: 'text/plain'\n" + "header: Content-Disposition, value: 'form-data; name=\"text3\"'\n" + "header: Content-Location, value: 'http://my.test.location.tld'\n" + "content: even more bytes\n\n"; + QTest::newRow("text-text-text") << url << multiPart3 << expectedData << QByteArray("alternative"); + + + + // text and image parts + + QHttpPart imagePart11; + imagePart11.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); + imagePart11.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage\"")); + imagePart11.setRawHeader("Content-Location", "http://my.test.location.tld"); + imagePart11.setRawHeader("Content-ID", "my@id.tld"); + QFile *file11 = new QFile(SRCDIR "/image1.jpg"); + file11->open(QIODevice::ReadOnly); + imagePart11.setBodyDevice(file11); + QHttpMultiPart *imageMultiPart1 = new QHttpMultiPart(QHttpMultiPart::FormDataType); + imageMultiPart1->append(imagePart11); + file11->setParent(imageMultiPart1); + expectedData = "key: testImage, value: 87ef3bb319b004ba9e5e9c9fa713776e\n"; // md5 sum of file + QTest::newRow("image") << url << imageMultiPart1 << expectedData << QByteArray("form-data"); + + QHttpPart imagePart21; + imagePart21.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); + imagePart21.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage1\"")); + imagePart21.setRawHeader("Content-Location", "http://my.test.location.tld"); + imagePart21.setRawHeader("Content-ID", "my@id.tld"); + QFile *file21 = new QFile(SRCDIR "/image1.jpg"); + file21->open(QIODevice::ReadOnly); + imagePart21.setBodyDevice(file21); + QHttpMultiPart *imageMultiPart2 = new QHttpMultiPart(); + imageMultiPart2->setContentType(QHttpMultiPart::FormDataType); + imageMultiPart2->append(textPart); + imageMultiPart2->append(imagePart21); + file21->setParent(imageMultiPart2); + QHttpPart imagePart22; + imagePart22.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); + imagePart22.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage2\"")); + QFile *file22 = new QFile(SRCDIR "/image2.jpg"); + file22->open(QIODevice::ReadOnly); + imagePart22.setBodyDevice(file22); + imageMultiPart2->append(imagePart22); + file22->setParent(imageMultiPart2); + expectedData = "key: testImage1, value: 87ef3bb319b004ba9e5e9c9fa713776e\n" + "key: text, value: 7 bytes\n" + "key: testImage2, value: 483761b893f7fb1bd2414344cd1f3dfb\n"; + QTest::newRow("text-image-image") << url << imageMultiPart2 << expectedData << QByteArray("form-data"); + + + QHttpPart imagePart31; + imagePart31.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); + imagePart31.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage1\"")); + imagePart31.setRawHeader("Content-Location", "http://my.test.location.tld"); + imagePart31.setRawHeader("Content-ID", "my@id.tld"); + QFile *file31 = new QFile(SRCDIR "/image1.jpg"); + file31->open(QIODevice::ReadOnly); + imagePart31.setBodyDevice(file31); + QHttpMultiPart *imageMultiPart3 = new QHttpMultiPart(QHttpMultiPart::FormDataType); + imageMultiPart3->append(imagePart31); + file31->setParent(imageMultiPart3); + QHttpPart imagePart32; + imagePart32.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); + imagePart32.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage2\"")); + QFile *file32 = new QFile(SRCDIR "/image2.jpg"); + file32->open(QIODevice::ReadOnly); + imagePart32.setBodyDevice(file31); // check that resetting works + imagePart32.setBodyDevice(file32); + imageMultiPart3->append(imagePart32); + file32->setParent(imageMultiPart3); + QHttpPart imagePart33; + imagePart33.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); + imagePart33.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage3\"")); + QFile *file33 = new QFile(SRCDIR "/image3.jpg"); + file33->open(QIODevice::ReadOnly); + imagePart33.setBodyDevice(file33); + imageMultiPart3->append(imagePart33); + file33->setParent(imageMultiPart3); + expectedData = "key: testImage1, value: 87ef3bb319b004ba9e5e9c9fa713776e\n" + "key: testImage2, value: 483761b893f7fb1bd2414344cd1f3dfb\n" + "key: testImage3, value: ab0eb6fd4fcf8b4436254870b4513033\n"; + QTest::newRow("3-images") << url << imageMultiPart3 << expectedData << QByteArray("form-data"); + + + // note: nesting multiparts is not working currently; for that, the outputDevice would need to be public + +// QHttpPart imagePart41; +// imagePart41.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); +// QFile *file41 = new QFile(SRCDIR "/image1.jpg"); +// file41->open(QIODevice::ReadOnly); +// imagePart41.setBodyDevice(file41); +// +// QHttpMultiPart *innerMultiPart = new QHttpMultiPart(); +// innerMultiPart->setContentType(QHttpMultiPart::FormDataType); +// textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant()); +// innerMultiPart->append(textPart); +// innerMultiPart->append(imagePart41); +// textPart2.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant()); +// innerMultiPart->append(textPart2); +// +// QHttpPart nestedPart; +// nestedPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"nestedMessage")); +// nestedPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("multipart/alternative; boundary=\"" + innerMultiPart->boundary() + "\"")); +// innerMultiPart->outputDevice()->open(QIODevice::ReadOnly); +// nestedPart.setBodyDevice(innerMultiPart->outputDevice()); +// +// QHttpMultiPart *outerMultiPart = new QHttpMultiPart; +// outerMultiPart->setContentType(QHttpMultiPart::FormDataType); +// outerMultiPart->append(textPart); +// outerMultiPart->append(nestedPart); +// outerMultiPart->append(textPart2); +// expectedData = "nothing"; // the CGI.pm module running on the test server does not understand nested multiparts +// openFiles.clear(); +// openFiles << file41; +// QTest::newRow("nested") << url << outerMultiPart << expectedData << openFiles; + + + // test setting large chunks of content with a byte array instead of a device (DISCOURAGED because of high memory consumption, + // but we need to test that the behavior is correct) + QHttpPart imagePart51; + imagePart51.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); + imagePart51.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage\"")); + QFile *file51 = new QFile(SRCDIR "/image1.jpg"); + file51->open(QIODevice::ReadOnly); + QByteArray imageData = file51->readAll(); + file51->close(); + delete file51; + imagePart51.setBody("7 bytes"); // check that resetting works + imagePart51.setBody(imageData); + QHttpMultiPart *imageMultiPart5 = new QHttpMultiPart; + imageMultiPart5->setContentType(QHttpMultiPart::FormDataType); + imageMultiPart5->append(imagePart51); + expectedData = "key: testImage, value: 87ef3bb319b004ba9e5e9c9fa713776e\n"; // md5 sum of file + QTest::newRow("image-as-content") << url << imageMultiPart5 << expectedData << QByteArray("form-data"); +} + +void tst_QNetworkReply::postToHttpMultipart() +{ + QFETCH(QUrl, url); + + static QSet<QByteArray> boundaries; + + QNetworkRequest request(url); + QNetworkReplyPtr reply; + + QFETCH(QHttpMultiPart *, multiPart); + QFETCH(QByteArray, expectedReplyData); + QFETCH(QByteArray, contentType); + + // hack for testing the setting of the content-type header by hand: + if (contentType == "custom") { + QByteArray contentType("multipart/custom; boundary=\"" + multiPart->boundary() + "\""); + request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); + } + + QVERIFY2(! boundaries.contains(multiPart->boundary()), "boundary '" + multiPart->boundary() + "' has been created twice"); + boundaries.insert(multiPart->boundary()); + + RUN_REQUEST(runMultipartRequest(request, reply, multiPart, "POST")); + multiPart->deleteLater(); + + QCOMPARE(reply->url(), url); + QCOMPARE(reply->error(), QNetworkReply::NoError); + + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok + + QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string + QVERIFY(multiPart->boundary().count() < 70); + QByteArray replyData = reply->readAll(); + + expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n"); +// QEXPECT_FAIL("nested", "the server does not understand nested multipart messages", Continue); // see above + QCOMPARE(replyData, expectedReplyData); +} + +void tst_QNetworkReply::putToHttpMultipart_data() +{ + postToHttpMultipart_data(); +} + +void tst_QNetworkReply::putToHttpMultipart() +{ + QSKIP("test server script cannot handle PUT data yet", SkipAll); + QFETCH(QUrl, url); + + static QSet<QByteArray> boundaries; + + QNetworkRequest request(url); + QNetworkReplyPtr reply; + + QFETCH(QHttpMultiPart *, multiPart); + QFETCH(QByteArray, expectedReplyData); + QFETCH(QByteArray, contentType); + + // hack for testing the setting of the content-type header by hand: + if (contentType == "custom") { + QByteArray contentType("multipart/custom; boundary=\"" + multiPart->boundary() + "\""); + request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); + } + + QVERIFY2(! boundaries.contains(multiPart->boundary()), "boundary '" + multiPart->boundary() + "' has been created twice"); + boundaries.insert(multiPart->boundary()); + + RUN_REQUEST(runMultipartRequest(request, reply, multiPart, "PUT")); + multiPart->deleteLater(); + + QCOMPARE(reply->url(), url); + QCOMPARE(reply->error(), QNetworkReply::NoError); + + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok + + QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string + QVERIFY(multiPart->boundary().count() < 70); + QByteArray replyData = reply->readAll(); + + expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n"); +// QEXPECT_FAIL("nested", "the server does not understand nested multipart messages", Continue); // see above + QCOMPARE(replyData, expectedReplyData); +} + void tst_QNetworkReply::deleteFromHttp_data() { QTest::addColumn<QUrl>("url"); @@ -3814,14 +4162,8 @@ void tst_QNetworkReply::ioPostToHttpsUploadProgress() // some progress should have been made QVERIFY(!spy.isEmpty()); QList<QVariant> args = spy.last(); - qDebug() << "tst_QNetworkReply::ioPostToHttpsUploadProgress" - << args.at(0).toLongLong() - << sourceFile.size() - << spy.size(); QVERIFY(args.at(0).toLongLong() > 0); - // FIXME this is where it messes up - QEXPECT_FAIL("", "Either the readBufferSize of QSslSocket is broken or we do upload too much. Hm.", Abort); QVERIFY(args.at(0).toLongLong() != sourceFile.size()); incomingSocket->setReadBufferSize(32*1024); @@ -5025,6 +5367,37 @@ void tst_QNetworkReply::ignoreSslErrorsListWithSlot() QCOMPARE(reply->error(), expectedNetworkError); } +void tst_QNetworkReply::sslConfiguration_data() +{ + QTest::addColumn<QSslConfiguration>("configuration"); + QTest::addColumn<bool>("works"); + + QTest::newRow("empty") << QSslConfiguration() << false; + QSslConfiguration conf = QSslConfiguration::defaultConfiguration(); + QTest::newRow("default") << conf << false; // does not contain test server cert + QList<QSslCertificate> testServerCert = QSslCertificate::fromPath(SRCDIR "/certs/qt-test-server-cacert.pem"); + conf.setCaCertificates(testServerCert); + QTest::newRow("set-root-cert") << conf << true; + conf.setProtocol(QSsl::SecureProtocols); + QTest::newRow("secure") << conf << true; +} + +void tst_QNetworkReply::sslConfiguration() +{ + QNetworkRequest request(QUrl("https://" + QtNetworkSettings::serverName() + "/index.html")); + QFETCH(QSslConfiguration, configuration); + request.setSslConfiguration(configuration); + QNetworkReplyPtr reply = manager.get(request); + + connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); + QTestEventLoop::instance().enterLoop(10); + QVERIFY(!QTestEventLoop::instance().timeout()); + + QFETCH(bool, works); + QNetworkReply::NetworkError expectedError = works ? QNetworkReply::NoError : QNetworkReply::SslHandshakeFailedError; + QCOMPARE(reply->error(), expectedError); +} + #endif // QT_NO_OPENSSL void tst_QNetworkReply::getAndThenDeleteObject_data() @@ -5532,6 +5905,25 @@ void tst_QNetworkReply::qtbug15311doubleContentLength() QCOMPARE(reply->readAll(), QByteArray("ABC")); } +void tst_QNetworkReply::qtbug18232gzipContentLengthZero() +{ + QByteArray response("HTTP/1.0 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: 0\r\n\r\n"); + MiniHttpServer server(response); + server.doClose = true; + + QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); + QNetworkReplyPtr reply = manager.get(request); + + connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); + QTestEventLoop::instance().enterLoop(10); + QVERIFY(!QTestEventLoop::instance().timeout()); + QVERIFY(reply->isFinished()); + QCOMPARE(reply->error(), QNetworkReply::NoError); + QCOMPARE(reply->size(), qint64(0)); + QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(0)); + QCOMPARE(reply->readAll(), QByteArray()); +} + void tst_QNetworkReply::synchronousRequest_data() { QTest::addColumn<QUrl>("url"); diff --git a/tests/auto/qobject/tst_qobject.cpp b/tests/auto/qobject/tst_qobject.cpp index d2307ee..4b926e4 100644 --- a/tests/auto/qobject/tst_qobject.cpp +++ b/tests/auto/qobject/tst_qobject.cpp @@ -135,7 +135,7 @@ private slots: void disconnectByMetaMethod(); void disconnectNotSignalMetaMethod(); void autoConnectionBehavior(); - + void baseDestroyed(); protected: }; @@ -3925,5 +3925,34 @@ void tst_QObject::autoConnectionBehavior() delete receiver; } +class BaseDestroyed : public QObject +{ Q_OBJECT + QList<QString> fooList; + bool destroyed; +public: + BaseDestroyed() : destroyed(false) + { fooList << "a" << "b"; } + ~BaseDestroyed() + { + QVERIFY(!destroyed); + destroyed = true; + } + +public slots: + void slotUseList() + { + QVERIFY(!destroyed); + fooList << "c" << "d"; + } +}; + +void tst_QObject::baseDestroyed() +{ + BaseDestroyed d; + connect(&d, SIGNAL(destroyed()), &d, SLOT(slotUseList())); + //When d goes out of scope, slotUseList should not be called as the BaseDestroyed has + // already been destroyed while ~QObject emit destroyed +} + QTEST_MAIN(tst_QObject) #include "tst_qobject.moc" diff --git a/tests/auto/qsslsocket/tst_qsslsocket.cpp b/tests/auto/qsslsocket/tst_qsslsocket.cpp index ccfe0f3..5b30a39 100644 --- a/tests/auto/qsslsocket/tst_qsslsocket.cpp +++ b/tests/auto/qsslsocket/tst_qsslsocket.cpp @@ -67,6 +67,7 @@ typedef QList<QSslError::SslError> SslErrorList; Q_DECLARE_METATYPE(SslErrorList) Q_DECLARE_METATYPE(QSslError) Q_DECLARE_METATYPE(QSsl::SslProtocol) +Q_DECLARE_METATYPE(QSslConfiguration) #endif #if defined Q_OS_HPUX && defined Q_CC_GNU @@ -152,6 +153,8 @@ private slots: void setLocalCertificate(); void setPrivateKey(); void setSocketDescriptor(); + void setSslConfiguration_data(); + void setSslConfiguration(); void waitForEncrypted(); void waitForConnectedEncryptedReadyRead(); void startClientEncryption(); @@ -185,7 +188,7 @@ private slots: void ignoreSslErrorsListWithSlot(); void readFromClosedSocket(); void writeBigChunk(); - void blacklist(); + void blacklistedCertificates(); void setEmptyDefaultConfiguration(); static void exitLoop() @@ -926,13 +929,15 @@ void tst_QSslSocket::protocolServerSide_data() QTest::newRow("ssl3-tls1") << QSsl::SslV3 << QSsl::TlsV1 << false; QTest::newRow("ssl3-tls1ssl3") << QSsl::SslV3 << QSsl::TlsV1SslV3 << true; QTest::newRow("ssl3-secure") << QSsl::SslV3 << QSsl::SecureProtocols << true; - QTest::newRow("ssl3-any") << QSsl::SslV3 << QSsl::AnyProtocol << true; + QTest::newRow("ssl3-any") << QSsl::SslV3 << QSsl::AnyProtocol << false; // we wont set a SNI header here because we connect to a + // numerical IP, so OpenSSL will send a SSL 2 handshake QTest::newRow("tls1-ssl2") << QSsl::TlsV1 << QSsl::SslV2 << false; QTest::newRow("tls1-ssl3") << QSsl::TlsV1 << QSsl::SslV3 << false; QTest::newRow("tls1-tls1ssl3") << QSsl::TlsV1 << QSsl::TlsV1SslV3 << true; QTest::newRow("tls1-secure") << QSsl::TlsV1 << QSsl::SecureProtocols << true; - QTest::newRow("tls1-any") << QSsl::TlsV1 << QSsl::AnyProtocol << true; + QTest::newRow("tls1-any") << QSsl::TlsV1 << QSsl::AnyProtocol << false; // we wont set a SNI header here because we connect to a + // numerical IP, so OpenSSL will send a SSL 2 handshake QTest::newRow("tls1ssl3-ssl2") << QSsl::TlsV1SslV3 << QSsl::SslV2 << false; QTest::newRow("tls1ssl3-ssl3") << QSsl::TlsV1SslV3 << QSsl::SslV3 << true; @@ -1044,6 +1049,39 @@ void tst_QSslSocket::setSocketDescriptor() QVERIFY(client->localPort() != 0); } +void tst_QSslSocket::setSslConfiguration_data() +{ + QTest::addColumn<QSslConfiguration>("configuration"); + QTest::addColumn<bool>("works"); + + QTest::newRow("empty") << QSslConfiguration() << false; + QSslConfiguration conf = QSslConfiguration::defaultConfiguration(); + QTest::newRow("default") << conf << false; // does not contain test server cert + QList<QSslCertificate> testServerCert = QSslCertificate::fromPath(SRCDIR "certs/qt-test-server-cacert.pem"); + conf.setCaCertificates(testServerCert); + QTest::newRow("set-root-cert") << conf << true; + conf.setProtocol(QSsl::SecureProtocols); + QTest::newRow("secure") << conf << true; +} + +void tst_QSslSocket::setSslConfiguration() +{ + if (!QSslSocket::supportsSsl()) + return; + + QSslSocketPtr socket = newSocket(); + QFETCH(QSslConfiguration, configuration); + socket->setSslConfiguration(configuration); + this->socket = socket; + socket->connectToHostEncrypted(QtNetworkSettings::serverName(), 443); + QFETCH(bool, works); + QCOMPARE(socket->waitForEncrypted(10000), works); + if (works) { + socket->disconnectFromHost(); + QVERIFY2(socket->waitForDisconnected(), qPrintable(socket->errorString())); + } +} + void tst_QSslSocket::waitForEncrypted() { if (!QSslSocket::supportsSsl()) @@ -1945,7 +1983,7 @@ void tst_QSslSocket::writeBigChunk() socket->close(); } -void tst_QSslSocket::blacklist() +void tst_QSslSocket::blacklistedCertificates() { QFETCH_GLOBAL(bool, setProxy); if (setProxy) @@ -1966,14 +2004,15 @@ void tst_QSslSocket::blacklist() QVERIFY(sender->state() == QAbstractSocket::ConnectedState); receiver->setObjectName("receiver"); sender->setObjectName("sender"); - receiver->ignoreSslErrors(); receiver->startClientEncryption(); - connect(receiver, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(exitLoop())); + connect(receiver, SIGNAL(sslErrors(QList<QSslError>)), SLOT(exitLoop())); connect(receiver, SIGNAL(encrypted()), SLOT(exitLoop())); enterLoop(1); - QCOMPARE(receiver->error(), QAbstractSocket::SslHandshakeFailedError); - QCOMPARE(receiver->errorString(), QString("The peer certificate is blacklisted")); + QList<QSslError> sslErrors = receiver->sslErrors(); + QVERIFY(sslErrors.count() > 0); + // there are more errors (self signed cert and hostname mismatch), but we only care about the blacklist error + QCOMPARE(sslErrors.at(0).error(), QSslError::CertificateBlacklisted); } void tst_QSslSocket::setEmptyDefaultConfiguration() @@ -1987,8 +2026,9 @@ void tst_QSslSocket::setEmptyDefaultConfiguration() QSslConfiguration::setDefaultConfiguration(emptyConf); QSslSocketPtr socket = newSocket(); + connect(socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(ignoreErrorSlot())); socket->connectToHostEncrypted(QtNetworkSettings::serverName(), 443); - + QVERIFY2(!socket->waitForEncrypted(4000), qPrintable(socket->errorString())); } #endif // QT_NO_OPENSSL diff --git a/tests/auto/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp b/tests/auto/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp index abdd550..6d3590a 100644 --- a/tests/auto/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp +++ b/tests/auto/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp @@ -217,6 +217,13 @@ void tst_QSslSocket_onDemandCertificates_member::onDemandRootCertLoadingMemberMe socket3->setCaCertificates(QList<QSslCertificate>()); socket3->connectToHostEncrypted(host, 443); QVERIFY(!socket3->waitForEncrypted()); + + // setting empty SSL configuration explicitly -> should not work + QSslSocketPtr socket4 = newSocket(); + this->socket = socket4; + socket4->setSslConfiguration(QSslConfiguration()); + socket4->connectToHostEncrypted(host, 443); + QVERIFY(!socket4->waitForEncrypted()); } #endif // QT_NO_OPENSSL diff --git a/tests/auto/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp b/tests/auto/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp index 5003b5c..14a7c3b 100644 --- a/tests/auto/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp +++ b/tests/auto/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp @@ -218,6 +218,18 @@ void tst_QSslSocket_onDemandCertificates_static::onDemandRootCertLoadingStaticMe this->socket = socket3; socket3->connectToHostEncrypted(host, 443); QVERIFY(!socket3->waitForEncrypted()); + + QSslSocket::setDefaultCaCertificates(QSslSocket::systemCaCertificates()); + + // setting empty default configuration -> should not work + QSslConfiguration conf; + QSslConfiguration originalDefaultConf = QSslConfiguration::defaultConfiguration(); + QSslConfiguration::setDefaultConfiguration(conf); + QSslSocketPtr socket4 = newSocket(); + this->socket = socket4; + socket4->connectToHostEncrypted(host, 443); + QVERIFY(!socket4->waitForEncrypted(4000)); + QSslConfiguration::setDefaultConfiguration(originalDefaultConf); // restore old behaviour for run with proxies etc. } #endif // QT_NO_OPENSSL diff --git a/tests/auto/qstring/tst_qstring.cpp b/tests/auto/qstring/tst_qstring.cpp index abc8d9a..25e16fe 100644 --- a/tests/auto/qstring/tst_qstring.cpp +++ b/tests/auto/qstring/tst_qstring.cpp @@ -697,11 +697,11 @@ void tst_QString::acc_01() QVERIFY(a<=c); QVERIFY(!(c<=a)); QVERIFY(!(d<=a)); - QCOMPARE(a+b,(QString)"ABCABC"); - QCOMPARE(a +"XXXX",(QString)"ABCXXXX"); - QCOMPARE(a+'X',(QString)"ABCX"); - QCOMPARE("XXXX"+a,(QString)"XXXXABC"); - QCOMPARE('X'+a,(QString)"XABC"); + QCOMPARE(QString(a+b),(QString)"ABCABC"); + QCOMPARE(QString(a+"XXXX"),(QString)"ABCXXXX"); + QCOMPARE(QString(a+'X'),(QString)"ABCX"); + QCOMPARE(QString("XXXX"+a),(QString)"XXXXABC"); + QCOMPARE(QString('X'+a),(QString)"XABC"); a = (const char*)0; QVERIFY(a.isNull()); QVERIFY(*a.toLatin1().constData() == '\0'); @@ -1060,12 +1060,12 @@ void tst_QString::indexOf_data() QString veryBigHaystack(500, 'a'); veryBigHaystack += 'B'; QTest::newRow("BoyerMooreStressTest") << veryBigHaystack << veryBigHaystack << 0 << true << 0; - QTest::newRow("BoyerMooreStressTest2") << veryBigHaystack + 'c' << veryBigHaystack << 0 << true << 0; - QTest::newRow("BoyerMooreStressTest3") << 'c' + veryBigHaystack << veryBigHaystack << 0 << true << 1; - QTest::newRow("BoyerMooreStressTest4") << veryBigHaystack << veryBigHaystack + 'c' << 0 << true << -1; - QTest::newRow("BoyerMooreStressTest5") << veryBigHaystack << 'c' + veryBigHaystack << 0 << true << -1; - QTest::newRow("BoyerMooreStressTest6") << 'd' + veryBigHaystack << 'c' + veryBigHaystack << 0 << true << -1; - QTest::newRow("BoyerMooreStressTest6") << veryBigHaystack + 'c' << 'c' + veryBigHaystack << 0 << true << -1; + QTest::newRow("BoyerMooreStressTest2") << QString(veryBigHaystack + 'c') << veryBigHaystack << 0 << true << 0; + QTest::newRow("BoyerMooreStressTest3") << QString('c' + veryBigHaystack) << veryBigHaystack << 0 << true << 1; + QTest::newRow("BoyerMooreStressTest4") << veryBigHaystack << QString(veryBigHaystack + 'c') << 0 << true << -1; + QTest::newRow("BoyerMooreStressTest5") << veryBigHaystack << QString('c' + veryBigHaystack) << 0 << true << -1; + QTest::newRow("BoyerMooreStressTest6") << QString('d' + veryBigHaystack) << QString('c' + veryBigHaystack) << 0 << true << -1; + QTest::newRow("BoyerMooreStressTest6") << QString(veryBigHaystack + 'c') << QString('c' + veryBigHaystack) << 0 << true << -1; QTest::newRow("BoyerMooreInsensitiveStressTest") << veryBigHaystack << veryBigHaystack << 0 << false << 0; @@ -1175,14 +1175,14 @@ void tst_QString::indexOf2_data() QString whale = "a5zby6cx7dw8evf9ug0th1si2rj3qkp4lomn"; QString minnow = "zby"; QTest::newRow( "data40" ) << whale << minnow << 2; - QTest::newRow( "data41" ) << (whale + whale) << minnow << 2; - QTest::newRow( "data42" ) << (minnow + whale) << minnow << 0; + QTest::newRow( "data41" ) << QString(whale + whale) << minnow << 2; + QTest::newRow( "data42" ) << QString(minnow + whale) << minnow << 0; QTest::newRow( "data43" ) << whale << whale << 0; - QTest::newRow( "data44" ) << (whale + whale) << whale << 0; - QTest::newRow( "data45" ) << whale << (whale + whale) << -1; - QTest::newRow( "data46" ) << (whale + whale) << (whale + whale) << 0; - QTest::newRow( "data47" ) << (whale + whale) << (whale + minnow) << -1; - QTest::newRow( "data48" ) << (minnow + whale) << whale << (int)minnow.length(); + QTest::newRow( "data44" ) << QString(whale + whale) << whale << 0; + QTest::newRow( "data45" ) << whale << QString(whale + whale) << -1; + QTest::newRow( "data46" ) << QString(whale + whale) << QString(whale + whale) << 0; + QTest::newRow( "data47" ) << QString(whale + whale) << QString(whale + minnow) << -1; + QTest::newRow( "data48" ) << QString(minnow + whale) << whale << (int)minnow.length(); } void tst_QString::indexOf2() @@ -1631,7 +1631,7 @@ void tst_QString::toLower() QCOMPARE( QString("`ABYZ{").toLower(), QString("`abyz{")); QCOMPARE( QString("`abyz{").toLower(), QString("`abyz{")); - QCOMPARE( QString(1, QChar(0x130)).toLower(), QString(1, QChar(0x69)) + QChar(0x307)); + QCOMPARE( QString(1, QChar(0x130)).toLower(), QString(QString(1, QChar(0x69)) + QChar(0x307))); QString lower; lower += QChar(QChar::highSurrogate(0x10428)); diff --git a/tests/auto/qstringbuilder1/stringbuilder.cpp b/tests/auto/qstringbuilder1/stringbuilder.cpp index f3c0ea9..d7a32bf 100644 --- a/tests/auto/qstringbuilder1/stringbuilder.cpp +++ b/tests/auto/qstringbuilder1/stringbuilder.cpp @@ -137,4 +137,60 @@ void runScenario() string = QString::fromLatin1(LITERAL); QCOMPARE(QByteArray(qPrintable(string P string)), QByteArray(string.toLatin1() + string.toLatin1())); + + + + //QByteArray + { + QByteArray ba = LITERAL; + QByteArray superba = ba P ba P LITERAL; + QCOMPARE(superba, QByteArray(LITERAL LITERAL LITERAL)); + + QByteArray testWith0 = ba P "test\0with\0zero" P ba; + QCOMPARE(testWith0, QByteArray(LITERAL "test" LITERAL)); + + QByteArray ba2 = ba P '\0' + LITERAL; + QCOMPARE(ba2, QByteArray(LITERAL "\0" LITERAL, ba.size()*2+1)); + + const char *mmh = "test\0foo"; + QCOMPARE(QByteArray(ba P mmh P ba), testWith0); + + QByteArray raw = QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN); + QByteArray r = "hello" P raw; + QByteArray r2 = "hello" UTF8_LITERAL; + QCOMPARE(r, r2); + r2 = QByteArray("hello\0") P UTF8_LITERAL; + QCOMPARE(r, r2); + } + + //operator QString += + { + QString str = QString::fromUtf8(UTF8_LITERAL); + str += QLatin1String(LITERAL) P str; + QCOMPARE(str, QString::fromUtf8(UTF8_LITERAL LITERAL UTF8_LITERAL)); +#ifndef QT_NO_CAST_FROM_ASCII + str = (QString::fromUtf8(UTF8_LITERAL) += QLatin1String(LITERAL) P UTF8_LITERAL); + QCOMPARE(str, QString::fromUtf8(UTF8_LITERAL LITERAL UTF8_LITERAL)); +#endif + } + + //operator QByteArray += + { + QByteArray ba = UTF8_LITERAL; + ba += QByteArray(LITERAL) P UTF8_LITERAL; + QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL)); + ba += LITERAL P QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN); + QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL LITERAL UTF8_LITERAL)); + QByteArray withZero = QByteArray(LITERAL "\0" LITERAL, LITERAL_LEN*2+1); + QByteArray ba2 = withZero; + ba2 += ba2 P withZero; + QCOMPARE(ba2, QByteArray(withZero + withZero + withZero)); +#ifndef QT_NO_CAST_TO_ASCII + ba = UTF8_LITERAL; + ba2 = (ba += QLatin1String(LITERAL) + QString::fromUtf8(UTF8_LITERAL)); + QCOMPARE(ba2, ba); + QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL)); +#endif + } + } diff --git a/tests/auto/qstringlist/tst_qstringlist.cpp b/tests/auto/qstringlist/tst_qstringlist.cpp index 283c17f..d8db00a 100644 --- a/tests/auto/qstringlist/tst_qstringlist.cpp +++ b/tests/auto/qstringlist/tst_qstringlist.cpp @@ -78,6 +78,8 @@ private slots: void join() const; void join_data() const; void joinEmptiness() const; + + void initializeList() const; }; extern const char email[]; @@ -321,5 +323,16 @@ void tst_QStringList::joinEmptiness() const QVERIFY(string.isNull()); } +void tst_QStringList::initializeList() const +{ +#ifdef Q_COMPILER_INITIALIZER_LISTS + QStringList v1{QLatin1String("hello"),"world",QString::fromLatin1("plop")}; + QCOMPARE(v1, (QStringList() << "hello" << "world" << "plop")); + QCOMPARE(v1, (QStringList{"hello","world","plop"})); +#else + QSKIP("Require C++0x support, pass the right flag to the compiler", SkipAll); +#endif +} + QTEST_APPLESS_MAIN(tst_QStringList) #include "tst_qstringlist.moc" diff --git a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp index f89e033..b6b0d3c 100644 --- a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp +++ b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp @@ -75,6 +75,10 @@ public: public slots: void init(); void cleanup(); + + void initTestCase(); + void cleanupTestCase(); + private slots: void construction(); void fileTemplate(); @@ -97,9 +101,24 @@ private slots: void setTemplateAfterOpen(); void autoRemoveAfterFailedRename(); + void QTBUG_4796_data(); + void QTBUG_4796(); + public: }; +void tst_QTemporaryFile::initTestCase() +{ + // For QTBUG_4796 + QVERIFY(QDir("test-XXXXXX").exists() || QDir().mkdir("test-XXXXXX")); +} + +void tst_QTemporaryFile::cleanupTestCase() +{ + // From QTBUG_4796 + QVERIFY(QDir().rmdir("test-XXXXXX")); +} + void tst_QTemporaryFile::construction() { QTemporaryFile file(0); @@ -144,26 +163,35 @@ void tst_QTemporaryFile::cleanup() void tst_QTemporaryFile::fileTemplate_data() { QTest::addColumn<QString>("constructorTemplate"); + QTest::addColumn<QString>("prefix"); QTest::addColumn<QString>("suffix"); QTest::addColumn<QString>("fileTemplate"); - QTest::newRow("constructor default") << "" << "" << ""; - QTest::newRow("constructor with xxx sufix") << "qt_XXXXXXxxx" << "xxx" << ""; - QTest::newRow("constructor with xXx sufix") << "qt_XXXXXXxXx" << "xXx" << ""; - QTest::newRow("constructor with no sufix") << "qt_XXXXXX" << "" << ""; - QTest::newRow("constructor with >6 X's and xxx suffix") << "qt_XXXXXXXXXXxxx" << "xxx" << ""; - QTest::newRow("constructor with >6 X's, no suffix") << "qt_XXXXXXXXXX" << "" << ""; - - QTest::newRow("set template, no suffix") << "" << "" << "foo"; - QTest::newRow("set template, with lowercase XXXXXX") << "" << "xxxxxx" << "qt_XXXXXXxxxxxx"; - QTest::newRow("set template, with xxx") << "" << ".xxx" << "qt_XXXXXX.xxx"; - QTest::newRow("set template, with >6 X's") << "" << ".xxx" << "qt_XXXXXXXXXXXXXX.xxx"; - QTest::newRow("set template, with >6 X's, no suffix") << "" << "" << "qt_XXXXXXXXXXXXXX"; + QTest::newRow("constructor default") << "" << "." << "" << ""; + QTest::newRow("constructor with xxx sufix") << "qt_XXXXXXxxx" << "qt_" << "xxx" << ""; + QTest::newRow("constructor with xXx sufix") << "qt_XXXXXXxXx" << "qt_" << "xXx" << ""; + QTest::newRow("constructor with no sufix") << "qt_XXXXXX" << "qt_" << "" << ""; + QTest::newRow("constructor with >6 X's and xxx suffix") << "qt_XXXXXXXXXXxxx" << "qt_" << "xxx" << ""; + QTest::newRow("constructor with >6 X's, no suffix") << "qt_XXXXXXXXXX" << "qt_" << "" << ""; + + QTest::newRow("constructor with XXXX suffix") << "qt_XXXXXX_XXXX" << "qt_" << "_XXXX" << ""; + QTest::newRow("constructor with XXXXX suffix") << "qt_XXXXXX_XXXXX" << "qt_" << "_XXXXX" << ""; + QTest::newRow("constructor with XXXX prefix") << "qt_XXXX" << "qt_XXXX." << "" << ""; + QTest::newRow("constructor with XXXXX prefix") << "qt_XXXXX" << "qt_XXXXX." << "" << ""; + QTest::newRow("constructor with XXXX prefix and suffix") << "qt_XXXX_XXXXXX_XXXX" << "qt_XXXX_" << "_XXXX" << ""; + QTest::newRow("constructor with XXXXX prefix and suffix") << "qt_XXXXX_XXXXXX_XXXXX" << "qt_XXXXX_" << "_XXXXX" << ""; + + QTest::newRow("set template, no suffix") << "" << "foo" << "" << "foo"; + QTest::newRow("set template, with lowercase XXXXXX") << "" << "qt_" << "xxxxxx" << "qt_XXXXXXxxxxxx"; + QTest::newRow("set template, with xxx") << "" << "qt_" << ".xxx" << "qt_XXXXXX.xxx"; + QTest::newRow("set template, with >6 X's") << "" << "qt_" << ".xxx" << "qt_XXXXXXXXXXXXXX.xxx"; + QTest::newRow("set template, with >6 X's, no suffix") << "" << "qt_" << "" << "qt_XXXXXXXXXXXXXX"; } void tst_QTemporaryFile::fileTemplate() { QFETCH(QString, constructorTemplate); + QFETCH(QString, prefix); QFETCH(QString, suffix); QFETCH(QString, fileTemplate); @@ -173,8 +201,11 @@ void tst_QTemporaryFile::fileTemplate() QCOMPARE(file.open(), true); - QCOMPARE(file.fileName().right(suffix.length()), suffix); - file.close(); + if (prefix.length()) + QCOMPARE(file.fileName().left(prefix.length()), prefix); + + if (suffix.length()) + QCOMPARE(file.fileName().right(suffix.length()), suffix); } @@ -359,10 +390,7 @@ void tst_QTemporaryFile::stressTest() for (int i = 0; i < iterations; ++i) { QTemporaryFile file; file.setAutoRemove(false); - if (!file.open()) { - qDebug() << "Could not open File:" << file.fileName(); - continue; - } + QVERIFY2(file.open(), qPrintable(file.errorString())); QVERIFY(!names.contains(file.fileName())); names.insert(file.fileName()); } @@ -594,5 +622,108 @@ void tst_QTemporaryFile::autoRemoveAfterFailedRename() cleaner.reset(); } +void tst_QTemporaryFile::QTBUG_4796_data() +{ + QTest::addColumn<QString>("prefix"); + QTest::addColumn<QString>("suffix"); + QTest::addColumn<bool>("openResult"); + + QString unicode = QString::fromUtf8("\xc3\xa5\xc3\xa6\xc3\xb8"); + + QTest::newRow("<empty>") << QString() << QString() << true; + QTest::newRow("blaXXXXXX") << QString("bla") << QString() << true; + QTest::newRow("XXXXXXbla") << QString() << QString("bla") << true; + QTest::newRow("does-not-exist/qt_temp.XXXXXX") << QString("does-not-exist/qt_temp") << QString() << false; + QTest::newRow("XXXXXX<unicode>") << QString() << unicode << true; + QTest::newRow("<unicode>XXXXXX") << unicode << QString() << true; + QTest::newRow("<unicode>XXXXXX<unicode>") << unicode << unicode << true; +} + +void tst_QTemporaryFile::QTBUG_4796() +{ + QVERIFY(QDir("test-XXXXXX").exists()); + + struct CleanOnReturn + { + ~CleanOnReturn() + { + Q_FOREACH(QString tempName, tempNames) + QFile::remove(tempName); + } + + void reset() + { + tempNames.clear(); + } + + QStringList tempNames; + }; + + CleanOnReturn cleaner; + + QFETCH(QString, prefix); + QFETCH(QString, suffix); + QFETCH(bool, openResult); + + { + QString fileTemplate1 = prefix + QString("XX") + suffix; + QString fileTemplate2 = prefix + QString("XXXX") + suffix; + QString fileTemplate3 = prefix + QString("XXXXXX") + suffix; + QString fileTemplate4 = prefix + QString("XXXXXXXX") + suffix; + + QTemporaryFile file1(fileTemplate1); + QTemporaryFile file2(fileTemplate2); + QTemporaryFile file3(fileTemplate3); + QTemporaryFile file4(fileTemplate4); + QTemporaryFile file5("test-XXXXXX/" + fileTemplate1); + QTemporaryFile file6("test-XXXXXX/" + fileTemplate3); + + QCOMPARE(file1.open(), openResult); + QCOMPARE(file2.open(), openResult); + QCOMPARE(file3.open(), openResult); + QCOMPARE(file4.open(), openResult); + QCOMPARE(file5.open(), openResult); + QCOMPARE(file6.open(), openResult); + + QCOMPARE(file1.exists(), openResult); + QCOMPARE(file2.exists(), openResult); + QCOMPARE(file3.exists(), openResult); + QCOMPARE(file4.exists(), openResult); + QCOMPARE(file5.exists(), openResult); + QCOMPARE(file6.exists(), openResult); + + // make sure the file exists under the *correct* name + if (openResult) { + cleaner.tempNames << file1.fileName() + << file2.fileName() + << file3.fileName() + << file4.fileName() + << file5.fileName() + << file6.fileName(); + + QVERIFY(file1.fileName().startsWith(fileTemplate1 + QLatin1Char('.'))); + QVERIFY(file2.fileName().startsWith(fileTemplate2 + QLatin1Char('.'))); + QVERIFY(file5.fileName().startsWith("test-XXXXXX/" + fileTemplate1 + QLatin1Char('.'))); + QVERIFY(file6.fileName().startsWith("test-XXXXXX/" + prefix)); + + if (!prefix.isEmpty()) { + QVERIFY(file3.fileName().startsWith(prefix)); + QVERIFY(file4.fileName().startsWith(prefix)); + } + + if (!suffix.isEmpty()) { + QVERIFY(file3.fileName().endsWith(suffix)); + QVERIFY(file4.fileName().endsWith(suffix)); + QVERIFY(file6.fileName().endsWith(suffix)); + } + } + } + + Q_FOREACH(QString const &tempName, cleaner.tempNames) + QVERIFY( !QFile::exists(tempName) ); + + cleaner.reset(); +} + QTEST_MAIN(tst_QTemporaryFile) #include "tst_qtemporaryfile.moc" diff --git a/tests/auto/qthread/tst_qthread.cpp b/tests/auto/qthread/tst_qthread.cpp index 7386d9d..6ad0678 100644 --- a/tests/auto/qthread/tst_qthread.cpp +++ b/tests/auto/qthread/tst_qthread.cpp @@ -103,6 +103,7 @@ private slots: void adoptedThreadExit(); void adoptedThreadExec(); void adoptedThreadFinished(); + void adoptedThreadExecFinished(); void adoptMultipleThreads(); void adoptMultipleThreadsOverlap(); @@ -913,6 +914,21 @@ void tst_QThread::adoptedThreadFinished() QVERIFY(!QTestEventLoop::instance().timeout()); } +void tst_QThread::adoptedThreadExecFinished() +{ + NativeThreadWrapper nativeThread; + nativeThread.setWaitForStop(); + nativeThread.startAndWait(adoptedThreadExecFunction); + + QObject::connect(nativeThread.qthread, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); + + nativeThread.stop(); + nativeThread.join(); + + QTestEventLoop::instance().enterLoop(5); + QVERIFY(!QTestEventLoop::instance().timeout()); +} + void tst_QThread::adoptMultipleThreads() { #if defined(Q_OS_WIN) diff --git a/tests/auto/qvariant/tst_qvariant.cpp b/tests/auto/qvariant/tst_qvariant.cpp index 62babdb..6ebe84e 100644 --- a/tests/auto/qvariant/tst_qvariant.cpp +++ b/tests/auto/qvariant/tst_qvariant.cpp @@ -275,6 +275,8 @@ private slots: void variantInVariant(); void colorInteger(); + + void forwardDeclare(); }; Q_DECLARE_METATYPE(QDate) @@ -2660,7 +2662,10 @@ void tst_QVariant::qvariant_cast_QObject_data() { QTest::addColumn<QVariant>("data"); QTest::addColumn<bool>("success"); - QTest::newRow("from QObject") << QVariant(QMetaType::QObjectStar, new QObject(this)) << true; + QObject *obj = new QObject(this); + obj->setObjectName(QString::fromLatin1("Hello")); + QTest::newRow("from QObject") << QVariant(QMetaType::QObjectStar, &obj) << true; + QTest::newRow("from QObject2") << QVariant::fromValue(obj) << true; QTest::newRow("from String") << QVariant(QLatin1String("1, 2, 3")) << false; QTest::newRow("from int") << QVariant((int) 123) << false; } @@ -2672,6 +2677,9 @@ void tst_QVariant::qvariant_cast_QObject() { QObject *o = qvariant_cast<QObject *>(data); QCOMPARE(o != 0, success); + if (success) { + QCOMPARE(o->objectName(), QString::fromLatin1("Hello")); + } } Q_DECLARE_METATYPE(qint8); @@ -3433,5 +3441,16 @@ void tst_QVariant::colorInteger() QCOMPARE(v.value<QColor>(), QColor(Qt::yellow)); } +class Forward; +Q_DECLARE_METATYPE(Forward*); + +void tst_QVariant::forwardDeclare() +{ + Forward *f = 0; + QVariant v = QVariant::fromValue(f); + QCOMPARE(qvariant_cast<Forward*>(v), f); +} + + QTEST_MAIN(tst_QVariant) #include "tst_qvariant.moc" diff --git a/tests/benchmarks/network/access/access.pro b/tests/benchmarks/network/access/access.pro index 43357e2..6cbd367 100644 --- a/tests/benchmarks/network/access/access.pro +++ b/tests/benchmarks/network/access/access.pro @@ -1,4 +1,5 @@ TEMPLATE = subdirs SUBDIRS = \ qfile_vs_qnetworkaccessmanager \ - qnetworkreply + qnetworkreply \ + qnetworkdiskcache diff --git a/tests/benchmarks/network/access/qnetworkdiskcache/qnetworkdiskcache.pro b/tests/benchmarks/network/access/qnetworkdiskcache/qnetworkdiskcache.pro new file mode 100644 index 0000000..7f665b3 --- /dev/null +++ b/tests/benchmarks/network/access/qnetworkdiskcache/qnetworkdiskcache.pro @@ -0,0 +1,15 @@ +load(qttest_p4) +TEMPLATE = app +TARGET = tst_bench_qnetworkdiskcache +DEPENDPATH += . +INCLUDEPATH += . + +QT += gui # for QDesktopServices +QT += network testlib + +CONFIG += release + +# Input +SOURCES += tst_qnetworkdiskcache.cpp + + diff --git a/tests/benchmarks/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp b/tests/benchmarks/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp new file mode 100644 index 0000000..55cbf55 --- /dev/null +++ b/tests/benchmarks/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp @@ -0,0 +1,435 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QNetworkDiskCache> +#include <QNetworkCacheMetaData> +#include <QDir> +#include <QBuffer> +#include <QTextStream> +#include <QDebug> +#include <QtTest/QtTest> +#include <QIODevice> +#include <QDesktopServices> + + + +enum Numbers { NumFakeCacheObjects = 200, //entries in pre-populated cache + NumInsertions = 100, //insertions to be timed + NumRemovals = 100, //removals to be timed + NumReadContent = 100, //meta requests to be timed + HugeCacheLimit = 50*1024*1024, // max size for a big cache + TinyCacheLimit = 1*512*1024}; // max size for a tiny cache + +const QString fakeURLbase = "http://127.0.0.1/fake/"; +//fake HTTP body aka payload +const QByteArray payload("Qt rocks!"); + +class tst_qnetworkdiskcache : public QObject +{ + Q_OBJECT +private: + void injectFakeData(); + void insertOneItem(); + bool isUrlCached(quint32 id); + void cleanRecursive(QString &path); + void cleanupCacheObject(); + void initCacheObject(); + QString cacheDir; + QNetworkDiskCache *cache; + +public slots: + void initTestCase(); + void cleanupTestCase(); + +private slots: + + void timeInsertion_data(); + void timeInsertion(); + void timeRead_data(); + void timeRead(); + void timeRemoval_data(); + void timeRemoval(); + + void timeExpiration_data(); + void timeExpiration(); +}; + + +void tst_qnetworkdiskcache::initTestCase() +{ + cache = 0; +} + + +void tst_qnetworkdiskcache::cleanupTestCase() +{ + cleanupCacheObject(); + cleanRecursive(cacheDir); +} + +void tst_qnetworkdiskcache::timeInsertion_data() +{ + QTest::addColumn<QString>("cacheRootDirectory"); + + QString cacheLoc = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); + QTest::newRow("QDesktopServices Cache Location") << cacheLoc; +#ifdef Q_OS_SYMBIAN + if (QDir::drives().contains(QFileInfo("E:\\"))) + QTest::newRow("Symbian E: drive") << cacheLoc.replace(0, 1, QString("E")); +#endif + +} + +//This functions times an insert() operation. +//You can run it after populating the cache with +//fake data so that more realistic performance +//estimates are obtained. +void tst_qnetworkdiskcache::timeInsertion() +{ + + QFETCH(QString, cacheRootDirectory); + + cacheDir = QString( cacheRootDirectory + QDir::separator() + "man_qndc"); + QDir d; + qDebug() << "Setting cache directory to = " << d.absoluteFilePath(cacheDir); + + //Housekeeping + cleanRecursive(cacheDir); // slow op. + initCacheObject(); + + cache->setCacheDirectory(cacheDir); + cache->setMaximumCacheSize(qint64(HugeCacheLimit)); + cache->clear(); + + //populate some fake data to simulate partially full cache + injectFakeData(); // SLOW + + //Sanity-check that the first URL that we insert below isn't already in there. + QVERIFY(isUrlCached(NumFakeCacheObjects) == false); + + // IMPORTANT: max cache size should be HugeCacheLimit, to avoid evictions below + //time insertion of previously-uncached URLs. + QBENCHMARK_ONCE { + for (quint32 i = NumFakeCacheObjects; i < (NumFakeCacheObjects + NumInsertions); i++) { + //prepare metata for url + QNetworkCacheMetaData meta; + QString fakeURL; + QTextStream stream(&fakeURL); + stream << fakeURLbase << i; + QUrl url(fakeURL); + meta.setUrl(url); + meta.setSaveToDisk(true); + + //commit payload and metadata to disk + QIODevice *device = cache->prepare(meta); + device->write(payload); + cache->insert(device); + } + } + + //SLOW cleanup + cleanupCacheObject(); + cleanRecursive(cacheDir); + +} + +void tst_qnetworkdiskcache::timeRead_data() +{ + QTest::addColumn<QString>("cacheRootDirectory"); + + QString cacheLoc = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); + QTest::newRow("QDesktopServices Cache Location") << cacheLoc; +#ifdef Q_OS_SYMBIAN + if (QDir::drives().contains(QFileInfo("E:\\"))) + QTest::newRow("Symbian E: drive") << cacheLoc.replace(0, 1, QString("E")); +#endif + +} + +//Times metadata as well payload lookup +// i.e metaData(), rawHeaders() and data() +void tst_qnetworkdiskcache::timeRead() +{ + + QFETCH(QString, cacheRootDirectory); + + cacheDir = QString( cacheRootDirectory + QDir::separator() + "man_qndc"); + QDir d; + qDebug() << "Setting cache directory to = " << d.absoluteFilePath(cacheDir); + + //Housekeeping + cleanRecursive(cacheDir); // slow op. + initCacheObject(); + cache->setCacheDirectory(cacheDir); + cache->setMaximumCacheSize(qint64(HugeCacheLimit)); + cache->clear(); + + //populate some fake data to simulate partially full cache + injectFakeData(); + + //Entries in the cache should be > what we try to remove + QVERIFY(NumFakeCacheObjects > NumReadContent); + + //time metadata lookup of previously inserted URL. + QBENCHMARK_ONCE { + for (quint32 i = 0; i < NumReadContent; i++) { + QString fakeURL; + QTextStream stream(&fakeURL); + stream << fakeURLbase << i; + QUrl url(fakeURL); + + QNetworkCacheMetaData qndc = cache->metaData(url); + QVERIFY(qndc.isValid()); // we must have read the metadata + + QNetworkCacheMetaData::RawHeaderList raw(qndc.rawHeaders()); + QVERIFY(raw.size()); // we must have parsed the headers from the meta + + QIODevice *iodevice(cache->data(url)); + QVERIFY(iodevice); //must not be NULL + iodevice->close(); + delete iodevice; + } + } + + //Cleanup (slow) + cleanupCacheObject(); + cleanRecursive(cacheDir); + +} + +void tst_qnetworkdiskcache::timeRemoval_data() +{ + QTest::addColumn<QString>("cacheRootDirectory"); + + QString cacheLoc = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); + QTest::newRow("QDesktopServices Cache Location") << cacheLoc; +#ifdef Q_OS_SYMBIAN + if (QDir::drives().contains(QFileInfo("E:\\"))) + QTest::newRow("Symbian E: drive") << cacheLoc.replace(0, 1, QString("E")); +#endif + +} + +void tst_qnetworkdiskcache::timeRemoval() +{ + + QFETCH(QString, cacheRootDirectory); + + cacheDir = QString( cacheRootDirectory + QDir::separator() + "man_qndc"); + QDir d; + qDebug() << "Setting cache directory to = " << d.absoluteFilePath(cacheDir); + + //Housekeeping + initCacheObject(); + cleanRecursive(cacheDir); // slow op. + cache->setCacheDirectory(cacheDir); + // Make max cache size HUGE, so that evictions don't happen below + cache->setMaximumCacheSize(qint64(HugeCacheLimit)); + cache->clear(); + + //populate some fake data to simulate partially full cache + injectFakeData(); + + //Sanity-check that the URL is already in there somewhere + QVERIFY(isUrlCached(NumRemovals-1) == true); + //Entries in the cache should be > what we try to remove + QVERIFY(NumFakeCacheObjects > NumRemovals); + + //time removal of previously-inserted URL. + QBENCHMARK_ONCE { + for (quint32 i = 0; i < NumRemovals; i++) { + QString fakeURL; + QTextStream stream(&fakeURL); + stream << fakeURLbase << i; + QUrl url(fakeURL); + cache->remove(url); + } + } + + //Cleanup (slow) + cleanupCacheObject(); + cleanRecursive(cacheDir); + +} + +void tst_qnetworkdiskcache::timeExpiration_data() +{ + QTest::addColumn<QString>("cacheRootDirectory"); + + QString cacheLoc = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); + QTest::newRow("QDesktopServices Cache Location") << cacheLoc; +#ifdef Q_OS_SYMBIAN + if (QDir::drives().contains(QFileInfo("E:\\"))) + QTest::newRow("Symbian E: drive") << cacheLoc.replace(0, 1, QString("E")); +#endif + +} +void tst_qnetworkdiskcache::timeExpiration() +{ + + QFETCH(QString, cacheRootDirectory); + + cacheDir = QString( cacheRootDirectory + QDir::separator() + "man_qndc"); + QDir d; + qDebug() << "Setting cache directory to = " << d.absoluteFilePath(cacheDir); + + //Housekeeping + initCacheObject(); + cleanRecursive(cacheDir); // slow op. + cache->setCacheDirectory(cacheDir); + // Make max cache size HUGE, so that evictions don't happen below + cache->setMaximumCacheSize(qint64(HugeCacheLimit)); + cache->clear(); + + //populate some fake data to simulate partially full cache + injectFakeData(); + + //Sanity-check that the URL is already in there somewhere + QVERIFY(isUrlCached(NumRemovals-1) == true); + //Entries in the cache should be > what we try to remove + QVERIFY(NumFakeCacheObjects > NumRemovals); + + + //Set cache limit lower, so this force 1 round of eviction + cache->setMaximumCacheSize(qint64(TinyCacheLimit)); + + //time insertions of additional content, which is likely to internally cause evictions + QBENCHMARK_ONCE { + for (quint32 i = NumFakeCacheObjects; i < (NumFakeCacheObjects + NumInsertions); i++) { + //prepare metata for url + QNetworkCacheMetaData meta; + QString fakeURL; + QTextStream stream(&fakeURL); + stream << fakeURLbase << i;//codescanner::leave + QUrl url(fakeURL); + meta.setUrl(url); + meta.setSaveToDisk(true); + + //commit payload and metadata to disk + QIODevice *device = cache->prepare(meta); + device->write(payload); + cache->insert(device); // this should trigger evictions, if TinyCacheLimit is small enough + } + } + + //Cleanup (slow) + cleanupCacheObject(); + cleanRecursive(cacheDir); + +} +// This function simulates a partially or fully occupied disk cache +// like a normal user of a cache might encounter is real-life browsing. +// The point of this is to trigger degradation in file-system and media performance +// that occur due to the quantity and layout of data. +void tst_qnetworkdiskcache::injectFakeData() +{ + + QNetworkCacheMetaData::RawHeaderList headers; + headers.append(qMakePair(QByteArray("X-TestHeader"),QByteArray("HeaderValue"))); + + + //Prep cache dir with fake data using QNetworkDiskCache APIs + for (quint32 i = 0; i < NumFakeCacheObjects; i++) { + + //prepare metata for url + QNetworkCacheMetaData meta; + QString fakeURL; + QTextStream stream(&fakeURL); + stream << fakeURLbase << i; + QUrl url(fakeURL); + meta.setUrl(url); + meta.setRawHeaders(headers); + meta.setSaveToDisk(true); + + //commit payload and metadata to disk + QIODevice *device = cache->prepare(meta); + device->write(payload); + cache->insert(device); + } + +} + + +// Checks if the fake URL #id is already cached or not. +bool tst_qnetworkdiskcache::isUrlCached(quint32 id) +{ + QString str; + QTextStream stream(&str); + stream << fakeURLbase << id; + QUrl url(str); + QIODevice *iod = cache->data(url); + return ((iod == 0) ? false : true) ; + +} + + +// Utility function for recursive directory cleanup. +void tst_qnetworkdiskcache::cleanRecursive(QString &path) +{ + QDirIterator it(path, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); + while (it.hasNext()) { + QFile f(it.next()); + bool err = f.remove(); + Q_UNUSED(err); + } + + QDirIterator it2(path, QDir::AllDirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); + while (it2.hasNext()) { + QString s(it2.next()); + QDir dir(s); + dir.rmdir(s); + } +} + +void tst_qnetworkdiskcache::cleanupCacheObject() +{ + delete cache; + cache = 0; +} + +void tst_qnetworkdiskcache::initCacheObject() +{ + + cache = new QNetworkDiskCache(); + +} +QTEST_MAIN(tst_qnetworkdiskcache) +#include "tst_qnetworkdiskcache.moc" diff --git a/tests/manual/qlocale/calendar.cpp b/tests/manual/qlocale/calendar.cpp new file mode 100644 index 0000000..bd4756e --- /dev/null +++ b/tests/manual/qlocale/calendar.cpp @@ -0,0 +1,405 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtGui> + +#include "calendar.h" + +CalendarWidget::CalendarWidget() +{ + createPreviewGroupBox(); + createGeneralOptionsGroupBox(); + createDatesGroupBox(); + createTextFormatsGroupBox(); + + QGridLayout *layout = new QGridLayout; + layout->addWidget(previewGroupBox, 0, 0); + layout->addWidget(generalOptionsGroupBox, 0, 1); + layout->addWidget(datesGroupBox, 1, 0); + layout->addWidget(textFormatsGroupBox, 1, 1); + layout->setSizeConstraint(QLayout::SetFixedSize); + setLayout(layout); + + previewLayout->setRowMinimumHeight(0, calendar->sizeHint().height()); + previewLayout->setColumnMinimumWidth(0, calendar->sizeHint().width()); + + setWindowTitle(tr("Calendar Widget")); +} + +void CalendarWidget::localeChanged(QLocale locale) +{ + calendar->setLocale(locale); + firstDayCombo->setCurrentIndex(locale.firstDayOfWeek()-1); + updateWeekendDays(); +} + +void CalendarWidget::firstDayChanged(int index) +{ + calendar->setFirstDayOfWeek(Qt::DayOfWeek( + firstDayCombo->itemData(index).toInt())); +} + +void CalendarWidget::selectionModeChanged(int index) +{ + calendar->setSelectionMode(QCalendarWidget::SelectionMode( + selectionModeCombo->itemData(index).toInt())); +} + +void CalendarWidget::horizontalHeaderChanged(int index) +{ + calendar->setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat( + horizontalHeaderCombo->itemData(index).toInt())); +} + +void CalendarWidget::verticalHeaderChanged(int index) +{ + calendar->setVerticalHeaderFormat(QCalendarWidget::VerticalHeaderFormat( + verticalHeaderCombo->itemData(index).toInt())); +} + +void CalendarWidget::selectedDateChanged() +{ + currentDateEdit->setDate(calendar->selectedDate()); +} + +void CalendarWidget::minimumDateChanged(const QDate &date) +{ + calendar->setMinimumDate(date); + maximumDateEdit->setDate(calendar->maximumDate()); +} + +void CalendarWidget::maximumDateChanged(const QDate &date) +{ + calendar->setMaximumDate(date); + minimumDateEdit->setDate(calendar->minimumDate()); +} + +bool CalendarWidget::isWeekendDay(Qt::DayOfWeek day) { + QList<Qt::DayOfWeek> week = calendar->locale().weekdays(); + return !week.contains(day); +} + +void CalendarWidget::updateWeekendDays() { + QTextCharFormat weekFormat, weekendFormat; + weekFormat.setForeground(qvariant_cast<QColor>( + weekdayColorCombo->itemData(weekdayColorCombo->currentIndex()))); + weekendFormat.setForeground(qvariant_cast<QColor>( + weekendColorCombo->itemData(weekendColorCombo->currentIndex()))); + + calendar->setWeekdayTextFormat(Qt::Monday, isWeekendDay(Qt::Monday) ? weekendFormat : weekFormat); + calendar->setWeekdayTextFormat(Qt::Tuesday, isWeekendDay(Qt::Tuesday) ? weekendFormat : weekFormat); + calendar->setWeekdayTextFormat(Qt::Wednesday, isWeekendDay(Qt::Wednesday) ? weekendFormat : weekFormat); + calendar->setWeekdayTextFormat(Qt::Thursday, isWeekendDay(Qt::Thursday) ? weekendFormat : weekFormat); + calendar->setWeekdayTextFormat(Qt::Friday, isWeekendDay(Qt::Friday) ? weekendFormat : weekFormat); + calendar->setWeekdayTextFormat(Qt::Saturday, isWeekendDay(Qt::Saturday) ? weekendFormat : weekFormat); + calendar->setWeekdayTextFormat(Qt::Sunday, isWeekendDay(Qt::Sunday) ? weekendFormat : weekFormat); +} + +void CalendarWidget::weekdayFormatChanged() +{ + updateWeekendDays(); +} + +void CalendarWidget::weekendFormatChanged() +{ + updateWeekendDays(); +} + +void CalendarWidget::reformatHeaders() +{ + QString text = headerTextFormatCombo->currentText(); + QTextCharFormat format; + + if (text == tr("Bold")) { + format.setFontWeight(QFont::Bold); + } else if (text == tr("Italic")) { + format.setFontItalic(true); + } else if (text == tr("Green")) { + format.setForeground(Qt::green); + } + calendar->setHeaderTextFormat(format); +} + +void CalendarWidget::reformatCalendarPage() +{ + if (firstFridayCheckBox->isChecked()) { + QDate firstFriday(calendar->yearShown(), calendar->monthShown(), 1); + while (firstFriday.dayOfWeek() != Qt::Friday) + firstFriday = firstFriday.addDays(1); + QTextCharFormat firstFridayFormat; + firstFridayFormat.setForeground(Qt::blue); + calendar->setDateTextFormat(firstFriday, firstFridayFormat); + } + + //May First in Red takes precedence + if (mayFirstCheckBox->isChecked()) { + const QDate mayFirst(calendar->yearShown(), 5, 1); + QTextCharFormat mayFirstFormat; + mayFirstFormat.setForeground(Qt::red); + calendar->setDateTextFormat(mayFirst, mayFirstFormat); + } +} + +void CalendarWidget::createPreviewGroupBox() +{ + previewGroupBox = new QGroupBox(tr("Preview")); + + calendar = new QCalendarWidget; + calendar->setMinimumDate(QDate(1900, 1, 1)); + calendar->setMaximumDate(QDate(3000, 1, 1)); + calendar->setGridVisible(true); + + connect(calendar, SIGNAL(currentPageChanged(int,int)), + this, SLOT(reformatCalendarPage())); + + previewLayout = new QGridLayout; + previewLayout->addWidget(calendar, 0, 0, Qt::AlignCenter); + previewGroupBox->setLayout(previewLayout); +} + +void CalendarWidget::createGeneralOptionsGroupBox() +{ + generalOptionsGroupBox = new QGroupBox(tr("General Options")); + + firstDayCombo = new QComboBox; + firstDayCombo->addItem(tr("Monday"), Qt::Monday); + firstDayCombo->addItem(tr("Tuesday"), Qt::Tuesday); + firstDayCombo->addItem(tr("Wednesday"), Qt::Wednesday); + firstDayCombo->addItem(tr("Thursday"), Qt::Thursday); + firstDayCombo->addItem(tr("Friday"), Qt::Friday); + firstDayCombo->addItem(tr("Saturday"), Qt::Saturday); + firstDayCombo->addItem(tr("Sunday"), Qt::Sunday); + + firstDayLabel = new QLabel(tr("Wee&k starts on:")); + firstDayLabel->setBuddy(firstDayCombo); + + selectionModeCombo = new QComboBox; + selectionModeCombo->addItem(tr("Single selection"), + QCalendarWidget::SingleSelection); + selectionModeCombo->addItem(tr("None"), QCalendarWidget::NoSelection); + + selectionModeLabel = new QLabel(tr("&Selection mode:")); + selectionModeLabel->setBuddy(selectionModeCombo); + + gridCheckBox = new QCheckBox(tr("&Grid")); + gridCheckBox->setChecked(calendar->isGridVisible()); + + navigationCheckBox = new QCheckBox(tr("&Navigation bar")); + navigationCheckBox->setChecked(true); + + horizontalHeaderCombo = new QComboBox; + horizontalHeaderCombo->addItem(tr("Single letter day names"), + QCalendarWidget::SingleLetterDayNames); + horizontalHeaderCombo->addItem(tr("Short day names"), + QCalendarWidget::ShortDayNames); + horizontalHeaderCombo->addItem(tr("None"), + QCalendarWidget::NoHorizontalHeader); + horizontalHeaderCombo->setCurrentIndex(1); + + horizontalHeaderLabel = new QLabel(tr("&Horizontal header:")); + horizontalHeaderLabel->setBuddy(horizontalHeaderCombo); + + verticalHeaderCombo = new QComboBox; + verticalHeaderCombo->addItem(tr("ISO week numbers"), + QCalendarWidget::ISOWeekNumbers); + verticalHeaderCombo->addItem(tr("None"), QCalendarWidget::NoVerticalHeader); + + verticalHeaderLabel = new QLabel(tr("&Vertical header:")); + verticalHeaderLabel->setBuddy(verticalHeaderCombo); + + connect(firstDayCombo, SIGNAL(currentIndexChanged(int)), + this, SLOT(firstDayChanged(int))); + connect(selectionModeCombo, SIGNAL(currentIndexChanged(int)), + this, SLOT(selectionModeChanged(int))); + connect(gridCheckBox, SIGNAL(toggled(bool)), + calendar, SLOT(setGridVisible(bool))); + connect(navigationCheckBox, SIGNAL(toggled(bool)), + calendar, SLOT(setNavigationBarVisible(bool))); + connect(horizontalHeaderCombo, SIGNAL(currentIndexChanged(int)), + this, SLOT(horizontalHeaderChanged(int))); + connect(verticalHeaderCombo, SIGNAL(currentIndexChanged(int)), + this, SLOT(verticalHeaderChanged(int))); + + QHBoxLayout *checkBoxLayout = new QHBoxLayout; + checkBoxLayout->addWidget(gridCheckBox); + checkBoxLayout->addStretch(); + checkBoxLayout->addWidget(navigationCheckBox); + + QGridLayout *outerLayout = new QGridLayout; + outerLayout->addWidget(firstDayLabel, 0, 0); + outerLayout->addWidget(firstDayCombo, 0, 1); + outerLayout->addWidget(selectionModeLabel, 1, 0); + outerLayout->addWidget(selectionModeCombo, 1, 1); + outerLayout->addLayout(checkBoxLayout, 2, 0, 1, 2); + outerLayout->addWidget(horizontalHeaderLabel, 3, 0); + outerLayout->addWidget(horizontalHeaderCombo, 3, 1); + outerLayout->addWidget(verticalHeaderLabel, 4, 0); + outerLayout->addWidget(verticalHeaderCombo, 4, 1); + generalOptionsGroupBox->setLayout(outerLayout); + + firstDayChanged(firstDayCombo->currentIndex()); + selectionModeChanged(selectionModeCombo->currentIndex()); + horizontalHeaderChanged(horizontalHeaderCombo->currentIndex()); + verticalHeaderChanged(verticalHeaderCombo->currentIndex()); +} + +void CalendarWidget::createDatesGroupBox() +{ + datesGroupBox = new QGroupBox(tr("Dates")); + + minimumDateEdit = new QDateEdit; + minimumDateEdit->setDisplayFormat("MMM d yyyy"); + minimumDateEdit->setDateRange(calendar->minimumDate(), + calendar->maximumDate()); + minimumDateEdit->setDate(calendar->minimumDate()); + + minimumDateLabel = new QLabel(tr("&Minimum Date:")); + minimumDateLabel->setBuddy(minimumDateEdit); + + currentDateEdit = new QDateEdit; + currentDateEdit->setDisplayFormat("MMM d yyyy"); + currentDateEdit->setDate(calendar->selectedDate()); + currentDateEdit->setDateRange(calendar->minimumDate(), + calendar->maximumDate()); + + currentDateLabel = new QLabel(tr("&Current Date:")); + currentDateLabel->setBuddy(currentDateEdit); + + maximumDateEdit = new QDateEdit; + maximumDateEdit->setDisplayFormat("MMM d yyyy"); + maximumDateEdit->setDateRange(calendar->minimumDate(), + calendar->maximumDate()); + maximumDateEdit->setDate(calendar->maximumDate()); + + maximumDateLabel = new QLabel(tr("Ma&ximum Date:")); + maximumDateLabel->setBuddy(maximumDateEdit); + + connect(currentDateEdit, SIGNAL(dateChanged(QDate)), + calendar, SLOT(setSelectedDate(QDate))); + connect(calendar, SIGNAL(selectionChanged()), + this, SLOT(selectedDateChanged())); + connect(minimumDateEdit, SIGNAL(dateChanged(QDate)), + this, SLOT(minimumDateChanged(QDate))); + connect(maximumDateEdit, SIGNAL(dateChanged(QDate)), + this, SLOT(maximumDateChanged(QDate))); + + QGridLayout *dateBoxLayout = new QGridLayout; + dateBoxLayout->addWidget(currentDateLabel, 1, 0); + dateBoxLayout->addWidget(currentDateEdit, 1, 1); + dateBoxLayout->addWidget(minimumDateLabel, 0, 0); + dateBoxLayout->addWidget(minimumDateEdit, 0, 1); + dateBoxLayout->addWidget(maximumDateLabel, 2, 0); + dateBoxLayout->addWidget(maximumDateEdit, 2, 1); + dateBoxLayout->setRowStretch(3, 1); + + datesGroupBox->setLayout(dateBoxLayout); +} + +void CalendarWidget::createTextFormatsGroupBox() +{ + textFormatsGroupBox = new QGroupBox(tr("Text Formats")); + + weekdayColorCombo = createColorComboBox(); + weekdayColorCombo->setCurrentIndex( + weekdayColorCombo->findText(tr("Black"))); + + weekdayColorLabel = new QLabel(tr("&Weekday color:")); + weekdayColorLabel->setBuddy(weekdayColorCombo); + + weekendColorCombo = createColorComboBox(); + weekendColorCombo->setCurrentIndex( + weekendColorCombo->findText(tr("Red"))); + + weekendColorLabel = new QLabel(tr("Week&end color:")); + weekendColorLabel->setBuddy(weekendColorCombo); + + headerTextFormatCombo = new QComboBox; + headerTextFormatCombo->addItem(tr("Bold")); + headerTextFormatCombo->addItem(tr("Italic")); + headerTextFormatCombo->addItem(tr("Plain")); + + headerTextFormatLabel = new QLabel(tr("&Header text:")); + headerTextFormatLabel->setBuddy(headerTextFormatCombo); + + firstFridayCheckBox = new QCheckBox(tr("&First Friday in blue")); + + mayFirstCheckBox = new QCheckBox(tr("May &1 in red")); + + connect(weekdayColorCombo, SIGNAL(currentIndexChanged(int)), + this, SLOT(weekdayFormatChanged())); + connect(weekendColorCombo, SIGNAL(currentIndexChanged(int)), + this, SLOT(weekendFormatChanged())); + connect(headerTextFormatCombo, SIGNAL(currentIndexChanged(QString)), + this, SLOT(reformatHeaders())); + connect(firstFridayCheckBox, SIGNAL(toggled(bool)), + this, SLOT(reformatCalendarPage())); + connect(mayFirstCheckBox, SIGNAL(toggled(bool)), + this, SLOT(reformatCalendarPage())); + + QHBoxLayout *checkBoxLayout = new QHBoxLayout; + checkBoxLayout->addWidget(firstFridayCheckBox); + checkBoxLayout->addStretch(); + checkBoxLayout->addWidget(mayFirstCheckBox); + + QGridLayout *outerLayout = new QGridLayout; + outerLayout->addWidget(weekdayColorLabel, 0, 0); + outerLayout->addWidget(weekdayColorCombo, 0, 1); + outerLayout->addWidget(weekendColorLabel, 1, 0); + outerLayout->addWidget(weekendColorCombo, 1, 1); + outerLayout->addWidget(headerTextFormatLabel, 2, 0); + outerLayout->addWidget(headerTextFormatCombo, 2, 1); + outerLayout->addLayout(checkBoxLayout, 3, 0, 1, 2); + textFormatsGroupBox->setLayout(outerLayout); + + weekdayFormatChanged(); + weekendFormatChanged(); + reformatHeaders(); + reformatCalendarPage(); +} + +QComboBox *CalendarWidget::createColorComboBox() +{ + QComboBox *comboBox = new QComboBox; + comboBox->addItem(tr("Red"), Qt::red); + comboBox->addItem(tr("Blue"), Qt::blue); + comboBox->addItem(tr("Black"), Qt::black); + comboBox->addItem(tr("Magenta"), Qt::magenta); + return comboBox; +} diff --git a/tests/manual/qlocale/calendar.h b/tests/manual/qlocale/calendar.h new file mode 100644 index 0000000..b5bb3c9 --- /dev/null +++ b/tests/manual/qlocale/calendar.h @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CALENDAR_H +#define CALENDAR_H + +#include <QtGui> + +class CalendarWidget : public QWidget +{ + Q_OBJECT + +public: + CalendarWidget(); + +private slots: + void localeChanged(QLocale locale); + void firstDayChanged(int index); + void selectionModeChanged(int index); + void horizontalHeaderChanged(int index); + void verticalHeaderChanged(int index); + void selectedDateChanged(); + void minimumDateChanged(const QDate &date); + void maximumDateChanged(const QDate &date); + void updateWeekendDays(); + void weekdayFormatChanged(); + void weekendFormatChanged(); + void reformatHeaders(); + void reformatCalendarPage(); + +private: + bool isWeekendDay(Qt::DayOfWeek); + void createPreviewGroupBox(); + void createGeneralOptionsGroupBox(); + void createDatesGroupBox(); + void createTextFormatsGroupBox(); + QComboBox *createColorComboBox(); + + QGroupBox *previewGroupBox; + QGridLayout *previewLayout; + QCalendarWidget *calendar; + + QGroupBox *generalOptionsGroupBox; + QLabel *localeLabel; + QLabel *firstDayLabel; + + QLabel *selectionModeLabel; + QLabel *horizontalHeaderLabel; + QLabel *verticalHeaderLabel; + QComboBox *localeCombo; + QComboBox *firstDayCombo; + QComboBox *selectionModeCombo; + QCheckBox *gridCheckBox; + QCheckBox *navigationCheckBox; + QComboBox *horizontalHeaderCombo; + QComboBox *verticalHeaderCombo; + + QGroupBox *datesGroupBox; + QLabel *currentDateLabel; + QLabel *minimumDateLabel; + QLabel *maximumDateLabel; + QDateEdit *currentDateEdit; + QDateEdit *minimumDateEdit; + QDateEdit *maximumDateEdit; + + QGroupBox *textFormatsGroupBox; + QLabel *weekdayColorLabel; + QLabel *weekendColorLabel; + QLabel *headerTextFormatLabel; + QComboBox *weekdayColorCombo; + QComboBox *weekendColorCombo; + QComboBox *headerTextFormatCombo; + + QCheckBox *firstFridayCheckBox; + QCheckBox *mayFirstCheckBox; +}; + +#endif diff --git a/tests/manual/qlocale/currency.cpp b/tests/manual/qlocale/currency.cpp new file mode 100644 index 0000000..4ef157c --- /dev/null +++ b/tests/manual/qlocale/currency.cpp @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "currency.h" + +CurrencyWidget::CurrencyWidget() +{ + QGridLayout *l = new QGridLayout; + + currencySymbolLabel = new QLabel("Symbol:"); + currencySymbol = new QLineEdit; + currencyISOLabel = new QLabel("ISO Code:"); + currencyISO = new QLineEdit; + currencyNameLabel = new QLabel("Display name:"); + currencyName = new QLineEdit; + currencyFormattingLabel = new QLabel("Currency formatting:"); + currencyFormattingValue = new QLineEdit(QString::number(1234.56, 'f', 2)); + currencyFormattingSymbolLabel = new QLabel("currency:"); + currencyFormattingSymbol = new QLineEdit; + currencyFormatting = new QLineEdit; + + currencyFormattingValue->setFixedWidth(150); + currencyFormattingSymbol->setFixedWidth(50); + + l->addWidget(currencySymbolLabel, 0, 0); + l->addWidget(currencySymbol, 0, 1, 1, 4); + l->addWidget(currencyISOLabel, 1, 0); + l->addWidget(currencyISO, 1, 1, 1, 4); + l->addWidget(currencyNameLabel, 2, 0); + l->addWidget(currencyName, 2, 1, 1, 4); + l->addWidget(currencyFormattingLabel, 3, 0); + l->addWidget(currencyFormattingValue, 3, 1); + l->addWidget(currencyFormattingSymbolLabel, 3, 2); + l->addWidget(currencyFormattingSymbol, 3, 3); + l->addWidget(currencyFormatting, 3, 4); + + QVBoxLayout *v = new QVBoxLayout(this); + v->addLayout(l); + v->addStretch(); + + connect(currencyFormattingSymbol, SIGNAL(textChanged(QString)), + this, SLOT(updateCurrencyFormatting())); + connect(currencyFormattingValue, SIGNAL(textChanged(QString)), + this, SLOT(updateCurrencyFormatting())); +} + +void CurrencyWidget::updateCurrencyFormatting() +{ + QString result; + bool ok; + QString symbol = currencyFormattingSymbol->text(); + QString value = currencyFormattingValue->text(); + int i = value.toInt(&ok); + if (ok) { + result = locale().toCurrencyString(i, symbol); + } else { + double d = value.toDouble(&ok); + if (ok) + result = locale().toCurrencyString(d, symbol); + } + currencyFormatting->setText(result); +} + +void CurrencyWidget::localeChanged(QLocale locale) +{ + setLocale(locale); + currencySymbol->setText(locale.currencySymbol()); + currencyISO->setText(locale.currencySymbol(QLocale::CurrencyIsoCode)); + currencyName->setText(locale.currencySymbol(QLocale::CurrencyDisplayName)); + updateCurrencyFormatting(); +} + diff --git a/tests/manual/qlocale/currency.h b/tests/manual/qlocale/currency.h new file mode 100644 index 0000000..3a12553 --- /dev/null +++ b/tests/manual/qlocale/currency.h @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CURRENCY_H +#define CURRENCY_H + +#include <QtGui> + +class CurrencyWidget : public QWidget +{ + Q_OBJECT +public: + CurrencyWidget(); + +private: + QLabel *currencySymbolLabel; + QLineEdit *currencySymbol; + QLabel *currencyISOLabel; + QLineEdit *currencyISO; + QLabel *currencyNameLabel; + QLineEdit *currencyName; + QLabel *currencyFormattingLabel; + QLineEdit *currencyFormattingValue; + QLabel *currencyFormattingSymbolLabel; + QLineEdit *currencyFormattingSymbol; + QLineEdit *currencyFormatting; + +private slots: + void localeChanged(QLocale locale); + void updateCurrencyFormatting(); +}; + +#endif diff --git a/tests/manual/qlocale/dateformats.cpp b/tests/manual/qlocale/dateformats.cpp new file mode 100644 index 0000000..25b3e7a --- /dev/null +++ b/tests/manual/qlocale/dateformats.cpp @@ -0,0 +1,179 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "dateformats.h" + +DateFormatsWidget::DateFormatsWidget() +{ + scrollArea = new QScrollArea; + scrollAreaWidget = new QWidget; + scrollArea->setWidget(scrollAreaWidget); + scrollArea->setWidgetResizable(true); + layout = new QGridLayout(scrollAreaWidget); + QVBoxLayout *l = new QVBoxLayout(this); + l->addWidget(scrollArea); + + shortDateFormat = addItem("Date format (short):"); + longDateFormat = addItem("Date format (long):"); + shortTimeFormat = addItem("Time format (short):"); + longTimeFormat = addItem("Time format (long):"); + shortDateTimeFormat = addItem("DateTime format (short):"); + longDateTimeFormat = addItem("DateTime format (long):"); + amText = addItem("Before noon:"); + pmText = addItem("After noon:"); + firstDayOfWeek = addItem("First day of week:"); + + monthNamesShort = new QComboBox; + monthNamesLong = new QComboBox; + standaloneMonthNamesShort = new QComboBox; + standaloneMonthNamesLong = new QComboBox; + dayNamesShort = new QComboBox; + dayNamesLong = new QComboBox; + standaloneDayNamesShort = new QComboBox; + standaloneDayNamesLong = new QComboBox; + + int row = layout->rowCount(); + layout->addWidget(new QLabel("Month names [short/long]:"), row, 0); + layout->addWidget(monthNamesShort, row, 1); + layout->addWidget(monthNamesLong, row, 2); + row = layout->rowCount(); + layout->addWidget(new QLabel("Standalone month names [short/long]:"), row, 0); + layout->addWidget(standaloneMonthNamesShort, row, 1); + layout->addWidget(standaloneMonthNamesLong, row, 2); + row = layout->rowCount(); + layout->addWidget(new QLabel("Day names [short/long]:"), row, 0); + layout->addWidget(dayNamesShort, row, 1); + layout->addWidget(dayNamesLong, row, 2); + row = layout->rowCount(); + layout->addWidget(new QLabel("Standalone day names [short/long]:"), row, 0); + layout->addWidget(standaloneDayNamesShort, row, 1); + layout->addWidget(standaloneDayNamesLong, row, 2); +} + +QString toString(Qt::DayOfWeek dow) +{ + static const char *names[] = { + "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" + }; + return QString::fromLatin1(names[dow-1]); +} + +void DateFormatsWidget::localeChanged(QLocale locale) +{ + setLocale(locale); + QDateTime now = QDateTime::currentDateTime(); + shortDateFormat->setText(locale.toString(now.date(), QLocale::ShortFormat)); + shortDateFormat->setToolTip(locale.dateFormat(QLocale::ShortFormat)); + longDateFormat->setText(locale.toString(now.date(), QLocale::LongFormat)); + longDateFormat->setToolTip(locale.dateFormat(QLocale::LongFormat)); + shortTimeFormat->setText(locale.toString(now.time(), QLocale::ShortFormat)); + shortTimeFormat->setToolTip(locale.timeFormat(QLocale::ShortFormat)); + longTimeFormat->setText(locale.toString(now.time(), QLocale::LongFormat)); + longTimeFormat->setToolTip(locale.timeFormat(QLocale::LongFormat)); + shortDateTimeFormat->setText(locale.toString(now, QLocale::ShortFormat)); + shortDateTimeFormat->setToolTip(locale.dateTimeFormat(QLocale::ShortFormat)); + longDateTimeFormat->setText(locale.toString(now, QLocale::LongFormat)); + longDateTimeFormat->setToolTip(locale.dateTimeFormat(QLocale::LongFormat)); + amText->setText(locale.amText()); + pmText->setText(locale.pmText()); + firstDayOfWeek->setText(toString(locale.firstDayOfWeek())); + + int mns = monthNamesShort->currentIndex(); + int mnl = monthNamesLong->currentIndex(); + int smns = standaloneMonthNamesShort->currentIndex(); + int smnl = standaloneMonthNamesLong->currentIndex(); + int dnl = dayNamesLong->currentIndex(); + int dns = dayNamesShort->currentIndex(); + int sdnl = standaloneDayNamesLong->currentIndex(); + int sdns = standaloneDayNamesShort->currentIndex(); + + monthNamesShort->clear(); + monthNamesLong->clear(); + standaloneMonthNamesShort->clear(); + standaloneMonthNamesLong->clear(); + dayNamesLong->clear(); + dayNamesShort->clear(); + standaloneDayNamesLong->clear(); + standaloneDayNamesShort->clear(); + + for (int i = 1; i <= 12; ++i) + monthNamesShort->addItem(locale.monthName(i, QLocale::ShortFormat)); + monthNamesShort->setCurrentIndex(mns >= 0 ? mns : 0); + for (int i = 1; i <= 12; ++i) + monthNamesLong->addItem(locale.monthName(i, QLocale::LongFormat)); + monthNamesLong->setCurrentIndex(mnl >= 0 ? mnl : 0); + + for (int i = 1; i <= 12; ++i) + standaloneMonthNamesShort->addItem(locale.standaloneMonthName(i, QLocale::ShortFormat)); + standaloneMonthNamesShort->setCurrentIndex(smns >= 0 ? smns : 0); + for (int i = 1; i <= 12; ++i) + standaloneMonthNamesLong->addItem(locale.standaloneMonthName(i, QLocale::LongFormat)); + standaloneMonthNamesLong->setCurrentIndex(smnl >= 0 ? smnl : 0); + + for (int i = 1; i <= 7; ++i) + dayNamesLong->addItem(locale.dayName(i, QLocale::LongFormat)); + dayNamesLong->setCurrentIndex(dnl >= 0 ? dnl : 0); + for (int i = 1; i <= 7; ++i) + dayNamesShort->addItem(locale.dayName(i, QLocale::ShortFormat)); + dayNamesShort->setCurrentIndex(dns >= 0 ? dns : 0); + + for (int i = 1; i <= 7; ++i) + standaloneDayNamesLong->addItem(locale.standaloneDayName(i, QLocale::LongFormat)); + standaloneDayNamesLong->setCurrentIndex(sdnl >= 0 ? sdnl : 0); + for (int i = 1; i <= 7; ++i) + standaloneDayNamesShort->addItem(locale.standaloneDayName(i, QLocale::ShortFormat)); + standaloneDayNamesShort->setCurrentIndex(sdns >= 0 ? sdns : 0); +} + +void DateFormatsWidget::addItem(const QString &label, QWidget *w) +{ + QLabel *lbl = new QLabel(label); + int row = layout->rowCount(); + layout->addWidget(lbl, row, 0); + layout->addWidget(w, row, 1, 1, 2); +} + +QLineEdit *DateFormatsWidget::addItem(const QString &label) +{ + QLineEdit *le = new QLineEdit; + le->setReadOnly(true); + addItem(label, le); + return le; +} diff --git a/tests/manual/qlocale/dateformats.h b/tests/manual/qlocale/dateformats.h new file mode 100644 index 0000000..f05ad2a --- /dev/null +++ b/tests/manual/qlocale/dateformats.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DATEFORMATS_H +#define DATEFORMATS_H + +#include <QtGui> + +class DateFormatsWidget : public QWidget +{ + Q_OBJECT +public: + DateFormatsWidget(); + +private: + void addItem(const QString &label, QWidget *); + QLineEdit *addItem(const QString &label); + + QScrollArea *scrollArea; + QWidget *scrollAreaWidget; + QGridLayout *layout; + + QLineEdit *shortDateFormat; + QLineEdit *longDateFormat; + QLineEdit *shortTimeFormat; + QLineEdit *longTimeFormat; + QLineEdit *shortDateTimeFormat; + QLineEdit *longDateTimeFormat; + QLineEdit *amText; + QLineEdit *pmText; + QLineEdit *firstDayOfWeek; + QComboBox *monthNamesShort, *monthNamesLong; + QComboBox *standaloneMonthNamesShort, *standaloneMonthNamesLong; + QComboBox *dayNamesShort, *dayNamesLong; + QComboBox *standaloneDayNamesShort, *standaloneDayNamesLong; + +private slots: + void localeChanged(QLocale locale); +}; + +#endif diff --git a/tests/manual/qlocale/info.cpp b/tests/manual/qlocale/info.cpp new file mode 100644 index 0000000..a4f6adf --- /dev/null +++ b/tests/manual/qlocale/info.cpp @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "info.h" + +InfoWidget::InfoWidget() +{ + scrollArea = new QScrollArea; + scrollAreaWidget = new QWidget; + scrollArea->setWidget(scrollAreaWidget); + scrollArea->setWidgetResizable(true); + layout = new QGridLayout(); + QVBoxLayout *v = new QVBoxLayout(scrollAreaWidget); + v->addLayout(layout); + v->addStretch(); + + QVBoxLayout *l = new QVBoxLayout(this); + l->addWidget(scrollArea); + + name = addItem("Name:"); + bcp47Name = addItem("Bcp47 name:"); + languageName = addItem("Language name:"); + nativeLanguageName = addItem("Native language name:"); + scriptName = addItem("Script name:"); + countryName = addItem("Country name:"); + nativeCountryName = addItem("Native country name:"); +} + +void InfoWidget::localeChanged(QLocale locale) +{ + setLocale(locale); + name->setText(locale.name()); + bcp47Name->setText(locale.bcp47Name()); + languageName->setText(QLocale::languageToString(locale.language())); + nativeLanguageName->setText(locale.nativeLanguageName()); + scriptName->setText(QLocale::scriptToString(locale.script())); + countryName->setText(QLocale::countryToString(locale.country())); + nativeCountryName->setText(locale.nativeCountryName()); +} + +void InfoWidget::addItem(const QString &label, QWidget *w) +{ + QLabel *lbl = new QLabel(label); + int row = layout->rowCount(); + layout->addWidget(lbl, row, 0); + layout->addWidget(w, row, 1, 1, 2); +} + +QLineEdit *InfoWidget::addItem(const QString &label) +{ + QLineEdit *le = new QLineEdit; + le->setReadOnly(true); + addItem(label, le); + return le; +} diff --git a/tests/manual/qlocale/info.h b/tests/manual/qlocale/info.h new file mode 100644 index 0000000..b23ecf5 --- /dev/null +++ b/tests/manual/qlocale/info.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef INFO_H +#define INFO_H + +#include <QtGui> + +class InfoWidget : public QWidget +{ + Q_OBJECT +public: + InfoWidget(); + +private: + void addItem(const QString &label, QWidget *); + QLineEdit *addItem(const QString &label); + + QScrollArea *scrollArea; + QWidget *scrollAreaWidget; + QGridLayout *layout; + + QLineEdit *name; + QLineEdit *bcp47Name; + QLineEdit *languageName; + QLineEdit *nativeLanguageName; + QLineEdit *scriptName; + QLineEdit *countryName; + QLineEdit *nativeCountryName; + +private slots: + void localeChanged(QLocale locale); +}; + +#endif diff --git a/tests/manual/qlocale/languages.cpp b/tests/manual/qlocale/languages.cpp new file mode 100644 index 0000000..18d72d7 --- /dev/null +++ b/tests/manual/qlocale/languages.cpp @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "languages.h" + +LanguagesWidget::LanguagesWidget() +{ + QVBoxLayout *l = new QVBoxLayout(this); + + languagesLabel = new QLabel("Preferred languages:"); + languagesList = new QListWidget; + + l->addWidget(languagesLabel); + l->addWidget(languagesList); + + localeChanged(QLocale()); +} + +void LanguagesWidget::localeChanged(QLocale locale) +{ + languagesList->clear(); + foreach (const QString &lang, locale.uiLanguages()) { + QListWidgetItem *item = new QListWidgetItem(lang, languagesList); + QLocale l(lang); + if (l.language() != QLocale::C) { + QString language = QLocale::languageToString(l.language()); + QString country = QLocale::countryToString(l.country()); + QString tooltip = QString(QLatin1String("%1: %2/%3")).arg(l.name(), language, country); + item->setToolTip(tooltip); + } + } +} + + diff --git a/tests/manual/qlocale/languages.h b/tests/manual/qlocale/languages.h new file mode 100644 index 0000000..18e503f --- /dev/null +++ b/tests/manual/qlocale/languages.h @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef LANGUAGES_H +#define LANGUAGES_H + +#include <QtGui> + +class LanguagesWidget : public QWidget +{ + Q_OBJECT +public: + LanguagesWidget(); + +private: + QLocale currentLocale; + + QLabel *languagesLabel; + QListWidget *languagesList; + +private slots: + void localeChanged(QLocale locale); +}; + +#endif diff --git a/tests/manual/qlocale/main.cpp b/tests/manual/qlocale/main.cpp new file mode 100644 index 0000000..c85bd19 --- /dev/null +++ b/tests/manual/qlocale/main.cpp @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtGui> + +#include "window.h" + +int main(int argv, char *args[]) +{ + QApplication app(argv, args); + Window window; +#if !defined(Q_OS_SYMBIAN) + window.show(); +#else + window.showFullScreen(); +#endif + return app.exec(); +} diff --git a/tests/manual/qlocale/miscellaneous.cpp b/tests/manual/qlocale/miscellaneous.cpp new file mode 100644 index 0000000..89c80dc --- /dev/null +++ b/tests/manual/qlocale/miscellaneous.cpp @@ -0,0 +1,103 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "miscellaneous.h" + +MiscWidget::MiscWidget() +{ + QGridLayout *l = new QGridLayout; + + createLineEdit("Text to quote:", &textToQuoteLabel, &textToQuote); + createLineEdit("Standard quotes:", &standardQuotedTextLabel, &standardQuotedText); + createLineEdit("Alternate quotes:", &alternateQuotedTextLabel, &alternateQuotedText); + textToQuote->setText("some text"); + createLineEdit("Text direction:", &textDirectionLabel, &textDirection); + createLineEdit("List to separated string:", &listToSeparatedStringLabel, &listToSeparatedStringText); + + l->addWidget(textToQuoteLabel, 0, 0); + l->addWidget(textToQuote, 0, 1); + l->addWidget(standardQuotedTextLabel, 0, 2); + l->addWidget(standardQuotedText, 0, 3); + l->addWidget(alternateQuotedTextLabel, 1, 2); + l->addWidget(alternateQuotedText, 1, 3); + l->addWidget(textDirectionLabel, 2, 0); + l->addWidget(textDirection, 2, 1, 1, 3); + l->addWidget(listToSeparatedStringLabel, 3, 0); + l->addWidget(listToSeparatedStringText, 3, 1, 1, 3); + + connect(textToQuote, SIGNAL(textChanged(QString)), this, SLOT(updateQuotedText(QString))); + + QVBoxLayout *v = new QVBoxLayout(this); + v->addLayout(l); + v->addStretch(); +} + +void MiscWidget::updateQuotedText(QString str) +{ + standardQuotedText->setText(locale().quoteString(str)); + alternateQuotedText->setText(locale().quoteString(str, QLocale::AlternateQuotation)); +} + +void MiscWidget::updateListToSeparatedStringText() +{ + QStringList test; + test << "aaa" << "bbb" << "ccc" << "ddd"; + listToSeparatedStringText->setText(locale().createSeparatedList(test)); +} + +void MiscWidget::localeChanged(QLocale locale) +{ + setLocale(locale); + updateQuotedText(textToQuote->text()); + updateListToSeparatedStringText(); + textDirection->setText(locale.textDirection() == Qt::LeftToRight ? "Left To Right" : "Right To Left"); +} + +void MiscWidget::createLineEdit(const QString &label, QLabel **labelWidget, QLineEdit **lineEditWidget) +{ + QLabel *lbl = new QLabel(label); + QLineEdit *le = new QLineEdit; + le->setReadOnly(true); + lbl->setBuddy(le); + if (labelWidget) + *labelWidget = lbl; + if (lineEditWidget) + *lineEditWidget = le; +} diff --git a/tests/manual/qlocale/miscellaneous.h b/tests/manual/qlocale/miscellaneous.h new file mode 100644 index 0000000..3b635b8 --- /dev/null +++ b/tests/manual/qlocale/miscellaneous.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MISCELLANEOUS_H +#define MISCELLANEOUS_H + +#include <QtGui> + +class MiscWidget : public QWidget +{ + Q_OBJECT +public: + MiscWidget(); + +private: + void createLineEdit(const QString &label, QLabel **labelWidget = 0, QLineEdit **lineEditWidget = 0); + + QLabel *textToQuoteLabel; + QLabel *standardQuotedTextLabel; + QLabel *alternateQuotedTextLabel; + QLabel *textDirectionLabel; + QLabel *listToSeparatedStringLabel; + QLineEdit *textToQuote; + QLineEdit *standardQuotedText; + QLineEdit *alternateQuotedText; + QLineEdit *textDirection; + QLineEdit *listToSeparatedStringText; + +private slots: + void localeChanged(QLocale locale); + void updateQuotedText(QString str); + void updateListToSeparatedStringText(); +}; + +#endif // MISCELLANEOUS_H diff --git a/tests/manual/qlocale/numberformats.cpp b/tests/manual/qlocale/numberformats.cpp new file mode 100644 index 0000000..7b5fce4 --- /dev/null +++ b/tests/manual/qlocale/numberformats.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "numberformats.h" + +NumberFormatsWidget::NumberFormatsWidget() +{ + QGridLayout *l = new QGridLayout; + + QLabel *numbersLabel = new QLabel("Numbers:"); + number1 = createLineEdit(); + number2 = createLineEdit(); + number3 = createLineEdit(); + + measurementLabel = new QLabel("Measurement units:"); + measurementSystem = createLineEdit(); + + l->addWidget(numbersLabel, 0, 0); + l->addWidget(number1, 0, 1); + l->addWidget(number2, 0, 2); + l->addWidget(number3, 0, 3); + + l->addWidget(measurementLabel, 1, 0); + l->addWidget(measurementSystem, 1, 1, 1, 3); + + QVBoxLayout *v = new QVBoxLayout(this); + v->addLayout(l); + v->addStretch(); +} + +void NumberFormatsWidget::localeChanged(QLocale locale) +{ + number1->setText(locale.toString(-123456)); + number2->setText(locale.toString(1234.56, 'f', 2)); + number3->setText(locale.toString(1234.56, 'e', 4)); + + measurementSystem->setText( + locale.measurementSystem() == QLocale::ImperialSystem ? "US" : "Metric"); +} + +QLineEdit *NumberFormatsWidget::createLineEdit() +{ + QLineEdit *le = new QLineEdit; + le->setReadOnly(true); + return le; +} diff --git a/tests/manual/qlocale/numberformats.h b/tests/manual/qlocale/numberformats.h new file mode 100644 index 0000000..4a3ab36 --- /dev/null +++ b/tests/manual/qlocale/numberformats.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef NUMBERFORMATS_H +#define NUMBERFORMATS_H + +#include <QtGui> + +class NumberFormatsWidget : public QWidget +{ + Q_OBJECT +public: + NumberFormatsWidget(); + +private: + QLineEdit *createLineEdit(); + + QLineEdit *number1, *number2, *number3; + QLabel *measurementLabel; + QLineEdit *measurementSystem; + +private slots: + void localeChanged(QLocale locale); +}; + +#endif diff --git a/tests/manual/qlocale/qlocale.pro b/tests/manual/qlocale/qlocale.pro new file mode 100644 index 0000000..e9f17f4 --- /dev/null +++ b/tests/manual/qlocale/qlocale.pro @@ -0,0 +1,8 @@ +TEMPLATE = app +TARGET = +DEPENDPATH += . +INCLUDEPATH += . + +# Input +HEADERS += currency.h calendar.h dateformats.h numberformats.h languages.h window.h miscellaneous.h info.h +SOURCES += currency.cpp main.cpp calendar.cpp dateformats.cpp numberformats.cpp languages.cpp window.cpp miscellaneous.cpp info.cpp diff --git a/tests/manual/qlocale/window.cpp b/tests/manual/qlocale/window.cpp new file mode 100644 index 0000000..775023e --- /dev/null +++ b/tests/manual/qlocale/window.cpp @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "window.h" + +Window::Window() +{ + localeCombo = new QComboBox; + + localeCombo->addItem("System", QLocale::system()); + + QList<QLocale> locales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry); + foreach (const QLocale &locale, locales) { + QString label = QLocale::languageToString(locale.language()); + label += QLatin1Char('/'); + if (locale.script() != QLocale::AnyScript) { + label += QLocale::scriptToString(locale.script()); + label += QLatin1Char('/'); + } + label += QLocale::countryToString(locale.country()); + localeCombo->addItem(label, locale); + } + + connect(localeCombo, SIGNAL(currentIndexChanged(int)), + this, SLOT(localeChanged(int))); + + tabWidget = new QTabWidget; + info = new InfoWidget; + connect(this, SIGNAL(localeChanged(QLocale)), info, SLOT(localeChanged(QLocale))); + calendar = new CalendarWidget; + connect(this, SIGNAL(localeChanged(QLocale)), calendar, SLOT(localeChanged(QLocale))); + currency = new CurrencyWidget; + connect(this, SIGNAL(localeChanged(QLocale)), currency, SLOT(localeChanged(QLocale))); + languages = new LanguagesWidget; + connect(this, SIGNAL(localeChanged(QLocale)), languages, SLOT(localeChanged(QLocale))); + dateFormats = new DateFormatsWidget; + connect(this, SIGNAL(localeChanged(QLocale)), dateFormats, SLOT(localeChanged(QLocale))); + numberFormats = new NumberFormatsWidget; + connect(this, SIGNAL(localeChanged(QLocale)), numberFormats, SLOT(localeChanged(QLocale))); + miscellaneous = new MiscWidget; + connect(this, SIGNAL(localeChanged(QLocale)), miscellaneous, SLOT(localeChanged(QLocale))); + + localeName = new QLabel("Locale: foo_BAR"); + + QWidget *w = new QWidget; + QHBoxLayout *headerLayout = new QHBoxLayout(w); + headerLayout->addWidget(localeCombo); + headerLayout->addWidget(localeName); + + QWidget *central = new QWidget; + QVBoxLayout *l = new QVBoxLayout(central); + l->addWidget(w); + l->addWidget(tabWidget); + + tabWidget->addTab(info, "Info"); + tabWidget->addTab(calendar, "Calendar"); + tabWidget->addTab(currency, "Currency"); + tabWidget->addTab(languages, "Languages"); + tabWidget->addTab(dateFormats, "Date Formats"); + tabWidget->addTab(numberFormats, "Number Formats"); + tabWidget->addTab(miscellaneous, "Text"); + + localeCombo->setCurrentIndex(0); + systemLocaleChanged(); + + setCentralWidget(central); +} + +void Window::systemLocaleChanged() +{ + QLocale l = QLocale::system(); + QString lang = QLocale::languageToString(l.language()); + QString script = QLocale::scriptToString(l.script()); + QString country = QLocale::countryToString(l.country()); + if (l.script() != QLocale::AnyScript) + localeCombo->setItemText(0, QString("System: %1-%2-%3").arg(lang, script, country)); + else + localeCombo->setItemText(0, QString("System: %1-%2").arg(lang, country)); + emit localeChanged(0); +} + +void Window::localeChanged(int idx) +{ + QLocale locale = localeCombo->itemData(idx).toLocale(); + localeName->setText(QString("Locale: %1 (%2)").arg(locale.bcp47Name(), locale.name())); + emit localeChanged(locale); +} + +bool Window::event(QEvent *event) +{ + switch (event->type()) { + case QEvent::LocaleChange: { + if (localeCombo->currentIndex() == 0) + systemLocaleChanged(); + return true; + } + default: + break; + } + return QMainWindow::event(event); +} diff --git a/tests/manual/qlocale/window.h b/tests/manual/qlocale/window.h new file mode 100644 index 0000000..aee728f --- /dev/null +++ b/tests/manual/qlocale/window.h @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include <QtGui> + +#include "calendar.h" +#include "currency.h" +#include "languages.h" +#include "dateformats.h" +#include "numberformats.h" +#include "miscellaneous.h" +#include "info.h" + +class Window : public QMainWindow +{ + Q_OBJECT +public: + Window(); + + QLabel *localeName; + QComboBox *localeCombo; + QTabWidget *tabWidget; + CalendarWidget *calendar; + CurrencyWidget *currency; + LanguagesWidget *languages; + DateFormatsWidget *dateFormats; + NumberFormatsWidget *numberFormats; + MiscWidget *miscellaneous; + InfoWidget *info; + +private: + bool event(QEvent *); + void systemLocaleChanged(); + +signals: + void localeChanged(QLocale); + +private slots: + void localeChanged(int); +}; + +#endif |