From 0d8a94c74a8799b278d32d9cf0c32dee7cd35d11 Mon Sep 17 00:00:00 2001 From: Bea Lam Date: Mon, 1 Mar 2010 16:45:59 +1000 Subject: Export QDeclarativeWorkerScript and QDeclarativeWorkerListModel and call other usual macros. --- src/declarative/qml/qdeclarativeworkerscript_p.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/declarative/qml/qdeclarativeworkerscript_p.h b/src/declarative/qml/qdeclarativeworkerscript_p.h index 8ebd2c1..a810801 100644 --- a/src/declarative/qml/qdeclarativeworkerscript_p.h +++ b/src/declarative/qml/qdeclarativeworkerscript_p.h @@ -61,8 +61,12 @@ #include #include +QT_BEGIN_HEADER + QT_BEGIN_NAMESPACE +QT_MODULE(Declarative) + class QDeclarativeWorkerScript; class QDeclarativeWorkerScriptEnginePrivate; class QDeclarativeWorkerScriptEngine : public QThread @@ -84,7 +88,7 @@ private: QDeclarativeWorkerScriptEnginePrivate *d; }; -class QDeclarativeWorkerScript : public QObject, public QDeclarativeParserStatus +class Q_DECLARATIVE_EXPORT QDeclarativeWorkerScript : public QObject, public QDeclarativeParserStatus { Q_OBJECT Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged) @@ -115,7 +119,7 @@ private: }; class QDeclarativeWorkerListModelAgent; -class QDeclarativeWorkerListModel : public QListModelInterface +class Q_DECLARATIVE_EXPORT QDeclarativeWorkerListModel : public QListModelInterface { Q_OBJECT Q_PROPERTY(int count READ count NOTIFY countChanged) @@ -157,4 +161,6 @@ QT_END_NAMESPACE QML_DECLARE_TYPE(QDeclarativeWorkerScript); QML_DECLARE_TYPE(QDeclarativeWorkerListModel); +QT_END_HEADER + #endif // QDECLARATIVEWORKERSCRIPT_P_H -- cgit v0.12 From a76c8424dab298c2fa36226f47bf7ac6f7e4014a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Mon, 1 Mar 2010 15:28:36 +0100 Subject: Fixed qDrawPixmaps() to draw on integer coordinates on Mac OS X. This is the 4.7 port of d04f5336f769d9e5d2f9105e1da4a7d23ea91795. Task-number: related to QTBUG-8455 Reviewed-by: Kim --- src/gui/painting/qpainter.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index dc96c17..9d83718 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -8933,8 +8933,15 @@ void QPainter::drawPixmapFragments(const Fragment *fragments, int fragmentCount, for (int i = 0; i < fragmentCount; ++i) { QTransform transform = oldTransform; - transform.translate(fragments[i].x, fragments[i].y); - transform.rotate(fragments[i].rotation); + qreal xOffset = 0; + qreal yOffset = 0; + if (fragments[i].rotation == 0) { + xOffset = fragments[i].x; + yOffset = fragments[i].y; + } else { + transform.translate(fragments[i].x, fragments[i].y); + transform.rotate(fragments[i].rotation); + } setOpacity(oldOpacity * fragments[i].opacity); setTransform(transform); @@ -8942,7 +8949,7 @@ void QPainter::drawPixmapFragments(const Fragment *fragments, int fragmentCount, qreal h = fragments[i].scaleY * fragments[i].height; QRectF sourceRect(fragments[i].sourceLeft, fragments[i].sourceTop, fragments[i].width, fragments[i].height); - drawPixmap(QRectF(-0.5 * w, -0.5 * h, w, h), pixmap, sourceRect); + drawPixmap(QRectF(-0.5 * w + xOffset, -0.5 * h + yOffset, w, h), pixmap, sourceRect); } setOpacity(oldOpacity); -- cgit v0.12 From 31f2d97e28dff1a72511ab1ef7737e5f78d4cf66 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Mon, 1 Mar 2010 12:40:33 +0100 Subject: QMetaObject::invokeMethod: print a warning if the method is not found. Also adapt QTestLib not to call invokeMethod on unexisting method to avoid warnings Task-number: QTBUG-7331 Reviewed-by: Brad --- src/corelib/kernel/qmetaobject.cpp | 5 ++++- src/testlib/qtestcase.cpp | 28 +++++++++++++++++++++------- tests/auto/qmetaobject/tst_qmetaobject.cpp | 13 +++++++++++++ 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/src/corelib/kernel/qmetaobject.cpp b/src/corelib/kernel/qmetaobject.cpp index be1b2ae..ecffe99 100644 --- a/src/corelib/kernel/qmetaobject.cpp +++ b/src/corelib/kernel/qmetaobject.cpp @@ -1137,8 +1137,11 @@ bool QMetaObject::invokeMethod(QObject *obj, idx = obj->metaObject()->indexOfMethod(norm.constData()); } - if (idx < 0 || idx >= obj->metaObject()->methodCount()) + if (idx < 0 || idx >= obj->metaObject()->methodCount()) { + qWarning("QMetaObject::invokeMethod: No such method %s::%s", + obj->metaObject()->className(), sig.constData()); return false; + } QMetaMethod method = obj->metaObject()->method(idx); return method.invoke(obj, type, ret, val0, val1, val2, val3, val4, val5, val6, val7, val8, val9); diff --git a/src/testlib/qtestcase.cpp b/src/testlib/qtestcase.cpp index 5c9dd55..4590f17 100644 --- a/src/testlib/qtestcase.cpp +++ b/src/testlib/qtestcase.cpp @@ -877,6 +877,19 @@ int qt_snprintf(char *str, int size, const char *format, ...) return res; } +/*! \internal + Invoke a method of the object without generating warning if the method does not exist + */ +static void invokeMethod(QObject *obj, const char *methodName) +{ + const QMetaObject *metaObject = obj->metaObject(); + int funcIndex = metaObject->indexOfMethod(methodName); + if (funcIndex >= 0) { + QMetaMethod method = metaObject->method(funcIndex); + method.invoke(obj, Qt::DirectConnection); + } +} + bool Q_TESTLIB_EXPORT defaultKeyVerbose() { if (keyVerbose == -1) { @@ -1213,7 +1226,7 @@ static void qInvokeTestMethodDataEntry(char *slot) bool invokeOk; do { QTestResult::setCurrentTestLocation(QTestResult::InitFunc); - QMetaObject::invokeMethod(QTest::currentTestObject, "init"); + invokeMethod(QTest::currentTestObject, "init()"); if (QTestResult::skipCurrentTest()) break; @@ -1233,7 +1246,7 @@ static void qInvokeTestMethodDataEntry(char *slot) QTestResult::addFailure("Unable to execute slot", __FILE__, __LINE__); QTestResult::setCurrentTestLocation(QTestResult::CleanupFunc); - QMetaObject::invokeMethod(QTest::currentTestObject, "cleanup"); + invokeMethod(QTest::currentTestObject, "cleanup()"); QTestResult::setCurrentTestLocation(QTestResult::NoWhere); // If this test method has a benchmark, repeat until all measurements are @@ -1300,8 +1313,9 @@ static bool qInvokeTestMethod(const char *slotName, const char *data=0) if (curGlobalDataIndex == 0) { QTestResult::setCurrentTestLocation(QTestResult::DataFunc); - QTest::qt_snprintf(member, 512, "%s_data", slot); - QMetaObject::invokeMethod(QTest::currentTestObject, member, Qt::DirectConnection); + QTest::qt_snprintf(member, 512, "%s_data()", slot); + invokeMethod(QTest::currentTestObject, member); + // if we encounter a SkipAll in the _data slot, we skip the whole // testfunction, no matter how much global data exists if (QTestResult::skipCurrentTest()) { @@ -1466,11 +1480,11 @@ static void qInvokeTestMethods(QObject *testObject) QTestResult::setCurrentTestFunction("initTestCase"); QTestResult::setCurrentTestLocation(QTestResult::DataFunc); QTestTable::globalTestTable(); - QMetaObject::invokeMethod(testObject, "initTestCase_data", Qt::DirectConnection); + invokeMethod(testObject, "initTestCase_data()"); if (!QTestResult::skipCurrentTest() && !QTest::currentTestFailed()) { QTestResult::setCurrentTestLocation(QTestResult::InitFunc); - QMetaObject::invokeMethod(testObject, "initTestCase"); + invokeMethod(testObject, "initTestCase()"); // finishedCurrentTestFunction() resets QTestResult::testFailed(), so use a local copy. const bool previousFailed = QTestResult::testFailed(); @@ -1498,7 +1512,7 @@ static void qInvokeTestMethods(QObject *testObject) QTestResult::setSkipCurrentTest(false); QTestResult::setCurrentTestFunction("cleanupTestCase"); - QMetaObject::invokeMethod(testObject, "cleanupTestCase"); + invokeMethod(testObject, "cleanupTestCase()"); } QTestResult::finishedCurrentTestFunction(); QTestResult::setCurrentTestFunction(0); diff --git a/tests/auto/qmetaobject/tst_qmetaobject.cpp b/tests/auto/qmetaobject/tst_qmetaobject.cpp index 15b6204..bd54975 100644 --- a/tests/auto/qmetaobject/tst_qmetaobject.cpp +++ b/tests/auto/qmetaobject/tst_qmetaobject.cpp @@ -513,6 +513,19 @@ void tst_QMetaObject::invokeMetaMember() QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", Q_RETURN_ARG(QString, exp), Q_ARG(QString, "hehe"))); QCOMPARE(exp, QString("yessir")); QCOMPARE(obj.slotResult, QString("sl1:hehe")); + + QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::doesNotExist()"); + QVERIFY(!QMetaObject::invokeMethod(&obj, "doesNotExist")); + QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString)(QString)"); + QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1(QString)", Q_ARG(QString, "arg"))); + QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl3(QString)"); + QVERIFY(!QMetaObject::invokeMethod(&obj, "sl3", Q_ARG(QString, "arg"))); + QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString,QString,QString)"); + QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1", Q_ARG(QString, "arg"), Q_ARG(QString, "arg"), Q_ARG(QString, "arg"))); + + //should not have changed since last test. + QCOMPARE(exp, QString("yessir")); + QCOMPARE(obj.slotResult, QString("sl1:hehe")); } void tst_QMetaObject::invokeQueuedMetaMember() -- cgit v0.12 From 83c37c2cdf7adf2604e1e6012a9e0e6e67d97d6b Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 1 Mar 2010 17:31:44 +0100 Subject: removed dead code Reviewed-by: denis --- src/gui/kernel/qcursor_mac.mm | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/src/gui/kernel/qcursor_mac.mm b/src/gui/kernel/qcursor_mac.mm index cfebf60..03e38b0 100644 --- a/src/gui/kernel/qcursor_mac.mm +++ b/src/gui/kernel/qcursor_mac.mm @@ -114,27 +114,18 @@ void qt_mac_set_cursor(const QCursor *c, const QPoint &) } c->handle(); //force the cursor to get loaded, if it's not - if(1 || currentCursor != c->d) { - if(currentCursor && currentCursor->type == QCursorData::TYPE_ThemeCursor - && currentCursor->curs.tc.anim) - currentCursor->curs.tc.anim->stop(); - QMacCocoaAutoReleasePool pool; - if(c->d->type == QCursorData::TYPE_ImageCursor) { - [static_cast(c->d->curs.cp.nscursor) set]; - } else if(c->d->type == QCursorData::TYPE_ThemeCursor) { -#ifdef QT_MAC_USE_COCOA - if (c->d->curs.cp.nscursor == 0) - [[NSCursor arrowCursor] set]; - [static_cast(c->d->curs.cp.nscursor) set]; -#else - if(SetAnimatedThemeCursor(c->d->curs.tc.curs, 0) == themeBadCursorIndexErr) { - SetThemeCursor(c->d->curs.tc.curs); - } else { - if(!c->d->curs.tc.anim) - c->d->curs.tc.anim = new QMacAnimateCursor; - c->d->curs.tc.anim->start(c->d->curs.tc.curs); - } -#endif + if(currentCursor && currentCursor->type == QCursorData::TYPE_ThemeCursor + && currentCursor->curs.tc.anim) + currentCursor->curs.tc.anim->stop(); + if(c->d->type == QCursorData::TYPE_ImageCursor) { + [static_cast(c->d->curs.cp.nscursor) set]; + } else if(c->d->type == QCursorData::TYPE_ThemeCursor) { + if(SetAnimatedThemeCursor(c->d->curs.tc.curs, 0) == themeBadCursorIndexErr) { + SetThemeCursor(c->d->curs.tc.curs); + } else { + if(!c->d->curs.tc.anim) + c->d->curs.tc.anim = new QMacAnimateCursor; + c->d->curs.tc.anim->start(c->d->curs.tc.curs); } } currentCursor = c->d; -- cgit v0.12 From ffe622b5424bd13155fea01116ed6504f06d9d83 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Mon, 1 Mar 2010 15:55:03 +1000 Subject: Example of text focus. Task-number: QT-448 --- examples/declarative/focusscope/test5.qml | 83 +++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 examples/declarative/focusscope/test5.qml diff --git a/examples/declarative/focusscope/test5.qml b/examples/declarative/focusscope/test5.qml new file mode 100644 index 0000000..da98350 --- /dev/null +++ b/examples/declarative/focusscope/test5.qml @@ -0,0 +1,83 @@ +import Qt 4.6 + +Rectangle { + color: "white" + width: 800 + height: 600 + + Keys.onReturnPressed: console.log("Error - Root") + + FocusScope { + id: myScope + focus: true + + Keys.onReturnPressed: console.log("Error - FocusScope") + + Rectangle { + height: 120 + width: 420 + + color: "transparent" + border.width: 5 + border.color: myScope.wantsFocus?"blue":"black" + + Rectangle { + x: 10; y: 10 + width: 100; height: 100; color: "green" + border.width: 5 + border.color: item1.wantsFocus?"blue":"black" + } + + TextEdit { + id: item1 + x: 20; y: 20 + width: 90; height: 90 + color: "white" + font.pixelSize: 20 + Keys.onReturnPressed: console.log("Top Left"); + KeyNavigation.right: item2 + focus: true + wrap: true + text: "Box 1" + } + + Rectangle { + id: item2 + x: 310; y: 10 + width: 100; height: 100; color: "green" + border.width: 5 + border.color: wantsFocus?"blue":"black" + KeyNavigation.left: item1 + Keys.onReturnPressed: console.log("Top Right"); + + Rectangle { + width: 50; height: 50; anchors.centerIn: parent + color: parent.focus?"red":"transparent" + } + } + } + KeyNavigation.down: item3 + } + + Text { x:100; y:170; text: "Blue border indicates scoped focus\nBlack border indicates NOT scoped focus\nRed box or flashing cursor indicates active focus\nUse arrow keys to navigate\nPress Ctrl-Return to print currently focused item" } + + Rectangle { + x: 10; y: 300 + width: 100; height: 100; color: "green" + border.width: 5 + border.color: item3.wantsFocus?"blue":"black" + } + + TextEdit { + id: item3 + x: 20; y: 310 + width: 90; height: 90 + color: "white" + font.pixelSize: 20 + text: "Box 3" + + Keys.onReturnPressed: console.log("Bottom Left"); + KeyNavigation.up: myScope + wrap: true + } +} -- cgit v0.12 From 2de0a9ff40c6dcbfca5dc75aae7ac0a294618f4a Mon Sep 17 00:00:00 2001 From: Joona Petrell Date: Fri, 26 Feb 2010 16:34:28 +1000 Subject: Add NOTIFY signals to list, grid and path views Reviewed-by: akennedy --- .../graphicsitems/qdeclarativegridview.cpp | 12 +- .../graphicsitems/qdeclarativegridview_p.h | 20 ++- .../graphicsitems/qdeclarativelistview.cpp | 24 ++- .../graphicsitems/qdeclarativelistview_p.h | 38 +++-- src/declarative/graphicsitems/qdeclarativepath.cpp | 11 +- src/declarative/graphicsitems/qdeclarativepath_p.h | 11 +- .../graphicsitems/qdeclarativepathview.cpp | 26 +++- .../graphicsitems/qdeclarativepathview_p.h | 18 ++- .../qdeclarativegridview/data/propertychanges.qml | 69 +++++++++ .../tst_qdeclarativegridview.cpp | 125 +++++++++++++-- .../qdeclarativelistview/data/propertychanges.qml | 71 +++++++++ .../tst_qdeclarativelistview.cpp | 168 +++++++++++++++++++-- .../qdeclarativepathview/data/displaypath.qml | 2 +- .../qdeclarativepathview/data/pathview.qml | 2 +- .../qdeclarativepathview/data/pathview3.qml | 2 +- .../qdeclarativepathview/data/propertychanges.qml | 115 ++++++++++++++ .../tst_qdeclarativepathview.cpp | 167 +++++++++++++++++++- 17 files changed, 815 insertions(+), 66 deletions(-) create mode 100644 tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml create mode 100644 tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml create mode 100644 tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml diff --git a/src/declarative/graphicsitems/qdeclarativegridview.cpp b/src/declarative/graphicsitems/qdeclarativegridview.cpp index b43b30b..a7376cc 100644 --- a/src/declarative/graphicsitems/qdeclarativegridview.cpp +++ b/src/declarative/graphicsitems/qdeclarativegridview.cpp @@ -618,7 +618,7 @@ void QDeclarativeGridViewPrivate::createHighlight() } } if (changed) - emit q->highlightChanged(); + emit q->highlightItemChanged(); } void QDeclarativeGridViewPrivate::updateHighlight() @@ -784,6 +784,8 @@ QVariant QDeclarativeGridView::model() const void QDeclarativeGridView::setModel(const QVariant &model) { Q_D(QDeclarativeGridView); + if (d->modelVariant == model) + return; if (d->model) { disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int))); disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int))); @@ -828,6 +830,7 @@ void QDeclarativeGridView::setModel(const QVariant &model) connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*))); emit countChanged(); } + emit modelChanged(); } /*! @@ -871,6 +874,7 @@ void QDeclarativeGridView::setDelegate(QDeclarativeComponent *delegate) d->moveReason = QDeclarativeGridViewPrivate::SetIndex; d->updateCurrent(d->currentIndex); } + emit delegateChanged(); } } @@ -966,6 +970,7 @@ void QDeclarativeGridView::setHighlight(QDeclarativeComponent *highlight) if (highlight != d->highlightComponent) { d->highlightComponent = highlight; d->updateCurrent(d->currentIndex); + emit highlightChanged(); } } @@ -1039,6 +1044,7 @@ void QDeclarativeGridView::setFlow(Flow flow) d->updateGrid(); refill(); d->updateCurrent(d->currentIndex); + emit flowChanged(); } } @@ -1058,7 +1064,10 @@ bool QDeclarativeGridView::isWrapEnabled() const void QDeclarativeGridView::setWrapEnabled(bool wrap) { Q_D(QDeclarativeGridView); + if (d->wrap == wrap) + return; d->wrap = wrap; + emit keyNavigationWrapsChanged(); } /*! @@ -1082,6 +1091,7 @@ void QDeclarativeGridView::setCacheBuffer(int buffer) d->buffer = buffer; if (isComponentComplete()) refill(); + emit cacheBufferChanged(); } } diff --git a/src/declarative/graphicsitems/qdeclarativegridview_p.h b/src/declarative/graphicsitems/qdeclarativegridview_p.h index b488475..d463a46 100644 --- a/src/declarative/graphicsitems/qdeclarativegridview_p.h +++ b/src/declarative/graphicsitems/qdeclarativegridview_p.h @@ -57,19 +57,19 @@ class Q_DECLARATIVE_EXPORT QDeclarativeGridView : public QDeclarativeFlickable Q_OBJECT Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeGridView) - Q_PROPERTY(QVariant model READ model WRITE setModel) - Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate) + Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged) + Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(QDeclarativeItem *currentItem READ currentItem NOTIFY currentIndexChanged) Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight) - Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightChanged) + Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight NOTIFY highlightChanged) + Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightItemChanged) Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem) - Q_PROPERTY(Flow flow READ flow WRITE setFlow) - Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled) - Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer) + Q_PROPERTY(Flow flow READ flow WRITE setFlow NOTIFY flowChanged) + Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled NOTIFY keyNavigationWrapsChanged) + Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer NOTIFY cacheBufferChanged) Q_PROPERTY(int cellWidth READ cellWidth WRITE setCellWidth NOTIFY cellWidthChanged) Q_PROPERTY(int cellHeight READ cellHeight WRITE setCellHeight NOTIFY cellHeightChanged) Q_CLASSINFO("DefaultProperty", "data") @@ -129,6 +129,12 @@ Q_SIGNALS: void cellWidthChanged(); void cellHeightChanged(); void highlightChanged(); + void highlightItemChanged(); + void modelChanged(); + void delegateChanged(); + void flowChanged(); + void keyNavigationWrapsChanged(); + void cacheBufferChanged(); protected: virtual void viewportMoved(); diff --git a/src/declarative/graphicsitems/qdeclarativelistview.cpp b/src/declarative/graphicsitems/qdeclarativelistview.cpp index 03303a0..e7fff90 100644 --- a/src/declarative/graphicsitems/qdeclarativelistview.cpp +++ b/src/declarative/graphicsitems/qdeclarativelistview.cpp @@ -816,7 +816,7 @@ void QDeclarativeListViewPrivate::createHighlight() } } if (changed) - emit q->highlightChanged(); + emit q->highlightItemChanged(); } void QDeclarativeListViewPrivate::updateHighlight() @@ -1473,6 +1473,8 @@ QVariant QDeclarativeListView::model() const void QDeclarativeListView::setModel(const QVariant &model) { Q_D(QDeclarativeListView); + if (d->modelVariant == model) + return; if (d->model) { disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int))); disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int))); @@ -1517,6 +1519,7 @@ void QDeclarativeListView::setModel(const QVariant &model) connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*))); emit countChanged(); } + emit modelChanged(); } /*! @@ -1563,6 +1566,7 @@ void QDeclarativeListView::setDelegate(QDeclarativeComponent *delegate) d->updateCurrent(d->currentIndex); } } + emit delegateChanged(); } /*! @@ -1663,6 +1667,7 @@ void QDeclarativeListView::setHighlight(QDeclarativeComponent *highlight) d->createHighlight(); if (d->currentItem) d->updateHighlight(); + emit highlightChanged(); } } @@ -1700,6 +1705,7 @@ void QDeclarativeListView::setHighlightFollowsCurrentItem(bool autoHighlight) d->highlightSizeAnimator->setEnabled(d->autoHighlight); } d->updateHighlight(); + emit highlightFollowsCurrentItemChanged(); } } @@ -1745,8 +1751,11 @@ qreal QDeclarativeListView::preferredHighlightBegin() const void QDeclarativeListView::setPreferredHighlightBegin(qreal start) { Q_D(QDeclarativeListView); + if (d->highlightRangeStart == start) + return; d->highlightRangeStart = start; d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd; + emit preferredHighlightBeginChanged(); } qreal QDeclarativeListView::preferredHighlightEnd() const @@ -1758,8 +1767,11 @@ qreal QDeclarativeListView::preferredHighlightEnd() const void QDeclarativeListView::setPreferredHighlightEnd(qreal end) { Q_D(QDeclarativeListView); + if (d->highlightRangeEnd == end) + return; d->highlightRangeEnd = end; d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd; + emit preferredHighlightEndChanged(); } QDeclarativeListView::HighlightRangeMode QDeclarativeListView::highlightRangeMode() const @@ -1771,8 +1783,11 @@ QDeclarativeListView::HighlightRangeMode QDeclarativeListView::highlightRangeMod void QDeclarativeListView::setHighlightRangeMode(HighlightRangeMode mode) { Q_D(QDeclarativeListView); + if (d->highlightRange == mode) + return; d->highlightRange = mode; d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd; + emit highlightRangeModeChanged(); } /*! @@ -1848,7 +1863,10 @@ bool QDeclarativeListView::isWrapEnabled() const void QDeclarativeListView::setWrapEnabled(bool wrap) { Q_D(QDeclarativeListView); + if (d->wrap == wrap) + return; d->wrap = wrap; + emit keyNavigationWrapsChanged(); } /*! @@ -1874,6 +1892,7 @@ void QDeclarativeListView::setCacheBuffer(int b) d->bufferMode = QDeclarativeListViewPrivate::BufferBefore | QDeclarativeListViewPrivate::BufferAfter; refill(); } + emit cacheBufferChanged(); } } @@ -1998,6 +2017,7 @@ void QDeclarativeListView::setSnapMode(SnapMode mode) Q_D(QDeclarativeListView); if (d->snapMode != mode) { d->snapMode = mode; + emit snapModeChanged(); } } @@ -2020,6 +2040,7 @@ void QDeclarativeListView::setFooter(QDeclarativeComponent *footer) d->maxExtentDirty = true; d->updateFooter(); d->updateViewport(); + emit footerChanged(); } } @@ -2043,6 +2064,7 @@ void QDeclarativeListView::setHeader(QDeclarativeComponent *header) d->updateHeader(); d->updateFooter(); d->updateViewport(); + emit headerChanged(); } } diff --git a/src/declarative/graphicsitems/qdeclarativelistview_p.h b/src/declarative/graphicsitems/qdeclarativelistview_p.h index 5e3edb0..f9b7b50 100644 --- a/src/declarative/graphicsitems/qdeclarativelistview_p.h +++ b/src/declarative/graphicsitems/qdeclarativelistview_p.h @@ -91,33 +91,33 @@ class Q_DECLARATIVE_EXPORT QDeclarativeListView : public QDeclarativeFlickable Q_OBJECT Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeListView) - Q_PROPERTY(QVariant model READ model WRITE setModel) - Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate) + Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged) + Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(QDeclarativeItem *currentItem READ currentItem NOTIFY currentIndexChanged) Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight) - Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightChanged) - Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem) + Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight NOTIFY highlightChanged) + Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightItemChanged) + Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem NOTIFY highlightFollowsCurrentItemChanged) Q_PROPERTY(qreal highlightMoveSpeed READ highlightMoveSpeed WRITE setHighlightMoveSpeed NOTIFY highlightMoveSpeedChanged) Q_PROPERTY(qreal highlightResizeSpeed READ highlightResizeSpeed WRITE setHighlightResizeSpeed NOTIFY highlightResizeSpeedChanged) - Q_PROPERTY(qreal preferredHighlightBegin READ preferredHighlightBegin WRITE setPreferredHighlightBegin) - Q_PROPERTY(qreal preferredHighlightEnd READ preferredHighlightEnd WRITE setPreferredHighlightEnd) - Q_PROPERTY(HighlightRangeMode highlightRangeMode READ highlightRangeMode WRITE setHighlightRangeMode) + Q_PROPERTY(qreal preferredHighlightBegin READ preferredHighlightBegin WRITE setPreferredHighlightBegin NOTIFY preferredHighlightBeginChanged) + Q_PROPERTY(qreal preferredHighlightEnd READ preferredHighlightEnd WRITE setPreferredHighlightEnd NOTIFY preferredHighlightEndChanged) + Q_PROPERTY(HighlightRangeMode highlightRangeMode READ highlightRangeMode WRITE setHighlightRangeMode NOTIFY highlightRangeModeChanged) Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing NOTIFY spacingChanged) Q_PROPERTY(Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged) - Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled) - Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer) + Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled NOTIFY keyNavigationWrapsChanged) + Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer NOTIFY cacheBufferChanged) Q_PROPERTY(QDeclarativeViewSection *section READ sectionCriteria CONSTANT) Q_PROPERTY(QString currentSection READ currentSection NOTIFY currentSectionChanged) - Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode) + Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode NOTIFY snapModeChanged) - Q_PROPERTY(QDeclarativeComponent *header READ header WRITE setHeader) - Q_PROPERTY(QDeclarativeComponent *footer READ footer WRITE setFooter) + Q_PROPERTY(QDeclarativeComponent *header READ header WRITE setHeader NOTIFY headerChanged) + Q_PROPERTY(QDeclarativeComponent *footer READ footer WRITE setFooter NOTIFY footerChanged) Q_ENUMS(HighlightRangeMode) Q_ENUMS(Orientation) @@ -205,6 +205,18 @@ Q_SIGNALS: void highlightMoveSpeedChanged(); void highlightResizeSpeedChanged(); void highlightChanged(); + void highlightItemChanged(); + void modelChanged(); + void delegateChanged(); + void highlightFollowsCurrentItemChanged(); + void preferredHighlightBeginChanged(); + void preferredHighlightEndChanged(); + void highlightRangeModeChanged(); + void keyNavigationWrapsChanged(); + void cacheBufferChanged(); + void snapModeChanged(); + void headerChanged(); + void footerChanged(); protected: virtual void viewportMoved(); diff --git a/src/declarative/graphicsitems/qdeclarativepath.cpp b/src/declarative/graphicsitems/qdeclarativepath.cpp index 48f112a..80586b8 100644 --- a/src/declarative/graphicsitems/qdeclarativepath.cpp +++ b/src/declarative/graphicsitems/qdeclarativepath.cpp @@ -114,7 +114,10 @@ qreal QDeclarativePath::startX() const void QDeclarativePath::setStartX(qreal x) { Q_D(QDeclarativePath); + if (qFuzzyCompare(x, d->startX)) + return; d->startX = x; + emit startXChanged(); } qreal QDeclarativePath::startY() const @@ -126,7 +129,10 @@ qreal QDeclarativePath::startY() const void QDeclarativePath::setStartY(qreal y) { Q_D(QDeclarativePath); + if (qFuzzyCompare(y, d->startY)) + return; d->startY = y; + emit startYChanged(); } /*! @@ -522,7 +528,10 @@ QString QDeclarativePathAttribute::name() const void QDeclarativePathAttribute::setName(const QString &name) { - _name = name; + if (_name == name) + return; + _name = name; + emit nameChanged(); } /*! diff --git a/src/declarative/graphicsitems/qdeclarativepath_p.h b/src/declarative/graphicsitems/qdeclarativepath_p.h index b3139f8..d7cfca1 100644 --- a/src/declarative/graphicsitems/qdeclarativepath_p.h +++ b/src/declarative/graphicsitems/qdeclarativepath_p.h @@ -67,7 +67,7 @@ class Q_DECLARATIVE_EXPORT QDeclarativePathAttribute : public QDeclarativePathEl { Q_OBJECT - Q_PROPERTY(QString name READ name WRITE setName) + Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY changed) public: QDeclarativePathAttribute(QObject *parent=0) : QDeclarativePathElement(parent), _value(0) {} @@ -79,6 +79,9 @@ public: qreal value() const; void setValue(qreal value); +Q_SIGNALS: + void nameChanged(); + private: QString _name; qreal _value; @@ -190,8 +193,8 @@ class Q_DECLARATIVE_EXPORT QDeclarativePath : public QObject, public QDeclarativ Q_INTERFACES(QDeclarativeParserStatus) Q_PROPERTY(QDeclarativeListProperty pathElements READ pathElements) - Q_PROPERTY(qreal startX READ startX WRITE setStartX) - Q_PROPERTY(qreal startY READ startY WRITE setStartY) + Q_PROPERTY(qreal startX READ startX WRITE setStartX NOTIFY startXChanged) + Q_PROPERTY(qreal startY READ startY WRITE setStartY NOTIFY startYChanged) Q_PROPERTY(bool closed READ isClosed NOTIFY changed) Q_CLASSINFO("DefaultProperty", "pathElements") Q_INTERFACES(QDeclarativeParserStatus) @@ -216,6 +219,8 @@ public: Q_SIGNALS: void changed(); + void startXChanged(); + void startYChanged(); protected: virtual void componentComplete(); diff --git a/src/declarative/graphicsitems/qdeclarativepathview.cpp b/src/declarative/graphicsitems/qdeclarativepathview.cpp index f1b0213..50aa9ef 100644 --- a/src/declarative/graphicsitems/qdeclarativepathview.cpp +++ b/src/declarative/graphicsitems/qdeclarativepathview.cpp @@ -203,6 +203,9 @@ QVariant QDeclarativePathView::model() const void QDeclarativePathView::setModel(const QVariant &model) { Q_D(QDeclarativePathView); + if (d->modelVariant == model) + return; + if (d->model) { disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int))); disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int))); @@ -242,6 +245,7 @@ void QDeclarativePathView::setModel(const QVariant &model) d->pathOffset = 0; d->regenerate(); d->fixOffset(); + emit modelChanged(); } /*! @@ -269,9 +273,12 @@ QDeclarativePath *QDeclarativePathView::path() const void QDeclarativePathView::setPath(QDeclarativePath *path) { Q_D(QDeclarativePathView); + if (d->path == path) + return; d->path = path; connect(d->path, SIGNAL(changed()), this, SLOT(refill())); d->regenerate(); + emit pathChanged(); } /*! @@ -333,7 +340,7 @@ void QDeclarativePathViewPrivate::setOffset(qreal o) /*! \qmlproperty real PathView::snapPosition - This property determines the position (0-100) the nearest item will snap to. + This property determines the position (0.0-1.0) the nearest item will snap to. */ qreal QDeclarativePathView::snapPosition() const { @@ -344,8 +351,12 @@ qreal QDeclarativePathView::snapPosition() const void QDeclarativePathView::setSnapPosition(qreal pos) { Q_D(QDeclarativePathView); - d->snapPos = pos/100; + qreal normalizedPos = pos - int(pos); + if (qFuzzyCompare(normalizedPos, d->snapPos)) + return; + d->snapPos = normalizedPos; d->fixOffset(); + emit snapPositionChanged(); } /*! @@ -365,7 +376,10 @@ qreal QDeclarativePathView::dragMargin() const void QDeclarativePathView::setDragMargin(qreal dragMargin) { Q_D(QDeclarativePathView); + if (d->dragMargin == dragMargin) + return; d->dragMargin = dragMargin; + emit dragMarginChanged(); } /*! @@ -392,16 +406,19 @@ QDeclarativeComponent *QDeclarativePathView::delegate() const return 0; } -void QDeclarativePathView::setDelegate(QDeclarativeComponent *c) +void QDeclarativePathView::setDelegate(QDeclarativeComponent *delegate) { Q_D(QDeclarativePathView); + if (delegate == this->delegate()) + return; if (!d->ownModel) { d->model = new QDeclarativeVisualDataModel(qmlContext(this)); d->ownModel = true; } if (QDeclarativeVisualDataModel *dataModel = qobject_cast(d->model)) { - dataModel->setDelegate(c); + dataModel->setDelegate(delegate); d->regenerate(); + emit delegateChanged(); } } @@ -422,6 +439,7 @@ void QDeclarativePathView::setPathItemCount(int i) return; d->pathItems = i; d->regenerate(); + pathItemCountChanged(); } QPointF QDeclarativePathViewPrivate::pointNear(const QPointF &point, qreal *nearPercent) const diff --git a/src/declarative/graphicsitems/qdeclarativepathview_p.h b/src/declarative/graphicsitems/qdeclarativepathview_p.h index 709a4fc..df9c6ae 100644 --- a/src/declarative/graphicsitems/qdeclarativepathview_p.h +++ b/src/declarative/graphicsitems/qdeclarativepathview_p.h @@ -56,15 +56,15 @@ class Q_DECLARATIVE_EXPORT QDeclarativePathView : public QDeclarativeItem { Q_OBJECT - Q_PROPERTY(QVariant model READ model WRITE setModel) - Q_PROPERTY(QDeclarativePath *path READ path WRITE setPath) + Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged) + Q_PROPERTY(QDeclarativePath *path READ path WRITE setPath NOTIFY pathChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(qreal offset READ offset WRITE setOffset NOTIFY offsetChanged) - Q_PROPERTY(qreal snapPosition READ snapPosition WRITE setSnapPosition) - Q_PROPERTY(qreal dragMargin READ dragMargin WRITE setDragMargin) + Q_PROPERTY(qreal snapPosition READ snapPosition WRITE setSnapPosition NOTIFY snapPositionChanged) + Q_PROPERTY(qreal dragMargin READ dragMargin WRITE setDragMargin NOTIFY dragMarginChanged) Q_PROPERTY(int count READ count) - Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate) - Q_PROPERTY(int pathItemCount READ pathItemCount WRITE setPathItemCount) + Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged) + Q_PROPERTY(int pathItemCount READ pathItemCount WRITE setPathItemCount NOTIFY pathItemCountChanged) public: QDeclarativePathView(QDeclarativeItem *parent=0); @@ -101,6 +101,12 @@ public: Q_SIGNALS: void currentIndexChanged(); void offsetChanged(); + void modelChanged(); + void pathChanged(); + void dragMarginChanged(); + void snapPositionChanged(); + void delegateChanged(); + void pathItemCountChanged(); protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); diff --git a/tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml new file mode 100644 index 0000000..da2e8d0 --- /dev/null +++ b/tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml @@ -0,0 +1,69 @@ +import Qt 4.6 + +Rectangle { + width: 360; height: 120; color: "white" + Component { + id: delegate + Item { + id: wrapper + width: 180; height: 40; + Column { + x: 5; y: 5 + Text { text: 'Name: ' + name } + Text { text: 'Number: ' + number } + } + } + } + Component { + id: highlightRed + Rectangle { + color: "red" + radius: 10 + opacity: 0.5 + } + } + GridView { + cellWidth:180 + cellHeight:40 + objectName: "gridView" + anchors.fill: parent + model: listModel + delegate: delegate + highlight: highlightRed + focus: true + keyNavigationWraps: true + cacheBuffer: 10 + flow: GridView.LeftToRight + } + + data:[ + ListModel { + id: listModel + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + }, + ListModel { + objectName: "alternateModel" + ListElement { + name: "Jack" + number: "555 8426" + } + ListElement { + name: "Mary" + number: "555 3264" + } + } + ] +} + + \ No newline at end of file diff --git a/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp b/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp index 2a60fee..cc65d32 100644 --- a/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp +++ b/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp @@ -39,16 +39,17 @@ ** ****************************************************************************/ -#include -#include -#include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include class tst_QDeclarativeGridView : public QObject { @@ -66,6 +67,9 @@ private slots: void currentIndex(); void defaultValues(); void properties(); + void propertyChanges(); + void componentChanges(); + void modelChanges(); void positionViewAtIndex(); void resetModel(); void QTBUG_8456(); @@ -91,7 +95,7 @@ public: setRoleNames(roles); } - int rowCount(const QModelIndex &parent=QModelIndex()) const { return list.count(); } + int rowCount(const QModelIndex &parent=QModelIndex()) const { Q_UNUSED(parent); return list.count(); } QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const { QVariant rv; if (role == Name) @@ -796,6 +800,107 @@ void tst_QDeclarativeGridView::properties() delete obj; } +void tst_QDeclarativeGridView::propertyChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeGridView *gridView = canvas->rootObject()->findChild("gridView"); + QVERIFY(gridView); + + QSignalSpy keyNavigationWrapsSpy(gridView, SIGNAL(keyNavigationWrapsChanged())); + QSignalSpy cacheBufferSpy(gridView, SIGNAL(cacheBufferChanged())); + QSignalSpy flowSpy(gridView, SIGNAL(flowChanged())); + + QCOMPARE(gridView->isWrapEnabled(), true); + QCOMPARE(gridView->cacheBuffer(), 10); + QCOMPARE(gridView->flow(), QDeclarativeGridView::LeftToRight); + + gridView->setWrapEnabled(false); + gridView->setCacheBuffer(3); + gridView->setFlow(QDeclarativeGridView::TopToBottom); + + QCOMPARE(gridView->isWrapEnabled(), false); + QCOMPARE(gridView->cacheBuffer(), 3); + QCOMPARE(gridView->flow(), QDeclarativeGridView::TopToBottom); + + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(flowSpy.count(),1); + + gridView->setWrapEnabled(false); + gridView->setCacheBuffer(3); + gridView->setFlow(QDeclarativeGridView::TopToBottom); + + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(flowSpy.count(),1); + + delete canvas; +} + +void tst_QDeclarativeGridView::componentChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeGridView *gridView = canvas->rootObject()->findChild("gridView"); + QVERIFY(gridView); + + QDeclarativeComponent component(canvas->engine()); + component.setData("import Qt 4.6; Rectangle { color: \"blue\"; }", QUrl::fromLocalFile("")); + + QDeclarativeComponent delegateComponent(canvas->engine()); + delegateComponent.setData("import Qt 4.6; Text { text: 'Name: ' + name }", QUrl::fromLocalFile("")); + + QSignalSpy highlightSpy(gridView, SIGNAL(highlightChanged())); + QSignalSpy delegateSpy(gridView, SIGNAL(delegateChanged())); + + gridView->setHighlight(&component); + gridView->setDelegate(&delegateComponent); + + QCOMPARE(gridView->highlight(), &component); + QCOMPARE(gridView->delegate(), &delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + + gridView->setHighlight(&component); + gridView->setDelegate(&delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + delete canvas; +} + +void tst_QDeclarativeGridView::modelChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeGridView *gridView = canvas->rootObject()->findChild("gridView"); + QVERIFY(gridView); + + QDeclarativeListModel *alternateModel = canvas->rootObject()->findChild("alternateModel"); + QVERIFY(alternateModel); + QVariant modelVariant = QVariant::fromValue(alternateModel); + QSignalSpy modelSpy(gridView, SIGNAL(modelChanged())); + + gridView->setModel(modelVariant); + QCOMPARE(gridView->model(), modelVariant); + QCOMPARE(modelSpy.count(),1); + + gridView->setModel(modelVariant); + QCOMPARE(modelSpy.count(),1); + + gridView->setModel(QVariant()); + QCOMPARE(modelSpy.count(),2); + delete canvas; +} + void tst_QDeclarativeGridView::positionViewAtIndex() { QDeclarativeView *canvas = createView(); diff --git a/tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml new file mode 100644 index 0000000..a41f003 --- /dev/null +++ b/tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml @@ -0,0 +1,71 @@ +import Qt 4.6 + +Rectangle { + width: 180; height: 120; color: "white" + Component { + id: delegate + Item { + id: wrapper + width: 180; height: 40; + Column { + x: 5; y: 5 + Text { text: 'Name: ' + name } + Text { text: 'Number: ' + number } + } + } + } + Component { + id: highlightRed + Rectangle { + color: "red" + radius: 10 + opacity: 0.5 + } + } + ListView { + objectName: "listView" + anchors.fill: parent + model: listModel + delegate: delegate + highlight: highlightRed + focus: true + highlightFollowsCurrentItem: true + preferredHighlightBegin: 0.0 + preferredHighlightEnd: 0.0 + highlightRangeMode: ListView.ApplyRange + keyNavigationWraps: true + cacheBuffer: 10 + snapMode: ListView.SnapToItem + } + + data:[ + ListModel { + id: listModel + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + }, + ListModel { + objectName: "alternateModel" + ListElement { + name: "Jack" + number: "555 8426" + } + ListElement { + name: "Mary" + number: "555 3264" + } + } + ] +} + + \ No newline at end of file diff --git a/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp b/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp index f15f26b..a36224f 100644 --- a/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp +++ b/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp @@ -38,15 +38,18 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ + #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include class tst_QDeclarativeListView : public QObject { @@ -82,6 +85,9 @@ private slots: void cacheBuffer(); void positionViewAtIndex(); void resetModel(); + void propertyChanges(); + void componentChanges(); + void modelChanges(); private: template void items(); @@ -240,7 +246,7 @@ public: setRoleNames(roles); } - int rowCount(const QModelIndex &parent=QModelIndex()) const { return list.count(); } + int rowCount(const QModelIndex &parent=QModelIndex()) const { Q_UNUSED(parent); return list.count(); } QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const { QVariant rv; if (role == Name) @@ -379,6 +385,7 @@ void tst_QDeclarativeListView::items() delete canvas; } + template void tst_QDeclarativeListView::changed() { @@ -1275,6 +1282,149 @@ void tst_QDeclarativeListView::resetModel() } } +void tst_QDeclarativeListView::propertyChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeListView *listView = canvas->rootObject()->findChild("listView"); + QVERIFY(listView); + + QSignalSpy highlightFollowsCurrentItemSpy(listView, SIGNAL(highlightFollowsCurrentItemChanged())); + QSignalSpy preferredHighlightBeginSpy(listView, SIGNAL(preferredHighlightBeginChanged())); + QSignalSpy preferredHighlightEndSpy(listView, SIGNAL(preferredHighlightEndChanged())); + QSignalSpy highlightRangeModeSpy(listView, SIGNAL(highlightRangeModeChanged())); + QSignalSpy keyNavigationWrapsSpy(listView, SIGNAL(keyNavigationWrapsChanged())); + QSignalSpy cacheBufferSpy(listView, SIGNAL(cacheBufferChanged())); + QSignalSpy snapModeSpy(listView, SIGNAL(snapModeChanged())); + + QCOMPARE(listView->highlightFollowsCurrentItem(), true); + QCOMPARE(listView->preferredHighlightBegin(), 0.0); + QCOMPARE(listView->preferredHighlightEnd(), 0.0); + QCOMPARE(listView->highlightRangeMode(), QDeclarativeListView::ApplyRange); + QCOMPARE(listView->isWrapEnabled(), true); + QCOMPARE(listView->cacheBuffer(), 10); + QCOMPARE(listView->snapMode(), QDeclarativeListView::SnapToItem); + + listView->setHighlightFollowsCurrentItem(false); + listView->setPreferredHighlightBegin(1.0); + listView->setPreferredHighlightEnd(1.0); + listView->setHighlightRangeMode(QDeclarativeListView::StrictlyEnforceRange); + listView->setWrapEnabled(false); + listView->setCacheBuffer(3); + listView->setSnapMode(QDeclarativeListView::SnapOneItem); + + QCOMPARE(listView->highlightFollowsCurrentItem(), false); + QCOMPARE(listView->preferredHighlightBegin(), 1.0); + QCOMPARE(listView->preferredHighlightEnd(), 1.0); + QCOMPARE(listView->highlightRangeMode(), QDeclarativeListView::StrictlyEnforceRange); + QCOMPARE(listView->isWrapEnabled(), false); + QCOMPARE(listView->cacheBuffer(), 3); + QCOMPARE(listView->snapMode(), QDeclarativeListView::SnapOneItem); + + QCOMPARE(highlightFollowsCurrentItemSpy.count(),1); + QCOMPARE(preferredHighlightBeginSpy.count(),1); + QCOMPARE(preferredHighlightEndSpy.count(),1); + QCOMPARE(highlightRangeModeSpy.count(),1); + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(snapModeSpy.count(),1); + + listView->setHighlightFollowsCurrentItem(false); + listView->setPreferredHighlightBegin(1.0); + listView->setPreferredHighlightEnd(1.0); + listView->setHighlightRangeMode(QDeclarativeListView::StrictlyEnforceRange); + listView->setWrapEnabled(false); + listView->setCacheBuffer(3); + listView->setSnapMode(QDeclarativeListView::SnapOneItem); + + QCOMPARE(highlightFollowsCurrentItemSpy.count(),1); + QCOMPARE(preferredHighlightBeginSpy.count(),1); + QCOMPARE(preferredHighlightEndSpy.count(),1); + QCOMPARE(highlightRangeModeSpy.count(),1); + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(snapModeSpy.count(),1); + + delete canvas; +} + +void tst_QDeclarativeListView::componentChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeListView *listView = canvas->rootObject()->findChild("listView"); + QVERIFY(listView); + + QDeclarativeComponent component(canvas->engine()); + component.setData("import Qt 4.6; Rectangle { color: \"blue\"; }", QUrl::fromLocalFile("")); + + QDeclarativeComponent delegateComponent(canvas->engine()); + delegateComponent.setData("import Qt 4.6; Text { text: 'Name: ' + name }", QUrl::fromLocalFile("")); + + QSignalSpy highlightSpy(listView, SIGNAL(highlightChanged())); + QSignalSpy delegateSpy(listView, SIGNAL(delegateChanged())); + QSignalSpy headerSpy(listView, SIGNAL(headerChanged())); + QSignalSpy footerSpy(listView, SIGNAL(footerChanged())); + + listView->setHighlight(&component); + listView->setHeader(&component); + listView->setFooter(&component); + listView->setDelegate(&delegateComponent); + + QCOMPARE(listView->highlight(), &component); + QCOMPARE(listView->header(), &component); + QCOMPARE(listView->footer(), &component); + QCOMPARE(listView->delegate(), &delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + QCOMPARE(headerSpy.count(),1); + QCOMPARE(footerSpy.count(),1); + + listView->setHighlight(&component); + listView->setHeader(&component); + listView->setFooter(&component); + listView->setDelegate(&delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + QCOMPARE(headerSpy.count(),1); + QCOMPARE(footerSpy.count(),1); + + delete canvas; +} + +void tst_QDeclarativeListView::modelChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeListView *listView = canvas->rootObject()->findChild("listView"); + QVERIFY(listView); + + QDeclarativeListModel *alternateModel = canvas->rootObject()->findChild("alternateModel"); + QVERIFY(alternateModel); + QVariant modelVariant = QVariant::fromValue(alternateModel); + QSignalSpy modelSpy(listView, SIGNAL(modelChanged())); + + listView->setModel(modelVariant); + QCOMPARE(listView->model(), modelVariant); + QCOMPARE(modelSpy.count(),1); + + listView->setModel(modelVariant); + QCOMPARE(modelSpy.count(),1); + + listView->setModel(QVariant()); + QCOMPARE(modelSpy.count(),2); + + delete canvas; +} + void tst_QDeclarativeListView::qListModelInterface_items() { items(); diff --git a/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml b/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml index 627f38a..ab1538b 100644 --- a/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml +++ b/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml @@ -33,7 +33,7 @@ Rectangle { height: 320 model: testModel delegate: delegate - snapPosition: 0.01 + snapPosition: 0.0001 path: Path { startY: 120 startX: 160 diff --git a/tests/auto/declarative/qdeclarativepathview/data/pathview.qml b/tests/auto/declarative/qdeclarativepathview/data/pathview.qml index 8fa8d59..c5d88cd 100644 --- a/tests/auto/declarative/qdeclarativepathview/data/pathview.qml +++ b/tests/auto/declarative/qdeclarativepathview/data/pathview.qml @@ -39,7 +39,7 @@ Rectangle { height: 320 model: testModel delegate: delegate - snapPosition: 0.01 + snapPosition: 0.0001 path: Path { startY: 120 startX: 160 diff --git a/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml b/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml index af3ae13..f8ed29f 100644 --- a/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml +++ b/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml @@ -3,7 +3,7 @@ import Qt 4.6 PathView { id: photoPathView y: 100; width: 800; height: 330; pathItemCount: 4; offset: 10 - dragMargin: 24; snapPosition: 50 + dragMargin: 24; snapPosition: 0.50 path: Path { startX: -50; startY: 40; diff --git a/tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml new file mode 100644 index 0000000..db70b7b --- /dev/null +++ b/tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml @@ -0,0 +1,115 @@ +import Qt 4.6 + +Rectangle { + width: 350; height: 220; color: "white" + Component { + id: myDelegate + Item { + id: wrapper + width: 180; height: 40; + opacity: PathView.opacity + Column { + x: 5; y: 5 + Text { text: 'Name: ' + name } + Text { text: 'Number: ' + number } + } + } + } + + PathView { + snapPosition: 0.1 + dragMargin: 5.0 + id: pathView + objectName: "pathView" + anchors.fill: parent + model: listModel + delegate: myDelegate + focus: true + path: Path { + id: myPath + objectName: "path" + startX: 220; startY: 200 + PathAttribute { name: "opacity"; value: 1.0; objectName: "pathAttribute"; } + PathQuad { x: 220; y: 25; controlX: 260; controlY: 75 } + PathAttribute { name: "opacity"; value: 0.3 } + PathQuad { x: 220; y: 200; controlX: -20; controlY: 75 } + } + Timer { + interval: 2000; running: true; repeat: true + onTriggered: { + if (pathView.path == alternatePath) + pathView.path = myPath; + else + pathView.path = alternatePath; + } + } + } + + data:[ + ListModel { + id: listModel + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + }, + ListModel { + objectName: "alternateModel" + ListElement { + name: "Jack" + number: "555 8426" + } + ListElement { + name: "Mary" + number: "555 3264" + } + }, + Path { + id: alternatePath + objectName: "alternatePath" + startX: 100; startY: 40 + PathAttribute { name: "opacity"; value: 0.0 } + PathLine { x: 100; y: 160 } + PathAttribute { name: "opacity"; value: 0.2 } + PathLine { x: 300; y: 160 } + PathAttribute { name: "opacity"; value: 0.0 } + PathLine { x: 300; y: 40 } + PathAttribute { name: "opacity"; value: 0.2 } + PathLine { x: 100; y: 40 } + } + ] +} + + diff --git a/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp b/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp index 79bc607..fa4e9d3 100644 --- a/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp +++ b/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp @@ -38,20 +38,23 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ -#include -#include -#include -#include -#include + +#include +#include #include #include -#include +#include +#include +#include +#include #include #include +#include +#include #include #include #include -#include + #include "../../../shared/util.h" class tst_QDeclarativePathView : public QObject @@ -69,6 +72,11 @@ private slots: void path(); void pathMoved(); void resetModel(); + void propertyChanges(); + void pathChanges(); + void componentChanges(); + void modelChanges(); + private: QDeclarativeView *createView(); @@ -120,7 +128,7 @@ public: setRoleNames(roles); } - int rowCount(const QModelIndex &parent=QModelIndex()) const { return list.count(); } + int rowCount(const QModelIndex &parent=QModelIndex()) const { Q_UNUSED(parent); return list.count(); } QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const { QVariant rv; if (role == Name) @@ -465,6 +473,149 @@ void tst_QDeclarativePathView::resetModel() } } +void tst_QDeclarativePathView::propertyChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QSignalSpy snapPositionSpy(pathView, SIGNAL(snapPositionChanged())); + QSignalSpy dragMarginSpy(pathView, SIGNAL(dragMarginChanged())); + + QCOMPARE(pathView->snapPosition(), 0.1); + QCOMPARE(pathView->dragMargin(), 5.0); + + pathView->setSnapPosition(0.4); + pathView->setDragMargin(20.0); + + QCOMPARE(pathView->snapPosition(), 0.4); + QCOMPARE(pathView->dragMargin(), 20.0); + + QCOMPARE(snapPositionSpy.count(), 1); + QCOMPARE(dragMarginSpy.count(), 1); + + pathView->setSnapPosition(0.4); + pathView->setDragMargin(20.0); + + QCOMPARE(snapPositionSpy.count(), 1); + QCOMPARE(dragMarginSpy.count(), 1); + delete canvas; +} + +void tst_QDeclarativePathView::pathChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QDeclarativePath *path = canvas->rootObject()->findChild("path"); + QVERIFY(path); + + QSignalSpy startXSpy(path, SIGNAL(startXChanged())); + QSignalSpy startYSpy(path, SIGNAL(startYChanged())); + + QCOMPARE(path->startX(), 220.0); + QCOMPARE(path->startY(), 200.0); + + path->setStartX(240.0); + path->setStartY(220.0); + + QCOMPARE(path->startX(), 240.0); + QCOMPARE(path->startY(), 220.0); + + QCOMPARE(startXSpy.count(),1); + QCOMPARE(startYSpy.count(),1); + + path->setStartX(240); + path->setStartY(220); + + QCOMPARE(startXSpy.count(),1); + QCOMPARE(startYSpy.count(),1); + + QDeclarativePath *alternatePath = canvas->rootObject()->findChild("alternatePath"); + QVERIFY(alternatePath); + + QSignalSpy pathSpy(pathView, SIGNAL(pathChanged())); + + QCOMPARE(pathView->path(), path); + + pathView->setPath(alternatePath); + QCOMPARE(pathView->path(), alternatePath); + QCOMPARE(pathSpy.count(),1); + + pathView->setPath(alternatePath); + QCOMPARE(pathSpy.count(),1); + + QDeclarativePathAttribute *pathAttribute = canvas->rootObject()->findChild("pathAttribute"); + QVERIFY(pathAttribute); + + QSignalSpy nameSpy(pathAttribute, SIGNAL(nameChanged())); + QCOMPARE(pathAttribute->name(), QString("opacity")); + + pathAttribute->setName("scale"); + QCOMPARE(pathAttribute->name(), QString("scale")); + QCOMPARE(nameSpy.count(),1); + + pathAttribute->setName("scale"); + QCOMPARE(nameSpy.count(),1); + delete canvas; +} + +void tst_QDeclarativePathView::componentChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QDeclarativeComponent delegateComponent(canvas->engine()); + delegateComponent.setData("import Qt 4.6; Text { text: 'Name: ' + name }", QUrl::fromLocalFile("")); + + QSignalSpy delegateSpy(pathView, SIGNAL(delegateChanged())); + + pathView->setDelegate(&delegateComponent); + QCOMPARE(pathView->delegate(), &delegateComponent); + QCOMPARE(delegateSpy.count(),1); + + pathView->setDelegate(&delegateComponent); + QCOMPARE(delegateSpy.count(),1); + delete canvas; +} + +void tst_QDeclarativePathView::modelChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QDeclarativeListModel *alternateModel = canvas->rootObject()->findChild("alternateModel"); + QVERIFY(alternateModel); + QVariant modelVariant = QVariant::fromValue(alternateModel); + QSignalSpy modelSpy(pathView, SIGNAL(modelChanged())); + + pathView->setModel(modelVariant); + QCOMPARE(pathView->model(), modelVariant); + QCOMPARE(modelSpy.count(),1); + + pathView->setModel(modelVariant); + QCOMPARE(modelSpy.count(),1); + + pathView->setModel(QVariant()); + QCOMPARE(modelSpy.count(),2); + + delete canvas; +} QDeclarativeView *tst_QDeclarativePathView::createView() { -- cgit v0.12 From e71f8823d22c99a4da7de4f49463a05427186c0f Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Mon, 1 Mar 2010 15:55:03 +1000 Subject: Example of text focus. Task-number: QT-448 --- examples/declarative/focusscope/test5.qml | 83 +++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 examples/declarative/focusscope/test5.qml diff --git a/examples/declarative/focusscope/test5.qml b/examples/declarative/focusscope/test5.qml new file mode 100644 index 0000000..da98350 --- /dev/null +++ b/examples/declarative/focusscope/test5.qml @@ -0,0 +1,83 @@ +import Qt 4.6 + +Rectangle { + color: "white" + width: 800 + height: 600 + + Keys.onReturnPressed: console.log("Error - Root") + + FocusScope { + id: myScope + focus: true + + Keys.onReturnPressed: console.log("Error - FocusScope") + + Rectangle { + height: 120 + width: 420 + + color: "transparent" + border.width: 5 + border.color: myScope.wantsFocus?"blue":"black" + + Rectangle { + x: 10; y: 10 + width: 100; height: 100; color: "green" + border.width: 5 + border.color: item1.wantsFocus?"blue":"black" + } + + TextEdit { + id: item1 + x: 20; y: 20 + width: 90; height: 90 + color: "white" + font.pixelSize: 20 + Keys.onReturnPressed: console.log("Top Left"); + KeyNavigation.right: item2 + focus: true + wrap: true + text: "Box 1" + } + + Rectangle { + id: item2 + x: 310; y: 10 + width: 100; height: 100; color: "green" + border.width: 5 + border.color: wantsFocus?"blue":"black" + KeyNavigation.left: item1 + Keys.onReturnPressed: console.log("Top Right"); + + Rectangle { + width: 50; height: 50; anchors.centerIn: parent + color: parent.focus?"red":"transparent" + } + } + } + KeyNavigation.down: item3 + } + + Text { x:100; y:170; text: "Blue border indicates scoped focus\nBlack border indicates NOT scoped focus\nRed box or flashing cursor indicates active focus\nUse arrow keys to navigate\nPress Ctrl-Return to print currently focused item" } + + Rectangle { + x: 10; y: 300 + width: 100; height: 100; color: "green" + border.width: 5 + border.color: item3.wantsFocus?"blue":"black" + } + + TextEdit { + id: item3 + x: 20; y: 310 + width: 90; height: 90 + color: "white" + font.pixelSize: 20 + text: "Box 3" + + Keys.onReturnPressed: console.log("Bottom Left"); + KeyNavigation.up: myScope + wrap: true + } +} -- cgit v0.12 From 05f9a6aa5d6e4f20eb4dacff3acea9d186867ab1 Mon Sep 17 00:00:00 2001 From: Joona Petrell Date: Fri, 26 Feb 2010 16:34:28 +1000 Subject: Add NOTIFY signals to list, grid and path views Reviewed-by: akennedy --- .../graphicsitems/qdeclarativegridview.cpp | 12 +- .../graphicsitems/qdeclarativegridview_p.h | 20 ++- .../graphicsitems/qdeclarativelistview.cpp | 24 ++- .../graphicsitems/qdeclarativelistview_p.h | 38 +++-- src/declarative/graphicsitems/qdeclarativepath.cpp | 11 +- src/declarative/graphicsitems/qdeclarativepath_p.h | 11 +- .../graphicsitems/qdeclarativepathview.cpp | 26 +++- .../graphicsitems/qdeclarativepathview_p.h | 18 ++- .../qdeclarativegridview/data/propertychanges.qml | 69 +++++++++ .../tst_qdeclarativegridview.cpp | 122 ++++++++++++++- .../qdeclarativelistview/data/propertychanges.qml | 71 +++++++++ .../tst_qdeclarativelistview.cpp | 168 +++++++++++++++++++-- .../qdeclarativepathview/data/displaypath.qml | 2 +- .../qdeclarativepathview/data/pathview.qml | 2 +- .../qdeclarativepathview/data/pathview3.qml | 2 +- .../qdeclarativepathview/data/propertychanges.qml | 115 ++++++++++++++ .../tst_qdeclarativepathview.cpp | 167 +++++++++++++++++++- 17 files changed, 818 insertions(+), 60 deletions(-) create mode 100644 tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml create mode 100644 tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml create mode 100644 tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml diff --git a/src/declarative/graphicsitems/qdeclarativegridview.cpp b/src/declarative/graphicsitems/qdeclarativegridview.cpp index 8d778f8..090c46d 100644 --- a/src/declarative/graphicsitems/qdeclarativegridview.cpp +++ b/src/declarative/graphicsitems/qdeclarativegridview.cpp @@ -619,7 +619,7 @@ void QDeclarativeGridViewPrivate::createHighlight() } } if (changed) - emit q->highlightChanged(); + emit q->highlightItemChanged(); } void QDeclarativeGridViewPrivate::updateHighlight() @@ -785,6 +785,8 @@ QVariant QDeclarativeGridView::model() const void QDeclarativeGridView::setModel(const QVariant &model) { Q_D(QDeclarativeGridView); + if (d->modelVariant == model) + return; if (d->model) { disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int))); disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int))); @@ -829,6 +831,7 @@ void QDeclarativeGridView::setModel(const QVariant &model) connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*))); emit countChanged(); } + emit modelChanged(); } /*! @@ -872,6 +875,7 @@ void QDeclarativeGridView::setDelegate(QDeclarativeComponent *delegate) d->moveReason = QDeclarativeGridViewPrivate::SetIndex; d->updateCurrent(d->currentIndex); } + emit delegateChanged(); } } @@ -967,6 +971,7 @@ void QDeclarativeGridView::setHighlight(QDeclarativeComponent *highlight) if (highlight != d->highlightComponent) { d->highlightComponent = highlight; d->updateCurrent(d->currentIndex); + emit highlightChanged(); } } @@ -1040,6 +1045,7 @@ void QDeclarativeGridView::setFlow(Flow flow) d->updateGrid(); refill(); d->updateCurrent(d->currentIndex); + emit flowChanged(); } } @@ -1059,7 +1065,10 @@ bool QDeclarativeGridView::isWrapEnabled() const void QDeclarativeGridView::setWrapEnabled(bool wrap) { Q_D(QDeclarativeGridView); + if (d->wrap == wrap) + return; d->wrap = wrap; + emit keyNavigationWrapsChanged(); } /*! @@ -1083,6 +1092,7 @@ void QDeclarativeGridView::setCacheBuffer(int buffer) d->buffer = buffer; if (isComponentComplete()) refill(); + emit cacheBufferChanged(); } } diff --git a/src/declarative/graphicsitems/qdeclarativegridview_p.h b/src/declarative/graphicsitems/qdeclarativegridview_p.h index b488475..d463a46 100644 --- a/src/declarative/graphicsitems/qdeclarativegridview_p.h +++ b/src/declarative/graphicsitems/qdeclarativegridview_p.h @@ -57,19 +57,19 @@ class Q_DECLARATIVE_EXPORT QDeclarativeGridView : public QDeclarativeFlickable Q_OBJECT Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeGridView) - Q_PROPERTY(QVariant model READ model WRITE setModel) - Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate) + Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged) + Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(QDeclarativeItem *currentItem READ currentItem NOTIFY currentIndexChanged) Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight) - Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightChanged) + Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight NOTIFY highlightChanged) + Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightItemChanged) Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem) - Q_PROPERTY(Flow flow READ flow WRITE setFlow) - Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled) - Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer) + Q_PROPERTY(Flow flow READ flow WRITE setFlow NOTIFY flowChanged) + Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled NOTIFY keyNavigationWrapsChanged) + Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer NOTIFY cacheBufferChanged) Q_PROPERTY(int cellWidth READ cellWidth WRITE setCellWidth NOTIFY cellWidthChanged) Q_PROPERTY(int cellHeight READ cellHeight WRITE setCellHeight NOTIFY cellHeightChanged) Q_CLASSINFO("DefaultProperty", "data") @@ -129,6 +129,12 @@ Q_SIGNALS: void cellWidthChanged(); void cellHeightChanged(); void highlightChanged(); + void highlightItemChanged(); + void modelChanged(); + void delegateChanged(); + void flowChanged(); + void keyNavigationWrapsChanged(); + void cacheBufferChanged(); protected: virtual void viewportMoved(); diff --git a/src/declarative/graphicsitems/qdeclarativelistview.cpp b/src/declarative/graphicsitems/qdeclarativelistview.cpp index 02a8493..a05e638 100644 --- a/src/declarative/graphicsitems/qdeclarativelistview.cpp +++ b/src/declarative/graphicsitems/qdeclarativelistview.cpp @@ -817,7 +817,7 @@ void QDeclarativeListViewPrivate::createHighlight() } } if (changed) - emit q->highlightChanged(); + emit q->highlightItemChanged(); } void QDeclarativeListViewPrivate::updateHighlight() @@ -1474,6 +1474,8 @@ QVariant QDeclarativeListView::model() const void QDeclarativeListView::setModel(const QVariant &model) { Q_D(QDeclarativeListView); + if (d->modelVariant == model) + return; if (d->model) { disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int))); disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int))); @@ -1518,6 +1520,7 @@ void QDeclarativeListView::setModel(const QVariant &model) connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*))); emit countChanged(); } + emit modelChanged(); } /*! @@ -1564,6 +1567,7 @@ void QDeclarativeListView::setDelegate(QDeclarativeComponent *delegate) d->updateCurrent(d->currentIndex); } } + emit delegateChanged(); } /*! @@ -1664,6 +1668,7 @@ void QDeclarativeListView::setHighlight(QDeclarativeComponent *highlight) d->createHighlight(); if (d->currentItem) d->updateHighlight(); + emit highlightChanged(); } } @@ -1701,6 +1706,7 @@ void QDeclarativeListView::setHighlightFollowsCurrentItem(bool autoHighlight) d->highlightSizeAnimator->setEnabled(d->autoHighlight); } d->updateHighlight(); + emit highlightFollowsCurrentItemChanged(); } } @@ -1746,8 +1752,11 @@ qreal QDeclarativeListView::preferredHighlightBegin() const void QDeclarativeListView::setPreferredHighlightBegin(qreal start) { Q_D(QDeclarativeListView); + if (d->highlightRangeStart == start) + return; d->highlightRangeStart = start; d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd; + emit preferredHighlightBeginChanged(); } qreal QDeclarativeListView::preferredHighlightEnd() const @@ -1759,8 +1768,11 @@ qreal QDeclarativeListView::preferredHighlightEnd() const void QDeclarativeListView::setPreferredHighlightEnd(qreal end) { Q_D(QDeclarativeListView); + if (d->highlightRangeEnd == end) + return; d->highlightRangeEnd = end; d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd; + emit preferredHighlightEndChanged(); } QDeclarativeListView::HighlightRangeMode QDeclarativeListView::highlightRangeMode() const @@ -1772,8 +1784,11 @@ QDeclarativeListView::HighlightRangeMode QDeclarativeListView::highlightRangeMod void QDeclarativeListView::setHighlightRangeMode(HighlightRangeMode mode) { Q_D(QDeclarativeListView); + if (d->highlightRange == mode) + return; d->highlightRange = mode; d->haveHighlightRange = d->highlightRange != NoHighlightRange && d->highlightRangeStart <= d->highlightRangeEnd; + emit highlightRangeModeChanged(); } /*! @@ -1849,7 +1864,10 @@ bool QDeclarativeListView::isWrapEnabled() const void QDeclarativeListView::setWrapEnabled(bool wrap) { Q_D(QDeclarativeListView); + if (d->wrap == wrap) + return; d->wrap = wrap; + emit keyNavigationWrapsChanged(); } /*! @@ -1875,6 +1893,7 @@ void QDeclarativeListView::setCacheBuffer(int b) d->bufferMode = QDeclarativeListViewPrivate::BufferBefore | QDeclarativeListViewPrivate::BufferAfter; refill(); } + emit cacheBufferChanged(); } } @@ -1999,6 +2018,7 @@ void QDeclarativeListView::setSnapMode(SnapMode mode) Q_D(QDeclarativeListView); if (d->snapMode != mode) { d->snapMode = mode; + emit snapModeChanged(); } } @@ -2021,6 +2041,7 @@ void QDeclarativeListView::setFooter(QDeclarativeComponent *footer) d->maxExtentDirty = true; d->updateFooter(); d->updateViewport(); + emit footerChanged(); } } @@ -2044,6 +2065,7 @@ void QDeclarativeListView::setHeader(QDeclarativeComponent *header) d->updateHeader(); d->updateFooter(); d->updateViewport(); + emit headerChanged(); } } diff --git a/src/declarative/graphicsitems/qdeclarativelistview_p.h b/src/declarative/graphicsitems/qdeclarativelistview_p.h index 5e3edb0..f9b7b50 100644 --- a/src/declarative/graphicsitems/qdeclarativelistview_p.h +++ b/src/declarative/graphicsitems/qdeclarativelistview_p.h @@ -91,33 +91,33 @@ class Q_DECLARATIVE_EXPORT QDeclarativeListView : public QDeclarativeFlickable Q_OBJECT Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeListView) - Q_PROPERTY(QVariant model READ model WRITE setModel) - Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate) + Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged) + Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(QDeclarativeItem *currentItem READ currentItem NOTIFY currentIndexChanged) Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight) - Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightChanged) - Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem) + Q_PROPERTY(QDeclarativeComponent *highlight READ highlight WRITE setHighlight NOTIFY highlightChanged) + Q_PROPERTY(QDeclarativeItem *highlightItem READ highlightItem NOTIFY highlightItemChanged) + Q_PROPERTY(bool highlightFollowsCurrentItem READ highlightFollowsCurrentItem WRITE setHighlightFollowsCurrentItem NOTIFY highlightFollowsCurrentItemChanged) Q_PROPERTY(qreal highlightMoveSpeed READ highlightMoveSpeed WRITE setHighlightMoveSpeed NOTIFY highlightMoveSpeedChanged) Q_PROPERTY(qreal highlightResizeSpeed READ highlightResizeSpeed WRITE setHighlightResizeSpeed NOTIFY highlightResizeSpeedChanged) - Q_PROPERTY(qreal preferredHighlightBegin READ preferredHighlightBegin WRITE setPreferredHighlightBegin) - Q_PROPERTY(qreal preferredHighlightEnd READ preferredHighlightEnd WRITE setPreferredHighlightEnd) - Q_PROPERTY(HighlightRangeMode highlightRangeMode READ highlightRangeMode WRITE setHighlightRangeMode) + Q_PROPERTY(qreal preferredHighlightBegin READ preferredHighlightBegin WRITE setPreferredHighlightBegin NOTIFY preferredHighlightBeginChanged) + Q_PROPERTY(qreal preferredHighlightEnd READ preferredHighlightEnd WRITE setPreferredHighlightEnd NOTIFY preferredHighlightEndChanged) + Q_PROPERTY(HighlightRangeMode highlightRangeMode READ highlightRangeMode WRITE setHighlightRangeMode NOTIFY highlightRangeModeChanged) Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing NOTIFY spacingChanged) Q_PROPERTY(Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged) - Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled) - Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer) + Q_PROPERTY(bool keyNavigationWraps READ isWrapEnabled WRITE setWrapEnabled NOTIFY keyNavigationWrapsChanged) + Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer NOTIFY cacheBufferChanged) Q_PROPERTY(QDeclarativeViewSection *section READ sectionCriteria CONSTANT) Q_PROPERTY(QString currentSection READ currentSection NOTIFY currentSectionChanged) - Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode) + Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode NOTIFY snapModeChanged) - Q_PROPERTY(QDeclarativeComponent *header READ header WRITE setHeader) - Q_PROPERTY(QDeclarativeComponent *footer READ footer WRITE setFooter) + Q_PROPERTY(QDeclarativeComponent *header READ header WRITE setHeader NOTIFY headerChanged) + Q_PROPERTY(QDeclarativeComponent *footer READ footer WRITE setFooter NOTIFY footerChanged) Q_ENUMS(HighlightRangeMode) Q_ENUMS(Orientation) @@ -205,6 +205,18 @@ Q_SIGNALS: void highlightMoveSpeedChanged(); void highlightResizeSpeedChanged(); void highlightChanged(); + void highlightItemChanged(); + void modelChanged(); + void delegateChanged(); + void highlightFollowsCurrentItemChanged(); + void preferredHighlightBeginChanged(); + void preferredHighlightEndChanged(); + void highlightRangeModeChanged(); + void keyNavigationWrapsChanged(); + void cacheBufferChanged(); + void snapModeChanged(); + void headerChanged(); + void footerChanged(); protected: virtual void viewportMoved(); diff --git a/src/declarative/graphicsitems/qdeclarativepath.cpp b/src/declarative/graphicsitems/qdeclarativepath.cpp index 48f112a..80586b8 100644 --- a/src/declarative/graphicsitems/qdeclarativepath.cpp +++ b/src/declarative/graphicsitems/qdeclarativepath.cpp @@ -114,7 +114,10 @@ qreal QDeclarativePath::startX() const void QDeclarativePath::setStartX(qreal x) { Q_D(QDeclarativePath); + if (qFuzzyCompare(x, d->startX)) + return; d->startX = x; + emit startXChanged(); } qreal QDeclarativePath::startY() const @@ -126,7 +129,10 @@ qreal QDeclarativePath::startY() const void QDeclarativePath::setStartY(qreal y) { Q_D(QDeclarativePath); + if (qFuzzyCompare(y, d->startY)) + return; d->startY = y; + emit startYChanged(); } /*! @@ -522,7 +528,10 @@ QString QDeclarativePathAttribute::name() const void QDeclarativePathAttribute::setName(const QString &name) { - _name = name; + if (_name == name) + return; + _name = name; + emit nameChanged(); } /*! diff --git a/src/declarative/graphicsitems/qdeclarativepath_p.h b/src/declarative/graphicsitems/qdeclarativepath_p.h index b3139f8..d7cfca1 100644 --- a/src/declarative/graphicsitems/qdeclarativepath_p.h +++ b/src/declarative/graphicsitems/qdeclarativepath_p.h @@ -67,7 +67,7 @@ class Q_DECLARATIVE_EXPORT QDeclarativePathAttribute : public QDeclarativePathEl { Q_OBJECT - Q_PROPERTY(QString name READ name WRITE setName) + Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY changed) public: QDeclarativePathAttribute(QObject *parent=0) : QDeclarativePathElement(parent), _value(0) {} @@ -79,6 +79,9 @@ public: qreal value() const; void setValue(qreal value); +Q_SIGNALS: + void nameChanged(); + private: QString _name; qreal _value; @@ -190,8 +193,8 @@ class Q_DECLARATIVE_EXPORT QDeclarativePath : public QObject, public QDeclarativ Q_INTERFACES(QDeclarativeParserStatus) Q_PROPERTY(QDeclarativeListProperty pathElements READ pathElements) - Q_PROPERTY(qreal startX READ startX WRITE setStartX) - Q_PROPERTY(qreal startY READ startY WRITE setStartY) + Q_PROPERTY(qreal startX READ startX WRITE setStartX NOTIFY startXChanged) + Q_PROPERTY(qreal startY READ startY WRITE setStartY NOTIFY startYChanged) Q_PROPERTY(bool closed READ isClosed NOTIFY changed) Q_CLASSINFO("DefaultProperty", "pathElements") Q_INTERFACES(QDeclarativeParserStatus) @@ -216,6 +219,8 @@ public: Q_SIGNALS: void changed(); + void startXChanged(); + void startYChanged(); protected: virtual void componentComplete(); diff --git a/src/declarative/graphicsitems/qdeclarativepathview.cpp b/src/declarative/graphicsitems/qdeclarativepathview.cpp index f1b0213..50aa9ef 100644 --- a/src/declarative/graphicsitems/qdeclarativepathview.cpp +++ b/src/declarative/graphicsitems/qdeclarativepathview.cpp @@ -203,6 +203,9 @@ QVariant QDeclarativePathView::model() const void QDeclarativePathView::setModel(const QVariant &model) { Q_D(QDeclarativePathView); + if (d->modelVariant == model) + return; + if (d->model) { disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int))); disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int))); @@ -242,6 +245,7 @@ void QDeclarativePathView::setModel(const QVariant &model) d->pathOffset = 0; d->regenerate(); d->fixOffset(); + emit modelChanged(); } /*! @@ -269,9 +273,12 @@ QDeclarativePath *QDeclarativePathView::path() const void QDeclarativePathView::setPath(QDeclarativePath *path) { Q_D(QDeclarativePathView); + if (d->path == path) + return; d->path = path; connect(d->path, SIGNAL(changed()), this, SLOT(refill())); d->regenerate(); + emit pathChanged(); } /*! @@ -333,7 +340,7 @@ void QDeclarativePathViewPrivate::setOffset(qreal o) /*! \qmlproperty real PathView::snapPosition - This property determines the position (0-100) the nearest item will snap to. + This property determines the position (0.0-1.0) the nearest item will snap to. */ qreal QDeclarativePathView::snapPosition() const { @@ -344,8 +351,12 @@ qreal QDeclarativePathView::snapPosition() const void QDeclarativePathView::setSnapPosition(qreal pos) { Q_D(QDeclarativePathView); - d->snapPos = pos/100; + qreal normalizedPos = pos - int(pos); + if (qFuzzyCompare(normalizedPos, d->snapPos)) + return; + d->snapPos = normalizedPos; d->fixOffset(); + emit snapPositionChanged(); } /*! @@ -365,7 +376,10 @@ qreal QDeclarativePathView::dragMargin() const void QDeclarativePathView::setDragMargin(qreal dragMargin) { Q_D(QDeclarativePathView); + if (d->dragMargin == dragMargin) + return; d->dragMargin = dragMargin; + emit dragMarginChanged(); } /*! @@ -392,16 +406,19 @@ QDeclarativeComponent *QDeclarativePathView::delegate() const return 0; } -void QDeclarativePathView::setDelegate(QDeclarativeComponent *c) +void QDeclarativePathView::setDelegate(QDeclarativeComponent *delegate) { Q_D(QDeclarativePathView); + if (delegate == this->delegate()) + return; if (!d->ownModel) { d->model = new QDeclarativeVisualDataModel(qmlContext(this)); d->ownModel = true; } if (QDeclarativeVisualDataModel *dataModel = qobject_cast(d->model)) { - dataModel->setDelegate(c); + dataModel->setDelegate(delegate); d->regenerate(); + emit delegateChanged(); } } @@ -422,6 +439,7 @@ void QDeclarativePathView::setPathItemCount(int i) return; d->pathItems = i; d->regenerate(); + pathItemCountChanged(); } QPointF QDeclarativePathViewPrivate::pointNear(const QPointF &point, qreal *nearPercent) const diff --git a/src/declarative/graphicsitems/qdeclarativepathview_p.h b/src/declarative/graphicsitems/qdeclarativepathview_p.h index 709a4fc..df9c6ae 100644 --- a/src/declarative/graphicsitems/qdeclarativepathview_p.h +++ b/src/declarative/graphicsitems/qdeclarativepathview_p.h @@ -56,15 +56,15 @@ class Q_DECLARATIVE_EXPORT QDeclarativePathView : public QDeclarativeItem { Q_OBJECT - Q_PROPERTY(QVariant model READ model WRITE setModel) - Q_PROPERTY(QDeclarativePath *path READ path WRITE setPath) + Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged) + Q_PROPERTY(QDeclarativePath *path READ path WRITE setPath NOTIFY pathChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(qreal offset READ offset WRITE setOffset NOTIFY offsetChanged) - Q_PROPERTY(qreal snapPosition READ snapPosition WRITE setSnapPosition) - Q_PROPERTY(qreal dragMargin READ dragMargin WRITE setDragMargin) + Q_PROPERTY(qreal snapPosition READ snapPosition WRITE setSnapPosition NOTIFY snapPositionChanged) + Q_PROPERTY(qreal dragMargin READ dragMargin WRITE setDragMargin NOTIFY dragMarginChanged) Q_PROPERTY(int count READ count) - Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate) - Q_PROPERTY(int pathItemCount READ pathItemCount WRITE setPathItemCount) + Q_PROPERTY(QDeclarativeComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged) + Q_PROPERTY(int pathItemCount READ pathItemCount WRITE setPathItemCount NOTIFY pathItemCountChanged) public: QDeclarativePathView(QDeclarativeItem *parent=0); @@ -101,6 +101,12 @@ public: Q_SIGNALS: void currentIndexChanged(); void offsetChanged(); + void modelChanged(); + void pathChanged(); + void dragMarginChanged(); + void snapPositionChanged(); + void delegateChanged(); + void pathItemCountChanged(); protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); diff --git a/tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml new file mode 100644 index 0000000..da2e8d0 --- /dev/null +++ b/tests/auto/declarative/qdeclarativegridview/data/propertychanges.qml @@ -0,0 +1,69 @@ +import Qt 4.6 + +Rectangle { + width: 360; height: 120; color: "white" + Component { + id: delegate + Item { + id: wrapper + width: 180; height: 40; + Column { + x: 5; y: 5 + Text { text: 'Name: ' + name } + Text { text: 'Number: ' + number } + } + } + } + Component { + id: highlightRed + Rectangle { + color: "red" + radius: 10 + opacity: 0.5 + } + } + GridView { + cellWidth:180 + cellHeight:40 + objectName: "gridView" + anchors.fill: parent + model: listModel + delegate: delegate + highlight: highlightRed + focus: true + keyNavigationWraps: true + cacheBuffer: 10 + flow: GridView.LeftToRight + } + + data:[ + ListModel { + id: listModel + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + }, + ListModel { + objectName: "alternateModel" + ListElement { + name: "Jack" + number: "555 8426" + } + ListElement { + name: "Mary" + number: "555 3264" + } + } + ] +} + + \ No newline at end of file diff --git a/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp b/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp index 7a6a060..5d57bb4 100644 --- a/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp +++ b/tests/auto/declarative/qdeclarativegridview/tst_qdeclarativegridview.cpp @@ -39,10 +39,8 @@ ** ****************************************************************************/ -#include -#include -#include #include +<<<<<<< HEAD #include #include #include @@ -50,6 +48,18 @@ #include #include #include +======= +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +>>>>>>> Add NOTIFY signals to list, grid and path views class tst_QDeclarativeGridView : public QObject { @@ -67,6 +77,9 @@ private slots: void currentIndex(); void defaultValues(); void properties(); + void propertyChanges(); + void componentChanges(); + void modelChanges(); void positionViewAtIndex(); void resetModel(); void QTBUG_8456(); @@ -92,7 +105,7 @@ public: setRoleNames(roles); } - int rowCount(const QModelIndex &parent=QModelIndex()) const { return list.count(); } + int rowCount(const QModelIndex &parent=QModelIndex()) const { Q_UNUSED(parent); return list.count(); } QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const { QVariant rv; if (role == Name) @@ -803,6 +816,107 @@ void tst_QDeclarativeGridView::properties() delete obj; } +void tst_QDeclarativeGridView::propertyChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeGridView *gridView = canvas->rootObject()->findChild("gridView"); + QVERIFY(gridView); + + QSignalSpy keyNavigationWrapsSpy(gridView, SIGNAL(keyNavigationWrapsChanged())); + QSignalSpy cacheBufferSpy(gridView, SIGNAL(cacheBufferChanged())); + QSignalSpy flowSpy(gridView, SIGNAL(flowChanged())); + + QCOMPARE(gridView->isWrapEnabled(), true); + QCOMPARE(gridView->cacheBuffer(), 10); + QCOMPARE(gridView->flow(), QDeclarativeGridView::LeftToRight); + + gridView->setWrapEnabled(false); + gridView->setCacheBuffer(3); + gridView->setFlow(QDeclarativeGridView::TopToBottom); + + QCOMPARE(gridView->isWrapEnabled(), false); + QCOMPARE(gridView->cacheBuffer(), 3); + QCOMPARE(gridView->flow(), QDeclarativeGridView::TopToBottom); + + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(flowSpy.count(),1); + + gridView->setWrapEnabled(false); + gridView->setCacheBuffer(3); + gridView->setFlow(QDeclarativeGridView::TopToBottom); + + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(flowSpy.count(),1); + + delete canvas; +} + +void tst_QDeclarativeGridView::componentChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeGridView *gridView = canvas->rootObject()->findChild("gridView"); + QVERIFY(gridView); + + QDeclarativeComponent component(canvas->engine()); + component.setData("import Qt 4.6; Rectangle { color: \"blue\"; }", QUrl::fromLocalFile("")); + + QDeclarativeComponent delegateComponent(canvas->engine()); + delegateComponent.setData("import Qt 4.6; Text { text: 'Name: ' + name }", QUrl::fromLocalFile("")); + + QSignalSpy highlightSpy(gridView, SIGNAL(highlightChanged())); + QSignalSpy delegateSpy(gridView, SIGNAL(delegateChanged())); + + gridView->setHighlight(&component); + gridView->setDelegate(&delegateComponent); + + QCOMPARE(gridView->highlight(), &component); + QCOMPARE(gridView->delegate(), &delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + + gridView->setHighlight(&component); + gridView->setDelegate(&delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + delete canvas; +} + +void tst_QDeclarativeGridView::modelChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeGridView *gridView = canvas->rootObject()->findChild("gridView"); + QVERIFY(gridView); + + QDeclarativeListModel *alternateModel = canvas->rootObject()->findChild("alternateModel"); + QVERIFY(alternateModel); + QVariant modelVariant = QVariant::fromValue(alternateModel); + QSignalSpy modelSpy(gridView, SIGNAL(modelChanged())); + + gridView->setModel(modelVariant); + QCOMPARE(gridView->model(), modelVariant); + QCOMPARE(modelSpy.count(),1); + + gridView->setModel(modelVariant); + QCOMPARE(modelSpy.count(),1); + + gridView->setModel(QVariant()); + QCOMPARE(modelSpy.count(),2); + delete canvas; +} + void tst_QDeclarativeGridView::positionViewAtIndex() { QDeclarativeView *canvas = createView(); diff --git a/tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml new file mode 100644 index 0000000..a41f003 --- /dev/null +++ b/tests/auto/declarative/qdeclarativelistview/data/propertychanges.qml @@ -0,0 +1,71 @@ +import Qt 4.6 + +Rectangle { + width: 180; height: 120; color: "white" + Component { + id: delegate + Item { + id: wrapper + width: 180; height: 40; + Column { + x: 5; y: 5 + Text { text: 'Name: ' + name } + Text { text: 'Number: ' + number } + } + } + } + Component { + id: highlightRed + Rectangle { + color: "red" + radius: 10 + opacity: 0.5 + } + } + ListView { + objectName: "listView" + anchors.fill: parent + model: listModel + delegate: delegate + highlight: highlightRed + focus: true + highlightFollowsCurrentItem: true + preferredHighlightBegin: 0.0 + preferredHighlightEnd: 0.0 + highlightRangeMode: ListView.ApplyRange + keyNavigationWraps: true + cacheBuffer: 10 + snapMode: ListView.SnapToItem + } + + data:[ + ListModel { + id: listModel + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + }, + ListModel { + objectName: "alternateModel" + ListElement { + name: "Jack" + number: "555 8426" + } + ListElement { + name: "Mary" + number: "555 3264" + } + } + ] +} + + \ No newline at end of file diff --git a/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp b/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp index f15f26b..a36224f 100644 --- a/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp +++ b/tests/auto/declarative/qdeclarativelistview/tst_qdeclarativelistview.cpp @@ -38,15 +38,18 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ + #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include class tst_QDeclarativeListView : public QObject { @@ -82,6 +85,9 @@ private slots: void cacheBuffer(); void positionViewAtIndex(); void resetModel(); + void propertyChanges(); + void componentChanges(); + void modelChanges(); private: template void items(); @@ -240,7 +246,7 @@ public: setRoleNames(roles); } - int rowCount(const QModelIndex &parent=QModelIndex()) const { return list.count(); } + int rowCount(const QModelIndex &parent=QModelIndex()) const { Q_UNUSED(parent); return list.count(); } QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const { QVariant rv; if (role == Name) @@ -379,6 +385,7 @@ void tst_QDeclarativeListView::items() delete canvas; } + template void tst_QDeclarativeListView::changed() { @@ -1275,6 +1282,149 @@ void tst_QDeclarativeListView::resetModel() } } +void tst_QDeclarativeListView::propertyChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeListView *listView = canvas->rootObject()->findChild("listView"); + QVERIFY(listView); + + QSignalSpy highlightFollowsCurrentItemSpy(listView, SIGNAL(highlightFollowsCurrentItemChanged())); + QSignalSpy preferredHighlightBeginSpy(listView, SIGNAL(preferredHighlightBeginChanged())); + QSignalSpy preferredHighlightEndSpy(listView, SIGNAL(preferredHighlightEndChanged())); + QSignalSpy highlightRangeModeSpy(listView, SIGNAL(highlightRangeModeChanged())); + QSignalSpy keyNavigationWrapsSpy(listView, SIGNAL(keyNavigationWrapsChanged())); + QSignalSpy cacheBufferSpy(listView, SIGNAL(cacheBufferChanged())); + QSignalSpy snapModeSpy(listView, SIGNAL(snapModeChanged())); + + QCOMPARE(listView->highlightFollowsCurrentItem(), true); + QCOMPARE(listView->preferredHighlightBegin(), 0.0); + QCOMPARE(listView->preferredHighlightEnd(), 0.0); + QCOMPARE(listView->highlightRangeMode(), QDeclarativeListView::ApplyRange); + QCOMPARE(listView->isWrapEnabled(), true); + QCOMPARE(listView->cacheBuffer(), 10); + QCOMPARE(listView->snapMode(), QDeclarativeListView::SnapToItem); + + listView->setHighlightFollowsCurrentItem(false); + listView->setPreferredHighlightBegin(1.0); + listView->setPreferredHighlightEnd(1.0); + listView->setHighlightRangeMode(QDeclarativeListView::StrictlyEnforceRange); + listView->setWrapEnabled(false); + listView->setCacheBuffer(3); + listView->setSnapMode(QDeclarativeListView::SnapOneItem); + + QCOMPARE(listView->highlightFollowsCurrentItem(), false); + QCOMPARE(listView->preferredHighlightBegin(), 1.0); + QCOMPARE(listView->preferredHighlightEnd(), 1.0); + QCOMPARE(listView->highlightRangeMode(), QDeclarativeListView::StrictlyEnforceRange); + QCOMPARE(listView->isWrapEnabled(), false); + QCOMPARE(listView->cacheBuffer(), 3); + QCOMPARE(listView->snapMode(), QDeclarativeListView::SnapOneItem); + + QCOMPARE(highlightFollowsCurrentItemSpy.count(),1); + QCOMPARE(preferredHighlightBeginSpy.count(),1); + QCOMPARE(preferredHighlightEndSpy.count(),1); + QCOMPARE(highlightRangeModeSpy.count(),1); + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(snapModeSpy.count(),1); + + listView->setHighlightFollowsCurrentItem(false); + listView->setPreferredHighlightBegin(1.0); + listView->setPreferredHighlightEnd(1.0); + listView->setHighlightRangeMode(QDeclarativeListView::StrictlyEnforceRange); + listView->setWrapEnabled(false); + listView->setCacheBuffer(3); + listView->setSnapMode(QDeclarativeListView::SnapOneItem); + + QCOMPARE(highlightFollowsCurrentItemSpy.count(),1); + QCOMPARE(preferredHighlightBeginSpy.count(),1); + QCOMPARE(preferredHighlightEndSpy.count(),1); + QCOMPARE(highlightRangeModeSpy.count(),1); + QCOMPARE(keyNavigationWrapsSpy.count(),1); + QCOMPARE(cacheBufferSpy.count(),1); + QCOMPARE(snapModeSpy.count(),1); + + delete canvas; +} + +void tst_QDeclarativeListView::componentChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeListView *listView = canvas->rootObject()->findChild("listView"); + QVERIFY(listView); + + QDeclarativeComponent component(canvas->engine()); + component.setData("import Qt 4.6; Rectangle { color: \"blue\"; }", QUrl::fromLocalFile("")); + + QDeclarativeComponent delegateComponent(canvas->engine()); + delegateComponent.setData("import Qt 4.6; Text { text: 'Name: ' + name }", QUrl::fromLocalFile("")); + + QSignalSpy highlightSpy(listView, SIGNAL(highlightChanged())); + QSignalSpy delegateSpy(listView, SIGNAL(delegateChanged())); + QSignalSpy headerSpy(listView, SIGNAL(headerChanged())); + QSignalSpy footerSpy(listView, SIGNAL(footerChanged())); + + listView->setHighlight(&component); + listView->setHeader(&component); + listView->setFooter(&component); + listView->setDelegate(&delegateComponent); + + QCOMPARE(listView->highlight(), &component); + QCOMPARE(listView->header(), &component); + QCOMPARE(listView->footer(), &component); + QCOMPARE(listView->delegate(), &delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + QCOMPARE(headerSpy.count(),1); + QCOMPARE(footerSpy.count(),1); + + listView->setHighlight(&component); + listView->setHeader(&component); + listView->setFooter(&component); + listView->setDelegate(&delegateComponent); + + QCOMPARE(highlightSpy.count(),1); + QCOMPARE(delegateSpy.count(),1); + QCOMPARE(headerSpy.count(),1); + QCOMPARE(footerSpy.count(),1); + + delete canvas; +} + +void tst_QDeclarativeListView::modelChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativeListView *listView = canvas->rootObject()->findChild("listView"); + QVERIFY(listView); + + QDeclarativeListModel *alternateModel = canvas->rootObject()->findChild("alternateModel"); + QVERIFY(alternateModel); + QVariant modelVariant = QVariant::fromValue(alternateModel); + QSignalSpy modelSpy(listView, SIGNAL(modelChanged())); + + listView->setModel(modelVariant); + QCOMPARE(listView->model(), modelVariant); + QCOMPARE(modelSpy.count(),1); + + listView->setModel(modelVariant); + QCOMPARE(modelSpy.count(),1); + + listView->setModel(QVariant()); + QCOMPARE(modelSpy.count(),2); + + delete canvas; +} + void tst_QDeclarativeListView::qListModelInterface_items() { items(); diff --git a/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml b/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml index 627f38a..ab1538b 100644 --- a/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml +++ b/tests/auto/declarative/qdeclarativepathview/data/displaypath.qml @@ -33,7 +33,7 @@ Rectangle { height: 320 model: testModel delegate: delegate - snapPosition: 0.01 + snapPosition: 0.0001 path: Path { startY: 120 startX: 160 diff --git a/tests/auto/declarative/qdeclarativepathview/data/pathview.qml b/tests/auto/declarative/qdeclarativepathview/data/pathview.qml index 8fa8d59..c5d88cd 100644 --- a/tests/auto/declarative/qdeclarativepathview/data/pathview.qml +++ b/tests/auto/declarative/qdeclarativepathview/data/pathview.qml @@ -39,7 +39,7 @@ Rectangle { height: 320 model: testModel delegate: delegate - snapPosition: 0.01 + snapPosition: 0.0001 path: Path { startY: 120 startX: 160 diff --git a/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml b/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml index af3ae13..f8ed29f 100644 --- a/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml +++ b/tests/auto/declarative/qdeclarativepathview/data/pathview3.qml @@ -3,7 +3,7 @@ import Qt 4.6 PathView { id: photoPathView y: 100; width: 800; height: 330; pathItemCount: 4; offset: 10 - dragMargin: 24; snapPosition: 50 + dragMargin: 24; snapPosition: 0.50 path: Path { startX: -50; startY: 40; diff --git a/tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml new file mode 100644 index 0000000..db70b7b --- /dev/null +++ b/tests/auto/declarative/qdeclarativepathview/data/propertychanges.qml @@ -0,0 +1,115 @@ +import Qt 4.6 + +Rectangle { + width: 350; height: 220; color: "white" + Component { + id: myDelegate + Item { + id: wrapper + width: 180; height: 40; + opacity: PathView.opacity + Column { + x: 5; y: 5 + Text { text: 'Name: ' + name } + Text { text: 'Number: ' + number } + } + } + } + + PathView { + snapPosition: 0.1 + dragMargin: 5.0 + id: pathView + objectName: "pathView" + anchors.fill: parent + model: listModel + delegate: myDelegate + focus: true + path: Path { + id: myPath + objectName: "path" + startX: 220; startY: 200 + PathAttribute { name: "opacity"; value: 1.0; objectName: "pathAttribute"; } + PathQuad { x: 220; y: 25; controlX: 260; controlY: 75 } + PathAttribute { name: "opacity"; value: 0.3 } + PathQuad { x: 220; y: 200; controlX: -20; controlY: 75 } + } + Timer { + interval: 2000; running: true; repeat: true + onTriggered: { + if (pathView.path == alternatePath) + pathView.path = myPath; + else + pathView.path = alternatePath; + } + } + } + + data:[ + ListModel { + id: listModel + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + ListElement { + name: "Bill Smith" + number: "555 3264" + } + ListElement { + name: "John Brown" + number: "555 8426" + } + ListElement { + name: "Sam Wise" + number: "555 0473" + } + }, + ListModel { + objectName: "alternateModel" + ListElement { + name: "Jack" + number: "555 8426" + } + ListElement { + name: "Mary" + number: "555 3264" + } + }, + Path { + id: alternatePath + objectName: "alternatePath" + startX: 100; startY: 40 + PathAttribute { name: "opacity"; value: 0.0 } + PathLine { x: 100; y: 160 } + PathAttribute { name: "opacity"; value: 0.2 } + PathLine { x: 300; y: 160 } + PathAttribute { name: "opacity"; value: 0.0 } + PathLine { x: 300; y: 40 } + PathAttribute { name: "opacity"; value: 0.2 } + PathLine { x: 100; y: 40 } + } + ] +} + + diff --git a/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp b/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp index 79bc607..fa4e9d3 100644 --- a/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp +++ b/tests/auto/declarative/qdeclarativepathview/tst_qdeclarativepathview.cpp @@ -38,20 +38,23 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ -#include -#include -#include -#include -#include + +#include +#include #include #include -#include +#include +#include +#include +#include #include #include +#include +#include #include #include #include -#include + #include "../../../shared/util.h" class tst_QDeclarativePathView : public QObject @@ -69,6 +72,11 @@ private slots: void path(); void pathMoved(); void resetModel(); + void propertyChanges(); + void pathChanges(); + void componentChanges(); + void modelChanges(); + private: QDeclarativeView *createView(); @@ -120,7 +128,7 @@ public: setRoleNames(roles); } - int rowCount(const QModelIndex &parent=QModelIndex()) const { return list.count(); } + int rowCount(const QModelIndex &parent=QModelIndex()) const { Q_UNUSED(parent); return list.count(); } QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const { QVariant rv; if (role == Name) @@ -465,6 +473,149 @@ void tst_QDeclarativePathView::resetModel() } } +void tst_QDeclarativePathView::propertyChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QSignalSpy snapPositionSpy(pathView, SIGNAL(snapPositionChanged())); + QSignalSpy dragMarginSpy(pathView, SIGNAL(dragMarginChanged())); + + QCOMPARE(pathView->snapPosition(), 0.1); + QCOMPARE(pathView->dragMargin(), 5.0); + + pathView->setSnapPosition(0.4); + pathView->setDragMargin(20.0); + + QCOMPARE(pathView->snapPosition(), 0.4); + QCOMPARE(pathView->dragMargin(), 20.0); + + QCOMPARE(snapPositionSpy.count(), 1); + QCOMPARE(dragMarginSpy.count(), 1); + + pathView->setSnapPosition(0.4); + pathView->setDragMargin(20.0); + + QCOMPARE(snapPositionSpy.count(), 1); + QCOMPARE(dragMarginSpy.count(), 1); + delete canvas; +} + +void tst_QDeclarativePathView::pathChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QDeclarativePath *path = canvas->rootObject()->findChild("path"); + QVERIFY(path); + + QSignalSpy startXSpy(path, SIGNAL(startXChanged())); + QSignalSpy startYSpy(path, SIGNAL(startYChanged())); + + QCOMPARE(path->startX(), 220.0); + QCOMPARE(path->startY(), 200.0); + + path->setStartX(240.0); + path->setStartY(220.0); + + QCOMPARE(path->startX(), 240.0); + QCOMPARE(path->startY(), 220.0); + + QCOMPARE(startXSpy.count(),1); + QCOMPARE(startYSpy.count(),1); + + path->setStartX(240); + path->setStartY(220); + + QCOMPARE(startXSpy.count(),1); + QCOMPARE(startYSpy.count(),1); + + QDeclarativePath *alternatePath = canvas->rootObject()->findChild("alternatePath"); + QVERIFY(alternatePath); + + QSignalSpy pathSpy(pathView, SIGNAL(pathChanged())); + + QCOMPARE(pathView->path(), path); + + pathView->setPath(alternatePath); + QCOMPARE(pathView->path(), alternatePath); + QCOMPARE(pathSpy.count(),1); + + pathView->setPath(alternatePath); + QCOMPARE(pathSpy.count(),1); + + QDeclarativePathAttribute *pathAttribute = canvas->rootObject()->findChild("pathAttribute"); + QVERIFY(pathAttribute); + + QSignalSpy nameSpy(pathAttribute, SIGNAL(nameChanged())); + QCOMPARE(pathAttribute->name(), QString("opacity")); + + pathAttribute->setName("scale"); + QCOMPARE(pathAttribute->name(), QString("scale")); + QCOMPARE(nameSpy.count(),1); + + pathAttribute->setName("scale"); + QCOMPARE(nameSpy.count(),1); + delete canvas; +} + +void tst_QDeclarativePathView::componentChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QDeclarativeComponent delegateComponent(canvas->engine()); + delegateComponent.setData("import Qt 4.6; Text { text: 'Name: ' + name }", QUrl::fromLocalFile("")); + + QSignalSpy delegateSpy(pathView, SIGNAL(delegateChanged())); + + pathView->setDelegate(&delegateComponent); + QCOMPARE(pathView->delegate(), &delegateComponent); + QCOMPARE(delegateSpy.count(),1); + + pathView->setDelegate(&delegateComponent); + QCOMPARE(delegateSpy.count(),1); + delete canvas; +} + +void tst_QDeclarativePathView::modelChanges() +{ + QDeclarativeView *canvas = createView(); + QVERIFY(canvas); + canvas->setSource(QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); + + QDeclarativePathView *pathView = canvas->rootObject()->findChild("pathView"); + QVERIFY(pathView); + + QDeclarativeListModel *alternateModel = canvas->rootObject()->findChild("alternateModel"); + QVERIFY(alternateModel); + QVariant modelVariant = QVariant::fromValue(alternateModel); + QSignalSpy modelSpy(pathView, SIGNAL(modelChanged())); + + pathView->setModel(modelVariant); + QCOMPARE(pathView->model(), modelVariant); + QCOMPARE(modelSpy.count(),1); + + pathView->setModel(modelVariant); + QCOMPARE(modelSpy.count(),1); + + pathView->setModel(QVariant()); + QCOMPARE(modelSpy.count(),2); + + delete canvas; +} QDeclarativeView *tst_QDeclarativePathView::createView() { -- cgit v0.12 From 3507c6fbbb585ea3b7f6a13b16fa216aea4574ab Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 2 Mar 2010 14:35:02 +1000 Subject: Make test more reliable. --- .../qdeclarativeanimations/tst_qdeclarativeanimations.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp b/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp index 53c63b5..0c166df 100644 --- a/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp +++ b/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp @@ -221,17 +221,17 @@ void tst_qdeclarativeanimations::resume() QVERIFY(animation.from() == 10); animation.start(); - QTest::qWait(100); + QTest::qWait(200); animation.pause(); qreal x = rect.x(); - QVERIFY(x != qreal(200)); + QVERIFY(x != qreal(200) && x != qreal(10)); QVERIFY(animation.isRunning()); QVERIFY(animation.isPaused()); animation.resume(); QVERIFY(animation.isRunning()); QVERIFY(!animation.isPaused()); - QTest::qWait(100); + QTest::qWait(200); animation.stop(); QVERIFY(rect.x() > x); } -- cgit v0.12 From 861a9f127e04aa135649ed64f268d72da6a35fd9 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 2 Mar 2010 14:48:07 +1000 Subject: Add autotests for script block scoping. --- .../qdeclarativeecmascript/data/scriptScope.1.qml | 13 ++++++++++ .../qdeclarativeecmascript/data/scriptScope.2.qml | 11 +++++++++ .../qdeclarativeecmascript/data/scriptScope.js | 5 ++++ .../tst_qdeclarativeecmascript.cpp | 28 ++++++++++++++++++++++ 4 files changed, 57 insertions(+) create mode 100644 tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.1.qml create mode 100644 tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.2.qml create mode 100644 tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.js diff --git a/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.1.qml b/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.1.qml new file mode 100644 index 0000000..9b11fa9 --- /dev/null +++ b/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.1.qml @@ -0,0 +1,13 @@ +import Qt.test 1.0 + +MyQmlObject { + property string result + + Script{ + function f() { + result = b + } + + } + onArgumentSignal: f() +} diff --git a/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.2.qml b/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.2.qml new file mode 100644 index 0000000..ec727e2 --- /dev/null +++ b/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.2.qml @@ -0,0 +1,11 @@ +import Qt.test 1.0 + +MyQmlObject { + property string result + property string aProp: "hello" + + Script{ + source: "scriptScope.js" + } + onBasicSignal: f() +} diff --git a/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.js b/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.js new file mode 100644 index 0000000..5689930 --- /dev/null +++ b/tests/auto/declarative/qdeclarativeecmascript/data/scriptScope.js @@ -0,0 +1,5 @@ +var aProp = "world"; + +function f() { + result = aProp; +} diff --git a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp index 60c380c..8e7944d 100644 --- a/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp +++ b/tests/auto/declarative/qdeclarativeecmascript/tst_qdeclarativeecmascript.cpp @@ -122,6 +122,7 @@ private slots: void listToVariant(); void multiEngineObject(); void deletedObject(); + void scriptScope(); void bug1(); @@ -1657,6 +1658,33 @@ void tst_qdeclarativeecmascript::deletedObject() delete object; } +void tst_qdeclarativeecmascript::scriptScope() +{ + { + QDeclarativeComponent component(&engine, TEST_FILE("scriptScope.1.qml")); + + MyQmlObject *object = qobject_cast(component.create()); + QVERIFY(object != 0); + emit object->argumentSignal(19, "Hello world!", 10.3); + QEXPECT_FAIL("", "QTBUG-8641", Continue); + QCOMPARE(object->property("result").toString(), QLatin1String("undefined")); + + delete object; + } + + { + QDeclarativeComponent component(&engine, TEST_FILE("scriptScope.2.qml")); + + MyQmlObject *object = qobject_cast(component.create()); + QVERIFY(object != 0); + emit object->basicSignal(); + QEXPECT_FAIL("", "QTBUG-8641", Continue); + QCOMPARE(object->property("result").toString(), QLatin1String("world")); + + delete object; + } +} + QTEST_MAIN(tst_qdeclarativeecmascript) #include "tst_qdeclarativeecmascript.moc" -- cgit v0.12 From 685c0b930a1d1ecfdcc78aa688a333564cc9ca5b Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 2 Mar 2010 15:08:11 +1000 Subject: Optimization. --- src/declarative/qml/qdeclarativepropertycache.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/qml/qdeclarativepropertycache.cpp b/src/declarative/qml/qdeclarativepropertycache.cpp index 08b47b7..fea59e5 100644 --- a/src/declarative/qml/qdeclarativepropertycache.cpp +++ b/src/declarative/qml/qdeclarativepropertycache.cpp @@ -155,9 +155,9 @@ QDeclarativePropertyCache::Data QDeclarativePropertyCache::create(const QMetaObj int parenIdx = methodName.indexOf(QLatin1Char('(')); Q_ASSERT(parenIdx != -1); - methodName = methodName.left(parenIdx); + QStringRef methodNameRef = methodName.leftRef(parenIdx); - if (methodName == property) { + if (methodNameRef == property) { rv.load(m); return rv; } -- cgit v0.12 From d042a00b5828961e1e1fa82017717b5f72dde9ef Mon Sep 17 00:00:00 2001 From: Aaron McCarthy Date: Mon, 1 Mar 2010 17:45:35 +1000 Subject: Bearer management changes from Qt Mobility (fca9891). fca98911b75ce12e70d93cfc2932a9759758a605 --- src/network/bearer/qnetworkconfigmanager.cpp | 5 + src/network/bearer/qnetworkconfiguration.cpp | 1 - src/network/bearer/qnetworksession.cpp | 4 + src/plugins/bearer/corewlan/qcorewlanengine.h | 6 + src/plugins/bearer/corewlan/qcorewlanengine.mm | 196 +++++++++----- src/plugins/bearer/generic/qgenericengine.cpp | 11 +- src/plugins/bearer/icd/monitor.cpp | 56 +--- src/plugins/bearer/icd/monitor.h | 22 +- src/plugins/bearer/icd/qicdengine.cpp | 24 +- src/plugins/bearer/icd/qnetworksession_impl.cpp | 32 ++- src/plugins/bearer/icd/qnetworksession_impl.h | 7 +- .../networkmanager/qnetworkmanagerengine.cpp | 3 +- .../networkmanager/qnetworkmanagerservice.cpp | 293 +++++++++------------ .../bearer/networkmanager/qnetworkmanagerservice.h | 112 +++++--- .../bearer/networkmanager/qnmdbushelper.cpp | 11 +- src/plugins/bearer/networkmanager/qnmdbushelper.h | 2 + src/plugins/bearer/qnetworksession_impl.cpp | 3 +- .../bearer/symbian/qnetworksession_impl.cpp | 17 +- src/plugins/bearer/symbian/symbianengine.cpp | 38 ++- src/plugins/bearer/symbian/symbianengine.h | 1 + tests/auto/qbearertestcommon.h | 13 + tests/auto/qnetworksession/lackey/main.cpp | 13 +- .../qnetworksession/test/tst_qnetworksession.cpp | 293 ++++++++++++++++++++- 23 files changed, 794 insertions(+), 369 deletions(-) diff --git a/src/network/bearer/qnetworkconfigmanager.cpp b/src/network/bearer/qnetworkconfigmanager.cpp index e960323..9ff197b 100644 --- a/src/network/bearer/qnetworkconfigmanager.cpp +++ b/src/network/bearer/qnetworkconfigmanager.cpp @@ -302,6 +302,11 @@ QNetworkConfiguration QNetworkConfigurationManager::defaultConfiguration() const be used to update each configuration's state. Note that such an update may require some time. It's completion is signalled by updateCompleted(). In the absence of a configuration update this function returns the best estimate at the time of the call. + Therefore, if WLAN configurations are of interest, it is recommended that + updateConfigurations() is called once after QNetworkConfigurationManager + instantiation (WLAN scans are too time consuming to perform in constructor). + After this the data is kept automatically up-to-date as the system reports + any changes. */ QList QNetworkConfigurationManager::allConfigurations(QNetworkConfiguration::StateFlags filter) const { diff --git a/src/network/bearer/qnetworkconfiguration.cpp b/src/network/bearer/qnetworkconfiguration.cpp index c551dc5..c4ba406 100644 --- a/src/network/bearer/qnetworkconfiguration.cpp +++ b/src/network/bearer/qnetworkconfiguration.cpp @@ -40,7 +40,6 @@ ****************************************************************************/ #include "qnetworkconfiguration.h" - #include "qnetworkconfiguration_p.h" QT_BEGIN_NAMESPACE diff --git a/src/network/bearer/qnetworksession.cpp b/src/network/bearer/qnetworksession.cpp index 6a82791..f0d7ede 100644 --- a/src/network/bearer/qnetworksession.cpp +++ b/src/network/bearer/qnetworksession.cpp @@ -275,6 +275,8 @@ void QNetworkSession::open() { if (d) d->open(); + else + emit error(InvalidConfigurationError); } /*! @@ -308,6 +310,8 @@ bool QNetworkSession::waitForOpened(int msecs) QEventLoop* loop = new QEventLoop(this); QObject::connect(d, SIGNAL(quitPendingWaitsForOpened()), loop, SLOT(quit())); + QObject::connect(this, SIGNAL(error(QNetworkSession::SessionError)), + loop, SLOT(quit())); //final call if (msecs>=0) diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.h b/src/plugins/bearer/corewlan/qcorewlanengine.h index 044b433..cfd89e4 100644 --- a/src/plugins/bearer/corewlan/qcorewlanengine.h +++ b/src/plugins/bearer/corewlan/qcorewlanengine.h @@ -46,6 +46,7 @@ #include #include +#include QT_BEGIN_NAMESPACE @@ -91,6 +92,11 @@ private: bool isKnownSsid(const QString &interfaceName, const QString &ssid); QList foundConfigurations; + SCDynamicStoreRef storeSession; + CFRunLoopSourceRef runloopSource; + + void startNetworkChangeLoop(); + }; QT_END_NAMESPACE diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.mm b/src/plugins/bearer/corewlan/qcorewlanengine.mm index a5384d1..4ab4d88 100644 --- a/src/plugins/bearer/corewlan/qcorewlanengine.mm +++ b/src/plugins/bearer/corewlan/qcorewlanengine.mm @@ -105,12 +105,23 @@ static QString qGetInterfaceType(const QString &interfaceString) return networkInterfaces.value(interfaceString, QLatin1String("Unknown")); } +void networkChangeCallback(SCDynamicStoreRef/* store*/, CFArrayRef changedKeys, void *info) +{ + for ( long i = 0; i < CFArrayGetCount(changedKeys); i++) { + + CFStringRef changed = (CFStringRef)CFArrayGetValueAtIndex(changedKeys, i); + if( cfstringRefToQstring(changed).contains("/Network/Global/IPv4")) { + QCoreWlanEngine* wlanEngine = static_cast(info); + wlanEngine->requestUpdate(); + } + } + return; +} + QCoreWlanEngine::QCoreWlanEngine(QObject *parent) : QBearerEngineImpl(parent) { - connect(&pollTimer, SIGNAL(timeout()), this, SLOT(doRequestUpdate())); - pollTimer.setInterval(10000); - doRequestUpdate(); + startNetworkChangeLoop(); } QCoreWlanEngine::~QCoreWlanEngine() @@ -150,7 +161,6 @@ void QCoreWlanEngine::connectToId(const QString &id) NSEnumerator *enumerator = [remNets objectEnumerator]; CWWirelessProfile *wProfile; NSUInteger index=0; - CWNetwork *apNetwork; NSDictionary *parametersDict; NSArray* apArray; @@ -179,26 +189,24 @@ void QCoreWlanEngine::connectToId(const QString &id) if(!err) { for(uint row=0; row < [apArray count]; row++ ) { - apNetwork = [apArray objectAtIndex:row]; + CWNetwork *apNetwork = [apArray objectAtIndex:row]; if([[apNetwork ssid] compare:[wProfile ssid]] == NSOrderedSame) { bool result = [wifiInterface associateToNetwork: apNetwork parameters:[NSDictionary dictionaryWithDictionary:params] error:&err]; if(!result) { - qWarning() <<"ERROR"<< nsstringToQString([err localizedDescription ]); emit connectionError(id, ConnectError); } else { - [apNetwork release]; [autoreleasepool release]; return; } } + [apNetwork release]; } } } index++; } - [apNetwork release]; emit connectionError(id, InterfaceLookupError); #endif @@ -350,81 +358,83 @@ QStringList QCoreWlanEngine::scanForSsids(const QString &interfaceName) NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; CWInterface *currentInterface = [CWInterface interfaceWithName:qstringToNSString(interfaceName)]; - NSError *err = nil; - NSDictionary *parametersDict = nil; - NSArray* apArray = [currentInterface scanForNetworksWithParameters:parametersDict error:&err]; + if([currentInterface power]) { + NSError *err = nil; + NSDictionary *parametersDict = nil; + NSArray* apArray = [currentInterface scanForNetworksWithParameters:parametersDict error:&err]; - CWNetwork *apNetwork; - if (!err) { - for(uint row=0; row < [apArray count]; row++ ) { - NSAutoreleasePool *looppool = [[NSAutoreleasePool alloc] init]; + CWNetwork *apNetwork; + if (!err) { + for(uint row=0; row < [apArray count]; row++ ) { + NSAutoreleasePool *looppool = [[NSAutoreleasePool alloc] init]; - apNetwork = [apArray objectAtIndex:row]; + apNetwork = [apArray objectAtIndex:row]; - const QString networkSsid = nsstringToQString([apNetwork ssid]); + const QString networkSsid = nsstringToQString([apNetwork ssid]); - const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkSsid)); - found.append(id); + const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkSsid)); + found.append(id); - QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined; + QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined; - if ([currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) { - if (networkSsid == nsstringToQString([currentInterface ssid])) - state = QNetworkConfiguration::Active; - } else { - if (isKnownSsid(interfaceName, networkSsid)) - state = QNetworkConfiguration::Discovered; - else - state = QNetworkConfiguration::Defined; - } + if ([currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) { + if (networkSsid == nsstringToQString([currentInterface ssid])) + state = QNetworkConfiguration::Active; + } else { + if (isKnownSsid(interfaceName, networkSsid)) + state = QNetworkConfiguration::Discovered; + else + state = QNetworkConfiguration::Defined; + } - if (accessPointConfigurations.contains(id)) { - QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id); + if (accessPointConfigurations.contains(id)) { + QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id); - bool changed = false; + bool changed = false; - if (!ptr->isValid) { - ptr->isValid = true; - changed = true; - } + if (!ptr->isValid) { + ptr->isValid = true; + changed = true; + } - if (ptr->name != networkSsid) { - ptr->name = networkSsid; - changed = true; - } + if (ptr->name != networkSsid) { + ptr->name = networkSsid; + changed = true; + } - if (ptr->id != id) { - ptr->id = id; - changed = true; - } + if (ptr->id != id) { + ptr->id = id; + changed = true; + } - if (ptr->state != state) { - ptr->state = state; - changed = true; - } + if (ptr->state != state) { + ptr->state = state; + changed = true; + } - if (changed) - emit configurationChanged(ptr); - } else { - QNetworkConfigurationPrivatePointer ptr(new QNetworkConfigurationPrivate); + if (changed) + emit configurationChanged(ptr); + } else { + QNetworkConfigurationPrivatePointer ptr(new QNetworkConfigurationPrivate); - ptr->name = networkSsid; - ptr->isValid = true; - ptr->id = id; - ptr->state = state; - ptr->type = QNetworkConfiguration::InternetAccessPoint; - ptr->bearer = QLatin1String("WLAN"); + ptr->name = networkSsid; + ptr->isValid = true; + ptr->id = id; + ptr->state = state; + ptr->type = QNetworkConfiguration::InternetAccessPoint; + ptr->bearer = QLatin1String("WLAN"); - accessPointConfigurations.insert(id, ptr); - configurationInterface.insert(id, interfaceName); + accessPointConfigurations.insert(id, ptr); + configurationInterface.insert(id, interfaceName); - emit configurationAdded(ptr); + emit configurationAdded(ptr); + } + [looppool release]; } - [looppool release]; - } - } else { - qWarning() << "ERROR scanning for ssids" << nsstringToQString([err localizedDescription]) - <= 0) { - switch (request.ifr_hwaddr.sa_family) { - case ARPHRD_ETHER: - return QLatin1String("Ethernet"); - } - } - + int result = ioctl(sock, SIOCGIFHWADDR, &request); close(sock); + + if (result >= 0 && request.ifr_hwaddr.sa_family == ARPHRD_ETHER) + return QLatin1String("Ethernet"); #else Q_UNUSED(interface); #endif diff --git a/src/plugins/bearer/icd/monitor.cpp b/src/plugins/bearer/icd/monitor.cpp index 0ff45d2..5b0af7e 100644 --- a/src/plugins/bearer/icd/monitor.cpp +++ b/src/plugins/bearer/icd/monitor.cpp @@ -47,32 +47,12 @@ #include #include -#define IAP "/system/osso/connectivity/IAP" - -static int iap_prefix_len; - -/* Notify func that is called when IAP is added or deleted */ -void notify_iap(GConfClient *, guint, GConfEntry *entry, gpointer user_data) -{ - const char *key = gconf_entry_get_key(entry); - if (key && g_str_has_prefix(key, IAP)) { - IapMonitor *ptr = (IapMonitor *)user_data; - if (gconf_entry_get_value(entry)) { - ptr->iapAdded(key, entry); - } else { - ptr->iapDeleted(key, entry); - } - } -} - void IapMonitor::setup(QIcdEngine *d_ptr) { if (first_call) { - d = d_ptr; - iap_prefix_len = strlen(IAP); - iap = new Maemo::IAPMonitor(notify_iap, (gpointer)this); - first_call = false; + d = d_ptr; + first_call = false; } } @@ -80,37 +60,25 @@ void IapMonitor::setup(QIcdEngine *d_ptr) void IapMonitor::cleanup() { if (!first_call) { - delete iap; - timers.removeAll(); - first_call = true; + timers.removeAll(); + first_call = true; } } -void IapMonitor::iapAdded(const char *key, GConfEntry * /*entry*/) +void IapMonitor::iapAdded(const QString &iap_id) { - //qDebug("Notify called for added element: %s=%s", - // gconf_entry_get_key(entry), gconf_value_to_string(gconf_entry_get_value(entry))); - - /* We cannot know when the IAP is fully added to gconf, so a timer is + /* We cannot know when the IAP is fully added to db, so a timer is * installed instead. When the timer expires we hope that IAP is added ok. */ - QString iap_id = QString(key + iap_prefix_len + 1).section('/',0,0); - timers.add(iap_id, d); + QString id = iap_id; + timers.add(id, d); } -void IapMonitor::iapDeleted(const char *key, GConfEntry * /*entry*/) +void IapMonitor::iapRemoved(const QString &iap_id) { - //qDebug("Notify called for deleted element: %s", gconf_entry_get_key(entry)); - - /* We are only interested in IAP deletions so we skip the config entries - */ - if (strstr(key + iap_prefix_len + 1, "/")) { - //qDebug("Deleting IAP config %s", key+iap_prefix_len); - return; - } - - QString iap_id = key + iap_prefix_len + 1; - d->deleteConfiguration(iap_id); + QString id = iap_id; + d->deleteConfiguration(id); } + diff --git a/src/plugins/bearer/icd/monitor.h b/src/plugins/bearer/icd/monitor.h index 82b0f36..10ffb30 100644 --- a/src/plugins/bearer/icd/monitor.h +++ b/src/plugins/bearer/icd/monitor.h @@ -53,7 +53,7 @@ class QIcdEngine; /* The IapAddTimer is a helper class that makes sure we update - * the configuration only after all gconf additions to certain + * the configuration only after all db additions to certain * iap are finished (after a certain timeout) */ class _IapAddTimer : public QObject @@ -64,10 +64,10 @@ public: _IapAddTimer() {} ~_IapAddTimer() { - if (timer.isActive()) { - QObject::disconnect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); - timer.stop(); - } + if (timer.isActive()) { + QObject::disconnect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); + timer.stop(); + } } void add(QString& iap_id, QIcdEngine *d); @@ -92,23 +92,21 @@ public: void removeAll(); }; -class IapMonitor +class IapMonitor : public Maemo::IAPMonitor { public: IapMonitor() : first_call(true) { } - friend void notify_iap(GConfClient *, guint, - GConfEntry *entry, gpointer user_data); void setup(QIcdEngine *d); void cleanup(); +protected: + void iapAdded(const QString &iapId); + void iapRemoved(const QString &iapId); + private: bool first_call; - void iapAdded(const char *key, GConfEntry *entry); - void iapDeleted(const char *key, GConfEntry *entry); - - Maemo::IAPMonitor *iap; QIcdEngine *d; IapAddTimer timers; }; diff --git a/src/plugins/bearer/icd/qicdengine.cpp b/src/plugins/bearer/icd/qicdengine.cpp index f10042a..206a6fd 100644 --- a/src/plugins/bearer/icd/qicdengine.cpp +++ b/src/plugins/bearer/icd/qicdengine.cpp @@ -189,14 +189,9 @@ void QIcdEngine::doRequestUpdate() QList all_iaps; Maemo::IAPConf::getAll(all_iaps); - foreach (QString escaped_iap_id, all_iaps) { + foreach (QString iap_id, all_iaps) { QByteArray ssid; - /* The key that is returned by getAll() needs to be unescaped */ - gchar *unescaped_id = gconf_unescape_key(escaped_iap_id.toUtf8().data(), -1); - QString iap_id = QString((char *)unescaped_id); - g_free(unescaped_id); - previous.removeAll(iap_id); Maemo::IAPConf saved_ap(iap_id); @@ -231,11 +226,12 @@ void QIcdEngine::doRequestUpdate() IcdNetworkConfigurationPrivate *cpPriv = new IcdNetworkConfigurationPrivate; cpPriv->name = saved_ap.value("name").toString(); - if (cpPriv->name.isEmpty()) - if (!ssid.isEmpty() && ssid.size() > 0) - cpPriv->name = ssid.data(); - else - cpPriv->name = iap_id; + if (cpPriv->name.isEmpty()) { + if (!ssid.isEmpty() && ssid.size() > 0) + cpPriv->name = ssid.data(); + else + cpPriv->name = iap_id; + } cpPriv->isValid = true; cpPriv->id = iap_id; cpPriv->network_id = ssid; @@ -379,9 +375,9 @@ void QIcdEngine::deleteConfiguration(const QString &iap_id) { QMutexLocker locker(&mutex); - /* Called when IAPs are deleted in gconf, in this case we do not scan - * or read all the IAPs from gconf because it might take too much power - * (multiple applications would need to scan and read all IAPs from gconf) + /* Called when IAPs are deleted in db, in this case we do not scan + * or read all the IAPs from db because it might take too much power + * (multiple applications would need to scan and read all IAPs from db) */ if (accessPointConfigurations.contains(iap_id)) { QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.take(iap_id); diff --git a/src/plugins/bearer/icd/qnetworksession_impl.cpp b/src/plugins/bearer/icd/qnetworksession_impl.cpp index a9e93e0..2acaa47 100644 --- a/src/plugins/bearer/icd/qnetworksession_impl.cpp +++ b/src/plugins/bearer/icd/qnetworksession_impl.cpp @@ -49,6 +49,7 @@ #include #include +#include #include #include @@ -299,6 +300,8 @@ void IcdListener::cleanupSession(QNetworkSessionPrivateImpl *ptr) void QNetworkSessionPrivateImpl::cleanupSession(void) { icdListener()->cleanupSession(this); + + QObject::disconnect(q, SIGNAL(stateChanged(QNetworkSession::State)), this, SLOT(updateProxies(QNetworkSession::State))); } @@ -451,6 +454,8 @@ void QNetworkSessionPrivateImpl::syncStateWithInterface() connect(&manager, SIGNAL(configurationChanged(QNetworkConfiguration)), this, SLOT(configurationChanged(QNetworkConfiguration))); + QObject::connect(q, SIGNAL(stateChanged(QNetworkSession::State)), this, SLOT(updateProxies(QNetworkSession::State))); + state = QNetworkSession::Invalid; lastError = QNetworkSession::UnknownSessionError; @@ -867,7 +872,6 @@ void QNetworkSessionPrivateImpl::do_open() qDebug() << "connect to"<< iap << "failed, result is empty"; #endif updateState(QNetworkSession::Disconnected); - emit quitPendingWaitsForOpened(); emit QNetworkSessionPrivate::error(QNetworkSession::InvalidConfigurationError); if (publicConfig.type() == QNetworkConfiguration::UserChoice) cleanupAnyConfiguration(); @@ -882,7 +886,6 @@ void QNetworkSessionPrivateImpl::do_open() if ((publicConfig.type() != QNetworkConfiguration::UserChoice) && (connected_iap != config.identifier())) { updateState(QNetworkSession::Disconnected); - emit quitPendingWaitsForOpened(); emit QNetworkSessionPrivate::error(QNetworkSession::InvalidConfigurationError); return; } @@ -946,7 +949,6 @@ void QNetworkSessionPrivateImpl::do_open() updateState(QNetworkSession::Disconnected); if (publicConfig.type() == QNetworkConfiguration::UserChoice) cleanupAnyConfiguration(); - emit quitPendingWaitsForOpened(); emit QNetworkSessionPrivate::error(QNetworkSession::UnknownSessionError); } } @@ -1099,6 +1101,30 @@ QNetworkSession::SessionError QNetworkSessionPrivateImpl::error() const return QNetworkSession::UnknownSessionError; } +void QNetworkSessionPrivateImpl::updateProxies(QNetworkSession::State newState) +{ + if ((newState == QNetworkSession::Connected) && + (newState != currentState)) + updateProxyInformation(); + else if ((newState == QNetworkSession::Disconnected) && + (currentState == QNetworkSession::Closing)) + clearProxyInformation(); + + currentState = newState; +} + + +void QNetworkSessionPrivateImpl::updateProxyInformation() +{ + Maemo::ProxyConf::update(); +} + + +void QNetworkSessionPrivateImpl::clearProxyInformation() +{ + Maemo::ProxyConf::clear(); +} + #include "qnetworksession_impl.moc" QT_END_NAMESPACE diff --git a/src/plugins/bearer/icd/qnetworksession_impl.h b/src/plugins/bearer/icd/qnetworksession_impl.h index b7461dc..587e6dc 100644 --- a/src/plugins/bearer/icd/qnetworksession_impl.h +++ b/src/plugins/bearer/icd/qnetworksession_impl.h @@ -75,7 +75,7 @@ class QNetworkSessionPrivateImpl : public QNetworkSessionPrivate public: QNetworkSessionPrivateImpl(QIcdEngine *engine) - : engine(engine), connectFlags(ICD_CONNECTION_FLAG_USER_EVENT) + : engine(engine), connectFlags(ICD_CONNECTION_FLAG_USER_EVENT), currentState(QNetworkSession::Invalid) { } @@ -118,6 +118,7 @@ private Q_SLOTS: void do_open(); void networkConfigurationsChanged(); void configurationChanged(const QNetworkConfiguration &config); + void updateProxies(QNetworkSession::State newState); private: QNetworkConfigurationManager manager; @@ -139,6 +140,10 @@ private: void updateIdentifier(QString &newId); quint64 getStatistics(bool sent) const; void cleanupSession(void); + + void updateProxyInformation(); + void clearProxyInformation(); + QNetworkSession::State currentState; }; QT_END_NAMESPACE diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp index 5c6efe3..0fa8f3c 100644 --- a/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp +++ b/src/plugins/bearer/networkmanager/qnetworkmanagerengine.cpp @@ -49,7 +49,6 @@ #include -#include #include #include #include @@ -147,7 +146,7 @@ QString QNetworkManagerEngine::getInterfaceFromId(const QString &id) continue; QNetworkManagerInterfaceDevice device(devices.at(0).path()); - return device.interface().name(); + return device.networkInterface().name(); } } diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp b/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp index 5dc0ea4..c780fbc 100644 --- a/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp +++ b/src/plugins/bearer/networkmanager/qnetworkmanagerservice.cpp @@ -41,26 +41,22 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include "qnmdbushelper.h" #include "qnetworkmanagerservice.h" +#include "qnmdbushelper.h" -//Q_DECLARE_METATYPE(QList) QT_BEGIN_NAMESPACE static QDBusConnection dbusConnection = QDBusConnection::systemBus(); -//static QDBusInterface iface(NM_DBUS_SERVICE, NM_DBUS_PATH, NM_DBUS_INTERFACE, dbusConnection); class QNetworkManagerInterfacePrivate { @@ -70,19 +66,19 @@ public: }; QNetworkManagerInterface::QNetworkManagerInterface(QObject *parent) - : QObject(parent), nmDBusHelper(0) + : QObject(parent) { d = new QNetworkManagerInterfacePrivate(); - d->connectionInterface = new QDBusInterface(NM_DBUS_SERVICE, - NM_DBUS_PATH, - NM_DBUS_INTERFACE, + d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), + QLatin1String(NM_DBUS_PATH), + QLatin1String(NM_DBUS_INTERFACE), dbusConnection); if (!d->connectionInterface->isValid()) { d->valid = false; return; } d->valid = true; - nmDBusHelper = new QNmDBusHelper; + nmDBusHelper = new QNmDBusHelper(this); connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), this,SIGNAL(propertiesChanged( const QString &, QMap))); connect(nmDBusHelper,SIGNAL(pathForStateChanged(const QString &, quint32)), @@ -92,8 +88,6 @@ QNetworkManagerInterface::QNetworkManagerInterface(QObject *parent) QNetworkManagerInterface::~QNetworkManagerInterface() { - if (nmDBusHelper) - delete nmDBusHelper; delete d->connectionInterface; delete d; } @@ -108,24 +102,24 @@ bool QNetworkManagerInterface::setConnections() if(!isValid() ) return false; bool allOk = false; - if (!dbusConnection.connect(NM_DBUS_SERVICE, - NM_DBUS_PATH, - NM_DBUS_INTERFACE, - "PropertiesChanged", + if (!dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), + QLatin1String(NM_DBUS_PATH), + QLatin1String(NM_DBUS_INTERFACE), + QLatin1String("PropertiesChanged"), nmDBusHelper,SLOT(slotPropertiesChanged( QMap)))) { allOk = true; } - if (!dbusConnection.connect(NM_DBUS_SERVICE, - NM_DBUS_PATH, - NM_DBUS_INTERFACE, - "DeviceAdded", + if (!dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), + QLatin1String(NM_DBUS_PATH), + QLatin1String(NM_DBUS_INTERFACE), + QLatin1String("DeviceAdded"), this,SIGNAL(deviceAdded(QDBusObjectPath)))) { allOk = true; } - if (!dbusConnection.connect(NM_DBUS_SERVICE, - NM_DBUS_PATH, - NM_DBUS_INTERFACE, - "DeviceRemoved", + if (!dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), + QLatin1String(NM_DBUS_PATH), + QLatin1String(NM_DBUS_INTERFACE), + QLatin1String("DeviceRemoved"), this,SIGNAL(deviceRemoved(QDBusObjectPath)))) { allOk = true; } @@ -140,7 +134,7 @@ QDBusInterface *QNetworkManagerInterface::connectionInterface() const QList QNetworkManagerInterface::getDevices() const { - QDBusReply > reply = d->connectionInterface->call("GetDevices"); + QDBusReply > reply = d->connectionInterface->call(QLatin1String("GetDevices")); return reply.value(); } @@ -149,7 +143,7 @@ void QNetworkManagerInterface::activateConnection( const QString &serviceName, QDBusObjectPath devicePath, QDBusObjectPath specificObject) { - QDBusPendingCall pendingCall = d->connectionInterface->asyncCall("ActivateConnection", + QDBusPendingCall pendingCall = d->connectionInterface->asyncCall(QLatin1String("ActivateConnection"), QVariant(serviceName), QVariant::fromValue(connectionPath), QVariant::fromValue(devicePath), @@ -162,7 +156,7 @@ void QNetworkManagerInterface::activateConnection( const QString &serviceName, void QNetworkManagerInterface::deactivateConnection(QDBusObjectPath connectionPath) const { - d->connectionInterface->call("DeactivateConnection", QVariant::fromValue(connectionPath)); + d->connectionInterface->call(QLatin1String("DeactivateConnection"), QVariant::fromValue(connectionPath)); } bool QNetworkManagerInterface::wirelessEnabled() const @@ -186,7 +180,6 @@ quint32 QNetworkManagerInterface::state() return d->connectionInterface->property("State").toUInt(); } -///////////// class QNetworkManagerInterfaceAccessPointPrivate { public: @@ -200,9 +193,9 @@ QNetworkManagerInterfaceAccessPoint::QNetworkManagerInterfaceAccessPoint(const Q { d = new QNetworkManagerInterfaceAccessPointPrivate(); d->path = dbusPathName; - d->connectionInterface = new QDBusInterface(NM_DBUS_SERVICE, + d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_ACCESS_POINT, + QLatin1String(NM_DBUS_INTERFACE_ACCESS_POINT), dbusConnection); if (!d->connectionInterface->isValid()) { d->valid = false; @@ -215,8 +208,6 @@ QNetworkManagerInterfaceAccessPoint::QNetworkManagerInterfaceAccessPoint(const Q QNetworkManagerInterfaceAccessPoint::~QNetworkManagerInterfaceAccessPoint() { - if (nmDBusHelper) - delete nmDBusHelper; delete d->connectionInterface; delete d; } @@ -232,17 +223,15 @@ bool QNetworkManagerInterfaceAccessPoint::setConnections() return false; bool allOk = false; - if (nmDBusHelper) - delete nmDBusHelper; - nmDBusHelper = 0; - nmDBusHelper = new QNmDBusHelper; + delete nmDBusHelper; + nmDBusHelper = new QNmDBusHelper(this); connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), this,SIGNAL(propertiesChanged( const QString &, QMap))); - if(dbusConnection.connect(NM_DBUS_SERVICE, + if(dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_ACCESS_POINT, - "PropertiesChanged", + QLatin1String(NM_DBUS_INTERFACE_ACCESS_POINT), + QLatin1String("PropertiesChanged"), nmDBusHelper,SLOT(slotPropertiesChanged( QMap))) ) { allOk = true; @@ -300,7 +289,6 @@ quint32 QNetworkManagerInterfaceAccessPoint::strength() const return d->connectionInterface->property("Strength").toUInt(); } -///////////// class QNetworkManagerInterfaceDevicePrivate { public: @@ -314,9 +302,9 @@ QNetworkManagerInterfaceDevice::QNetworkManagerInterfaceDevice(const QString &de { d = new QNetworkManagerInterfaceDevicePrivate(); d->path = deviceObjectPath; - d->connectionInterface = new QDBusInterface(NM_DBUS_SERVICE, + d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE, + QLatin1String(NM_DBUS_INTERFACE_DEVICE), dbusConnection); if (!d->connectionInterface->isValid()) { d->valid = false; @@ -328,8 +316,6 @@ QNetworkManagerInterfaceDevice::QNetworkManagerInterfaceDevice(const QString &de QNetworkManagerInterfaceDevice::~QNetworkManagerInterfaceDevice() { - if (nmDBusHelper) - delete nmDBusHelper; delete d->connectionInterface; delete d; } @@ -345,16 +331,14 @@ bool QNetworkManagerInterfaceDevice::setConnections() return false; bool allOk = false; - if (nmDBusHelper) - delete nmDBusHelper; - nmDBusHelper = 0; - nmDBusHelper = new QNmDBusHelper; + delete nmDBusHelper; + nmDBusHelper = new QNmDBusHelper(this); connect(nmDBusHelper,SIGNAL(pathForStateChanged(const QString &, quint32)), this, SIGNAL(stateChanged(const QString&, quint32))); - if(dbusConnection.connect(NM_DBUS_SERVICE, + if(dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE, - "StateChanged", + QLatin1String(NM_DBUS_INTERFACE_DEVICE), + QLatin1String("StateChanged"), nmDBusHelper,SLOT(deviceStateChanged(quint32)))) { allOk = true; } @@ -371,7 +355,7 @@ QString QNetworkManagerInterfaceDevice::udi() const return d->connectionInterface->property("Udi").toString(); } -QNetworkInterface QNetworkManagerInterfaceDevice::interface() const +QNetworkInterface QNetworkManagerInterfaceDevice::networkInterface() const { return QNetworkInterface::interfaceFromName(d->connectionInterface->property("Interface").toString()); } @@ -397,7 +381,6 @@ QDBusObjectPath QNetworkManagerInterfaceDevice::ip4config() const return prop.value(); } -///////////// class QNetworkManagerInterfaceDeviceWiredPrivate { public: @@ -411,9 +394,9 @@ QNetworkManagerInterfaceDeviceWired::QNetworkManagerInterfaceDeviceWired(const Q { d = new QNetworkManagerInterfaceDeviceWiredPrivate(); d->path = ifaceDevicePath; - d->connectionInterface = new QDBusInterface(NM_DBUS_SERVICE, + d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE_WIRED, + QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRED), dbusConnection, parent); if (!d->connectionInterface->isValid()) { d->valid = false; @@ -425,8 +408,6 @@ QNetworkManagerInterfaceDeviceWired::QNetworkManagerInterfaceDeviceWired(const Q QNetworkManagerInterfaceDeviceWired::~QNetworkManagerInterfaceDeviceWired() { - if (nmDBusHelper) - delete nmDBusHelper; delete d->connectionInterface; delete d; } @@ -444,16 +425,14 @@ bool QNetworkManagerInterfaceDeviceWired::setConnections() bool allOk = false; - if (nmDBusHelper) - delete nmDBusHelper; - nmDBusHelper = 0; - nmDBusHelper = new QNmDBusHelper; + delete nmDBusHelper; + nmDBusHelper = new QNmDBusHelper(this); connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), this,SIGNAL(propertiesChanged( const QString &, QMap))); - if(dbusConnection.connect(NM_DBUS_SERVICE, + if(dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE_WIRED, - "PropertiesChanged", + QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRED), + QLatin1String("PropertiesChanged"), nmDBusHelper,SLOT(slotPropertiesChanged( QMap))) ) { allOk = true; } @@ -480,7 +459,6 @@ bool QNetworkManagerInterfaceDeviceWired::carrier() const return d->connectionInterface->property("Carrier").toBool(); } -///////////// class QNetworkManagerInterfaceDeviceWirelessPrivate { public: @@ -494,9 +472,9 @@ QNetworkManagerInterfaceDeviceWireless::QNetworkManagerInterfaceDeviceWireless(c { d = new QNetworkManagerInterfaceDeviceWirelessPrivate(); d->path = ifaceDevicePath; - d->connectionInterface = new QDBusInterface(NM_DBUS_SERVICE, + d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE_WIRELESS, + QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), dbusConnection, parent); if (!d->connectionInterface->isValid()) { d->valid = false; @@ -508,8 +486,6 @@ QNetworkManagerInterfaceDeviceWireless::QNetworkManagerInterfaceDeviceWireless(c QNetworkManagerInterfaceDeviceWireless::~QNetworkManagerInterfaceDeviceWireless() { - if (nmDBusHelper) - delete nmDBusHelper; delete d->connectionInterface; delete d; } @@ -525,10 +501,8 @@ bool QNetworkManagerInterfaceDeviceWireless::setConnections() return false; bool allOk = false; - if (nmDBusHelper) - delete nmDBusHelper; - nmDBusHelper = 0; - nmDBusHelper = new QNmDBusHelper; + delete nmDBusHelper; + nmDBusHelper = new QNmDBusHelper(this); connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), this,SIGNAL(propertiesChanged( const QString &, QMap))); @@ -538,28 +512,28 @@ bool QNetworkManagerInterfaceDeviceWireless::setConnections() connect(nmDBusHelper, SIGNAL(pathForAccessPointRemoved(const QString &,QDBusObjectPath)), this,SIGNAL(accessPointRemoved(const QString &,QDBusObjectPath))); - if(!dbusConnection.connect(NM_DBUS_SERVICE, + if(!dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE_WIRELESS, - "AccessPointAdded", + QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), + QLatin1String("AccessPointAdded"), nmDBusHelper, SLOT(slotAccessPointAdded( QDBusObjectPath )))) { allOk = true; } - if(!dbusConnection.connect(NM_DBUS_SERVICE, + if(!dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE_WIRELESS, - "AccessPointRemoved", + QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), + QLatin1String("AccessPointRemoved"), nmDBusHelper, SLOT(slotAccessPointRemoved( QDBusObjectPath )))) { allOk = true; } - if(!dbusConnection.connect(NM_DBUS_SERVICE, + if(!dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_DEVICE_WIRELESS, - "PropertiesChanged", + QLatin1String(NM_DBUS_INTERFACE_DEVICE_WIRELESS), + QLatin1String("PropertiesChanged"), nmDBusHelper,SLOT(slotPropertiesChanged( QMap)))) { allOk = true; } @@ -574,7 +548,7 @@ QDBusInterface *QNetworkManagerInterfaceDeviceWireless::connectionInterface() co QList QNetworkManagerInterfaceDeviceWireless::getAccessPoints() { - QDBusReply > reply = d->connectionInterface->call("GetAccessPoints"); + QDBusReply > reply = d->connectionInterface->call(QLatin1String("GetAccessPoints")); return reply.value(); } @@ -603,7 +577,6 @@ quint32 QNetworkManagerInterfaceDeviceWireless::wirelessCapabilities() const return d->connectionInterface->property("WirelelessCapabilities").toUInt(); } -///////////// class QNetworkManagerSettingsPrivate { public: @@ -618,8 +591,8 @@ QNetworkManagerSettings::QNetworkManagerSettings(const QString &settingsService, d = new QNetworkManagerSettingsPrivate(); d->path = settingsService; d->connectionInterface = new QDBusInterface(settingsService, - NM_DBUS_PATH_SETTINGS, - NM_DBUS_IFACE_SETTINGS, + QLatin1String(NM_DBUS_PATH_SETTINGS), + QLatin1String(NM_DBUS_IFACE_SETTINGS), dbusConnection); if (!d->connectionInterface->isValid()) { d->valid = false; @@ -644,8 +617,8 @@ bool QNetworkManagerSettings::setConnections() { bool allOk = false; - if (!dbusConnection.connect(d->path, NM_DBUS_PATH_SETTINGS, - NM_DBUS_IFACE_SETTINGS, "NewConnection", + if (!dbusConnection.connect(d->path, QLatin1String(NM_DBUS_PATH_SETTINGS), + QLatin1String(NM_DBUS_IFACE_SETTINGS), QLatin1String("NewConnection"), this, SIGNAL(newConnection(QDBusObjectPath)))) { allOk = true; } @@ -655,7 +628,7 @@ bool QNetworkManagerSettings::setConnections() QList QNetworkManagerSettings::listConnections() { - QDBusReply > reply = d->connectionInterface->call("ListConnections"); + QDBusReply > reply = d->connectionInterface->call(QLatin1String("ListConnections")); return reply.value(); } @@ -665,7 +638,6 @@ QDBusInterface *QNetworkManagerSettings::connectionInterface() const } -///////////// class QNetworkManagerSettingsConnectionPrivate { public: @@ -685,7 +657,7 @@ QNetworkManagerSettingsConnection::QNetworkManagerSettingsConnection(const QStri d->service = settingsService; d->connectionInterface = new QDBusInterface(settingsService, d->path, - NM_DBUS_IFACE_SETTINGS_CONNECTION, + QLatin1String(NM_DBUS_IFACE_SETTINGS_CONNECTION), dbusConnection, parent); if (!d->connectionInterface->isValid()) { //qWarning() << "Could not find NetworkManagerSettingsConnection"; @@ -693,14 +665,12 @@ QNetworkManagerSettingsConnection::QNetworkManagerSettingsConnection(const QStri return; } d->valid = true; - QDBusReply< QNmSettingsMap > rep = d->connectionInterface->call("GetSettings"); + QDBusReply< QNmSettingsMap > rep = d->connectionInterface->call(QLatin1String("GetSettings")); d->settingsMap = rep.value(); } QNetworkManagerSettingsConnection::~QNetworkManagerSettingsConnection() { - if (nmDBusHelper) - delete nmDBusHelper; delete d->connectionInterface; delete d; } @@ -717,32 +687,26 @@ bool QNetworkManagerSettingsConnection::setConnections() bool allOk = false; if(!dbusConnection.connect(d->service, d->path, - NM_DBUS_IFACE_SETTINGS_CONNECTION, "Updated", + QLatin1String(NM_DBUS_IFACE_SETTINGS_CONNECTION), QLatin1String("Updated"), this, SIGNAL(updated(QNmSettingsMap)))) { allOk = true; } else { QDBusError error = dbusConnection.lastError(); } - if (nmDBusHelper) - delete nmDBusHelper; - nmDBusHelper = 0; - nmDBusHelper = new QNmDBusHelper; + delete nmDBusHelper; + nmDBusHelper = new QNmDBusHelper(this); connect(nmDBusHelper, SIGNAL(pathForSettingsRemoved(const QString &)), this,SIGNAL(removed( const QString &))); if (!dbusConnection.connect(d->service, d->path, - NM_DBUS_IFACE_SETTINGS_CONNECTION, "Removed", + QLatin1String(NM_DBUS_IFACE_SETTINGS_CONNECTION), QLatin1String("Removed"), nmDBusHelper, SIGNAL(slotSettingsRemoved()))) { allOk = true; } return allOk; } -//QNetworkManagerSettingsConnection::update(QNmSettingsMap map) -//{ -// d->connectionInterface->call("Update", QVariant::fromValue(map)); -//} QDBusInterface *QNetworkManagerSettingsConnection::connectionInterface() const { @@ -751,23 +715,23 @@ QDBusInterface *QNetworkManagerSettingsConnection::connectionInterface() const QNmSettingsMap QNetworkManagerSettingsConnection::getSettings() { - QDBusReply< QNmSettingsMap > rep = d->connectionInterface->call("GetSettings"); + QDBusReply< QNmSettingsMap > rep = d->connectionInterface->call(QLatin1String("GetSettings")); d->settingsMap = rep.value(); return d->settingsMap; } NMDeviceType QNetworkManagerSettingsConnection::getType() { - QNmSettingsMap::const_iterator i = d->settingsMap.find("connection"); - while (i != d->settingsMap.end() && i.key() == "connection") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("connection")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("connection")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("type"); - while (ii != innerMap.end() && ii.key() == "type") { + QMap::const_iterator ii = innerMap.find(QLatin1String("type")); + while (ii != innerMap.end() && ii.key() == QLatin1String("type")) { QString devType = ii.value().toString(); - if (devType == "802-3-ethernet") { + if (devType == QLatin1String("802-3-ethernet")) { return DEVICE_TYPE_802_3_ETHERNET; } - if (devType == "802-11-wireless") { + if (devType == QLatin1String("802-11-wireless")) { return DEVICE_TYPE_802_11_WIRELESS; } ii++; @@ -779,11 +743,11 @@ NMDeviceType QNetworkManagerSettingsConnection::getType() bool QNetworkManagerSettingsConnection::isAutoConnect() { - QNmSettingsMap::const_iterator i = d->settingsMap.find("connection"); - while (i != d->settingsMap.end() && i.key() == "connection") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("connection")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("connection")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("autoconnect"); - while (ii != innerMap.end() && ii.key() == "autoconnect") { + QMap::const_iterator ii = innerMap.find(QLatin1String("autoconnect")); + while (ii != innerMap.end() && ii.key() == QLatin1String("autoconnect")) { return ii.value().toBool(); ii++; } @@ -794,11 +758,11 @@ bool QNetworkManagerSettingsConnection::isAutoConnect() quint64 QNetworkManagerSettingsConnection::getTimestamp() { - QNmSettingsMap::const_iterator i = d->settingsMap.find("connection"); - while (i != d->settingsMap.end() && i.key() == "connection") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("connection")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("connection")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("timestamp"); - while (ii != innerMap.end() && ii.key() == "timestamp") { + QMap::const_iterator ii = innerMap.find(QLatin1String("timestamp")); + while (ii != innerMap.end() && ii.key() == QLatin1String("timestamp")) { return ii.value().toUInt(); ii++; } @@ -809,11 +773,11 @@ quint64 QNetworkManagerSettingsConnection::getTimestamp() QString QNetworkManagerSettingsConnection::getId() { - QNmSettingsMap::const_iterator i = d->settingsMap.find("connection"); - while (i != d->settingsMap.end() && i.key() == "connection") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("connection")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("connection")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("id"); - while (ii != innerMap.end() && ii.key() == "id") { + QMap::const_iterator ii = innerMap.find(QLatin1String("id")); + while (ii != innerMap.end() && ii.key() == QLatin1String("id")) { return ii.value().toString(); ii++; } @@ -824,11 +788,11 @@ QString QNetworkManagerSettingsConnection::getId() QString QNetworkManagerSettingsConnection::getUuid() { - QNmSettingsMap::const_iterator i = d->settingsMap.find("connection"); - while (i != d->settingsMap.end() && i.key() == "connection") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("connection")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("connection")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("uuid"); - while (ii != innerMap.end() && ii.key() == "uuid") { + QMap::const_iterator ii = innerMap.find(QLatin1String("uuid")); + while (ii != innerMap.end() && ii.key() == QLatin1String("uuid")) { return ii.value().toString(); ii++; } @@ -840,11 +804,11 @@ QString QNetworkManagerSettingsConnection::getUuid() QString QNetworkManagerSettingsConnection::getSsid() { - QNmSettingsMap::const_iterator i = d->settingsMap.find("802-11-wireless"); - while (i != d->settingsMap.end() && i.key() == "802-11-wireless") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("802-11-wireless")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("802-11-wireless")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("ssid"); - while (ii != innerMap.end() && ii.key() == "ssid") { + QMap::const_iterator ii = innerMap.find(QLatin1String("ssid")); + while (ii != innerMap.end() && ii.key() == QLatin1String("ssid")) { return ii.value().toString(); ii++; } @@ -856,11 +820,11 @@ QString QNetworkManagerSettingsConnection::getSsid() QString QNetworkManagerSettingsConnection::getMacAddress() { if(getType() == DEVICE_TYPE_802_3_ETHERNET) { - QNmSettingsMap::const_iterator i = d->settingsMap.find("802-3-ethernet"); - while (i != d->settingsMap.end() && i.key() == "802-3-ethernet") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("802-3-ethernet")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("802-3-ethernet")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("mac-address"); - while (ii != innerMap.end() && ii.key() == "mac-address") { + QMap::const_iterator ii = innerMap.find(QLatin1String("mac-address")); + while (ii != innerMap.end() && ii.key() == QLatin1String("mac-address")) { return ii.value().toString(); ii++; } @@ -869,11 +833,11 @@ QString QNetworkManagerSettingsConnection::getMacAddress() } else if(getType() == DEVICE_TYPE_802_11_WIRELESS) { - QNmSettingsMap::const_iterator i = d->settingsMap.find("802-11-wireless"); - while (i != d->settingsMap.end() && i.key() == "802-11-wireless") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("802-11-wireless")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("802-11-wireless")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("mac-address"); - while (ii != innerMap.end() && ii.key() == "mac-address") { + QMap::const_iterator ii = innerMap.find(QLatin1String("mac-address")); + while (ii != innerMap.end() && ii.key() == QLatin1String("mac-address")) { return ii.value().toString(); ii++; } @@ -886,11 +850,11 @@ QString QNetworkManagerSettingsConnection::getMacAddress() QStringList QNetworkManagerSettingsConnection::getSeenBssids() { if(getType() == DEVICE_TYPE_802_11_WIRELESS) { - QNmSettingsMap::const_iterator i = d->settingsMap.find("802-11-wireless"); - while (i != d->settingsMap.end() && i.key() == "802-11-wireless") { + QNmSettingsMap::const_iterator i = d->settingsMap.find(QLatin1String("802-11-wireless")); + while (i != d->settingsMap.end() && i.key() == QLatin1String("802-11-wireless")) { QMap innerMap = i.value(); - QMap::const_iterator ii = innerMap.find("seen-bssids"); - while (ii != innerMap.end() && ii.key() == "seen-bssids") { + QMap::const_iterator ii = innerMap.find(QLatin1String("seen-bssids")); + while (ii != innerMap.end() && ii.key() == QLatin1String("seen-bssids")) { return ii.value().toStringList(); ii++; } @@ -900,7 +864,6 @@ QStringList QNetworkManagerSettingsConnection::getSeenBssids() return QStringList(); } -///////////// class QNetworkManagerConnectionActivePrivate { public: @@ -914,9 +877,9 @@ QNetworkManagerConnectionActive::QNetworkManagerConnectionActive( const QString { d = new QNetworkManagerConnectionActivePrivate(); d->path = activeConnectionObjectPath; - d->connectionInterface = new QDBusInterface(NM_DBUS_SERVICE, + d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_ACTIVE_CONNECTION, + QLatin1String(NM_DBUS_INTERFACE_ACTIVE_CONNECTION), dbusConnection, parent); if (!d->connectionInterface->isValid()) { d->valid = false; @@ -928,8 +891,6 @@ QNetworkManagerConnectionActive::QNetworkManagerConnectionActive( const QString QNetworkManagerConnectionActive::~QNetworkManagerConnectionActive() { - if (nmDBusHelper) - delete nmDBusHelper; delete d->connectionInterface; delete d; } @@ -945,16 +906,14 @@ bool QNetworkManagerConnectionActive::setConnections() return false; bool allOk = false; - if (nmDBusHelper) - delete nmDBusHelper; - nmDBusHelper = 0; - nmDBusHelper = new QNmDBusHelper; + delete nmDBusHelper; + nmDBusHelper = new QNmDBusHelper(this); connect(nmDBusHelper, SIGNAL(pathForPropertiesChanged(const QString &,QMap)), this,SIGNAL(propertiesChanged( const QString &, QMap))); - if(dbusConnection.connect(NM_DBUS_SERVICE, + if(dbusConnection.connect(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_ACTIVE_CONNECTION, - "PropertiesChanged", + QLatin1String(NM_DBUS_INTERFACE_ACTIVE_CONNECTION), + QLatin1String("PropertiesChanged"), nmDBusHelper,SLOT(slotPropertiesChanged( QMap))) ) { allOk = true; } @@ -1000,8 +959,6 @@ bool QNetworkManagerConnectionActive::defaultRoute() const return d->connectionInterface->property("Default").toBool(); } - -//// class QNetworkManagerIp4ConfigPrivate { public: @@ -1015,9 +972,9 @@ QNetworkManagerIp4Config::QNetworkManagerIp4Config( const QString &deviceObjectP { d = new QNetworkManagerIp4ConfigPrivate(); d->path = deviceObjectPath; - d->connectionInterface = new QDBusInterface(NM_DBUS_SERVICE, + d->connectionInterface = new QDBusInterface(QLatin1String(NM_DBUS_SERVICE), d->path, - NM_DBUS_INTERFACE_IP4_CONFIG, + QLatin1String(NM_DBUS_INTERFACE_IP4_CONFIG), dbusConnection, parent); if (!d->connectionInterface->isValid()) { d->valid = false; diff --git a/src/plugins/bearer/networkmanager/qnetworkmanagerservice.h b/src/plugins/bearer/networkmanager/qnetworkmanagerservice.h index 81903ec..048f628 100644 --- a/src/plugins/bearer/networkmanager/qnetworkmanagerservice.h +++ b/src/plugins/bearer/networkmanager/qnetworkmanagerservice.h @@ -53,26 +53,87 @@ // We mean it. // -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include -#include +#include +#include +#include +#include #include "qnmdbushelper.h" +#ifndef NETWORK_MANAGER_H +typedef enum NMDeviceType +{ + DEVICE_TYPE_UNKNOWN = 0, + DEVICE_TYPE_802_3_ETHERNET, + DEVICE_TYPE_802_11_WIRELESS, + DEVICE_TYPE_GSM, + DEVICE_TYPE_CDMA +} NMDeviceType; + +typedef enum +{ + NM_DEVICE_STATE_UNKNOWN = 0, + NM_DEVICE_STATE_UNMANAGED, + NM_DEVICE_STATE_UNAVAILABLE, + NM_DEVICE_STATE_DISCONNECTED, + NM_DEVICE_STATE_PREPARE, + NM_DEVICE_STATE_CONFIG, + NM_DEVICE_STATE_NEED_AUTH, + NM_DEVICE_STATE_IP_CONFIG, + NM_DEVICE_STATE_ACTIVATED, + NM_DEVICE_STATE_FAILED +} NMDeviceState; + +typedef enum +{ + NM_ACTIVE_CONNECTION_STATE_UNKNOWN = 0, + NM_ACTIVE_CONNECTION_STATE_ACTIVATING, + NM_ACTIVE_CONNECTION_STATE_ACTIVATED +} NMActiveConnectionState; + +#define NM_DBUS_SERVICE "org.freedesktop.NetworkManager" + +#define NM_DBUS_PATH "/org/freedesktop/NetworkManager" +#define NM_DBUS_INTERFACE "org.freedesktop.NetworkManager" +#define NM_DBUS_INTERFACE_DEVICE NM_DBUS_INTERFACE ".Device" +#define NM_DBUS_INTERFACE_DEVICE_WIRED NM_DBUS_INTERFACE_DEVICE ".Wired" +#define NM_DBUS_INTERFACE_DEVICE_WIRELESS NM_DBUS_INTERFACE_DEVICE ".Wireless" +#define NM_DBUS_PATH_ACCESS_POINT NM_DBUS_PATH "/AccessPoint" +#define NM_DBUS_INTERFACE_ACCESS_POINT NM_DBUS_INTERFACE ".AccessPoint" + +#define NM_DBUS_PATH_SETTINGS "/org/freedesktop/NetworkManagerSettings" + +#define NM_DBUS_IFACE_SETTINGS_CONNECTION "org.freedesktop.NetworkManagerSettings.Connection" +#define NM_DBUS_IFACE_SETTINGS "org.freedesktop.NetworkManagerSettings" +#define NM_DBUS_INTERFACE_ACTIVE_CONNECTION NM_DBUS_INTERFACE ".Connection.Active" +#define NM_DBUS_INTERFACE_IP4_CONFIG NM_DBUS_INTERFACE ".IP4Config" + +#define NM_DBUS_SERVICE_USER_SETTINGS "org.freedesktop.NetworkManagerUserSettings" +#define NM_DBUS_SERVICE_SYSTEM_SETTINGS "org.freedesktop.NetworkManagerSystemSettings" + +#define NM_802_11_AP_FLAGS_NONE 0x00000000 +#define NM_802_11_AP_FLAGS_PRIVACY 0x00000001 +#endif + QT_BEGIN_NAMESPACE typedef QMap< QString, QMap > QNmSettingsMap; typedef QList ServerThing; -Q_DECLARE_METATYPE(QNmSettingsMap) -Q_DECLARE_METATYPE(ServerThing) +QT_END_NAMESPACE + +Q_DECLARE_METATYPE(QT_PREPEND_NAMESPACE(QNmSettingsMap)) +Q_DECLARE_METATYPE(QT_PREPEND_NAMESPACE(ServerThing)) + +QT_BEGIN_NAMESPACE class QNetworkManagerInterfacePrivate; class QNetworkManagerInterface : public QObject @@ -107,12 +168,10 @@ Q_SIGNALS: private Q_SLOTS: private: -// Q_DISABLE_COPY(QNetworkManagerInterface); ?? QNetworkManagerInterfacePrivate *d; QNmDBusHelper *nmDBusHelper; -}; //end QNetworkManagerInterface +}; -//////// class QNetworkManagerInterfaceAccessPointPrivate; class QNetworkManagerInterfaceAccessPoint : public QObject { @@ -120,7 +179,6 @@ class QNetworkManagerInterfaceAccessPoint : public QObject public: - // NM_DEVICE_STATE enum DeviceState { Unknown = 0, Unmanaged, @@ -181,9 +239,8 @@ private: QNetworkManagerInterfaceAccessPointPrivate *d; QNmDBusHelper *nmDBusHelper; -}; //end QNetworkManagerInterfaceAccessPoint +}; -//////// class QNetworkManagerInterfaceDevicePrivate; class QNetworkManagerInterfaceDevice : public QObject { @@ -195,7 +252,7 @@ public: ~QNetworkManagerInterfaceDevice(); QString udi() const; - QNetworkInterface interface() const; + QNetworkInterface networkInterface() const; QDBusInterface *connectionInterface() const; quint32 ip4Address() const; quint32 state() const; @@ -211,9 +268,8 @@ Q_SIGNALS: private: QNetworkManagerInterfaceDevicePrivate *d; QNmDBusHelper *nmDBusHelper; -}; //end QNetworkManagerInterfaceDevice +}; -//////// class QNetworkManagerInterfaceDeviceWiredPrivate; class QNetworkManagerInterfaceDeviceWired : public QObject { @@ -236,9 +292,8 @@ Q_SIGNALS: private: QNetworkManagerInterfaceDeviceWiredPrivate *d; QNmDBusHelper *nmDBusHelper; -}; // end QNetworkManagerInterfaceDeviceWired +}; -//// class QNetworkManagerInterfaceDeviceWirelessPrivate; class QNetworkManagerInterfaceDeviceWireless : public QObject { @@ -278,9 +333,8 @@ Q_SIGNALS: private: QNetworkManagerInterfaceDeviceWirelessPrivate *d; QNmDBusHelper *nmDBusHelper; -}; // end QNetworkManagerInterfaceDeviceWireless +}; -//// class QNetworkManagerSettingsPrivate; class QNetworkManagerSettings : public QObject { @@ -300,9 +354,8 @@ Q_SIGNALS: void newConnection(QDBusObjectPath); private: QNetworkManagerSettingsPrivate *d; -}; //end QNetworkManagerSettings +}; -//// class QNetworkManagerSettingsConnectionPrivate; class QNetworkManagerSettingsConnection : public QObject { @@ -315,7 +368,6 @@ public: QDBusInterface *connectionInterface() const; QNmSettingsMap getSettings(); - // void update(QNmSettingsMap map); bool setConnections(); NMDeviceType getType(); bool isAutoConnect(); @@ -335,9 +387,8 @@ Q_SIGNALS: private: QNmDBusHelper *nmDBusHelper; QNetworkManagerSettingsConnectionPrivate *d; -}; //end QNetworkManagerSettingsConnection +}; -//// class QNetworkManagerConnectionActivePrivate; class QNetworkManagerConnectionActive : public QObject { @@ -371,9 +422,8 @@ Q_SIGNALS: private: QNetworkManagerConnectionActivePrivate *d; QNmDBusHelper *nmDBusHelper; -}; //QNetworkManagerConnectionActive +}; -//// class QNetworkManagerIp4ConfigPrivate; class QNetworkManagerIp4Config : public QObject { @@ -383,14 +433,12 @@ public: QNetworkManagerIp4Config(const QString &dbusPathName, QObject *parent = 0); ~QNetworkManagerIp4Config(); - // QList nameservers(); QStringList domains() const; bool isValid(); private: QNetworkManagerIp4ConfigPrivate *d; }; -//// QT_END_NAMESPACE diff --git a/src/plugins/bearer/networkmanager/qnmdbushelper.cpp b/src/plugins/bearer/networkmanager/qnmdbushelper.cpp index d5e20f3..e195eeb 100644 --- a/src/plugins/bearer/networkmanager/qnmdbushelper.cpp +++ b/src/plugins/bearer/networkmanager/qnmdbushelper.cpp @@ -43,7 +43,7 @@ #include "qnmdbushelper.h" -#include +#include "qnetworkmanagerservice.h" #include #include @@ -54,6 +54,15 @@ QT_BEGIN_NAMESPACE +QNmDBusHelper::QNmDBusHelper(QObject * parent) + : QObject(parent) +{ +} + +QNmDBusHelper::~QNmDBusHelper() +{ +} + void QNmDBusHelper::deviceStateChanged(quint32 state) { QDBusMessage msg = this->message(); diff --git a/src/plugins/bearer/networkmanager/qnmdbushelper.h b/src/plugins/bearer/networkmanager/qnmdbushelper.h index 862290c..933d55a 100644 --- a/src/plugins/bearer/networkmanager/qnmdbushelper.h +++ b/src/plugins/bearer/networkmanager/qnmdbushelper.h @@ -52,6 +52,8 @@ class QNmDBusHelper: public QObject, protected QDBusContext { Q_OBJECT public: + QNmDBusHelper(QObject *parent = 0); + ~QNmDBusHelper(); public slots: void deviceStateChanged(quint32); diff --git a/src/plugins/bearer/qnetworksession_impl.cpp b/src/plugins/bearer/qnetworksession_impl.cpp index f41fdba..5f03893 100644 --- a/src/plugins/bearer/qnetworksession_impl.cpp +++ b/src/plugins/bearer/qnetworksession_impl.cpp @@ -147,6 +147,8 @@ void QNetworkSessionPrivateImpl::open() if ((activeConfig.state() & QNetworkConfiguration::Discovered) != QNetworkConfiguration::Discovered) { lastError =QNetworkSession::InvalidConfigurationError; + state = QNetworkSession::Invalid; + emit stateChanged(state); emit QNetworkSessionPrivate::error(lastError); return; } @@ -400,7 +402,6 @@ void QNetworkSessionPrivateImpl::connectionError(const QString &id, lastError = QNetworkSession::UnknownSessionError; } - emit quitPendingWaitsForOpened(); emit QNetworkSessionPrivate::error(lastError); } } diff --git a/src/plugins/bearer/symbian/qnetworksession_impl.cpp b/src/plugins/bearer/symbian/qnetworksession_impl.cpp index 9af1fe9..bec562d 100644 --- a/src/plugins/bearer/symbian/qnetworksession_impl.cpp +++ b/src/plugins/bearer/symbian/qnetworksession_impl.cpp @@ -141,7 +141,10 @@ void QNetworkSessionPrivateImpl::syncStateWithInterface() if (state != QNetworkSession::Connected) { // There were no open connections to used IAP or SNAP - if ((privateConfiguration(publicConfig)->state & QNetworkConfiguration::Discovered) == + if (iError == QNetworkSession::InvalidConfigurationError) { + newState(QNetworkSession::Invalid); + } + else if ((privateConfiguration(publicConfig)->state & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) { newState(QNetworkSession::Disconnected); } else { @@ -231,13 +234,23 @@ QNetworkSession::SessionError QNetworkSessionPrivateImpl::error() const void QNetworkSessionPrivateImpl::open() { - if (isOpen || !privateConfiguration(publicConfig) || (state == QNetworkSession::Connecting)) { + if (isOpen || (state == QNetworkSession::Connecting)) { return; } // Cancel notifications from RConnectionMonitor // => RConnection::ProgressNotification will be used for IAP/SNAP monitoring iConnectionMonitor.CancelNotifications(); + + // Configuration must be at least in Discovered - state for connecting purposes. + if ((publicConfig.state() & QNetworkConfiguration::Discovered) != + QNetworkConfiguration::Discovered) { + newState(QNetworkSession::Invalid); + iError = QNetworkSession::InvalidConfigurationError; + emit QNetworkSessionPrivate::error(iError); + syncStateWithInterface(); + return; + } TInt error = iSocketServ.Connect(); if (error != KErrNone) { diff --git a/src/plugins/bearer/symbian/symbianengine.cpp b/src/plugins/bearer/symbian/symbianengine.cpp index b3c9cb3..88a563c 100644 --- a/src/plugins/bearer/symbian/symbianengine.cpp +++ b/src/plugins/bearer/symbian/symbianengine.cpp @@ -98,7 +98,7 @@ QString SymbianNetworkConfigurationPrivate::bearerName() const } SymbianEngine::SymbianEngine(QObject *parent) -: QBearerEngine(parent), CActive(CActive::EPriorityIdle), iInitOk(true) +: QBearerEngine(parent), CActive(CActive::EPriorityIdle), iFirstUpdate(true), iInitOk(true) { CActiveScheduler::Add(this); @@ -136,9 +136,12 @@ SymbianEngine::SymbianEngine(QObject *parent) updateConfigurations(); updateStatesToSnaps(); + + updateAvailableAccessPoints(); // On first time updates synchronously (without WLAN scans) // Start monitoring IAP and/or SNAP changes in Symbian CommsDB startCommsDatabaseNotifications(); + iFirstUpdate = false; } SymbianEngine::~SymbianEngine() @@ -153,7 +156,14 @@ SymbianEngine::~SymbianEngine() #endif delete ipAccessPointsAvailabilityScanner; + + // CCommsDatabase destructor uses cleanup stack. Since QNetworkConfigurationManager + // is a global static, but the time we are here, E32Main() has been exited already and + // the thread's default cleanup stack has been deleted. Without this line, a + // 'E32USER-CBase 69' -panic will occur. + CTrapCleanup* cleanup = CTrapCleanup::New(); delete ipCommsDB; + delete cleanup; } bool SymbianEngine::hasIdentifier(const QString &id) @@ -692,9 +702,10 @@ void SymbianEngine::accessPointScanningReady(TBool scanSuccessful, TConnMonIapIn updateStatesToSnaps(); - startCommsDatabaseNotifications(); - - emit updateCompleted(); + if (!iFirstUpdate) { + startCommsDatabaseNotifications(); + emit updateCompleted(); + } } void SymbianEngine::updateStatesToSnaps() @@ -987,11 +998,22 @@ void AccessPointsAvailabilityScanner::DoCancel() void AccessPointsAvailabilityScanner::StartScanning() { - iConnectionMonitor.GetPckgAttribute(EBearerIdAll, 0, KIapAvailability, iIapBuf, iStatus); - if (!IsActive()) { - SetActive(); + if (iOwner.iFirstUpdate) { + // On first update (the mgr is being instantiated) update only those bearers who + // don't need time-consuming scans (WLAN). + // Note: EBearerIdWCDMA covers also GPRS bearer + iConnectionMonitor.GetPckgAttribute(EBearerIdWCDMA, 0, KIapAvailability, iIapBuf, iStatus); + User::WaitForRequest(iStatus); + if (iStatus.Int() == KErrNone) { + iOwner.accessPointScanningReady(true,iIapBuf()); + } + } else { + iConnectionMonitor.GetPckgAttribute(EBearerIdAll, 0, KIapAvailability, iIapBuf, iStatus); + if (!IsActive()) { + SetActive(); + } } -} +} void AccessPointsAvailabilityScanner::RunL() { diff --git a/src/plugins/bearer/symbian/symbianengine.h b/src/plugins/bearer/symbian/symbianengine.h index 5448813..ee6d070 100644 --- a/src/plugins/bearer/symbian/symbianengine.h +++ b/src/plugins/bearer/symbian/symbianengine.h @@ -162,6 +162,7 @@ private: // MConnectionMonitorObserver void EventL(const CConnMonEventBase& aEvent); private: // Data + bool iFirstUpdate; CCommsDatabase* ipCommsDB; RConnectionMonitor iConnectionMonitor; diff --git a/tests/auto/qbearertestcommon.h b/tests/auto/qbearertestcommon.h index 0bfe622..c9df249 100644 --- a/tests/auto/qbearertestcommon.h +++ b/tests/auto/qbearertestcommon.h @@ -42,6 +42,19 @@ #ifndef QBEARERTESTCOMMON_H #define QBEARERTESTCOMMON_H +// Wait for __expr to happen, while still allowing events to be processed. +#define QTRY_NOOP(__expr) \ + do { \ + const int __step = 50; \ + const int __timeout = 15000; \ + if (!(__expr)) { \ + QTest::qWait(0); \ + } \ + for (int __i = 0; __i < __timeout && !(__expr); __i+=__step) { \ + QTest::qWait(__step); \ + } \ + } while(0) + // Will try to wait for the condition while allowing event processing #define QTRY_VERIFY(__expr) \ do { \ diff --git a/tests/auto/qnetworksession/lackey/main.cpp b/tests/auto/qnetworksession/lackey/main.cpp index 41e935a..66d6dd4 100644 --- a/tests/auto/qnetworksession/lackey/main.cpp +++ b/tests/auto/qnetworksession/lackey/main.cpp @@ -69,14 +69,15 @@ int main(int argc, char** argv) QNetworkConfigurationManager manager; QList discovered = -#if defined (Q_OS_SYMBIAN) - // On Symbian, on the first query (before updateConfigurations() call - // the discovered-states are not correct, so defined-state will do. - manager.allConfigurations(QNetworkConfiguration::Defined); -#else manager.allConfigurations(QNetworkConfiguration::Discovered); -#endif + + foreach(QNetworkConfiguration config, discovered) { + qDebug() << "Lackey: Name of the config enumerated: " << config.name(); + qDebug() << "Lackey: State of the config enumerated: " << config.state(); + } + if (discovered.isEmpty()) { + qDebug("Lackey: no discovered configurations, returning empty error."); return NO_DISCOVERED_CONFIGURATIONS_ERROR; } diff --git a/tests/auto/qnetworksession/test/tst_qnetworksession.cpp b/tests/auto/qnetworksession/test/tst_qnetworksession.cpp index 4ef3a4f..58b1a48 100644 --- a/tests/auto/qnetworksession/test/tst_qnetworksession.cpp +++ b/tests/auto/qnetworksession/test/tst_qnetworksession.cpp @@ -54,6 +54,7 @@ QT_USE_NAMESPACE Q_DECLARE_METATYPE(QNetworkConfiguration) +Q_DECLARE_METATYPE(QNetworkConfiguration::Type); Q_DECLARE_METATYPE(QNetworkSession::State); Q_DECLARE_METATYPE(QNetworkSession::SessionError); @@ -70,6 +71,11 @@ private slots: void outOfProcessSession(); void invalidSession(); + void repeatedOpenClose_data(); + void repeatedOpenClose(); + + void roamingErrorCodes(); + void sessionProperties_data(); void sessionProperties(); @@ -94,11 +100,17 @@ private: #endif }; +// Helper functions +bool openSession(QNetworkSession *session); +bool closeSession(QNetworkSession *session, bool lastSessionOnConfiguration = true); +QNetworkConfiguration suitableConfiguration(QString bearerType, QNetworkConfiguration::Type configType); + void tst_QNetworkSession::initTestCase() { qRegisterMetaType("QNetworkSession::State"); qRegisterMetaType("QNetworkSession::SessionError"); qRegisterMetaType("QNetworkConfiguration"); + qRegisterMetaType("QNetworkConfiguration::Type"); #ifdef Q_WS_MAEMO_6 iapconf = new Maemo::IAPConf("007"); @@ -211,9 +223,42 @@ void tst_QNetworkSession::cleanupTestCase() void tst_QNetworkSession::invalidSession() { + // Verify that session created with invalid configuration remains in invalid state QNetworkSession session(QNetworkConfiguration(), 0); QVERIFY(!session.isOpen()); QVERIFY(session.state() == QNetworkSession::Invalid); + QVERIFY(session.error() == QNetworkSession::InvalidConfigurationError); + + // Verify that opening session with invalid configuration both 1) emits invalidconfigurationerror + // and 2) sets session's state as invalid. + QSignalSpy errorSpy(&session, SIGNAL(error(QNetworkSession::SessionError))); + session.open(); + session.waitForOpened(1000); // Should bail out right away + QVERIFY(errorSpy.count() == 1); + QNetworkSession::SessionError error = + qvariant_cast (errorSpy.first().at(0)); + QVERIFY(error == QNetworkSession::InvalidConfigurationError); + QVERIFY(session.error() == QNetworkSession::InvalidConfigurationError); + QVERIFY(session.state() == QNetworkSession::Invalid); + + // Check same thing with a config from platform (there are subtle differences + // because emtpy configuration does not have private pointer). Test with config + // in '(un)defined' state + QList allConfigs = manager.allConfigurations(); + foreach(QNetworkConfiguration config, allConfigs) { + if ((config.state() & QNetworkConfiguration::Discovered) != QNetworkConfiguration::Discovered) { + QNetworkSession session2(config); + QSignalSpy errorSpy2(&session2, SIGNAL(error(QNetworkSession::SessionError))); + session2.open(); + session2.waitForOpened(1000); // Should bail out right away + QVERIFY(errorSpy2.count() == 1); + QNetworkSession::SessionError error2 = + qvariant_cast (errorSpy2.first().at(0)); + QVERIFY(error2 == QNetworkSession::InvalidConfigurationError); + QVERIFY(session2.state() == QNetworkSession::Invalid); + break; // Once is enough + } + } } void tst_QNetworkSession::sessionProperties_data() @@ -300,6 +345,100 @@ void tst_QNetworkSession::sessionProperties() } } +void tst_QNetworkSession::repeatedOpenClose_data() { + QTest::addColumn("bearerType"); + QTest::addColumn("configurationType"); + QTest::addColumn("repeatTimes"); + + QTest::newRow("WLAN_IAP") << "WLAN" << QNetworkConfiguration::InternetAccessPoint << 3; + // QTest::newRow("Cellular_IAP") << "cellular" << QNetworkConfiguration::InternetAccessPoint << 3; + // QTest::newRow("SNAP") << "bearer_type_not_relevant_with_SNAPs" << QNetworkConfiguration::ServiceNetwork << 3; +} + +// Tests repeated-open close. +void tst_QNetworkSession::repeatedOpenClose() { + QFETCH(QString, bearerType); + QFETCH(QNetworkConfiguration::Type, configurationType); + QFETCH(int, repeatTimes); + + // First check that opening once succeeds and determine if repeatable testing is doable + QNetworkConfiguration config = suitableConfiguration(bearerType, configurationType); + if (!config.isValid()) { + QSKIP("No suitable configurations, skipping this round of repeated open-close test.", SkipSingle); + } + qDebug() << "Using following configuratio to repeatedly open and close: " << config.name(); + QNetworkSession permanentSession(config); + if (!openSession(&permanentSession) || + !closeSession(&permanentSession)) { + QSKIP("Unable to open/close session, skipping this round of repeated open-close test.", SkipSingle); + } + for (int i = repeatTimes; i > 0; i--) { + QVERIFY(openSession(&permanentSession)); + QVERIFY(closeSession(&permanentSession)); + } +} + +void tst_QNetworkSession::roamingErrorCodes() { + +#ifndef Q_OS_SYMBIAN + QSKIP("Roaming supported on Symbian.", SkipAll); +#else + QNetworkConfiguration wlanIapConfig = suitableConfiguration("WLAN", QNetworkConfiguration::InternetAccessPoint); + if (!wlanIapConfig.isValid()) { + QSKIP("No WLAN IAP accessible, skipping test.", SkipAll); + } + // Check that opening and closing two sessions on same config work gracefully: + QNetworkSession iapSession(wlanIapConfig); + QVERIFY(openSession(&iapSession)); + QNetworkSession adminIapSession(wlanIapConfig); + QVERIFY(openSession(&adminIapSession)); + QVERIFY(closeSession(&iapSession, false)); // false == not a last session based on the configuration + QVERIFY(closeSession(&adminIapSession)); + + // Open configurations again, force close bearer and check that errors are emitted correctly + // on the other session + QVERIFY(openSession(&iapSession)); + QVERIFY(openSession(&adminIapSession)); + QSignalSpy errorSpy(&iapSession, SIGNAL(error(QNetworkSession::SessionError))); + adminIapSession.stop(); // requires NetworkControl capabilities + QTRY_VERIFY(!errorSpy.isEmpty()); // wait for error signals + QNetworkSession::SessionError error = qvariant_cast(errorSpy.first().at(0)); + QVERIFY(error == QNetworkSession::SessionAbortedError); + QVERIFY(iapSession.state() == QNetworkSession::Disconnected); + QVERIFY(adminIapSession.state() == QNetworkSession::Disconnected); +#endif // Q_OS_SYMBIAN + /* + // Check for roaming error. Challenging to automate, therefore commented out. + // Case requires that you have controllable WLAN in Internet SNAP (only). + QNetworkConfiguration snapConfig = suitableConfiguration("bearer_not_relevant_with_snaps", QNetworkConfiguration::ServiceNetwork); + if (!snapConfig.isValid()) { + QSKIP("No SNAP accessible, skipping test.", SkipAll); + } + QNetworkSession snapSession(snapConfig); + QVERIFY(openSession(&snapSession)); + QSignalSpy errorSpySnap(&snapSession, SIGNAL(error(QNetworkSession::SessionError))); + qDebug("Disconnect the WLAN now"); + QTRY_VERIFY(!errorSpySnap.isEmpty()); // wait for error signals + QVERIFY(errorSpySnap.count() == 1); + error = qvariant_cast(errorSpySnap.first().at(0)); + qDebug() << "Error received when turning off wlan on SNAP: " << error; + QVERIFY(error == QNetworkSession::RoamingError); + + qDebug("Connect the WLAN now"); + QTest::qWait(60000); // Wait for WLAN to get up + QNetworkConfiguration wlanIapConfig2 = suitableConfiguration("WLAN", QNetworkConfiguration::InternetAccessPoint); + QNetworkSession iapSession2(wlanIapConfig2); + QVERIFY(openSession(&iapSession2)); + QSignalSpy errorSpy2(&iapSession2, SIGNAL(error(QNetworkSession::SessionError))); + qDebug("Disconnect the WLAN now"); + QTRY_VERIFY(!errorSpy2.isEmpty()); // wait for error signals + QVERIFY(errorSpy2.count() == 1); + error = qvariant_cast(errorSpy2.first().at(0)); + QVERIFY(error == QNetworkSession::SessionAbortedError); + QVERIFY(iapSession2.state() == QNetworkSession::Disconnected); + */ +} + void tst_QNetworkSession::userChoiceSession_data() { QTest::addColumn("configuration"); @@ -810,7 +949,7 @@ QDebug operator<<(QDebug debug, const QList &list) } // Note: outOfProcessSession requires that at least one configuration is -// at Discovered -state (Defined is ok for symbian as well, as long as it is possible to open). +// at Discovered -state. void tst_QNetworkSession::outOfProcessSession() { qDebug() << "START"; @@ -913,6 +1052,158 @@ void tst_QNetworkSession::outOfProcessSession() qDebug("STOP"); } +// A convinience / helper function for testcases. Return the first matching configuration. +// Ignores configurations in other than 'discovered' -state. Returns invalid (QNetworkConfiguration()) +// if none found. +QNetworkConfiguration suitableConfiguration(QString bearerType, QNetworkConfiguration::Type configType) { + // Refresh configurations and derive configurations matching given parameters. + QNetworkConfigurationManager mgr; + QSignalSpy updateSpy(&mgr, SIGNAL(updateCompleted())); + mgr.updateConfigurations(); + QTRY_NOOP(updateSpy.count() == 1); + if (updateSpy.count() != 1) { + qDebug("tst_QNetworkSession::suitableConfiguration() failure: unable to update configurations"); + return QNetworkConfiguration(); + } + QList discoveredConfigs = mgr.allConfigurations(QNetworkConfiguration::Discovered); + foreach(QNetworkConfiguration config, discoveredConfigs) { + if ((config.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { + // qDebug() << "Dumping config because is active: " << config.name(); + discoveredConfigs.removeOne(config); + } else if (config.type() != configType) { + // qDebug() << "Dumping config because type (IAP/SNAP) mismatches: " << config.name(); + discoveredConfigs.removeOne(config); + } else if ((config.type() == QNetworkConfiguration::InternetAccessPoint) && + bearerType == "cellular") { // 'cellular' bearertype is for convinience + if (config.bearerName() != "2G" && + config.bearerName() != "CDMA2000" && + config.bearerName() != "WCDMA" && + config.bearerName() != "HSPA") { + // qDebug() << "Dumping config because bearer mismatches (cellular): " << config.name(); + discoveredConfigs.removeOne(config); + } + } else if ((config.type() == QNetworkConfiguration::InternetAccessPoint) && + bearerType != config.bearerName()) { + // qDebug() << "Dumping config because bearer mismatches (WLAN): " << config.name(); + discoveredConfigs.removeOne(config); + } + } + if (discoveredConfigs.isEmpty()) { + qDebug("tst_QNetworkSession::suitableConfiguration() failure: no suitable configurations present."); + return QNetworkConfiguration(); + } else { + return discoveredConfigs.first(); + } +} + +// A convinience function for test-cases: opens the given configuration and return +// true if it was done gracefully. +bool openSession(QNetworkSession *session) { + QNetworkConfigurationManager mgr; + QSignalSpy openedSpy(session, SIGNAL(opened())); + QSignalSpy stateChangeSpy(session, SIGNAL(stateChanged(QNetworkSession::State))); + QSignalSpy errorSpy(session, SIGNAL(error(QNetworkSession::SessionError))); + QSignalSpy configChangeSpy(&mgr, SIGNAL(configurationChanged(QNetworkConfiguration))); + // Store some initial statuses, because expected signals differ if the config is already + // active by some other session + QNetworkConfiguration::StateFlags configInitState = session->configuration().state(); + QNetworkSession::State sessionInitState = session->state(); + + if (session->isOpen() || + !session->sessionProperty("ActiveConfiguration").toString().isEmpty()) { + qDebug("tst_QNetworkSession::openSession() failure: session was already open / active."); + return false; + } else { + session->open(); + session->waitForOpened(120000); // Bringing interfaces up and down may take time at platform + } + // Check that connection opening went by the book. Add checks here if more strictness needed. + if (!session->isOpen()) { + qDebug("tst_QNetworkSession::openSession() failure: QNetworkSession::open() failed."); + return false; + } + if (openedSpy.count() != 1) { + qDebug("tst_QNetworkSession::openSession() failure: QNetworkSession::opened() - signal not received."); + return false; + } + if (!errorSpy.isEmpty()) { + qDebug("tst_QNetworkSession::openSession() failure: QNetworkSession::error() - signal was detected."); + return false; + } + if (sessionInitState != QNetworkSession::Connected && + stateChangeSpy.isEmpty()) { + qDebug("tst_QNetworkSession::openSession() failure: QNetworkSession::stateChanged() - signals not detected."); + return false; + } + if (configInitState != QNetworkConfiguration::Active && + configChangeSpy.isEmpty()) { + qDebug("tst_QNetworkSession::openSession() failure: QNetworkConfigurationManager::configurationChanged() - signals not detected."); + return false; + } + if (session->configuration().state() != QNetworkConfiguration::Active) { + qDebug("tst_QNetworkSession::openSession() failure: session's configuration is not in 'Active' -state."); + return false; + } + return true; +} + +// Helper function for closing opened session. Performs checks that +// session is closed gradefully (e.g. signals). Function does not delete +// the session. The lastSessionOnConfiguration (true by default) is used to +// tell if there are more sessions open, basing on same configration. This +// impacts the checks made. +bool closeSession(QNetworkSession *session, bool lastSessionOnConfiguration) { + if (!session) { + qDebug("tst_QNetworkSession::closeSession() failure: NULL session given"); + return false; + } + if (session->state() != QNetworkSession::Connected || + !session->isOpen()) { + qDebug("tst_QNetworkSession::closeSession() failure: session is not opened."); + return false; + } + QNetworkConfigurationManager mgr; + QSignalSpy sessionClosedSpy(session, SIGNAL(closed())); + QSignalSpy sessionStateChangedSpy(session, SIGNAL(stateChanged(QNetworkSession::State))); + QSignalSpy sessionErrorSpy(session, SIGNAL(error(QNetworkSession::SessionError))); + QSignalSpy configChangeSpy(&mgr, SIGNAL(configurationChanged(QNetworkConfiguration))); + + session->close(); + + if (!sessionErrorSpy.isEmpty()) { + qDebug("tst_QNetworkSession::closeSession() failure: QNetworkSession::error() received."); + return false; + } + if (sessionClosedSpy.count() != 1) { + qDebug("tst_QNetworkSession::closeSession() failure: QNetworkSession::closed() signal not received."); + return false; + } + if (lastSessionOnConfiguration && + sessionStateChangedSpy.isEmpty()) { + qDebug("tst_QNetworkSession::closeSession() failure: QNetworkSession::stateChanged() signals not received."); + return false; + } + if (lastSessionOnConfiguration && + session->state() != QNetworkSession::Disconnected) { + qDebug("tst_QNetworkSession::closeSession() failure: QNetworkSession is not in Disconnected -state"); + return false; + } + QTRY_NOOP(!configChangeSpy.isEmpty()); + if (lastSessionOnConfiguration && + configChangeSpy.isEmpty()) { + qDebug("tst_QNetworkSession::closeSession() failure: QNetworkConfigurationManager::configurationChanged() - signal not detected."); + return false; + } + if (lastSessionOnConfiguration && + session->configuration().state() != QNetworkConfiguration::Discovered) { + qDebug("tst_QNetworkSession::closeSession() failure: session's configuration is not back in 'Discovered' -state."); + return false; + } + return true; +} + + + QTEST_MAIN(tst_QNetworkSession) #include "tst_qnetworksession.moc" -- cgit v0.12 From c139d16df004721894c08e2c86ab2b3078c1d170 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Tue, 2 Mar 2010 15:47:19 +1000 Subject: missed file --- .../declarative/qdeclarativewebview/data/forward.png | Bin 0 -> 2377 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/auto/declarative/qdeclarativewebview/data/forward.png diff --git a/tests/auto/declarative/qdeclarativewebview/data/forward.png b/tests/auto/declarative/qdeclarativewebview/data/forward.png new file mode 100644 index 0000000..a82533e Binary files /dev/null and b/tests/auto/declarative/qdeclarativewebview/data/forward.png differ -- cgit v0.12 From 26e6b837ceb90ed3d0df63b39a1cd0ec4dc7aeae Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Tue, 2 Mar 2010 15:54:14 +1000 Subject: follow syntax change --- demos/declarative/webbrowser/content/fieldtext/FieldText.qml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demos/declarative/webbrowser/content/fieldtext/FieldText.qml b/demos/declarative/webbrowser/content/fieldtext/FieldText.qml index 19b6acc..d282209 100644 --- a/demos/declarative/webbrowser/content/fieldtext/FieldText.qml +++ b/demos/declarative/webbrowser/content/fieldtext/FieldText.qml @@ -85,7 +85,7 @@ Item { font.bold: true text: label opacity: textEdit.text == '' ? 1 : 0 - opacity: Behavior { + Behavior on opacity { NumberAnimation { property: "opacity" duration: 250 -- cgit v0.12 From feb79bba984520fa30bad83eb4a6f34cfb86a697 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Tue, 2 Mar 2010 15:55:06 +1000 Subject: Move WebView to an extension plugin. Using WebView now requires: import org.webkit 1.0 Task-number: QT-2995 --- demos/declarative/flickr/common/ImageDetails.qml | 1 + .../webbrowser/content/FlickableWebView.qml | 1 + demos/declarative/webbrowser/webbrowser.qml | 1 + examples/declarative/webview/autosize.qml | 1 + examples/declarative/webview/content/FieldText.qml | 2 +- .../declarative/webview/content/Mapping/Map.qml | 1 + examples/declarative/webview/evalandattach.qml | 1 + examples/declarative/webview/googleMaps.qml | 1 + examples/declarative/webview/inline-html.qml | 1 + examples/declarative/webview/newwindows.qml | 1 + .../declarative/webview/qdeclarative-in-html.qml | 1 + examples/declarative/webview/transparent.qml | 1 + imports/org/webkit/qmldir | 1 + src/declarative/graphicsitems/graphicsitems.pri | 7 - .../graphicsitems/qdeclarativeitemsmodule.cpp | 3 - .../graphicsitems/qdeclarativewebview.cpp | 1338 ------------------- .../graphicsitems/qdeclarativewebview_p.h | 286 ----- .../graphicsitems/qdeclarativewebview_p_p.h | 151 --- .../qdeclarativemodules/qdeclarativemodules.pro | 1 + .../qdeclarativemodules/webkitqmlplugin/plugin.cpp | 66 + .../webkitqmlplugin/qdeclarativewebview.cpp | 1340 ++++++++++++++++++++ .../webkitqmlplugin/qdeclarativewebview_p.h | 285 +++++ .../webkitqmlplugin/qdeclarativewebview_p_p.h | 151 +++ .../webkitqmlplugin/webkitqmlplugin.pro | 18 + .../declarative/qdeclarativewebview/data/basic.qml | 1 + .../qdeclarativewebview/data/elements.qml | 1 + .../qdeclarativewebview/data/javaScript.qml | 1 + .../qdeclarativewebview/data/loadError.qml | 1 + .../qdeclarativewebview/data/newwindows.qml | 1 + .../qdeclarativewebview/data/propertychanges.qml | 3 +- .../qdeclarativewebview/data/sethtml.qml | 1 + .../qdeclarativewebview/qdeclarativewebview.pro | 3 +- .../declarative/qdeclarativewebview/testtypes.cpp | 52 - .../declarative/qdeclarativewebview/testtypes.h | 66 - .../tst_qdeclarativewebview.cpp | 346 ++--- .../visual/qfxwebview/autosize/autosize.qml | 1 + .../visual/webview/embedding/nesting.qml | 1 + .../webview/javascript/evaluateJavaScript.qml | 1 + .../visual/webview/javascript/windowObjects.qml | 1 + .../visual/webview/settings/fontFamily.qml | 1 + .../visual/webview/settings/fontSize.qml | 1 + .../visual/webview/settings/noAutoLoadImages.qml | 1 + .../visual/webview/settings/setFontFamily.qml | 1 + .../visual/webview/zooming/pageWidth.qml | 1 + .../visual/webview/zooming/renderControl.qml | 1 + .../visual/webview/zooming/resolution.qml | 1 + .../visual/webview/zooming/zoomTextOnly.qml | 1 + .../declarative/visual/webview/zooming/zooming.qml | 1 + 48 files changed, 2072 insertions(+), 2077 deletions(-) create mode 100644 imports/org/webkit/qmldir delete mode 100644 src/declarative/graphicsitems/qdeclarativewebview.cpp delete mode 100644 src/declarative/graphicsitems/qdeclarativewebview_p.h delete mode 100644 src/declarative/graphicsitems/qdeclarativewebview_p_p.h create mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp create mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp create mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h create mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h create mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro delete mode 100644 tests/auto/declarative/qdeclarativewebview/testtypes.cpp delete mode 100644 tests/auto/declarative/qdeclarativewebview/testtypes.h diff --git a/demos/declarative/flickr/common/ImageDetails.qml b/demos/declarative/flickr/common/ImageDetails.qml index 9604f10..862eeb1 100644 --- a/demos/declarative/flickr/common/ImageDetails.qml +++ b/demos/declarative/flickr/common/ImageDetails.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Flipable { id: container diff --git a/demos/declarative/webbrowser/content/FlickableWebView.qml b/demos/declarative/webbrowser/content/FlickableWebView.qml index 76a5813..cf4c825 100644 --- a/demos/declarative/webbrowser/content/FlickableWebView.qml +++ b/demos/declarative/webbrowser/content/FlickableWebView.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Flickable { property alias title: webView.title diff --git a/demos/declarative/webbrowser/webbrowser.qml b/demos/declarative/webbrowser/webbrowser.qml index 6a427f4..b6cccb0 100644 --- a/demos/declarative/webbrowser/webbrowser.qml +++ b/demos/declarative/webbrowser/webbrowser.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 import "content" diff --git a/examples/declarative/webview/autosize.qml b/examples/declarative/webview/autosize.qml index 74c6844..3c00ee6 100644 --- a/examples/declarative/webview/autosize.qml +++ b/examples/declarative/webview/autosize.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 // The WebView size is determined by the width, height, // preferredWidth, and preferredHeight properties. diff --git a/examples/declarative/webview/content/FieldText.qml b/examples/declarative/webview/content/FieldText.qml index 19b6acc..d282209 100644 --- a/examples/declarative/webview/content/FieldText.qml +++ b/examples/declarative/webview/content/FieldText.qml @@ -85,7 +85,7 @@ Item { font.bold: true text: label opacity: textEdit.text == '' ? 1 : 0 - opacity: Behavior { + Behavior on opacity { NumberAnimation { property: "opacity" duration: 250 diff --git a/examples/declarative/webview/content/Mapping/Map.qml b/examples/declarative/webview/content/Mapping/Map.qml index 2e98940..6c3b021 100644 --- a/examples/declarative/webview/content/Mapping/Map.qml +++ b/examples/declarative/webview/content/Mapping/Map.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Item { id: page diff --git a/examples/declarative/webview/evalandattach.qml b/examples/declarative/webview/evalandattach.qml index 94301cd..d219d84 100644 --- a/examples/declarative/webview/evalandattach.qml +++ b/examples/declarative/webview/evalandattach.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Item { height: 640 diff --git a/examples/declarative/webview/googleMaps.qml b/examples/declarative/webview/googleMaps.qml index 1886961..a04fecb 100644 --- a/examples/declarative/webview/googleMaps.qml +++ b/examples/declarative/webview/googleMaps.qml @@ -6,6 +6,7 @@ // order to create a Map. import Qt 4.6 +import org.webkit 1.0 import "content/Mapping" Map { diff --git a/examples/declarative/webview/inline-html.qml b/examples/declarative/webview/inline-html.qml index 23b4555..41dfec3 100644 --- a/examples/declarative/webview/inline-html.qml +++ b/examples/declarative/webview/inline-html.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 // Inline HTML with loose formatting can be // set on the html property. diff --git a/examples/declarative/webview/newwindows.qml b/examples/declarative/webview/newwindows.qml index 5dd4cd5..c62aba6 100644 --- a/examples/declarative/webview/newwindows.qml +++ b/examples/declarative/webview/newwindows.qml @@ -4,6 +4,7 @@ // allow it on WebView with settings.javascriptCanOpenWindows: true import Qt 4.6 +import org.webkit 1.0 Grid { columns: 3 diff --git a/examples/declarative/webview/qdeclarative-in-html.qml b/examples/declarative/webview/qdeclarative-in-html.qml index 77180ec..172ea4b 100644 --- a/examples/declarative/webview/qdeclarative-in-html.qml +++ b/examples/declarative/webview/qdeclarative-in-html.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 // The WebView supports QML data through the HTML OBJECT tag Rectangle { diff --git a/examples/declarative/webview/transparent.qml b/examples/declarative/webview/transparent.qml index 9332f3e..5530819 100644 --- a/examples/declarative/webview/transparent.qml +++ b/examples/declarative/webview/transparent.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 // The WebView background is transparent // if the HTML does not specify a background diff --git a/imports/org/webkit/qmldir b/imports/org/webkit/qmldir new file mode 100644 index 0000000..258aa2c --- /dev/null +++ b/imports/org/webkit/qmldir @@ -0,0 +1 @@ +plugin webkitqmlplugin diff --git a/src/declarative/graphicsitems/graphicsitems.pri b/src/declarative/graphicsitems/graphicsitems.pri index 7a85f00..3ff92b1 100644 --- a/src/declarative/graphicsitems/graphicsitems.pri +++ b/src/declarative/graphicsitems/graphicsitems.pri @@ -84,10 +84,3 @@ SOURCES += \ $$PWD/qdeclarativegraphicsobjectcontainer.cpp \ $$PWD/qdeclarativeparticles.cpp \ $$PWD/qdeclarativelayoutitem.cpp \ - -contains(QT_CONFIG, webkit) { - QT+=webkit - SOURCES += $$PWD/qdeclarativewebview.cpp - HEADERS += $$PWD/qdeclarativewebview_p.h - HEADERS += $$PWD/qdeclarativewebview_p_p.h -} diff --git a/src/declarative/graphicsitems/qdeclarativeitemsmodule.cpp b/src/declarative/graphicsitems/qdeclarativeitemsmodule.cpp index f3b9385..e0ae2eb 100644 --- a/src/declarative/graphicsitems/qdeclarativeitemsmodule.cpp +++ b/src/declarative/graphicsitems/qdeclarativeitemsmodule.cpp @@ -139,9 +139,6 @@ void QDeclarativeItemModule::defineModule() QML_REGISTER_TYPE(Qt,4,6,VisibleArea,QDeclarativeFlickableVisibleArea); QML_REGISTER_TYPE(Qt,4,6,VisualDataModel,QDeclarativeVisualDataModel); QML_REGISTER_TYPE(Qt,4,6,VisualItemModel,QDeclarativeVisualItemModel); -#ifdef QT_WEBKIT_LIB - QML_REGISTER_TYPE(Qt,4,6,WebView,QDeclarativeWebView); -#endif QML_REGISTER_NOCREATE_TYPE(QDeclarativeAnchors); QML_REGISTER_NOCREATE_TYPE(QGraphicsEffect); diff --git a/src/declarative/graphicsitems/qdeclarativewebview.cpp b/src/declarative/graphicsitems/qdeclarativewebview.cpp deleted file mode 100644 index a2b16ba..0000000 --- a/src/declarative/graphicsitems/qdeclarativewebview.cpp +++ /dev/null @@ -1,1338 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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 "qdeclarativewebview_p.h" -#include "qdeclarativewebview_p_p.h" - -#include "qdeclarativepainteditem_p_p.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system - -class QDeclarativeWebViewPrivate : public QDeclarativePaintedItemPrivate -{ - Q_DECLARE_PUBLIC(QDeclarativeWebView) - -public: - QDeclarativeWebViewPrivate() - : QDeclarativePaintedItemPrivate(), page(0), preferredwidth(0), preferredheight(0), - progress(1.0), status(QDeclarativeWebView::Null), pending(PendingNone), - newWindowComponent(0), newWindowParent(0), - pressTime(400), - rendering(true) - { - } - - QUrl url; // page url might be different if it has not loaded yet - QWebPage *page; - - int preferredwidth, preferredheight; - qreal progress; - QDeclarativeWebView::Status status; - QString statusText; - enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending; - QUrl pending_url; - QString pending_string; - QByteArray pending_data; - mutable QDeclarativeWebSettings settings; - QDeclarativeComponent *newWindowComponent; - QDeclarativeItem *newWindowParent; - - QBasicTimer pressTimer; - QPoint pressPoint; - int pressTime; // milliseconds before it's a "hold" - - - static void windowObjects_append(QDeclarativeListProperty *prop, QObject *o) { - static_cast(prop->data)->windowObjects.append(o); - static_cast(prop->data)->updateWindowObjects(); - } - - void updateWindowObjects(); - QObjectList windowObjects; - - bool rendering; -}; - -/*! - \qmlclass WebView QDeclarativeWebView - \since 4.7 - \brief The WebView item allows you to add web content to a canvas. - \inherits Item - - A WebView renders web content based on a URL. - - If the width and height of the item is not set, they will - dynamically adjust to a size appropriate for the content. - This width may be large for typical online web pages. - - If the preferredWidth is set, the width will be this amount or larger, - usually laying out the web content to fit the preferredWidth. - - \qml - WebView { - url: "http://www.nokia.com" - width: 490 - height: 400 - scale: 0.5 - smooth: false - smoothCache: true - } - \endqml - - \image webview.png - - The item includes no scrolling, scaling, - toolbars, etc., those must be implemented around WebView. See the WebBrowser example - for a demonstration of this. -*/ - -/*! - \internal - \class QDeclarativeWebView - \brief The QDeclarativeWebView class allows you to add web content to a QDeclarativeView. - - A WebView renders web content base on a URL. - - \image webview.png - - The item includes no scrolling, scaling, - toolbars, etc., those must be implemented around WebView. See the WebBrowser example - for a demonstration of this. - - A QDeclarativeWebView object can be instantiated in Qml using the tag \l WebView. -*/ - -QDeclarativeWebView::QDeclarativeWebView(QDeclarativeItem *parent) - : QDeclarativePaintedItem(*(new QDeclarativeWebViewPrivate), parent) -{ - init(); -} - -QDeclarativeWebView::~QDeclarativeWebView() -{ - Q_D(QDeclarativeWebView); - delete d->page; -} - -void QDeclarativeWebView::init() -{ - Q_D(QDeclarativeWebView); - - QWebSettings::enablePersistentStorage(); - - setAcceptHoverEvents(true); - setAcceptedMouseButtons(Qt::LeftButton); - setFlag(QGraphicsItem::ItemHasNoContents, false); - - d->page = 0; -} - -void QDeclarativeWebView::componentComplete() -{ - QDeclarativePaintedItem::componentComplete(); - Q_D(QDeclarativeWebView); - switch (d->pending) { - case QDeclarativeWebViewPrivate::PendingUrl: - setUrl(d->pending_url); - break; - case QDeclarativeWebViewPrivate::PendingHtml: - setHtml(d->pending_string, d->pending_url); - break; - case QDeclarativeWebViewPrivate::PendingContent: - setContent(d->pending_data, d->pending_string, d->pending_url); - break; - default: - break; - } - d->pending = QDeclarativeWebViewPrivate::PendingNone; - d->updateWindowObjects(); -} - -QDeclarativeWebView::Status QDeclarativeWebView::status() const -{ - Q_D(const QDeclarativeWebView); - return d->status; -} - - -/*! - \qmlproperty real WebView::progress - This property holds the progress of loading the current URL, from 0 to 1. - - If you just want to know when progress gets to 1, use - WebView::onLoadFinished() or WebView::onLoadFailed() instead. -*/ -qreal QDeclarativeWebView::progress() const -{ - Q_D(const QDeclarativeWebView); - return d->progress; -} - -void QDeclarativeWebView::doLoadStarted() -{ - Q_D(QDeclarativeWebView); - - if (!d->url.isEmpty()) { - d->status = Loading; - emit statusChanged(d->status); - } - emit loadStarted(); -} - -void QDeclarativeWebView::doLoadProgress(int p) -{ - Q_D(QDeclarativeWebView); - if (d->progress == p/100.0) - return; - d->progress = p/100.0; - emit progressChanged(); -} - -void QDeclarativeWebView::pageUrlChanged() -{ - Q_D(QDeclarativeWebView); - - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - expandToWebPage(); - - if ((d->url.isEmpty() && page()->mainFrame()->url() != QUrl(QLatin1String("about:blank"))) - || (d->url != page()->mainFrame()->url() && !page()->mainFrame()->url().isEmpty())) - { - d->url = page()->mainFrame()->url(); - if (d->url == QUrl(QLatin1String("about:blank"))) - d->url = QUrl(); - emit urlChanged(); - } -} - -void QDeclarativeWebView::doLoadFinished(bool ok) -{ - Q_D(QDeclarativeWebView); - - if (title().isEmpty()) - pageUrlChanged(); // XXX bug 232556 - pages with no title never get urlChanged() - - if (ok) { - d->status = d->url.isEmpty() ? Null : Ready; - emit loadFinished(); - } else { - d->status = Error; - emit loadFailed(); - } - emit statusChanged(d->status); -} - -/*! - \qmlproperty url WebView::url - This property holds the URL to the page displayed in this item. It can be set, - but also can change spontaneously (eg. because of network redirection). - - If the url is empty, the page is blank. - - The url is always absolute (QML will resolve relative URL strings in the context - of the containing QML document). -*/ -QUrl QDeclarativeWebView::url() const -{ - Q_D(const QDeclarativeWebView); - return d->url; -} - -void QDeclarativeWebView::setUrl(const QUrl &url) -{ - Q_D(QDeclarativeWebView); - if (url == d->url) - return; - - if (isComponentComplete()) { - d->url = url; - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - QUrl seturl = url; - if (seturl.isEmpty()) - seturl = QUrl(QLatin1String("about:blank")); - - Q_ASSERT(!seturl.isRelative()); - - page()->mainFrame()->load(seturl); - - emit urlChanged(); - } else { - d->pending = d->PendingUrl; - d->pending_url = url; - } -} - -/*! - \qmlproperty int WebView::preferredWidth - This property holds the ideal width for displaying the current URL. -*/ -int QDeclarativeWebView::preferredWidth() const -{ - Q_D(const QDeclarativeWebView); - return d->preferredwidth; -} - -void QDeclarativeWebView::setPreferredWidth(int iw) -{ - Q_D(QDeclarativeWebView); - if (d->preferredwidth == iw) return; - d->preferredwidth = iw; - //expandToWebPage(); - emit preferredWidthChanged(); -} - -/*! - \qmlproperty int WebView::preferredHeight - This property holds the ideal height for displaying the current URL. - This only affects the area zoomed by heuristicZoom(). -*/ -int QDeclarativeWebView::preferredHeight() const -{ - Q_D(const QDeclarativeWebView); - return d->preferredheight; -} -void QDeclarativeWebView::setPreferredHeight(int ih) -{ - Q_D(QDeclarativeWebView); - if (d->preferredheight == ih) return; - d->preferredheight = ih; - emit preferredHeightChanged(); -} - -/*! - \qmlmethod bool WebView::evaluateJavaScript(string) - - Evaluates the \a scriptSource JavaScript inside the context of the - main web frame, and returns the result of the last executed statement. - - Note that this JavaScript does \e not have any access to QML objects - except as made available as windowObjects. -*/ -QVariant QDeclarativeWebView::evaluateJavaScript(const QString &scriptSource) -{ - return this->page()->mainFrame()->evaluateJavaScript(scriptSource); -} - -void QDeclarativeWebView::focusChanged(bool hasFocus) -{ - QFocusEvent e(hasFocus ? QEvent::FocusIn : QEvent::FocusOut); - page()->event(&e); - QDeclarativeItem::focusChanged(hasFocus); -} - -void QDeclarativeWebView::initialLayout() -{ - // nothing useful to do at this point -} - -void QDeclarativeWebView::noteContentsSizeChanged(const QSize&) -{ - expandToWebPage(); -} - -void QDeclarativeWebView::expandToWebPage() -{ - Q_D(QDeclarativeWebView); - QSize cs = page()->mainFrame()->contentsSize(); - if (cs.width() < d->preferredwidth) - cs.setWidth(d->preferredwidth); - if (cs.height() < d->preferredheight) - cs.setHeight(d->preferredheight); - if (widthValid()) - cs.setWidth(width()); - if (heightValid()) - cs.setHeight(height()); - if (cs != page()->viewportSize()) { - page()->setViewportSize(cs); - } - if (cs != contentsSize()) - setContentsSize(cs); -} - -void QDeclarativeWebView::geometryChanged(const QRectF &newGeometry, - const QRectF &oldGeometry) -{ - if (newGeometry.size() != oldGeometry.size()) - expandToWebPage(); - QDeclarativePaintedItem::geometryChanged(newGeometry, oldGeometry); -} - -void QDeclarativeWebView::paintPage(const QRect& r) -{ - dirtyCache(r); - update(); -} - -/*! - \qmlproperty list WebView::javaScriptWindowObjects - - This property is a list of object that are available from within - the webview's JavaScript context. - - The \a object will be inserted as a child of the frame's window - object, under the name given by the attached property \c WebView.windowObjectName. - - \qml - WebView { - javaScriptWindowObjects: Object { - WebView.windowObjectName: "coordinates" - } - } - \endqml - - Properties of the object will be exposed as JavaScript properties and slots as - JavaScript methods. - - If Javascript is not enabled for this page, then this property does nothing. -*/ -QDeclarativeListProperty QDeclarativeWebView::javaScriptWindowObjects() -{ - Q_D(QDeclarativeWebView); - return QDeclarativeListProperty(this, d, &QDeclarativeWebViewPrivate::windowObjects_append); -} - -QDeclarativeWebViewAttached *QDeclarativeWebView::qmlAttachedProperties(QObject *o) -{ - return new QDeclarativeWebViewAttached(o); -} - -void QDeclarativeWebViewPrivate::updateWindowObjects() -{ - Q_Q(QDeclarativeWebView); - if (!q->isComponentComplete() || !page) - return; - - for (int ii = 0; ii < windowObjects.count(); ++ii) { - QObject *object = windowObjects.at(ii); - QDeclarativeWebViewAttached *attached = static_cast(qmlAttachedPropertiesObject(object)); - if (attached && !attached->windowObjectName().isEmpty()) { - page->mainFrame()->addToJavaScriptWindowObject(attached->windowObjectName(), object); - } - } -} - -bool QDeclarativeWebView::renderingEnabled() const -{ - Q_D(const QDeclarativeWebView); - return d->rendering; -} - -void QDeclarativeWebView::setRenderingEnabled(bool enabled) -{ - Q_D(QDeclarativeWebView); - if (d->rendering == enabled) - return; - d->rendering = enabled; - emit renderingEnabledChanged(); - - setCacheFrozen(!enabled); - if (enabled) - clearCache(); -} - - -void QDeclarativeWebView::drawContents(QPainter *p, const QRect &r) -{ - Q_D(QDeclarativeWebView); - if (d->rendering) - page()->mainFrame()->render(p,r); -} - -QMouseEvent *QDeclarativeWebView::sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *e) -{ - QEvent::Type t; - switch(e->type()) { - default: - case QEvent::GraphicsSceneMousePress: - t = QEvent::MouseButtonPress; - break; - case QEvent::GraphicsSceneMouseRelease: - t = QEvent::MouseButtonRelease; - break; - case QEvent::GraphicsSceneMouseMove: - t = QEvent::MouseMove; - break; - case QGraphicsSceneEvent::GraphicsSceneMouseDoubleClick: - t = QEvent::MouseButtonDblClick; - break; - } - - QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), e->button(), e->buttons(), 0); - return me; -} - -QMouseEvent *QDeclarativeWebView::sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *e) -{ - QEvent::Type t = QEvent::MouseMove; - - QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), Qt::NoButton, Qt::NoButton, 0); - - return me; -} - - -/*! - \qmlsignal WebView::onDoubleClick(clickx,clicky) - - The WebView does not pass double-click events to the web engine, but rather - emits this signals. -*/ - -void QDeclarativeWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) -{ - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - emit doubleClick(me->x(),me->y()); - delete me; -} - -/*! - \qmlmethod bool WebView::heuristicZoom(clickX,clickY,maxzoom) - - Finds a zoom that: - \list - \i shows a whole item - \i includes (\a clickX, \a clickY) - \i fits into the preferredWidth and preferredHeight - \i zooms by no more than \a maxzoom - \i is more than 10% above the current zoom - \endlist - - If such a zoom exists, emits zoomTo(zoom,centerX,centerY) and returns true; otherwise, - no signal is emitted and returns false. -*/ -bool QDeclarativeWebView::heuristicZoom(int clickX, int clickY, qreal maxzoom) -{ - Q_D(QDeclarativeWebView); - if (contentsScale() >= maxzoom/zoomFactor()) - return false; - qreal ozf = contentsScale(); - QRect showarea = elementAreaAt(clickX, clickY, d->preferredwidth/maxzoom, d->preferredheight/maxzoom); - qreal z = qMin(qreal(d->preferredwidth)/showarea.width(),qreal(d->preferredheight)/showarea.height()); - if (z > maxzoom/zoomFactor()) - z = maxzoom/zoomFactor(); - if (z/ozf > 1.2) { - QRectF r(showarea.left()*z, showarea.top()*z, showarea.width()*z, showarea.height()*z); - emit zoomTo(z,r.x()+r.width()/2, r.y()+r.height()/2); - return true; - } else { - return false; - } -} - -/*! - \qmlproperty int WebView::pressGrabTime - - The number of milliseconds the user must press before the WebView - starts passing move events through to the web engine (rather than - letting other QML elements such as a Flickable take them). - - Defaults to 400ms. Set to 0 to always grab and pass move events to - the web engine. -*/ -int QDeclarativeWebView::pressGrabTime() const -{ - Q_D(const QDeclarativeWebView); - return d->pressTime; -} - -void QDeclarativeWebView::setPressGrabTime(int ms) -{ - Q_D(QDeclarativeWebView); - if (d->pressTime == ms) - return; - d->pressTime = ms; - emit pressGrabTimeChanged(); -} - -void QDeclarativeWebView::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - setFocus (true); - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - - d->pressPoint = me->pos(); - if (d->pressTime) { - d->pressTimer.start(d->pressTime,this); - setKeepMouseGrab(false); - } else { - grabMouse(); - setKeepMouseGrab(true); - } - - page()->event(me); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit - Might be a bug in WebKit, though - */ -#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) { - QDeclarativePaintedItem::mousePressEvent(event); - } -} - -void QDeclarativeWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - page()->event(me); - d->pressTimer.stop(); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send all the events to WebKit - */ -#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) { - QDeclarativePaintedItem::mouseReleaseEvent(event); - } - setKeepMouseGrab(false); - ungrabMouse(); -} - -void QDeclarativeWebView::timerEvent(QTimerEvent *event) -{ - Q_D(QDeclarativeWebView); - if (event->timerId() == d->pressTimer.timerId()) { - d->pressTimer.stop(); - grabMouse(); - setKeepMouseGrab(true); - } -} - -void QDeclarativeWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - if (d->pressTimer.isActive()) { - if ((me->pos() - d->pressPoint).manhattanLength() > QApplication::startDragDistance()) { - d->pressTimer.stop(); - } - } - if (keepMouseGrab()) { - page()->event(me); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit - Might be a bug in WebKit, though - */ -#if 1 // QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - } - delete me; - if (!event->isAccepted()) - QDeclarativePaintedItem::mouseMoveEvent(event); - -} -void QDeclarativeWebView::hoverMoveEvent (QGraphicsSceneHoverEvent * event) -{ - QMouseEvent *me = sceneHoverMoveEventToMouseEvent(event); - page()->event(me); - event->setAccepted( -#if QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) - QDeclarativePaintedItem::hoverMoveEvent(event); -} - -void QDeclarativeWebView::keyPressEvent(QKeyEvent* event) -{ - page()->event(event); - if (!event->isAccepted()) - QDeclarativePaintedItem::keyPressEvent(event); -} - -void QDeclarativeWebView::keyReleaseEvent(QKeyEvent* event) -{ - page()->event(event); - if (!event->isAccepted()) - QDeclarativePaintedItem::keyReleaseEvent(event); -} - -bool QDeclarativeWebView::sceneEvent(QEvent *event) -{ - if (event->type() == QEvent::KeyPress) { - QKeyEvent *k = static_cast(event); - if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) { - if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? - page()->event(event); - if (event->isAccepted()) - return true; - } - } - } - return QDeclarativePaintedItem::sceneEvent(event); -} - - -/*! - \qmlproperty action WebView::back - This property holds the action for causing the previous URL in the history to be displayed. -*/ -QAction *QDeclarativeWebView::backAction() const -{ - return page()->action(QWebPage::Back); -} - -/*! - \qmlproperty action WebView::forward - This property holds the action for causing the next URL in the history to be displayed. -*/ -QAction *QDeclarativeWebView::forwardAction() const -{ - return page()->action(QWebPage::Forward); -} - -/*! - \qmlproperty action WebView::reload - This property holds the action for reloading with the current URL -*/ -QAction *QDeclarativeWebView::reloadAction() const -{ - return page()->action(QWebPage::Reload); -} - -/*! - \qmlproperty action WebView::stop - This property holds the action for stopping loading with the current URL -*/ -QAction *QDeclarativeWebView::stopAction() const -{ - return page()->action(QWebPage::Stop); -} - -/*! - \qmlproperty real WebView::title - This property holds the title of the web page currently viewed - - By default, this property contains an empty string. -*/ -QString QDeclarativeWebView::title() const -{ - return page()->mainFrame()->title(); -} - - - -/*! - \qmlproperty pixmap WebView::icon - This property holds the icon associated with the web page currently viewed -*/ -QPixmap QDeclarativeWebView::icon() const -{ - return page()->mainFrame()->icon().pixmap(QSize(256,256)); -} - - -/*! - \qmlproperty real WebView::zoomFactor - This property holds the multiplier used to scale the contents of a Web page. -*/ -void QDeclarativeWebView::setZoomFactor(qreal factor) -{ - Q_D(QDeclarativeWebView); - if (factor == page()->mainFrame()->zoomFactor()) - return; - - page()->mainFrame()->setZoomFactor(factor); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth*factor : width()*factor, - d->preferredheight>0 ? d->preferredheight*factor : height()*factor)); - expandToWebPage(); - - emit zoomFactorChanged(); -} - -qreal QDeclarativeWebView::zoomFactor() const -{ - return page()->mainFrame()->zoomFactor(); -} - -/*! - \qmlproperty string WebView::statusText - - This property is the current status suggested by the current web page. In a web browser, - such status is often shown in some kind of status bar. -*/ -void QDeclarativeWebView::setStatusText(const QString& s) -{ - Q_D(QDeclarativeWebView); - d->statusText = s; - emit statusTextChanged(); -} - -void QDeclarativeWebView::windowObjectCleared() -{ - Q_D(QDeclarativeWebView); - d->updateWindowObjects(); -} - -QString QDeclarativeWebView::statusText() const -{ - Q_D(const QDeclarativeWebView); - return d->statusText; -} - -QWebPage *QDeclarativeWebView::page() const -{ - Q_D(const QDeclarativeWebView); - - if (!d->page) { - QDeclarativeWebView *self = const_cast(this); - QWebPage *wp = new QDeclarativeWebPage(self); - - // QML items don't default to having a background, - // even though most we pages will set one anyway. - QPalette pal = QApplication::palette(); - pal.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0)); - wp->setPalette(pal); - - wp->setNetworkAccessManager(qmlEngine(this)->networkAccessManager()); - - self->setPage(wp); - - return wp; - } - - return d->page; -} - - -// The QObject interface to settings(). -/*! - \qmlproperty string WebView::settings.standardFontFamily - \qmlproperty string WebView::settings.fixedFontFamily - \qmlproperty string WebView::settings.serifFontFamily - \qmlproperty string WebView::settings.sansSerifFontFamily - \qmlproperty string WebView::settings.cursiveFontFamily - \qmlproperty string WebView::settings.fantasyFontFamily - - \qmlproperty int WebView::settings.minimumFontSize - \qmlproperty int WebView::settings.minimumLogicalFontSize - \qmlproperty int WebView::settings.defaultFontSize - \qmlproperty int WebView::settings.defaultFixedFontSize - - \qmlproperty bool WebView::settings.autoLoadImages - \qmlproperty bool WebView::settings.javascriptEnabled - \qmlproperty bool WebView::settings.javaEnabled - \qmlproperty bool WebView::settings.pluginsEnabled - \qmlproperty bool WebView::settings.privateBrowsingEnabled - \qmlproperty bool WebView::settings.javascriptCanOpenWindows - \qmlproperty bool WebView::settings.javascriptCanAccessClipboard - \qmlproperty bool WebView::settings.developerExtrasEnabled - \qmlproperty bool WebView::settings.linksIncludedInFocusChain - \qmlproperty bool WebView::settings.zoomTextOnly - \qmlproperty bool WebView::settings.printElementBackgrounds - \qmlproperty bool WebView::settings.offlineStorageDatabaseEnabled - \qmlproperty bool WebView::settings.offlineWebApplicationCacheEnabled - \qmlproperty bool WebView::settings.localStorageDatabaseEnabled - \qmlproperty bool WebView::settings.localContentCanAccessRemoteUrls - - These properties give access to the settings controlling the web view. - - See QWebSettings for details of these properties. - - \qml - WebView { - settings.pluginsEnabled: true - settings.standardFontFamily: "Arial" - ... - } - \endqml -*/ -QDeclarativeWebSettings *QDeclarativeWebView::settingsObject() const -{ - Q_D(const QDeclarativeWebView); - d->settings.s = page()->settings(); - return &d->settings; -} - -void QDeclarativeWebView::setPage(QWebPage *page) -{ - Q_D(QDeclarativeWebView); - if (d->page == page) - return; - if (d->page) { - if (d->page->parent() == this) { - delete d->page; - } else { - d->page->disconnect(this); - } - } - d->page = page; - d->page->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - d->page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff); - d->page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff); - connect(d->page,SIGNAL(repaintRequested(QRect)),this,SLOT(paintPage(QRect))); - connect(d->page->mainFrame(),SIGNAL(urlChanged(QUrl)),this,SLOT(pageUrlChanged())); - connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString))); - connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(iconChanged())); - connect(d->page->mainFrame(), SIGNAL(iconChanged()), this, SIGNAL(iconChanged())); - connect(d->page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), this, SLOT(noteContentsSizeChanged(QSize))); - connect(d->page->mainFrame(), SIGNAL(initialLayoutCompleted()), this, SLOT(initialLayout())); - - connect(d->page,SIGNAL(loadStarted()),this,SLOT(doLoadStarted())); - connect(d->page,SIGNAL(loadProgress(int)),this,SLOT(doLoadProgress(int))); - connect(d->page,SIGNAL(loadFinished(bool)),this,SLOT(doLoadFinished(bool))); - connect(d->page,SIGNAL(statusBarMessage(QString)),this,SLOT(setStatusText(QString))); - - connect(d->page->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(windowObjectCleared())); -} - -/*! - \qmlsignal WebView::onLoadStarted() - - This handler is called when the web engine begins loading - a page. Later, WebView::onLoadFinished() or WebView::onLoadFailed() - will be emitted. -*/ - -/*! - \qmlsignal WebView::onLoadFinished() - - This handler is called when the web engine \e successfully - finishes loading a page, including any component content - (WebView::onLoadFailed() will be emitted otherwise). - - \sa progress -*/ - -/*! - \qmlsignal WebView::onLoadFailed() - - This handler is called when the web engine fails loading - a page or any component content - (WebView::onLoadFinished() will be emitted on success). -*/ - -void QDeclarativeWebView::load(const QNetworkRequest &request, - QNetworkAccessManager::Operation operation, - const QByteArray &body) -{ - page()->mainFrame()->load(request, operation, body); -} - -QString QDeclarativeWebView::html() const -{ - return page()->mainFrame()->toHtml(); -} - -/*! - \qmlproperty string WebView::html - This property holds HTML text set directly - - The html property can be set as a string. - - \qml - WebView { - html: "

This is HTML." - } - \endqml -*/ -void QDeclarativeWebView::setHtml(const QString &html, const QUrl &baseUrl) -{ - Q_D(QDeclarativeWebView); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - if (isComponentComplete()) - page()->mainFrame()->setHtml(html, baseUrl); - else { - d->pending = d->PendingHtml; - d->pending_url = baseUrl; - d->pending_string = html; - } - emit htmlChanged(); -} - -void QDeclarativeWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) -{ - Q_D(QDeclarativeWebView); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - - if (isComponentComplete()) - page()->mainFrame()->setContent(data,mimeType,qmlContext(this)->resolvedUrl(baseUrl)); - else { - d->pending = d->PendingContent; - d->pending_url = baseUrl; - d->pending_string = mimeType; - d->pending_data = data; - } -} - -QWebHistory *QDeclarativeWebView::history() const -{ - return page()->history(); -} - -QWebSettings *QDeclarativeWebView::settings() const -{ - return page()->settings(); -} - -QDeclarativeWebView *QDeclarativeWebView::createWindow(QWebPage::WebWindowType type) -{ - Q_D(QDeclarativeWebView); - switch (type) { - case QWebPage::WebBrowserWindow: { - if (!d->newWindowComponent && d->newWindowParent) - qWarning("WebView::newWindowComponent not set - WebView::newWindowParent ignored"); - else if (d->newWindowComponent && !d->newWindowParent) - qWarning("WebView::newWindowParent not set - WebView::newWindowComponent ignored"); - else if (d->newWindowComponent && d->newWindowParent) { - QDeclarativeWebView *webview = 0; - QDeclarativeContext *windowContext = new QDeclarativeContext(qmlContext(this)); - - QObject *nobj = d->newWindowComponent->create(windowContext); - if (nobj) { - windowContext->setParent(nobj); - QDeclarativeItem *item = qobject_cast(nobj); - if (!item) { - delete nobj; - } else { - webview = item->findChild(); - if (!webview) { - delete item; - } else { - nobj->setParent(d->newWindowParent); - static_cast(item)->setParentItem(d->newWindowParent); - } - } - } else { - delete windowContext; - } - - return webview; - } - } - break; - case QWebPage::WebModalDialog: { - // Not supported - } - } - return 0; -} - -/*! - \qmlproperty component WebView::newWindowComponent - - This property holds the component to use for new windows. - The component must have a WebView somewhere in its structure. - - When the web engine requests a new window, it will be an instance of - this component. - - The parent of the new window is set by newWindowParent. It must be set. -*/ -QDeclarativeComponent *QDeclarativeWebView::newWindowComponent() const -{ - Q_D(const QDeclarativeWebView); - return d->newWindowComponent; -} - -void QDeclarativeWebView::setNewWindowComponent(QDeclarativeComponent *newWindow) -{ - Q_D(QDeclarativeWebView); - if (newWindow == d->newWindowComponent) - return; - d->newWindowComponent = newWindow; - emit newWindowComponentChanged(); -} - - -/*! - \qmlproperty item WebView::newWindowParent - - The parent item for new windows. - - \sa newWindowComponent -*/ -QDeclarativeItem *QDeclarativeWebView::newWindowParent() const -{ - Q_D(const QDeclarativeWebView); - return d->newWindowParent; -} - -void QDeclarativeWebView::setNewWindowParent(QDeclarativeItem *parent) -{ - Q_D(QDeclarativeWebView); - if (parent == d->newWindowParent) - return; - if (d->newWindowParent && parent) { - QList children = d->newWindowParent->childItems(); - for (int i = 0; i < children.count(); ++i) { - children.at(i)->setParentItem(parent); - } - } - d->newWindowParent = parent; - emit newWindowParentChanged(); -} - -/*! - Returns the area of the largest element at position (\a x,\a y) that is no larger - than \a maxwidth by \a maxheight pixels. - - May return an area larger in the case when no smaller element is at the position. -*/ -QRect QDeclarativeWebView::elementAreaAt(int x, int y, int maxwidth, int maxheight) const -{ - QWebHitTestResult hit = page()->mainFrame()->hitTestContent(QPoint(x,y)); - QRect rv = hit.boundingRect(); - QWebElement element = hit.enclosingBlockElement(); - if (maxwidth<=0) maxwidth = INT_MAX; - if (maxheight<=0) maxheight = INT_MAX; - while (!element.parent().isNull() && element.geometry().width() <= maxwidth && element.geometry().height() <= maxheight) { - rv = element.geometry(); - element = element.parent(); - } - return rv; -} - -/*! - \internal - \class QDeclarativeWebPage - \brief The QDeclarativeWebPage class is a QWebPage that can create QML plugins. - - \sa QDeclarativeWebView -*/ -QDeclarativeWebPage::QDeclarativeWebPage(QDeclarativeWebView *parent) : - QWebPage(parent) -{ -} - -QDeclarativeWebPage::~QDeclarativeWebPage() -{ -} - -void QDeclarativeWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) -{ - qWarning() << sourceID << ':' << lineNumber << ':' << message; -} - -QString QDeclarativeWebPage::chooseFile(QWebFrame *originatingFrame, const QString& oldFile) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(oldFile) - return oldFile; -} - -void QDeclarativeWebPage::javaScriptAlert(QWebFrame *originatingFrame, const QString& msg) -{ - Q_UNUSED(originatingFrame) - emit viewItem()->alert(msg); -} - -bool QDeclarativeWebPage::javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(msg) - return false; -} - -bool QDeclarativeWebPage::javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(msg) - Q_UNUSED(defaultValue) - Q_UNUSED(result) - return false; -} - - -/* - Qt WebKit does not understand non-QWidget plugins, so dummy widgets - are created, parented to a single dummy tool window. - - The requirements for QML object plugins are input to the Qt WebKit - non-QWidget plugin support, which will obsolete this kludge. -*/ -class QWidget_Dummy_Plugin : public QWidget -{ - Q_OBJECT -public: - static QWidget *dummy_shared_parent() - { - static QWidget *dsp = 0; - if (!dsp) { - dsp = new QWidget(0,Qt::Tool); - dsp->setGeometry(-10000,-10000,0,0); - dsp->show(); - } - return dsp; - } - QWidget_Dummy_Plugin(const QUrl& url, QDeclarativeWebView *view, const QStringList ¶mNames, const QStringList ¶mValues) : - QWidget(dummy_shared_parent()), - propertyNames(paramNames), - propertyValues(paramValues), - webview(view) - { - QDeclarativeEngine *engine = qmlEngine(webview); - component = new QDeclarativeComponent(engine, url, this); - item = 0; - if (component->isLoading()) - connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(qmlLoaded())); - else - qmlLoaded(); - } - -public Q_SLOTS: - void qmlLoaded() - { - if (component->isError()) { - // ### Could instead give these errors to the WebView to handle. - qWarning() << component->errors(); - return; - } - item = qobject_cast(component->create(qmlContext(webview))); - item->setParent(webview); - QString jsObjName; - for (int i=0; isetProperty(propertyNames[i].toUtf8(),propertyValues[i]); - if (propertyNames[i] == QLatin1String("objectname")) - jsObjName = propertyValues[i]; - } - } - if (!jsObjName.isNull()) { - QWebFrame *f = webview->page()->mainFrame(); - f->addToJavaScriptWindowObject(jsObjName, item); - } - resizeEvent(0); - delete component; - component = 0; - } - void resizeEvent(QResizeEvent*) - { - if (item) { - item->setX(x()); - item->setY(y()); - item->setWidth(width()); - item->setHeight(height()); - } - } - -private: - QDeclarativeComponent *component; - QDeclarativeItem *item; - QStringList propertyNames, propertyValues; - QDeclarativeWebView *webview; -}; - -QDeclarativeWebView *QDeclarativeWebPage::viewItem() -{ - return static_cast(parent()); -} - -QObject *QDeclarativeWebPage::createPlugin(const QString &, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) -{ - QUrl comp = qmlContext(viewItem())->resolvedUrl(url); - return new QWidget_Dummy_Plugin(comp,viewItem(),paramNames,paramValues); -} - -QWebPage *QDeclarativeWebPage::createWindow(WebWindowType type) -{ - QDeclarativeWebView *newView = viewItem()->createWindow(type); - if (newView) - return newView->page(); - return 0; -} - -QT_END_NAMESPACE - -#include diff --git a/src/declarative/graphicsitems/qdeclarativewebview_p.h b/src/declarative/graphicsitems/qdeclarativewebview_p.h deleted file mode 100644 index a65aab3..0000000 --- a/src/declarative/graphicsitems/qdeclarativewebview_p.h +++ /dev/null @@ -1,286 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef QDECLARATIVEWEBVIEW_H -#define QDECLARATIVEWEBVIEW_H - -#include "qdeclarativepainteditem_p.h" - -#include -#include -#include -#include - -QT_BEGIN_HEADER - -class QWebHistory; -class QWebSettings; - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) -class QDeclarativeWebViewPrivate; -class QNetworkRequest; -class QDeclarativeWebView; - -class Q_DECLARATIVE_EXPORT QDeclarativeWebPage : public QWebPage -{ - Q_OBJECT -public: - explicit QDeclarativeWebPage(QDeclarativeWebView *parent); - ~QDeclarativeWebPage(); -protected: - QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); - QWebPage *createWindow(WebWindowType type); - void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); - QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); - void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); - bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); - bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); - -private: - QDeclarativeWebView *viewItem(); -}; - - -class QDeclarativeWebViewAttached; -class QDeclarativeWebSettings; - -//### TODO: browser plugins - -class Q_DECLARATIVE_EXPORT QDeclarativeWebView : public QDeclarativePaintedItem -{ - Q_OBJECT - - Q_ENUMS(Status SelectionMode) - - Q_PROPERTY(QString title READ title NOTIFY titleChanged) - Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged) - Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor NOTIFY zoomFactorChanged) - Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged) - - Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged) - - Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime NOTIFY pressGrabTimeChanged) - - Q_PROPERTY(int preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged) - Q_PROPERTY(int preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged) - Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) - Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) - Q_PROPERTY(Status status READ status NOTIFY statusChanged) - - Q_PROPERTY(QAction* reload READ reloadAction CONSTANT) - Q_PROPERTY(QAction* back READ backAction CONSTANT) - Q_PROPERTY(QAction* forward READ forwardAction CONSTANT) - Q_PROPERTY(QAction* stop READ stopAction CONSTANT) - - Q_PROPERTY(QDeclarativeWebSettings* settings READ settingsObject CONSTANT) - - Q_PROPERTY(QDeclarativeListProperty javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT) - - Q_PROPERTY(QDeclarativeComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent NOTIFY newWindowComponentChanged) - Q_PROPERTY(QDeclarativeItem* newWindowParent READ newWindowParent WRITE setNewWindowParent NOTIFY newWindowParentChanged) - - Q_PROPERTY(bool renderingEnabled READ renderingEnabled WRITE setRenderingEnabled NOTIFY renderingEnabledChanged) - -public: - QDeclarativeWebView(QDeclarativeItem *parent=0); - ~QDeclarativeWebView(); - - QUrl url() const; - void setUrl(const QUrl &); - - QString title() const; - - QPixmap icon() const; - - qreal zoomFactor() const; - void setZoomFactor(qreal); - Q_INVOKABLE bool heuristicZoom(int clickX, int clickY, qreal maxzoom); - QRect elementAreaAt(int x, int y, int minwidth, int minheight) const; - - int pressGrabTime() const; - void setPressGrabTime(int); - - int preferredWidth() const; - void setPreferredWidth(int); - int preferredHeight() const; - void setPreferredHeight(int); - - enum Status { Null, Ready, Loading, Error }; - Status status() const; - qreal progress() const; - QString statusText() const; - - QAction *reloadAction() const; - QAction *backAction() const; - QAction *forwardAction() const; - QAction *stopAction() const; - - QWebPage *page() const; - void setPage(QWebPage *page); - - void load(const QNetworkRequest &request, - QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, - const QByteArray &body = QByteArray()); - - QString html() const; - - void setHtml(const QString &html, const QUrl &baseUrl = QUrl()); - void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl()); - - QWebHistory *history() const; - QWebSettings *settings() const; - QDeclarativeWebSettings *settingsObject() const; - - bool renderingEnabled() const; - void setRenderingEnabled(bool); - - QDeclarativeListProperty javaScriptWindowObjects(); - - static QDeclarativeWebViewAttached *qmlAttachedProperties(QObject *); - - QDeclarativeComponent *newWindowComponent() const; - void setNewWindowComponent(QDeclarativeComponent *newWindow); - QDeclarativeItem *newWindowParent() const; - void setNewWindowParent(QDeclarativeItem *newWindow); - -Q_SIGNALS: - void preferredWidthChanged(); - void preferredHeightChanged(); - void urlChanged(); - void progressChanged(); - void statusChanged(Status); - void titleChanged(const QString&); - void iconChanged(); - void statusTextChanged(); - void htmlChanged(); - void pressGrabTimeChanged(); - void zoomFactorChanged(); - void newWindowComponentChanged(); - void newWindowParentChanged(); - void renderingEnabledChanged(); - - void loadStarted(); - void loadFinished(); - void loadFailed(); - - void doubleClick(int clickX, int clickY); - - void zoomTo(qreal zoom, int centerX, int centerY); - - void alert(const QString& message); - -public Q_SLOTS: - QVariant evaluateJavaScript(const QString&); - -private Q_SLOTS: - void expandToWebPage(); - void paintPage(const QRect&); - void doLoadStarted(); - void doLoadProgress(int p); - void doLoadFinished(bool ok); - void setStatusText(const QString&); - void windowObjectCleared(); - void pageUrlChanged(); - void noteContentsSizeChanged(const QSize&); - void initialLayout(); - -protected: - void drawContents(QPainter *, const QRect &); - - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - void timerEvent(QTimerEvent *event); - void hoverMoveEvent (QGraphicsSceneHoverEvent * event); - void keyPressEvent(QKeyEvent* event); - void keyReleaseEvent(QKeyEvent* event); - virtual void geometryChanged(const QRectF &newGeometry, - const QRectF &oldGeometry); - virtual void focusChanged(bool); - virtual bool sceneEvent(QEvent *event); - QDeclarativeWebView *createWindow(QWebPage::WebWindowType type); - -private: - void init(); - virtual void componentComplete(); - Q_DISABLE_COPY(QDeclarativeWebView) - Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeWebView) - QMouseEvent *sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *); - QMouseEvent *sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *); - friend class QDeclarativeWebPage; -}; - -class QDeclarativeWebViewAttached : public QObject -{ - Q_OBJECT - Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName) -public: - QDeclarativeWebViewAttached(QObject *parent) - : QObject(parent) - { - } - - QString windowObjectName() const - { - return m_windowObjectName; - } - - void setWindowObjectName(const QString &n) - { - m_windowObjectName = n; - } - -private: - QString m_windowObjectName; -}; - - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QDeclarativeWebView) -QML_DECLARE_TYPEINFO(QDeclarativeWebView, QML_HAS_ATTACHED_PROPERTIES) - -QT_END_HEADER - -#endif diff --git a/src/declarative/graphicsitems/qdeclarativewebview_p_p.h b/src/declarative/graphicsitems/qdeclarativewebview_p_p.h deleted file mode 100644 index 258b472..0000000 --- a/src/declarative/graphicsitems/qdeclarativewebview_p_p.h +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef QDECLARATIVEWEBVIEW_P_H -#define QDECLARATIVEWEBVIEW_P_H - -#include - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) - -class QDeclarativeWebSettings : public QObject { - Q_OBJECT - - Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily) - Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily) - Q_PROPERTY(QString serifFontFamily READ serifFontFamily WRITE setSerifFontFamily) - Q_PROPERTY(QString sansSerifFontFamily READ sansSerifFontFamily WRITE setSansSerifFontFamily) - Q_PROPERTY(QString cursiveFontFamily READ cursiveFontFamily WRITE setCursiveFontFamily) - Q_PROPERTY(QString fantasyFontFamily READ fantasyFontFamily WRITE setFantasyFontFamily) - - Q_PROPERTY(int minimumFontSize READ minimumFontSize WRITE setMinimumFontSize) - Q_PROPERTY(int minimumLogicalFontSize READ minimumLogicalFontSize WRITE setMinimumLogicalFontSize) - Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize) - Q_PROPERTY(int defaultFixedFontSize READ defaultFixedFontSize WRITE setDefaultFixedFontSize) - - Q_PROPERTY(bool autoLoadImages READ autoLoadImages WRITE setAutoLoadImages) - Q_PROPERTY(bool javascriptEnabled READ javascriptEnabled WRITE setJavascriptEnabled) - Q_PROPERTY(bool javaEnabled READ javaEnabled WRITE setJavaEnabled) - Q_PROPERTY(bool pluginsEnabled READ pluginsEnabled WRITE setPluginsEnabled) - Q_PROPERTY(bool privateBrowsingEnabled READ privateBrowsingEnabled WRITE setPrivateBrowsingEnabled) - Q_PROPERTY(bool javascriptCanOpenWindows READ javascriptCanOpenWindows WRITE setJavascriptCanOpenWindows) - Q_PROPERTY(bool javascriptCanAccessClipboard READ javascriptCanAccessClipboard WRITE setJavascriptCanAccessClipboard) - Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled) - Q_PROPERTY(bool linksIncludedInFocusChain READ linksIncludedInFocusChain WRITE setLinksIncludedInFocusChain) - Q_PROPERTY(bool zoomTextOnly READ zoomTextOnly WRITE setZoomTextOnly) - Q_PROPERTY(bool printElementBackgrounds READ printElementBackgrounds WRITE setPrintElementBackgrounds) - Q_PROPERTY(bool offlineStorageDatabaseEnabled READ offlineStorageDatabaseEnabled WRITE setOfflineStorageDatabaseEnabled) - Q_PROPERTY(bool offlineWebApplicationCacheEnabled READ offlineWebApplicationCacheEnabled WRITE setOfflineWebApplicationCacheEnabled) - Q_PROPERTY(bool localStorageDatabaseEnabled READ localStorageDatabaseEnabled WRITE setLocalStorageDatabaseEnabled) - Q_PROPERTY(bool localContentCanAccessRemoteUrls READ localContentCanAccessRemoteUrls WRITE setLocalContentCanAccessRemoteUrls) - -public: - QDeclarativeWebSettings() {} - - QString standardFontFamily() const { return s->fontFamily(QWebSettings::StandardFont); } - void setStandardFontFamily(const QString& f) { s->setFontFamily(QWebSettings::StandardFont,f); } - QString fixedFontFamily() const { return s->fontFamily(QWebSettings::FixedFont); } - void setFixedFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FixedFont,f); } - QString serifFontFamily() const { return s->fontFamily(QWebSettings::SerifFont); } - void setSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SerifFont,f); } - QString sansSerifFontFamily() const { return s->fontFamily(QWebSettings::SansSerifFont); } - void setSansSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SansSerifFont,f); } - QString cursiveFontFamily() const { return s->fontFamily(QWebSettings::CursiveFont); } - void setCursiveFontFamily(const QString& f) { s->setFontFamily(QWebSettings::CursiveFont,f); } - QString fantasyFontFamily() const { return s->fontFamily(QWebSettings::FantasyFont); } - void setFantasyFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FantasyFont,f); } - - int minimumFontSize() const { return s->fontSize(QWebSettings::MinimumFontSize); } - void setMinimumFontSize(int size) { s->setFontSize(QWebSettings::MinimumFontSize,size); } - int minimumLogicalFontSize() const { return s->fontSize(QWebSettings::MinimumLogicalFontSize); } - void setMinimumLogicalFontSize(int size) { s->setFontSize(QWebSettings::MinimumLogicalFontSize,size); } - int defaultFontSize() const { return s->fontSize(QWebSettings::DefaultFontSize); } - void setDefaultFontSize(int size) { s->setFontSize(QWebSettings::DefaultFontSize,size); } - int defaultFixedFontSize() const { return s->fontSize(QWebSettings::DefaultFixedFontSize); } - void setDefaultFixedFontSize(int size) { s->setFontSize(QWebSettings::DefaultFixedFontSize,size); } - - bool autoLoadImages() const { return s->testAttribute(QWebSettings::AutoLoadImages); } - void setAutoLoadImages(bool on) { s->setAttribute(QWebSettings::AutoLoadImages, on); } - bool javascriptEnabled() const { return s->testAttribute(QWebSettings::JavascriptEnabled); } - void setJavascriptEnabled(bool on) { s->setAttribute(QWebSettings::JavascriptEnabled, on); } - bool javaEnabled() const { return s->testAttribute(QWebSettings::JavaEnabled); } - void setJavaEnabled(bool on) { s->setAttribute(QWebSettings::JavaEnabled, on); } - bool pluginsEnabled() const { return s->testAttribute(QWebSettings::PluginsEnabled); } - void setPluginsEnabled(bool on) { s->setAttribute(QWebSettings::PluginsEnabled, on); } - bool privateBrowsingEnabled() const { return s->testAttribute(QWebSettings::PrivateBrowsingEnabled); } - void setPrivateBrowsingEnabled(bool on) { s->setAttribute(QWebSettings::PrivateBrowsingEnabled, on); } - bool javascriptCanOpenWindows() const { return s->testAttribute(QWebSettings::JavascriptCanOpenWindows); } - void setJavascriptCanOpenWindows(bool on) { s->setAttribute(QWebSettings::JavascriptCanOpenWindows, on); } - bool javascriptCanAccessClipboard() const { return s->testAttribute(QWebSettings::JavascriptCanAccessClipboard); } - void setJavascriptCanAccessClipboard(bool on) { s->setAttribute(QWebSettings::JavascriptCanAccessClipboard, on); } - bool developerExtrasEnabled() const { return s->testAttribute(QWebSettings::DeveloperExtrasEnabled); } - void setDeveloperExtrasEnabled(bool on) { s->setAttribute(QWebSettings::DeveloperExtrasEnabled, on); } - bool linksIncludedInFocusChain() const { return s->testAttribute(QWebSettings::LinksIncludedInFocusChain); } - void setLinksIncludedInFocusChain(bool on) { s->setAttribute(QWebSettings::LinksIncludedInFocusChain, on); } - bool zoomTextOnly() const { return s->testAttribute(QWebSettings::ZoomTextOnly); } - void setZoomTextOnly(bool on) { s->setAttribute(QWebSettings::ZoomTextOnly, on); } - bool printElementBackgrounds() const { return s->testAttribute(QWebSettings::PrintElementBackgrounds); } - void setPrintElementBackgrounds(bool on) { s->setAttribute(QWebSettings::PrintElementBackgrounds, on); } - bool offlineStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled); } - void setOfflineStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, on); } - bool offlineWebApplicationCacheEnabled() const { return s->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled); } - void setOfflineWebApplicationCacheEnabled(bool on) { s->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, on); } - bool localStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::LocalStorageDatabaseEnabled); } - void setLocalStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, on); } - bool localContentCanAccessRemoteUrls() const { return s->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls); } - void setLocalContentCanAccessRemoteUrls(bool on) { s->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, on); } - - QWebSettings *s; -}; - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QDeclarativeWebSettings) - -QT_END_HEADER - -#endif diff --git a/src/plugins/qdeclarativemodules/qdeclarativemodules.pro b/src/plugins/qdeclarativemodules/qdeclarativemodules.pro index 0a6f444..ae53578 100644 --- a/src/plugins/qdeclarativemodules/qdeclarativemodules.pro +++ b/src/plugins/qdeclarativemodules/qdeclarativemodules.pro @@ -3,4 +3,5 @@ TEMPLATE = subdirs SUBDIRS += widgets contains(QT_CONFIG, multimedia): SUBDIRS += multimedia +contains(QT_CONFIG, webkit): SUBDIRS += webkitqmlplugin diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp b/src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp new file mode 100644 index 0000000..2f6205d --- /dev/null +++ b/src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** 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 plugins 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 +#include + +#include "qdeclarativewebview_p.h" +#include "qdeclarativewebview_p_p.h" + +QT_BEGIN_NAMESPACE + +class WebKitQmlPlugin : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + virtual void registerTypes(const char *uri) + { + Q_ASSERT(QLatin1String(uri) == QLatin1String("org.webkit")); + qmlRegisterType(uri,1,0,"WebView"); + } +}; + +QT_END_NAMESPACE + +#include "plugin.moc" + +Q_EXPORT_PLUGIN2(webkitqmlplugin, QT_PREPEND_NAMESPACE(WebKitQmlPlugin)); + diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp new file mode 100644 index 0000000..733ac86 --- /dev/null +++ b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp @@ -0,0 +1,1340 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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 "qdeclarativewebview_p.h" +#include "qdeclarativewebview_p_p.h" + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system + +class QDeclarativeWebViewPrivate : public QDeclarativePaintedItemPrivate +{ + Q_DECLARE_PUBLIC(QDeclarativeWebView) + +public: + QDeclarativeWebViewPrivate() + : QDeclarativePaintedItemPrivate(), page(0), preferredwidth(0), preferredheight(0), + progress(1.0), status(QDeclarativeWebView::Null), pending(PendingNone), + newWindowComponent(0), newWindowParent(0), + pressTime(400), + rendering(true) + { + } + + QUrl url; // page url might be different if it has not loaded yet + QWebPage *page; + + int preferredwidth, preferredheight; + qreal progress; + QDeclarativeWebView::Status status; + QString statusText; + enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending; + QUrl pending_url; + QString pending_string; + QByteArray pending_data; + mutable QDeclarativeWebSettings settings; + QDeclarativeComponent *newWindowComponent; + QDeclarativeItem *newWindowParent; + + QBasicTimer pressTimer; + QPoint pressPoint; + int pressTime; // milliseconds before it's a "hold" + + + static void windowObjects_append(QDeclarativeListProperty *prop, QObject *o) { + static_cast(prop->data)->windowObjects.append(o); + static_cast(prop->data)->updateWindowObjects(); + } + + void updateWindowObjects(); + QObjectList windowObjects; + + bool rendering; +}; + +/*! + \qmlclass WebView QDeclarativeWebView + \since 4.7 + \brief The WebView item allows you to add web content to a canvas. + \inherits Item + + A WebView renders web content based on a URL. + + If the width and height of the item is not set, they will + dynamically adjust to a size appropriate for the content. + This width may be large for typical online web pages. + + If the preferredWidth is set, the width will be this amount or larger, + usually laying out the web content to fit the preferredWidth. + + \qml + import org.webkit 1.0 + + WebView { + url: "http://www.nokia.com" + width: 490 + height: 400 + scale: 0.5 + smooth: false + smoothCache: true + } + \endqml + + \image webview.png + + The item includes no scrolling, scaling, + toolbars, etc., those must be implemented around WebView. See the WebBrowser example + for a demonstration of this. +*/ + +/*! + \internal + \class QDeclarativeWebView + \brief The QDeclarativeWebView class allows you to add web content to a QDeclarativeView. + + A WebView renders web content base on a URL. + + \image webview.png + + The item includes no scrolling, scaling, + toolbars, etc., those must be implemented around WebView. See the WebBrowser example + for a demonstration of this. + + A QDeclarativeWebView object can be instantiated in Qml using the tag \l WebView. +*/ + +QDeclarativeWebView::QDeclarativeWebView(QDeclarativeItem *parent) + : QDeclarativePaintedItem(*(new QDeclarativeWebViewPrivate), parent) +{ + init(); +} + +QDeclarativeWebView::~QDeclarativeWebView() +{ + Q_D(QDeclarativeWebView); + delete d->page; +} + +void QDeclarativeWebView::init() +{ + Q_D(QDeclarativeWebView); + + QWebSettings::enablePersistentStorage(); + + setAcceptHoverEvents(true); + setAcceptedMouseButtons(Qt::LeftButton); + setFlag(QGraphicsItem::ItemHasNoContents, false); + + d->page = 0; +} + +void QDeclarativeWebView::componentComplete() +{ + QDeclarativePaintedItem::componentComplete(); + Q_D(QDeclarativeWebView); + switch (d->pending) { + case QDeclarativeWebViewPrivate::PendingUrl: + setUrl(d->pending_url); + break; + case QDeclarativeWebViewPrivate::PendingHtml: + setHtml(d->pending_string, d->pending_url); + break; + case QDeclarativeWebViewPrivate::PendingContent: + setContent(d->pending_data, d->pending_string, d->pending_url); + break; + default: + break; + } + d->pending = QDeclarativeWebViewPrivate::PendingNone; + d->updateWindowObjects(); +} + +QDeclarativeWebView::Status QDeclarativeWebView::status() const +{ + Q_D(const QDeclarativeWebView); + return d->status; +} + + +/*! + \qmlproperty real WebView::progress + This property holds the progress of loading the current URL, from 0 to 1. + + If you just want to know when progress gets to 1, use + WebView::onLoadFinished() or WebView::onLoadFailed() instead. +*/ +qreal QDeclarativeWebView::progress() const +{ + Q_D(const QDeclarativeWebView); + return d->progress; +} + +void QDeclarativeWebView::doLoadStarted() +{ + Q_D(QDeclarativeWebView); + + if (!d->url.isEmpty()) { + d->status = Loading; + emit statusChanged(d->status); + } + emit loadStarted(); +} + +void QDeclarativeWebView::doLoadProgress(int p) +{ + Q_D(QDeclarativeWebView); + if (d->progress == p/100.0) + return; + d->progress = p/100.0; + emit progressChanged(); +} + +void QDeclarativeWebView::pageUrlChanged() +{ + Q_D(QDeclarativeWebView); + + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + expandToWebPage(); + + if ((d->url.isEmpty() && page()->mainFrame()->url() != QUrl(QLatin1String("about:blank"))) + || (d->url != page()->mainFrame()->url() && !page()->mainFrame()->url().isEmpty())) + { + d->url = page()->mainFrame()->url(); + if (d->url == QUrl(QLatin1String("about:blank"))) + d->url = QUrl(); + emit urlChanged(); + } +} + +void QDeclarativeWebView::doLoadFinished(bool ok) +{ + Q_D(QDeclarativeWebView); + + if (title().isEmpty()) + pageUrlChanged(); // XXX bug 232556 - pages with no title never get urlChanged() + + if (ok) { + d->status = d->url.isEmpty() ? Null : Ready; + emit loadFinished(); + } else { + d->status = Error; + emit loadFailed(); + } + emit statusChanged(d->status); +} + +/*! + \qmlproperty url WebView::url + This property holds the URL to the page displayed in this item. It can be set, + but also can change spontaneously (eg. because of network redirection). + + If the url is empty, the page is blank. + + The url is always absolute (QML will resolve relative URL strings in the context + of the containing QML document). +*/ +QUrl QDeclarativeWebView::url() const +{ + Q_D(const QDeclarativeWebView); + return d->url; +} + +void QDeclarativeWebView::setUrl(const QUrl &url) +{ + Q_D(QDeclarativeWebView); + if (url == d->url) + return; + + if (isComponentComplete()) { + d->url = url; + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + QUrl seturl = url; + if (seturl.isEmpty()) + seturl = QUrl(QLatin1String("about:blank")); + + Q_ASSERT(!seturl.isRelative()); + + page()->mainFrame()->load(seturl); + + emit urlChanged(); + } else { + d->pending = d->PendingUrl; + d->pending_url = url; + } +} + +/*! + \qmlproperty int WebView::preferredWidth + This property holds the ideal width for displaying the current URL. +*/ +int QDeclarativeWebView::preferredWidth() const +{ + Q_D(const QDeclarativeWebView); + return d->preferredwidth; +} + +void QDeclarativeWebView::setPreferredWidth(int iw) +{ + Q_D(QDeclarativeWebView); + if (d->preferredwidth == iw) return; + d->preferredwidth = iw; + //expandToWebPage(); + emit preferredWidthChanged(); +} + +/*! + \qmlproperty int WebView::preferredHeight + This property holds the ideal height for displaying the current URL. + This only affects the area zoomed by heuristicZoom(). +*/ +int QDeclarativeWebView::preferredHeight() const +{ + Q_D(const QDeclarativeWebView); + return d->preferredheight; +} +void QDeclarativeWebView::setPreferredHeight(int ih) +{ + Q_D(QDeclarativeWebView); + if (d->preferredheight == ih) return; + d->preferredheight = ih; + emit preferredHeightChanged(); +} + +/*! + \qmlmethod bool WebView::evaluateJavaScript(string) + + Evaluates the \a scriptSource JavaScript inside the context of the + main web frame, and returns the result of the last executed statement. + + Note that this JavaScript does \e not have any access to QML objects + except as made available as windowObjects. +*/ +QVariant QDeclarativeWebView::evaluateJavaScript(const QString &scriptSource) +{ + return this->page()->mainFrame()->evaluateJavaScript(scriptSource); +} + +void QDeclarativeWebView::focusChanged(bool hasFocus) +{ + QFocusEvent e(hasFocus ? QEvent::FocusIn : QEvent::FocusOut); + page()->event(&e); + QDeclarativeItem::focusChanged(hasFocus); +} + +void QDeclarativeWebView::initialLayout() +{ + // nothing useful to do at this point +} + +void QDeclarativeWebView::noteContentsSizeChanged(const QSize&) +{ + expandToWebPage(); +} + +void QDeclarativeWebView::expandToWebPage() +{ + Q_D(QDeclarativeWebView); + QSize cs = page()->mainFrame()->contentsSize(); + if (cs.width() < d->preferredwidth) + cs.setWidth(d->preferredwidth); + if (cs.height() < d->preferredheight) + cs.setHeight(d->preferredheight); + if (widthValid()) + cs.setWidth(width()); + if (heightValid()) + cs.setHeight(height()); + if (cs != page()->viewportSize()) { + page()->setViewportSize(cs); + } + if (cs != contentsSize()) + setContentsSize(cs); +} + +void QDeclarativeWebView::geometryChanged(const QRectF &newGeometry, + const QRectF &oldGeometry) +{ + if (newGeometry.size() != oldGeometry.size()) + expandToWebPage(); + QDeclarativePaintedItem::geometryChanged(newGeometry, oldGeometry); +} + +void QDeclarativeWebView::paintPage(const QRect& r) +{ + dirtyCache(r); + update(); +} + +/*! + \qmlproperty list WebView::javaScriptWindowObjects + + This property is a list of object that are available from within + the webview's JavaScript context. + + The \a object will be inserted as a child of the frame's window + object, under the name given by the attached property \c WebView.windowObjectName. + + \qml + WebView { + javaScriptWindowObjects: Object { + WebView.windowObjectName: "coordinates" + } + } + \endqml + + Properties of the object will be exposed as JavaScript properties and slots as + JavaScript methods. + + If Javascript is not enabled for this page, then this property does nothing. +*/ +QDeclarativeListProperty QDeclarativeWebView::javaScriptWindowObjects() +{ + Q_D(QDeclarativeWebView); + return QDeclarativeListProperty(this, d, &QDeclarativeWebViewPrivate::windowObjects_append); +} + +QDeclarativeWebViewAttached *QDeclarativeWebView::qmlAttachedProperties(QObject *o) +{ + return new QDeclarativeWebViewAttached(o); +} + +void QDeclarativeWebViewPrivate::updateWindowObjects() +{ + Q_Q(QDeclarativeWebView); + if (!q->isComponentComplete() || !page) + return; + + for (int ii = 0; ii < windowObjects.count(); ++ii) { + QObject *object = windowObjects.at(ii); + QDeclarativeWebViewAttached *attached = static_cast(qmlAttachedPropertiesObject(object)); + if (attached && !attached->windowObjectName().isEmpty()) { + page->mainFrame()->addToJavaScriptWindowObject(attached->windowObjectName(), object); + } + } +} + +bool QDeclarativeWebView::renderingEnabled() const +{ + Q_D(const QDeclarativeWebView); + return d->rendering; +} + +void QDeclarativeWebView::setRenderingEnabled(bool enabled) +{ + Q_D(QDeclarativeWebView); + if (d->rendering == enabled) + return; + d->rendering = enabled; + emit renderingEnabledChanged(); + + setCacheFrozen(!enabled); + if (enabled) + clearCache(); +} + + +void QDeclarativeWebView::drawContents(QPainter *p, const QRect &r) +{ + Q_D(QDeclarativeWebView); + if (d->rendering) + page()->mainFrame()->render(p,r); +} + +QMouseEvent *QDeclarativeWebView::sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *e) +{ + QEvent::Type t; + switch(e->type()) { + default: + case QEvent::GraphicsSceneMousePress: + t = QEvent::MouseButtonPress; + break; + case QEvent::GraphicsSceneMouseRelease: + t = QEvent::MouseButtonRelease; + break; + case QEvent::GraphicsSceneMouseMove: + t = QEvent::MouseMove; + break; + case QGraphicsSceneEvent::GraphicsSceneMouseDoubleClick: + t = QEvent::MouseButtonDblClick; + break; + } + + QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), e->button(), e->buttons(), 0); + return me; +} + +QMouseEvent *QDeclarativeWebView::sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *e) +{ + QEvent::Type t = QEvent::MouseMove; + + QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), Qt::NoButton, Qt::NoButton, 0); + + return me; +} + + +/*! + \qmlsignal WebView::onDoubleClick(clickx,clicky) + + The WebView does not pass double-click events to the web engine, but rather + emits this signals. +*/ + +void QDeclarativeWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + emit doubleClick(me->x(),me->y()); + delete me; +} + +/*! + \qmlmethod bool WebView::heuristicZoom(clickX,clickY,maxzoom) + + Finds a zoom that: + \list + \i shows a whole item + \i includes (\a clickX, \a clickY) + \i fits into the preferredWidth and preferredHeight + \i zooms by no more than \a maxzoom + \i is more than 10% above the current zoom + \endlist + + If such a zoom exists, emits zoomTo(zoom,centerX,centerY) and returns true; otherwise, + no signal is emitted and returns false. +*/ +bool QDeclarativeWebView::heuristicZoom(int clickX, int clickY, qreal maxzoom) +{ + Q_D(QDeclarativeWebView); + if (contentsScale() >= maxzoom/zoomFactor()) + return false; + qreal ozf = contentsScale(); + QRect showarea = elementAreaAt(clickX, clickY, d->preferredwidth/maxzoom, d->preferredheight/maxzoom); + qreal z = qMin(qreal(d->preferredwidth)/showarea.width(),qreal(d->preferredheight)/showarea.height()); + if (z > maxzoom/zoomFactor()) + z = maxzoom/zoomFactor(); + if (z/ozf > 1.2) { + QRectF r(showarea.left()*z, showarea.top()*z, showarea.width()*z, showarea.height()*z); + emit zoomTo(z,r.x()+r.width()/2, r.y()+r.height()/2); + return true; + } else { + return false; + } +} + +/*! + \qmlproperty int WebView::pressGrabTime + + The number of milliseconds the user must press before the WebView + starts passing move events through to the web engine (rather than + letting other QML elements such as a Flickable take them). + + Defaults to 400ms. Set to 0 to always grab and pass move events to + the web engine. +*/ +int QDeclarativeWebView::pressGrabTime() const +{ + Q_D(const QDeclarativeWebView); + return d->pressTime; +} + +void QDeclarativeWebView::setPressGrabTime(int ms) +{ + Q_D(QDeclarativeWebView); + if (d->pressTime == ms) + return; + d->pressTime = ms; + emit pressGrabTimeChanged(); +} + +void QDeclarativeWebView::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + setFocus (true); + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + + d->pressPoint = me->pos(); + if (d->pressTime) { + d->pressTimer.start(d->pressTime,this); + setKeepMouseGrab(false); + } else { + grabMouse(); + setKeepMouseGrab(true); + } + + page()->event(me); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit + Might be a bug in WebKit, though + */ +#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) { + QDeclarativePaintedItem::mousePressEvent(event); + } +} + +void QDeclarativeWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + page()->event(me); + d->pressTimer.stop(); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send all the events to WebKit + */ +#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) { + QDeclarativePaintedItem::mouseReleaseEvent(event); + } + setKeepMouseGrab(false); + ungrabMouse(); +} + +void QDeclarativeWebView::timerEvent(QTimerEvent *event) +{ + Q_D(QDeclarativeWebView); + if (event->timerId() == d->pressTimer.timerId()) { + d->pressTimer.stop(); + grabMouse(); + setKeepMouseGrab(true); + } +} + +void QDeclarativeWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + if (d->pressTimer.isActive()) { + if ((me->pos() - d->pressPoint).manhattanLength() > QApplication::startDragDistance()) { + d->pressTimer.stop(); + } + } + if (keepMouseGrab()) { + page()->event(me); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit + Might be a bug in WebKit, though + */ +#if 1 // QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + } + delete me; + if (!event->isAccepted()) + QDeclarativePaintedItem::mouseMoveEvent(event); + +} +void QDeclarativeWebView::hoverMoveEvent (QGraphicsSceneHoverEvent * event) +{ + QMouseEvent *me = sceneHoverMoveEventToMouseEvent(event); + page()->event(me); + event->setAccepted( +#if QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) + QDeclarativePaintedItem::hoverMoveEvent(event); +} + +void QDeclarativeWebView::keyPressEvent(QKeyEvent* event) +{ + page()->event(event); + if (!event->isAccepted()) + QDeclarativePaintedItem::keyPressEvent(event); +} + +void QDeclarativeWebView::keyReleaseEvent(QKeyEvent* event) +{ + page()->event(event); + if (!event->isAccepted()) + QDeclarativePaintedItem::keyReleaseEvent(event); +} + +bool QDeclarativeWebView::sceneEvent(QEvent *event) +{ + if (event->type() == QEvent::KeyPress) { + QKeyEvent *k = static_cast(event); + if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) { + if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? + page()->event(event); + if (event->isAccepted()) + return true; + } + } + } + return QDeclarativePaintedItem::sceneEvent(event); +} + + +/*! + \qmlproperty action WebView::back + This property holds the action for causing the previous URL in the history to be displayed. +*/ +QAction *QDeclarativeWebView::backAction() const +{ + return page()->action(QWebPage::Back); +} + +/*! + \qmlproperty action WebView::forward + This property holds the action for causing the next URL in the history to be displayed. +*/ +QAction *QDeclarativeWebView::forwardAction() const +{ + return page()->action(QWebPage::Forward); +} + +/*! + \qmlproperty action WebView::reload + This property holds the action for reloading with the current URL +*/ +QAction *QDeclarativeWebView::reloadAction() const +{ + return page()->action(QWebPage::Reload); +} + +/*! + \qmlproperty action WebView::stop + This property holds the action for stopping loading with the current URL +*/ +QAction *QDeclarativeWebView::stopAction() const +{ + return page()->action(QWebPage::Stop); +} + +/*! + \qmlproperty real WebView::title + This property holds the title of the web page currently viewed + + By default, this property contains an empty string. +*/ +QString QDeclarativeWebView::title() const +{ + return page()->mainFrame()->title(); +} + + + +/*! + \qmlproperty pixmap WebView::icon + This property holds the icon associated with the web page currently viewed +*/ +QPixmap QDeclarativeWebView::icon() const +{ + return page()->mainFrame()->icon().pixmap(QSize(256,256)); +} + + +/*! + \qmlproperty real WebView::zoomFactor + This property holds the multiplier used to scale the contents of a Web page. +*/ +void QDeclarativeWebView::setZoomFactor(qreal factor) +{ + Q_D(QDeclarativeWebView); + if (factor == page()->mainFrame()->zoomFactor()) + return; + + page()->mainFrame()->setZoomFactor(factor); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth*factor : width()*factor, + d->preferredheight>0 ? d->preferredheight*factor : height()*factor)); + expandToWebPage(); + + emit zoomFactorChanged(); +} + +qreal QDeclarativeWebView::zoomFactor() const +{ + return page()->mainFrame()->zoomFactor(); +} + +/*! + \qmlproperty string WebView::statusText + + This property is the current status suggested by the current web page. In a web browser, + such status is often shown in some kind of status bar. +*/ +void QDeclarativeWebView::setStatusText(const QString& s) +{ + Q_D(QDeclarativeWebView); + d->statusText = s; + emit statusTextChanged(); +} + +void QDeclarativeWebView::windowObjectCleared() +{ + Q_D(QDeclarativeWebView); + d->updateWindowObjects(); +} + +QString QDeclarativeWebView::statusText() const +{ + Q_D(const QDeclarativeWebView); + return d->statusText; +} + +QWebPage *QDeclarativeWebView::page() const +{ + Q_D(const QDeclarativeWebView); + + if (!d->page) { + QDeclarativeWebView *self = const_cast(this); + QWebPage *wp = new QDeclarativeWebPage(self); + + // QML items don't default to having a background, + // even though most we pages will set one anyway. + QPalette pal = QApplication::palette(); + pal.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0)); + wp->setPalette(pal); + + wp->setNetworkAccessManager(qmlEngine(this)->networkAccessManager()); + + self->setPage(wp); + + return wp; + } + + return d->page; +} + + +// The QObject interface to settings(). +/*! + \qmlproperty string WebView::settings.standardFontFamily + \qmlproperty string WebView::settings.fixedFontFamily + \qmlproperty string WebView::settings.serifFontFamily + \qmlproperty string WebView::settings.sansSerifFontFamily + \qmlproperty string WebView::settings.cursiveFontFamily + \qmlproperty string WebView::settings.fantasyFontFamily + + \qmlproperty int WebView::settings.minimumFontSize + \qmlproperty int WebView::settings.minimumLogicalFontSize + \qmlproperty int WebView::settings.defaultFontSize + \qmlproperty int WebView::settings.defaultFixedFontSize + + \qmlproperty bool WebView::settings.autoLoadImages + \qmlproperty bool WebView::settings.javascriptEnabled + \qmlproperty bool WebView::settings.javaEnabled + \qmlproperty bool WebView::settings.pluginsEnabled + \qmlproperty bool WebView::settings.privateBrowsingEnabled + \qmlproperty bool WebView::settings.javascriptCanOpenWindows + \qmlproperty bool WebView::settings.javascriptCanAccessClipboard + \qmlproperty bool WebView::settings.developerExtrasEnabled + \qmlproperty bool WebView::settings.linksIncludedInFocusChain + \qmlproperty bool WebView::settings.zoomTextOnly + \qmlproperty bool WebView::settings.printElementBackgrounds + \qmlproperty bool WebView::settings.offlineStorageDatabaseEnabled + \qmlproperty bool WebView::settings.offlineWebApplicationCacheEnabled + \qmlproperty bool WebView::settings.localStorageDatabaseEnabled + \qmlproperty bool WebView::settings.localContentCanAccessRemoteUrls + + These properties give access to the settings controlling the web view. + + See QWebSettings for details of these properties. + + \qml + WebView { + settings.pluginsEnabled: true + settings.standardFontFamily: "Arial" + ... + } + \endqml +*/ +QObject *QDeclarativeWebView::settingsObject() const +{ + Q_D(const QDeclarativeWebView); + d->settings.s = page()->settings(); + return &d->settings; +} + +void QDeclarativeWebView::setPage(QWebPage *page) +{ + Q_D(QDeclarativeWebView); + if (d->page == page) + return; + if (d->page) { + if (d->page->parent() == this) { + delete d->page; + } else { + d->page->disconnect(this); + } + } + d->page = page; + d->page->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + d->page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff); + d->page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff); + connect(d->page,SIGNAL(repaintRequested(QRect)),this,SLOT(paintPage(QRect))); + connect(d->page->mainFrame(),SIGNAL(urlChanged(QUrl)),this,SLOT(pageUrlChanged())); + connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString))); + connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(iconChanged())); + connect(d->page->mainFrame(), SIGNAL(iconChanged()), this, SIGNAL(iconChanged())); + connect(d->page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), this, SLOT(noteContentsSizeChanged(QSize))); + connect(d->page->mainFrame(), SIGNAL(initialLayoutCompleted()), this, SLOT(initialLayout())); + + connect(d->page,SIGNAL(loadStarted()),this,SLOT(doLoadStarted())); + connect(d->page,SIGNAL(loadProgress(int)),this,SLOT(doLoadProgress(int))); + connect(d->page,SIGNAL(loadFinished(bool)),this,SLOT(doLoadFinished(bool))); + connect(d->page,SIGNAL(statusBarMessage(QString)),this,SLOT(setStatusText(QString))); + + connect(d->page->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(windowObjectCleared())); +} + +/*! + \qmlsignal WebView::onLoadStarted() + + This handler is called when the web engine begins loading + a page. Later, WebView::onLoadFinished() or WebView::onLoadFailed() + will be emitted. +*/ + +/*! + \qmlsignal WebView::onLoadFinished() + + This handler is called when the web engine \e successfully + finishes loading a page, including any component content + (WebView::onLoadFailed() will be emitted otherwise). + + \sa progress +*/ + +/*! + \qmlsignal WebView::onLoadFailed() + + This handler is called when the web engine fails loading + a page or any component content + (WebView::onLoadFinished() will be emitted on success). +*/ + +void QDeclarativeWebView::load(const QNetworkRequest &request, + QNetworkAccessManager::Operation operation, + const QByteArray &body) +{ + page()->mainFrame()->load(request, operation, body); +} + +QString QDeclarativeWebView::html() const +{ + return page()->mainFrame()->toHtml(); +} + +/*! + \qmlproperty string WebView::html + This property holds HTML text set directly + + The html property can be set as a string. + + \qml + WebView { + html: "

This is HTML." + } + \endqml +*/ +void QDeclarativeWebView::setHtml(const QString &html, const QUrl &baseUrl) +{ + Q_D(QDeclarativeWebView); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + if (isComponentComplete()) + page()->mainFrame()->setHtml(html, baseUrl); + else { + d->pending = d->PendingHtml; + d->pending_url = baseUrl; + d->pending_string = html; + } + emit htmlChanged(); +} + +void QDeclarativeWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) +{ + Q_D(QDeclarativeWebView); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + + if (isComponentComplete()) + page()->mainFrame()->setContent(data,mimeType,qmlContext(this)->resolvedUrl(baseUrl)); + else { + d->pending = d->PendingContent; + d->pending_url = baseUrl; + d->pending_string = mimeType; + d->pending_data = data; + } +} + +QWebHistory *QDeclarativeWebView::history() const +{ + return page()->history(); +} + +QWebSettings *QDeclarativeWebView::settings() const +{ + return page()->settings(); +} + +QDeclarativeWebView *QDeclarativeWebView::createWindow(QWebPage::WebWindowType type) +{ + Q_D(QDeclarativeWebView); + switch (type) { + case QWebPage::WebBrowserWindow: { + if (!d->newWindowComponent && d->newWindowParent) + qWarning("WebView::newWindowComponent not set - WebView::newWindowParent ignored"); + else if (d->newWindowComponent && !d->newWindowParent) + qWarning("WebView::newWindowParent not set - WebView::newWindowComponent ignored"); + else if (d->newWindowComponent && d->newWindowParent) { + QDeclarativeWebView *webview = 0; + QDeclarativeContext *windowContext = new QDeclarativeContext(qmlContext(this)); + + QObject *nobj = d->newWindowComponent->create(windowContext); + if (nobj) { + windowContext->setParent(nobj); + QDeclarativeItem *item = qobject_cast(nobj); + if (!item) { + delete nobj; + } else { + webview = item->findChild(); + if (!webview) { + delete item; + } else { + nobj->setParent(d->newWindowParent); + static_cast(item)->setParentItem(d->newWindowParent); + } + } + } else { + delete windowContext; + } + + return webview; + } + } + break; + case QWebPage::WebModalDialog: { + // Not supported + } + } + return 0; +} + +/*! + \qmlproperty component WebView::newWindowComponent + + This property holds the component to use for new windows. + The component must have a WebView somewhere in its structure. + + When the web engine requests a new window, it will be an instance of + this component. + + The parent of the new window is set by newWindowParent. It must be set. +*/ +QDeclarativeComponent *QDeclarativeWebView::newWindowComponent() const +{ + Q_D(const QDeclarativeWebView); + return d->newWindowComponent; +} + +void QDeclarativeWebView::setNewWindowComponent(QDeclarativeComponent *newWindow) +{ + Q_D(QDeclarativeWebView); + if (newWindow == d->newWindowComponent) + return; + d->newWindowComponent = newWindow; + emit newWindowComponentChanged(); +} + + +/*! + \qmlproperty item WebView::newWindowParent + + The parent item for new windows. + + \sa newWindowComponent +*/ +QDeclarativeItem *QDeclarativeWebView::newWindowParent() const +{ + Q_D(const QDeclarativeWebView); + return d->newWindowParent; +} + +void QDeclarativeWebView::setNewWindowParent(QDeclarativeItem *parent) +{ + Q_D(QDeclarativeWebView); + if (parent == d->newWindowParent) + return; + if (d->newWindowParent && parent) { + QList children = d->newWindowParent->childItems(); + for (int i = 0; i < children.count(); ++i) { + children.at(i)->setParentItem(parent); + } + } + d->newWindowParent = parent; + emit newWindowParentChanged(); +} + +/*! + Returns the area of the largest element at position (\a x,\a y) that is no larger + than \a maxwidth by \a maxheight pixels. + + May return an area larger in the case when no smaller element is at the position. +*/ +QRect QDeclarativeWebView::elementAreaAt(int x, int y, int maxwidth, int maxheight) const +{ + QWebHitTestResult hit = page()->mainFrame()->hitTestContent(QPoint(x,y)); + QRect rv = hit.boundingRect(); + QWebElement element = hit.enclosingBlockElement(); + if (maxwidth<=0) maxwidth = INT_MAX; + if (maxheight<=0) maxheight = INT_MAX; + while (!element.parent().isNull() && element.geometry().width() <= maxwidth && element.geometry().height() <= maxheight) { + rv = element.geometry(); + element = element.parent(); + } + return rv; +} + +/*! + \internal + \class QDeclarativeWebPage + \brief The QDeclarativeWebPage class is a QWebPage that can create QML plugins. + + \sa QDeclarativeWebView +*/ +QDeclarativeWebPage::QDeclarativeWebPage(QDeclarativeWebView *parent) : + QWebPage(parent) +{ +} + +QDeclarativeWebPage::~QDeclarativeWebPage() +{ +} + +void QDeclarativeWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) +{ + qWarning() << sourceID << ':' << lineNumber << ':' << message; +} + +QString QDeclarativeWebPage::chooseFile(QWebFrame *originatingFrame, const QString& oldFile) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(oldFile) + return oldFile; +} + +void QDeclarativeWebPage::javaScriptAlert(QWebFrame *originatingFrame, const QString& msg) +{ + Q_UNUSED(originatingFrame) + emit viewItem()->alert(msg); +} + +bool QDeclarativeWebPage::javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(msg) + return false; +} + +bool QDeclarativeWebPage::javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(msg) + Q_UNUSED(defaultValue) + Q_UNUSED(result) + return false; +} + + +/* + Qt WebKit does not understand non-QWidget plugins, so dummy widgets + are created, parented to a single dummy tool window. + + The requirements for QML object plugins are input to the Qt WebKit + non-QWidget plugin support, which will obsolete this kludge. +*/ +class QWidget_Dummy_Plugin : public QWidget +{ + Q_OBJECT +public: + static QWidget *dummy_shared_parent() + { + static QWidget *dsp = 0; + if (!dsp) { + dsp = new QWidget(0,Qt::Tool); + dsp->setGeometry(-10000,-10000,0,0); + dsp->show(); + } + return dsp; + } + QWidget_Dummy_Plugin(const QUrl& url, QDeclarativeWebView *view, const QStringList ¶mNames, const QStringList ¶mValues) : + QWidget(dummy_shared_parent()), + propertyNames(paramNames), + propertyValues(paramValues), + webview(view) + { + QDeclarativeEngine *engine = qmlEngine(webview); + component = new QDeclarativeComponent(engine, url, this); + item = 0; + if (component->isLoading()) + connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(qmlLoaded())); + else + qmlLoaded(); + } + +public Q_SLOTS: + void qmlLoaded() + { + if (component->isError()) { + // ### Could instead give these errors to the WebView to handle. + qWarning() << component->errors(); + return; + } + item = qobject_cast(component->create(qmlContext(webview))); + item->setParent(webview); + QString jsObjName; + for (int i=0; isetProperty(propertyNames[i].toUtf8(),propertyValues[i]); + if (propertyNames[i] == QLatin1String("objectname")) + jsObjName = propertyValues[i]; + } + } + if (!jsObjName.isNull()) { + QWebFrame *f = webview->page()->mainFrame(); + f->addToJavaScriptWindowObject(jsObjName, item); + } + resizeEvent(0); + delete component; + component = 0; + } + void resizeEvent(QResizeEvent*) + { + if (item) { + item->setX(x()); + item->setY(y()); + item->setWidth(width()); + item->setHeight(height()); + } + } + +private: + QDeclarativeComponent *component; + QDeclarativeItem *item; + QStringList propertyNames, propertyValues; + QDeclarativeWebView *webview; +}; + +QDeclarativeWebView *QDeclarativeWebPage::viewItem() +{ + return static_cast(parent()); +} + +QObject *QDeclarativeWebPage::createPlugin(const QString &, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) +{ + QUrl comp = qmlContext(viewItem())->resolvedUrl(url); + return new QWidget_Dummy_Plugin(comp,viewItem(),paramNames,paramValues); +} + +QWebPage *QDeclarativeWebPage::createWindow(WebWindowType type) +{ + QDeclarativeWebView *newView = viewItem()->createWindow(type); + if (newView) + return newView->page(); + return 0; +} + +QT_END_NAMESPACE + +#include diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h new file mode 100644 index 0000000..0bb5d29 --- /dev/null +++ b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h @@ -0,0 +1,285 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef QDECLARATIVEWEBVIEW_H +#define QDECLARATIVEWEBVIEW_H + +#include + +#include +#include +#include +#include + +QT_BEGIN_HEADER + +class QWebHistory; +class QWebSettings; + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) +class QDeclarativeWebViewPrivate; +class QNetworkRequest; +class QDeclarativeWebView; + +class Q_DECLARATIVE_EXPORT QDeclarativeWebPage : public QWebPage +{ + Q_OBJECT +public: + explicit QDeclarativeWebPage(QDeclarativeWebView *parent); + ~QDeclarativeWebPage(); +protected: + QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); + QWebPage *createWindow(WebWindowType type); + void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); + QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); + void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); + bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); + bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); + +private: + QDeclarativeWebView *viewItem(); +}; + + +class QDeclarativeWebViewAttached; + +//### TODO: browser plugins + +class Q_DECLARATIVE_EXPORT QDeclarativeWebView : public QDeclarativePaintedItem +{ + Q_OBJECT + + Q_ENUMS(Status SelectionMode) + + Q_PROPERTY(QString title READ title NOTIFY titleChanged) + Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged) + Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor NOTIFY zoomFactorChanged) + Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged) + + Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged) + + Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime NOTIFY pressGrabTimeChanged) + + Q_PROPERTY(int preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged) + Q_PROPERTY(int preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged) + Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) + Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) + Q_PROPERTY(Status status READ status NOTIFY statusChanged) + + Q_PROPERTY(QAction* reload READ reloadAction CONSTANT) + Q_PROPERTY(QAction* back READ backAction CONSTANT) + Q_PROPERTY(QAction* forward READ forwardAction CONSTANT) + Q_PROPERTY(QAction* stop READ stopAction CONSTANT) + + Q_PROPERTY(QObject* settings READ settingsObject CONSTANT) + + Q_PROPERTY(QDeclarativeListProperty javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT) + + Q_PROPERTY(QDeclarativeComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent NOTIFY newWindowComponentChanged) + Q_PROPERTY(QDeclarativeItem* newWindowParent READ newWindowParent WRITE setNewWindowParent NOTIFY newWindowParentChanged) + + Q_PROPERTY(bool renderingEnabled READ renderingEnabled WRITE setRenderingEnabled NOTIFY renderingEnabledChanged) + +public: + QDeclarativeWebView(QDeclarativeItem *parent=0); + ~QDeclarativeWebView(); + + QUrl url() const; + void setUrl(const QUrl &); + + QString title() const; + + QPixmap icon() const; + + qreal zoomFactor() const; + void setZoomFactor(qreal); + Q_INVOKABLE bool heuristicZoom(int clickX, int clickY, qreal maxzoom); + QRect elementAreaAt(int x, int y, int minwidth, int minheight) const; + + int pressGrabTime() const; + void setPressGrabTime(int); + + int preferredWidth() const; + void setPreferredWidth(int); + int preferredHeight() const; + void setPreferredHeight(int); + + enum Status { Null, Ready, Loading, Error }; + Status status() const; + qreal progress() const; + QString statusText() const; + + QAction *reloadAction() const; + QAction *backAction() const; + QAction *forwardAction() const; + QAction *stopAction() const; + + QWebPage *page() const; + void setPage(QWebPage *page); + + void load(const QNetworkRequest &request, + QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, + const QByteArray &body = QByteArray()); + + QString html() const; + + void setHtml(const QString &html, const QUrl &baseUrl = QUrl()); + void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl()); + + QWebHistory *history() const; + QWebSettings *settings() const; + QObject *settingsObject() const; + + bool renderingEnabled() const; + void setRenderingEnabled(bool); + + QDeclarativeListProperty javaScriptWindowObjects(); + + static QDeclarativeWebViewAttached *qmlAttachedProperties(QObject *); + + QDeclarativeComponent *newWindowComponent() const; + void setNewWindowComponent(QDeclarativeComponent *newWindow); + QDeclarativeItem *newWindowParent() const; + void setNewWindowParent(QDeclarativeItem *newWindow); + +Q_SIGNALS: + void preferredWidthChanged(); + void preferredHeightChanged(); + void urlChanged(); + void progressChanged(); + void statusChanged(Status); + void titleChanged(const QString&); + void iconChanged(); + void statusTextChanged(); + void htmlChanged(); + void pressGrabTimeChanged(); + void zoomFactorChanged(); + void newWindowComponentChanged(); + void newWindowParentChanged(); + void renderingEnabledChanged(); + + void loadStarted(); + void loadFinished(); + void loadFailed(); + + void doubleClick(int clickX, int clickY); + + void zoomTo(qreal zoom, int centerX, int centerY); + + void alert(const QString& message); + +public Q_SLOTS: + QVariant evaluateJavaScript(const QString&); + +private Q_SLOTS: + void expandToWebPage(); + void paintPage(const QRect&); + void doLoadStarted(); + void doLoadProgress(int p); + void doLoadFinished(bool ok); + void setStatusText(const QString&); + void windowObjectCleared(); + void pageUrlChanged(); + void noteContentsSizeChanged(const QSize&); + void initialLayout(); + +protected: + void drawContents(QPainter *, const QRect &); + + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void timerEvent(QTimerEvent *event); + void hoverMoveEvent (QGraphicsSceneHoverEvent * event); + void keyPressEvent(QKeyEvent* event); + void keyReleaseEvent(QKeyEvent* event); + virtual void geometryChanged(const QRectF &newGeometry, + const QRectF &oldGeometry); + virtual void focusChanged(bool); + virtual bool sceneEvent(QEvent *event); + QDeclarativeWebView *createWindow(QWebPage::WebWindowType type); + +private: + void init(); + virtual void componentComplete(); + Q_DISABLE_COPY(QDeclarativeWebView) + Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeWebView) + QMouseEvent *sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *); + QMouseEvent *sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *); + friend class QDeclarativeWebPage; +}; + +class QDeclarativeWebViewAttached : public QObject +{ + Q_OBJECT + Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName) +public: + QDeclarativeWebViewAttached(QObject *parent) + : QObject(parent) + { + } + + QString windowObjectName() const + { + return m_windowObjectName; + } + + void setWindowObjectName(const QString &n) + { + m_windowObjectName = n; + } + +private: + QString m_windowObjectName; +}; + + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QDeclarativeWebView) +QML_DECLARE_TYPEINFO(QDeclarativeWebView, QML_HAS_ATTACHED_PROPERTIES) + +QT_END_HEADER + +#endif diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h new file mode 100644 index 0000000..258b472 --- /dev/null +++ b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h @@ -0,0 +1,151 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef QDECLARATIVEWEBVIEW_P_H +#define QDECLARATIVEWEBVIEW_P_H + +#include + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +class QDeclarativeWebSettings : public QObject { + Q_OBJECT + + Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily) + Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily) + Q_PROPERTY(QString serifFontFamily READ serifFontFamily WRITE setSerifFontFamily) + Q_PROPERTY(QString sansSerifFontFamily READ sansSerifFontFamily WRITE setSansSerifFontFamily) + Q_PROPERTY(QString cursiveFontFamily READ cursiveFontFamily WRITE setCursiveFontFamily) + Q_PROPERTY(QString fantasyFontFamily READ fantasyFontFamily WRITE setFantasyFontFamily) + + Q_PROPERTY(int minimumFontSize READ minimumFontSize WRITE setMinimumFontSize) + Q_PROPERTY(int minimumLogicalFontSize READ minimumLogicalFontSize WRITE setMinimumLogicalFontSize) + Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize) + Q_PROPERTY(int defaultFixedFontSize READ defaultFixedFontSize WRITE setDefaultFixedFontSize) + + Q_PROPERTY(bool autoLoadImages READ autoLoadImages WRITE setAutoLoadImages) + Q_PROPERTY(bool javascriptEnabled READ javascriptEnabled WRITE setJavascriptEnabled) + Q_PROPERTY(bool javaEnabled READ javaEnabled WRITE setJavaEnabled) + Q_PROPERTY(bool pluginsEnabled READ pluginsEnabled WRITE setPluginsEnabled) + Q_PROPERTY(bool privateBrowsingEnabled READ privateBrowsingEnabled WRITE setPrivateBrowsingEnabled) + Q_PROPERTY(bool javascriptCanOpenWindows READ javascriptCanOpenWindows WRITE setJavascriptCanOpenWindows) + Q_PROPERTY(bool javascriptCanAccessClipboard READ javascriptCanAccessClipboard WRITE setJavascriptCanAccessClipboard) + Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled) + Q_PROPERTY(bool linksIncludedInFocusChain READ linksIncludedInFocusChain WRITE setLinksIncludedInFocusChain) + Q_PROPERTY(bool zoomTextOnly READ zoomTextOnly WRITE setZoomTextOnly) + Q_PROPERTY(bool printElementBackgrounds READ printElementBackgrounds WRITE setPrintElementBackgrounds) + Q_PROPERTY(bool offlineStorageDatabaseEnabled READ offlineStorageDatabaseEnabled WRITE setOfflineStorageDatabaseEnabled) + Q_PROPERTY(bool offlineWebApplicationCacheEnabled READ offlineWebApplicationCacheEnabled WRITE setOfflineWebApplicationCacheEnabled) + Q_PROPERTY(bool localStorageDatabaseEnabled READ localStorageDatabaseEnabled WRITE setLocalStorageDatabaseEnabled) + Q_PROPERTY(bool localContentCanAccessRemoteUrls READ localContentCanAccessRemoteUrls WRITE setLocalContentCanAccessRemoteUrls) + +public: + QDeclarativeWebSettings() {} + + QString standardFontFamily() const { return s->fontFamily(QWebSettings::StandardFont); } + void setStandardFontFamily(const QString& f) { s->setFontFamily(QWebSettings::StandardFont,f); } + QString fixedFontFamily() const { return s->fontFamily(QWebSettings::FixedFont); } + void setFixedFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FixedFont,f); } + QString serifFontFamily() const { return s->fontFamily(QWebSettings::SerifFont); } + void setSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SerifFont,f); } + QString sansSerifFontFamily() const { return s->fontFamily(QWebSettings::SansSerifFont); } + void setSansSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SansSerifFont,f); } + QString cursiveFontFamily() const { return s->fontFamily(QWebSettings::CursiveFont); } + void setCursiveFontFamily(const QString& f) { s->setFontFamily(QWebSettings::CursiveFont,f); } + QString fantasyFontFamily() const { return s->fontFamily(QWebSettings::FantasyFont); } + void setFantasyFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FantasyFont,f); } + + int minimumFontSize() const { return s->fontSize(QWebSettings::MinimumFontSize); } + void setMinimumFontSize(int size) { s->setFontSize(QWebSettings::MinimumFontSize,size); } + int minimumLogicalFontSize() const { return s->fontSize(QWebSettings::MinimumLogicalFontSize); } + void setMinimumLogicalFontSize(int size) { s->setFontSize(QWebSettings::MinimumLogicalFontSize,size); } + int defaultFontSize() const { return s->fontSize(QWebSettings::DefaultFontSize); } + void setDefaultFontSize(int size) { s->setFontSize(QWebSettings::DefaultFontSize,size); } + int defaultFixedFontSize() const { return s->fontSize(QWebSettings::DefaultFixedFontSize); } + void setDefaultFixedFontSize(int size) { s->setFontSize(QWebSettings::DefaultFixedFontSize,size); } + + bool autoLoadImages() const { return s->testAttribute(QWebSettings::AutoLoadImages); } + void setAutoLoadImages(bool on) { s->setAttribute(QWebSettings::AutoLoadImages, on); } + bool javascriptEnabled() const { return s->testAttribute(QWebSettings::JavascriptEnabled); } + void setJavascriptEnabled(bool on) { s->setAttribute(QWebSettings::JavascriptEnabled, on); } + bool javaEnabled() const { return s->testAttribute(QWebSettings::JavaEnabled); } + void setJavaEnabled(bool on) { s->setAttribute(QWebSettings::JavaEnabled, on); } + bool pluginsEnabled() const { return s->testAttribute(QWebSettings::PluginsEnabled); } + void setPluginsEnabled(bool on) { s->setAttribute(QWebSettings::PluginsEnabled, on); } + bool privateBrowsingEnabled() const { return s->testAttribute(QWebSettings::PrivateBrowsingEnabled); } + void setPrivateBrowsingEnabled(bool on) { s->setAttribute(QWebSettings::PrivateBrowsingEnabled, on); } + bool javascriptCanOpenWindows() const { return s->testAttribute(QWebSettings::JavascriptCanOpenWindows); } + void setJavascriptCanOpenWindows(bool on) { s->setAttribute(QWebSettings::JavascriptCanOpenWindows, on); } + bool javascriptCanAccessClipboard() const { return s->testAttribute(QWebSettings::JavascriptCanAccessClipboard); } + void setJavascriptCanAccessClipboard(bool on) { s->setAttribute(QWebSettings::JavascriptCanAccessClipboard, on); } + bool developerExtrasEnabled() const { return s->testAttribute(QWebSettings::DeveloperExtrasEnabled); } + void setDeveloperExtrasEnabled(bool on) { s->setAttribute(QWebSettings::DeveloperExtrasEnabled, on); } + bool linksIncludedInFocusChain() const { return s->testAttribute(QWebSettings::LinksIncludedInFocusChain); } + void setLinksIncludedInFocusChain(bool on) { s->setAttribute(QWebSettings::LinksIncludedInFocusChain, on); } + bool zoomTextOnly() const { return s->testAttribute(QWebSettings::ZoomTextOnly); } + void setZoomTextOnly(bool on) { s->setAttribute(QWebSettings::ZoomTextOnly, on); } + bool printElementBackgrounds() const { return s->testAttribute(QWebSettings::PrintElementBackgrounds); } + void setPrintElementBackgrounds(bool on) { s->setAttribute(QWebSettings::PrintElementBackgrounds, on); } + bool offlineStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled); } + void setOfflineStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, on); } + bool offlineWebApplicationCacheEnabled() const { return s->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled); } + void setOfflineWebApplicationCacheEnabled(bool on) { s->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, on); } + bool localStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::LocalStorageDatabaseEnabled); } + void setLocalStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, on); } + bool localContentCanAccessRemoteUrls() const { return s->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls); } + void setLocalContentCanAccessRemoteUrls(bool on) { s->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, on); } + + QWebSettings *s; +}; + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QDeclarativeWebSettings) + +QT_END_HEADER + +#endif diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro b/src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro new file mode 100644 index 0000000..37fe37c --- /dev/null +++ b/src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro @@ -0,0 +1,18 @@ +TARGET = webkitqmlplugin +include(../../qpluginbase.pri) + +contains(QT_CONFIG, webkit) { + QT += webkit declarative + + SOURCES += qdeclarativewebview.cpp plugin.cpp + HEADERS += qdeclarativewebview_p.h + HEADERS += qdeclarativewebview_p_p.h + + QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/org/webkit + target.path = $$[QT_INSTALL_IMPORTS]/org/webkit + + qmldir.files += $$QT_BUILD_TREE/imports/org/webkit/qmldir + qmldir.path += $$[QT_INSTALL_IMPORTS]/org/webkit + + INSTALLS += target qmldir +} diff --git a/tests/auto/declarative/qdeclarativewebview/data/basic.qml b/tests/auto/declarative/qdeclarativewebview/data/basic.qml index 5394837..f0b41ef 100644 --- a/tests/auto/declarative/qdeclarativewebview/data/basic.qml +++ b/tests/auto/declarative/qdeclarativewebview/data/basic.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { url: "basic.html" diff --git a/tests/auto/declarative/qdeclarativewebview/data/elements.qml b/tests/auto/declarative/qdeclarativewebview/data/elements.qml index 7c030e6..16e5788 100644 --- a/tests/auto/declarative/qdeclarativewebview/data/elements.qml +++ b/tests/auto/declarative/qdeclarativewebview/data/elements.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { url: "elements.html" diff --git a/tests/auto/declarative/qdeclarativewebview/data/javaScript.qml b/tests/auto/declarative/qdeclarativewebview/data/javaScript.qml index 07eee88..0e92e0e 100644 --- a/tests/auto/declarative/qdeclarativewebview/data/javaScript.qml +++ b/tests/auto/declarative/qdeclarativewebview/data/javaScript.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { url: "javaScript.html" diff --git a/tests/auto/declarative/qdeclarativewebview/data/loadError.qml b/tests/auto/declarative/qdeclarativewebview/data/loadError.qml index 1460f30..f827238 100644 --- a/tests/auto/declarative/qdeclarativewebview/data/loadError.qml +++ b/tests/auto/declarative/qdeclarativewebview/data/loadError.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { url: "does-not-exist.html" diff --git a/tests/auto/declarative/qdeclarativewebview/data/newwindows.qml b/tests/auto/declarative/qdeclarativewebview/data/newwindows.qml index 0bc8263..4d9df43 100644 --- a/tests/auto/declarative/qdeclarativewebview/data/newwindows.qml +++ b/tests/auto/declarative/qdeclarativewebview/data/newwindows.qml @@ -1,6 +1,7 @@ // Demonstrates opening new WebViews from HTML import Qt 4.6 +import org.webkit 1.0 Grid { columns: 3 diff --git a/tests/auto/declarative/qdeclarativewebview/data/propertychanges.qml b/tests/auto/declarative/qdeclarativewebview/data/propertychanges.qml index 3dd4e51..0770acf 100644 --- a/tests/auto/declarative/qdeclarativewebview/data/propertychanges.qml +++ b/tests/auto/declarative/qdeclarativewebview/data/propertychanges.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Item { width: 240 @@ -30,4 +31,4 @@ Item { pressGrabTime: 200 } } -} \ No newline at end of file +} diff --git a/tests/auto/declarative/qdeclarativewebview/data/sethtml.qml b/tests/auto/declarative/qdeclarativewebview/data/sethtml.qml index 063b5a8..9e17597 100644 --- a/tests/auto/declarative/qdeclarativewebview/data/sethtml.qml +++ b/tests/auto/declarative/qdeclarativewebview/data/sethtml.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { html: "

This is a string set on the WebView" diff --git a/tests/auto/declarative/qdeclarativewebview/qdeclarativewebview.pro b/tests/auto/declarative/qdeclarativewebview/qdeclarativewebview.pro index 6af0a60..20173c6 100644 --- a/tests/auto/declarative/qdeclarativewebview/qdeclarativewebview.pro +++ b/tests/auto/declarative/qdeclarativewebview/qdeclarativewebview.pro @@ -3,8 +3,7 @@ contains(QT_CONFIG,declarative): QT += declarative contains(QT_CONFIG,webkit): QT += webkit macx:CONFIG -= app_bundle -SOURCES += tst_qdeclarativewebview.cpp testtypes.cpp -HEADERS += testtypes.h +SOURCES += tst_qdeclarativewebview.cpp # Define SRCDIR equal to test's source directory DEFINES += SRCDIR=\\\"$$PWD\\\" diff --git a/tests/auto/declarative/qdeclarativewebview/testtypes.cpp b/tests/auto/declarative/qdeclarativewebview/testtypes.cpp deleted file mode 100644 index 7efc214..0000000 --- a/tests/auto/declarative/qdeclarativewebview/testtypes.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** 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 "testtypes.h" - -void MyWebView::drawContents(QPainter *p, const QRect &r) -{ - pp += r.width()*r.height(); - QDeclarativeWebView::drawContents(p,r); -} - -void registerTypes() -{ - QML_REGISTER_TYPE(Test,1,0,MyWebView,MyWebView); -} diff --git a/tests/auto/declarative/qdeclarativewebview/testtypes.h b/tests/auto/declarative/qdeclarativewebview/testtypes.h deleted file mode 100644 index 8eb703f..0000000 --- a/tests/auto/declarative/qdeclarativewebview/testtypes.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** 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$ -** -****************************************************************************/ -#ifndef TESTTYPES_H -#define TESTTYPES_H - -#include - -class MyWebView : public QDeclarativeWebView -{ - Q_OBJECT - Q_PROPERTY(int pixelsPainted READ pixelsPainted); - -public: - MyWebView() : pp(0) {} - - int pixelsPainted() const { return pp; } - - void drawContents(QPainter *p, const QRect &r); - -private: - int pp; -}; - -QML_DECLARE_TYPE(MyWebView); - -void registerTypes(); - -#endif // TESTTYPES_H diff --git a/tests/auto/declarative/qdeclarativewebview/tst_qdeclarativewebview.cpp b/tests/auto/declarative/qdeclarativewebview/tst_qdeclarativewebview.cpp index 6d16056..1d6bedc 100644 --- a/tests/auto/declarative/qdeclarativewebview/tst_qdeclarativewebview.cpp +++ b/tests/auto/declarative/qdeclarativewebview/tst_qdeclarativewebview.cpp @@ -43,15 +43,12 @@ #include "../../../shared/util.h" #include #include -#include -#include #include #include #include #include #include #include -#include "testtypes.h" class tst_qdeclarativewebview : public QObject { @@ -70,7 +67,7 @@ private slots: void setHtml(); void javaScript(); void cleanupTestCase(); - void pixelCache(); + //void pixelCache(); void newWindowParent(); void newWindowComponent(); void renderingEnabled(); @@ -89,7 +86,6 @@ private: void tst_qdeclarativewebview::initTestCase() { - registerTypes(); } static QString strippedHtml(QString html) @@ -148,81 +144,81 @@ void tst_qdeclarativewebview::basicProperties() checkNoErrors(component); QWebSettings::enablePersistentStorage(tmpDir()); - QDeclarativeWebView *wv = qobject_cast(component.create()); + QObject *wv = component.create(); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.0); - QCOMPARE(wv->title(),QString("Basic")); - QTRY_COMPARE(wv->icon().width(), 48); - QCOMPARE(wv->icon(),QPixmap(SRCDIR "/data/basic.png")); - QCOMPARE(wv->statusText(),QString("status here")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html())); - QCOMPARE(wv->width(), 123.0); - QCOMPARE(wv->preferredWidth(), 0); - QCOMPARE(wv->preferredHeight(), 0); - QCOMPARE(wv->zoomFactor(), 1.0); - QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); - QCOMPARE(wv->status(), QDeclarativeWebView::Ready); - QVERIFY(wv->reloadAction()); - QVERIFY(wv->reloadAction()->isEnabled()); - QVERIFY(wv->backAction()); - QVERIFY(!wv->backAction()->isEnabled()); - QVERIFY(wv->forwardAction()); - QVERIFY(!wv->forwardAction()->isEnabled()); - QVERIFY(wv->stopAction()); - QVERIFY(!wv->stopAction()->isEnabled()); - - wv->setPixelCacheSize(0); // mainly testing that it doesn't crash or anything! - QCOMPARE(wv->pixelCacheSize(),0); - wv->reloadAction()->trigger(); - QTRY_COMPARE(wv->progress(), 1.0); + QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); + QCOMPARE(wv->property("title").toString(),QString("Basic")); + QTRY_COMPARE(qvariant_cast(wv->property("icon")).width(), 48); + QCOMPARE(qvariant_cast(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("width").toDouble(), 123.0); + QCOMPARE(wv->property("preferredWidth").toInt(), 0); + QCOMPARE(wv->property("preferredHeight").toInt(), 0); + QCOMPARE(wv->property("zoomFactor").toDouble(), 1.0); + QCOMPARE(wv->property("url").toUrl(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); + QCOMPARE(wv->property("status").toInt(), 1 /*QDeclarativeWebView::Ready*/); + QVERIFY(qvariant_cast(wv->property("reload"))); + QVERIFY(qvariant_cast(wv->property("reload"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("back"))); + QVERIFY(!qvariant_cast(wv->property("back"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("forward"))); + QVERIFY(!qvariant_cast(wv->property("forward"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("stop"))); + QVERIFY(!qvariant_cast(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(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); - QDeclarativeWebView *wv = qobject_cast(component.create()); + QObject *wv = component.create(); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.0); + QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QDeclarativeWebSettings *s = wv->settingsObject(); + QObject *s = qvariant_cast(wv->property("settings")); // merely tests that setting gets stored (in QWebSettings) // behavioural tests are in WebKit. for (int b=0; b<=1; ++b) { bool on = !!b; - s->setAutoLoadImages(on); - s->setDeveloperExtrasEnabled(on); - s->setJavaEnabled(on); - s->setJavascriptCanAccessClipboard(on); - s->setJavascriptCanOpenWindows(on); - s->setJavascriptEnabled(on); - s->setLinksIncludedInFocusChain(on); - s->setLocalContentCanAccessRemoteUrls(on); - s->setLocalStorageDatabaseEnabled(on); - s->setOfflineStorageDatabaseEnabled(on); - s->setOfflineWebApplicationCacheEnabled(on); - s->setPluginsEnabled(on); - s->setPrintElementBackgrounds(on); - s->setPrivateBrowsingEnabled(on); - s->setZoomTextOnly(on); - - QVERIFY(s->autoLoadImages() == on); - QVERIFY(s->developerExtrasEnabled() == on); - QVERIFY(s->javaEnabled() == on); - QVERIFY(s->javascriptCanAccessClipboard() == on); - QVERIFY(s->javascriptCanOpenWindows() == on); - QVERIFY(s->javascriptEnabled() == on); - QVERIFY(s->linksIncludedInFocusChain() == on); - QVERIFY(s->localContentCanAccessRemoteUrls() == on); - QVERIFY(s->localStorageDatabaseEnabled() == on); - QVERIFY(s->offlineStorageDatabaseEnabled() == on); - QVERIFY(s->offlineWebApplicationCacheEnabled() == on); - QVERIFY(s->pluginsEnabled() == on); - QVERIFY(s->printElementBackgrounds() == on); - QVERIFY(s->privateBrowsingEnabled() == on); - QVERIFY(s->zoomTextOnly() == on); + 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); @@ -248,65 +244,65 @@ void tst_qdeclarativewebview::historyNav() checkNoErrors(component); QWebSettings::enablePersistentStorage(tmpDir()); - QDeclarativeWebView *wv = qobject_cast(component.create()); + QObject *wv = component.create(); QVERIFY(wv != 0); for (int i=1; i<=2; ++i) { - QTRY_COMPARE(wv->progress(), 1.0); - QCOMPARE(wv->title(),QString("Basic")); - QTRY_COMPARE(wv->icon().width(), 48); - QCOMPARE(wv->icon(),QPixmap(SRCDIR "/data/basic.png")); - QCOMPARE(wv->statusText(),QString("status here")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html())); - QCOMPARE(wv->width(), 123.0); - QCOMPARE(wv->preferredWidth(), 0); - QCOMPARE(wv->zoomFactor(), 1.0); - QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); - QCOMPARE(wv->status(), QDeclarativeWebView::Ready); - QVERIFY(wv->reloadAction()); - QVERIFY(wv->reloadAction()->isEnabled()); - QVERIFY(wv->backAction()); - QVERIFY(!wv->backAction()->isEnabled()); - QVERIFY(wv->forwardAction()); - QVERIFY(!wv->forwardAction()->isEnabled()); - QVERIFY(wv->stopAction()); - QVERIFY(!wv->stopAction()->isEnabled()); - - wv->reloadAction()->trigger(); + QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); + QCOMPARE(wv->property("title").toString(),QString("Basic")); + QTRY_COMPARE(qvariant_cast(wv->property("icon")).width(), 48); + QCOMPARE(qvariant_cast(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("width").toDouble(), 123.0); + QCOMPARE(wv->property("preferredWidth").toDouble(), 0.0); + QCOMPARE(wv->property("zoomFactor").toDouble(), 1.0); + QCOMPARE(wv->property("url").toUrl(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); + QCOMPARE(wv->property("status").toInt(), 1 /*QDeclarativeWebView::Ready*/); + QVERIFY(qvariant_cast(wv->property("reload"))); + QVERIFY(qvariant_cast(wv->property("reload"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("back"))); + QVERIFY(!qvariant_cast(wv->property("back"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("forward"))); + QVERIFY(!qvariant_cast(wv->property("forward"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("stop"))); + QVERIFY(!qvariant_cast(wv->property("stop"))->isEnabled()); + + qvariant_cast(wv->property("reload"))->trigger(); } - wv->setUrl(QUrl::fromLocalFile(SRCDIR "/data/forward.html")); - QTRY_COMPARE(wv->progress(), 1.0); - QCOMPARE(wv->title(),QString("Forward")); - QTRY_COMPARE(wv->icon().width(), 32); - QCOMPARE(wv->icon(),QPixmap(SRCDIR "/data/forward.png")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/forward.html")), strippedHtml(wv->html())); - QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/forward.html")); - QCOMPARE(wv->status(), QDeclarativeWebView::Ready); - QCOMPARE(wv->statusText(),QString("")); - QVERIFY(wv->reloadAction()); - QVERIFY(wv->reloadAction()->isEnabled()); - QVERIFY(wv->backAction()); - QVERIFY(wv->backAction()->isEnabled()); - QVERIFY(wv->forwardAction()); - QVERIFY(!wv->forwardAction()->isEnabled()); - QVERIFY(wv->stopAction()); - QVERIFY(!wv->stopAction()->isEnabled()); - - wv->backAction()->trigger(); - - QTRY_COMPARE(wv->progress(), 1.0); - QCOMPARE(wv->title(),QString("Basic")); - QCOMPARE(strippedHtml(fileContents(SRCDIR "/data/basic.html")), strippedHtml(wv->html())); - QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/basic.html")); - QCOMPARE(wv->status(), QDeclarativeWebView::Ready); - QVERIFY(wv->reloadAction()); - QVERIFY(wv->reloadAction()->isEnabled()); - QVERIFY(wv->backAction()); - QVERIFY(!wv->backAction()->isEnabled()); - QVERIFY(wv->forwardAction()); - QVERIFY(wv->forwardAction()->isEnabled()); - QVERIFY(wv->stopAction()); - QVERIFY(!wv->stopAction()->isEnabled()); + 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(wv->property("icon")).width(), 32); + QCOMPARE(qvariant_cast(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(wv->property("reload"))); + QVERIFY(qvariant_cast(wv->property("reload"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("back"))); + QVERIFY(qvariant_cast(wv->property("back"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("forward"))); + QVERIFY(!qvariant_cast(wv->property("forward"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("stop"))); + QVERIFY(!qvariant_cast(wv->property("stop"))->isEnabled()); + + qvariant_cast(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(wv->property("reload"))); + QVERIFY(qvariant_cast(wv->property("reload"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("back"))); + QVERIFY(!qvariant_cast(wv->property("back"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("forward"))); + QVERIFY(qvariant_cast(wv->property("forward"))->isEnabled()); + QVERIFY(qvariant_cast(wv->property("stop"))); + QVERIFY(!qvariant_cast(wv->property("stop"))->isEnabled()); } void tst_qdeclarativewebview::multipleWindows() @@ -328,16 +324,16 @@ void tst_qdeclarativewebview::loadError() checkNoErrors(component); QWebSettings::enablePersistentStorage(tmpDir()); - QDeclarativeWebView *wv = qobject_cast(component.create()); + QObject *wv = component.create(); QVERIFY(wv != 0); for (int i=1; i<=2; ++i) { - QTRY_COMPARE(wv->progress(), 1.0); - QCOMPARE(wv->title(),QString("")); - QCOMPARE(wv->statusText(),QString("")); // HTML 'status bar' text, not error message - QCOMPARE(wv->url(), QUrl::fromLocalFile(SRCDIR "/data/does-not-exist.html")); // Unlike QWebPage, which loses url - QCOMPARE(wv->status(), QDeclarativeWebView::Error); + 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*/); - wv->reloadAction()->trigger(); + qvariant_cast(wv->property("reload"))->trigger(); } } @@ -345,12 +341,12 @@ void tst_qdeclarativewebview::setHtml() { QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/sethtml.qml")); checkNoErrors(component); - QDeclarativeWebView *wv = qobject_cast(component.create()); + QObject *wv = component.create(); QVERIFY(wv != 0); - QCOMPARE(wv->html(),QString("

This is a string set on the WebView

")); + QCOMPARE(wv->property("html").toString(),QString("

This is a string set on the WebView

")); QSignalSpy spy(wv, SIGNAL(htmlChanged())); - wv->setHtml(QString("Basic

text

")); + wv->setProperty("html", QString("Basic

text

")); QCOMPARE(spy.count(),1); } @@ -358,81 +354,91 @@ void tst_qdeclarativewebview::elementAreaAt() { QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/elements.qml")); checkNoErrors(component); - QDeclarativeWebView *wv = qobject_cast(component.create()); + QObject *wv = component.create(); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.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); - QDeclarativeWebView *wv = qobject_cast(component.create()); + QObject *wv = component.create(); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.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(component.create()); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.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->pixelsPainted(), expected); + QCOMPARE(wv->property("pixelsPainted"), expected); wv->paint(&p,0,0); - QCOMPARE(wv->pixelsPainted(), expected); // nothing new needed to be painted - wv->setPixelCacheSize(0); // clears the cache + 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->pixelsPainted(), expected*2); // everything needed to be painted + 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->setPixelCacheSize(expected); // won't clear the cache + wv->setProperty("pixelCacheSize", expected); // won't clear the cache wv->paint(&p,0,0); - QCOMPARE(wv->pixelsPainted(), expected*2); // still there - wv->setPixelCacheSize(expected-1); // too small - will clear the cache + 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->pixelsPainted(), expected*3); // repainted + 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(component.create()); - QDeclarativeWebView *wv = rootItem->findChild("webView"); + QObject *wv = rootItem->findChild("webView"); QVERIFY(rootItem != 0); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.0); + QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); QDeclarativeItem* oldWindowParent = rootItem->findChild("oldWindowParent"); - QCOMPARE(wv->newWindowParent(), oldWindowParent); + QCOMPARE(qvariant_cast(wv->property("newWindowParent")), oldWindowParent); QSignalSpy newWindowParentSpy(wv, SIGNAL(newWindowParentChanged())); QDeclarativeItem* newWindowParent = rootItem->findChild("newWindowParent"); - wv->setNewWindowParent(newWindowParent); + wv->setProperty("newWindowParent", QVariant::fromValue(newWindowParent)); + QVERIFY(newWindowParent); QVERIFY(oldWindowParent); QVERIFY(oldWindowParent->childItems().count() == 0); - QCOMPARE(wv->newWindowParent(), newWindowParent); + QCOMPARE(wv->property("newWindowParent"), QVariant::fromValue(newWindowParent)); QCOMPARE(newWindowParentSpy.count(),1); - wv->setNewWindowParent(newWindowParent); + wv->setProperty("newWindowParent", QVariant::fromValue(newWindowParent)); QCOMPARE(newWindowParentSpy.count(),1); - wv->setNewWindowParent(0); + wv->setProperty("newWindowParent", QVariant::fromValue((QDeclarativeItem*)0)); QCOMPARE(newWindowParentSpy.count(),2); } @@ -441,23 +447,23 @@ void tst_qdeclarativewebview::newWindowComponent() QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); checkNoErrors(component); QDeclarativeItem *rootItem = qobject_cast(component.create()); - QDeclarativeWebView *wv = rootItem->findChild("webView"); + QObject *wv = rootItem->findChild("webView"); QVERIFY(rootItem != 0); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.0); + QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); QDeclarativeComponent substituteComponent(&engine); substituteComponent.setData("import Qt 4.6; WebView { objectName: 'newWebView'; url: 'basic.html'; }", QUrl::fromLocalFile("")); QSignalSpy newWindowComponentSpy(wv, SIGNAL(newWindowComponentChanged())); - wv->setNewWindowComponent(&substituteComponent); - QCOMPARE(wv->newWindowComponent(), &substituteComponent); + wv->setProperty("newWindowComponent", QVariant::fromValue(&substituteComponent)); + QCOMPARE(wv->property("newWindowComponent"), QVariant::fromValue(&substituteComponent)); QCOMPARE(newWindowComponentSpy.count(),1); - wv->setNewWindowComponent(&substituteComponent); + wv->setProperty("newWindowComponent", QVariant::fromValue(&substituteComponent)); QCOMPARE(newWindowComponentSpy.count(),1); - wv->setNewWindowComponent(0); + wv->setProperty("newWindowComponent", QVariant::fromValue((QDeclarativeComponent*)0)); QCOMPARE(newWindowComponentSpy.count(),2); } @@ -466,22 +472,22 @@ void tst_qdeclarativewebview::renderingEnabled() QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); checkNoErrors(component); QDeclarativeItem *rootItem = qobject_cast(component.create()); - QDeclarativeWebView *wv = rootItem->findChild("webView"); + QObject *wv = rootItem->findChild("webView"); QVERIFY(rootItem != 0); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.0); + QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); - QVERIFY(wv->renderingEnabled()); + QVERIFY(wv->property("renderingEnabled").toBool()); QSignalSpy renderingEnabledSpy(wv, SIGNAL(renderingEnabledChanged())); - wv->setRenderingEnabled(false); - QVERIFY(!wv->renderingEnabled()); + wv->setProperty("renderingEnabled", false); + QVERIFY(!wv->property("renderingEnabled").toBool()); QCOMPARE(renderingEnabledSpy.count(),1); - wv->setRenderingEnabled(false); + wv->setProperty("renderingEnabled", false); QCOMPARE(renderingEnabledSpy.count(),1); - wv->setRenderingEnabled(true); + wv->setProperty("renderingEnabled", true); QCOMPARE(renderingEnabledSpy.count(),2); } @@ -490,21 +496,21 @@ void tst_qdeclarativewebview::pressGrabTime() QDeclarativeComponent component(&engine, QUrl::fromLocalFile(SRCDIR "/data/propertychanges.qml")); checkNoErrors(component); QDeclarativeItem *rootItem = qobject_cast(component.create()); - QDeclarativeWebView *wv = rootItem->findChild("webView"); + QObject *wv = rootItem->findChild("webView"); QVERIFY(rootItem != 0); QVERIFY(wv != 0); - QTRY_COMPARE(wv->progress(), 1.0); - QCOMPARE(wv->pressGrabTime(), 200); + QTRY_COMPARE(wv->property("progress").toDouble(), 1.0); + QCOMPARE(wv->property("pressGrabTime").toInt(), 200); QSignalSpy pressGrabTimeSpy(wv, SIGNAL(pressGrabTimeChanged())); - wv->setPressGrabTime(100); - QCOMPARE(wv->pressGrabTime(), 100); + wv->setProperty("pressGrabTime", 100); + QCOMPARE(wv->property("pressGrabTime").toInt(), 100); QCOMPARE(pressGrabTimeSpy.count(),1); - wv->setPressGrabTime(100); + wv->setProperty("pressGrabTime", 100); QCOMPARE(pressGrabTimeSpy.count(),1); - wv->setPressGrabTime(0); + wv->setProperty("pressGrabTime", 0); QCOMPARE(pressGrabTimeSpy.count(),2); } diff --git a/tests/auto/declarative/visual/qfxwebview/autosize/autosize.qml b/tests/auto/declarative/visual/qfxwebview/autosize/autosize.qml index 74c6844..3c00ee6 100644 --- a/tests/auto/declarative/visual/qfxwebview/autosize/autosize.qml +++ b/tests/auto/declarative/visual/qfxwebview/autosize/autosize.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 // The WebView size is determined by the width, height, // preferredWidth, and preferredHeight properties. diff --git a/tests/auto/declarative/visual/webview/embedding/nesting.qml b/tests/auto/declarative/visual/webview/embedding/nesting.qml index 0d76579..5e35306 100644 --- a/tests/auto/declarative/visual/webview/embedding/nesting.qml +++ b/tests/auto/declarative/visual/webview/embedding/nesting.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { width: 300 diff --git a/tests/auto/declarative/visual/webview/javascript/evaluateJavaScript.qml b/tests/auto/declarative/visual/webview/javascript/evaluateJavaScript.qml index 78d5cfc..6c01382 100644 --- a/tests/auto/declarative/visual/webview/javascript/evaluateJavaScript.qml +++ b/tests/auto/declarative/visual/webview/javascript/evaluateJavaScript.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Column { WebView { diff --git a/tests/auto/declarative/visual/webview/javascript/windowObjects.qml b/tests/auto/declarative/visual/webview/javascript/windowObjects.qml index a41de9a..8c52aff 100644 --- a/tests/auto/declarative/visual/webview/javascript/windowObjects.qml +++ b/tests/auto/declarative/visual/webview/javascript/windowObjects.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Column { WebView { diff --git a/tests/auto/declarative/visual/webview/settings/fontFamily.qml b/tests/auto/declarative/visual/webview/settings/fontFamily.qml index 2bb2a53..f547b0e 100644 --- a/tests/auto/declarative/visual/webview/settings/fontFamily.qml +++ b/tests/auto/declarative/visual/webview/settings/fontFamily.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { id: web diff --git a/tests/auto/declarative/visual/webview/settings/fontSize.qml b/tests/auto/declarative/visual/webview/settings/fontSize.qml index b970783..7eaa96b 100644 --- a/tests/auto/declarative/visual/webview/settings/fontSize.qml +++ b/tests/auto/declarative/visual/webview/settings/fontSize.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Grid { columns: 3 diff --git a/tests/auto/declarative/visual/webview/settings/noAutoLoadImages.qml b/tests/auto/declarative/visual/webview/settings/noAutoLoadImages.qml index 72e672d..67f1633 100644 --- a/tests/auto/declarative/visual/webview/settings/noAutoLoadImages.qml +++ b/tests/auto/declarative/visual/webview/settings/noAutoLoadImages.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Grid { columns: 2 diff --git a/tests/auto/declarative/visual/webview/settings/setFontFamily.qml b/tests/auto/declarative/visual/webview/settings/setFontFamily.qml index 26deed8..823469f 100644 --- a/tests/auto/declarative/visual/webview/settings/setFontFamily.qml +++ b/tests/auto/declarative/visual/webview/settings/setFontFamily.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { url: "test.html" diff --git a/tests/auto/declarative/visual/webview/zooming/pageWidth.qml b/tests/auto/declarative/visual/webview/zooming/pageWidth.qml index 86dd7d2..4a876dd 100644 --- a/tests/auto/declarative/visual/webview/zooming/pageWidth.qml +++ b/tests/auto/declarative/visual/webview/zooming/pageWidth.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { width: 200 diff --git a/tests/auto/declarative/visual/webview/zooming/renderControl.qml b/tests/auto/declarative/visual/webview/zooming/renderControl.qml index 0c8bb3b..49eb91b 100644 --- a/tests/auto/declarative/visual/webview/zooming/renderControl.qml +++ b/tests/auto/declarative/visual/webview/zooming/renderControl.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 Rectangle { width: 200 diff --git a/tests/auto/declarative/visual/webview/zooming/resolution.qml b/tests/auto/declarative/visual/webview/zooming/resolution.qml index a9d4e3a..8542768 100644 --- a/tests/auto/declarative/visual/webview/zooming/resolution.qml +++ b/tests/auto/declarative/visual/webview/zooming/resolution.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { width: 200 * zoomFactor diff --git a/tests/auto/declarative/visual/webview/zooming/zoomTextOnly.qml b/tests/auto/declarative/visual/webview/zooming/zoomTextOnly.qml index 4455b43..c2e9348 100644 --- a/tests/auto/declarative/visual/webview/zooming/zoomTextOnly.qml +++ b/tests/auto/declarative/visual/webview/zooming/zoomTextOnly.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 WebView { width: 200 diff --git a/tests/auto/declarative/visual/webview/zooming/zooming.qml b/tests/auto/declarative/visual/webview/zooming/zooming.qml index 0ea9131..9f0b865 100644 --- a/tests/auto/declarative/visual/webview/zooming/zooming.qml +++ b/tests/auto/declarative/visual/webview/zooming/zooming.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import org.webkit 1.0 // Note that zooming is better done using zoomFactor and careful // control of rendering to avoid excessive re-rendering during -- cgit v0.12 From fd7d730d04862095898773a781bb9a254d0aeb00 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Tue, 2 Mar 2010 15:56:53 +1000 Subject: doc --- src/declarative/QmlChanges.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/declarative/QmlChanges.txt b/src/declarative/QmlChanges.txt index 34e4834..c312abf 100644 --- a/src/declarative/QmlChanges.txt +++ b/src/declarative/QmlChanges.txt @@ -12,6 +12,7 @@ Connection: syntax and rename: Connection { sender: a; signal: bar(); script: yyy } becomes: Connections { target: a; onFoo: xxx; onBar: yyy } +Using WebView now requires "import org.webkit 1.0" QmlView ------- -- cgit v0.12 From 1e4258c6098a87342b61935f1ad25102ce699af1 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Tue, 2 Mar 2010 16:27:06 +1000 Subject: Fix zooming (broke with transformOrigin default change). Task-number: QTBUG-5845 --- demos/declarative/webbrowser/content/FlickableWebView.qml | 1 + 1 file changed, 1 insertion(+) diff --git a/demos/declarative/webbrowser/content/FlickableWebView.qml b/demos/declarative/webbrowser/content/FlickableWebView.qml index cf4c825..30a5d78 100644 --- a/demos/declarative/webbrowser/content/FlickableWebView.qml +++ b/demos/declarative/webbrowser/content/FlickableWebView.qml @@ -23,6 +23,7 @@ Flickable { WebView { id: webView pixelCacheSize: 4000000 + transformOrigin: Item.TopLeft Script { function fixUrl(url) -- cgit v0.12 From 56d32b57814cb35409bc9b0076ec753de488ae7f Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 16 Feb 2010 09:38:23 +0100 Subject: Move qegl_p.h -> qeglcontext_p.h and add a new qegl_p.h This puts the QEgl namespace in a single file which can be used by both qeglcontext and qeglproperties. Files which need QEglContext should now include qeglcontext_p.h. Reviewed-By: Aleksandar Sasha Babic --- src/gui/egl/egl.pri | 1 + src/gui/egl/qegl.cpp | 3 + src/gui/egl/qegl_p.h | 108 +++++++++++------------------ src/gui/egl/qegl_qws.cpp | 2 + src/gui/egl/qegl_symbian.cpp | 2 + src/gui/egl/qegl_wince.cpp | 2 + src/gui/egl/qegl_x11.cpp | 3 +- src/gui/egl/qeglcontext_p.h | 130 +++++++++++++++++++++++++++++++++++ src/gui/egl/qeglproperties.cpp | 3 +- src/gui/egl/qeglproperties_p.h | 42 +---------- src/opengl/qgl_egl_p.h | 3 +- src/opengl/qgl_wince.cpp | 3 +- src/opengl/qpixmapdata_x11gl_egl.cpp | 1 + src/opengl/qwindowsurface_gl.cpp | 2 +- src/openvg/qpaintengine_vg.cpp | 2 +- src/openvg/qvg_p.h | 2 +- src/openvg/qwindowsurface_vg.cpp | 2 +- src/openvg/qwindowsurface_vgegl_p.h | 2 +- 18 files changed, 196 insertions(+), 117 deletions(-) create mode 100644 src/gui/egl/qeglcontext_p.h diff --git a/src/gui/egl/egl.pri b/src/gui/egl/egl.pri index 669d311..b90b9b0 100644 --- a/src/gui/egl/egl.pri +++ b/src/gui/egl/egl.pri @@ -2,6 +2,7 @@ CONFIG += egl HEADERS += \ egl/qegl_p.h \ + egl/qeglcontext_p.h \ egl/qeglproperties_p.h SOURCES += \ diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index 0ed95ea..5052dfc 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -43,7 +43,10 @@ #include #include #include + #include "qegl_p.h" +#include "qeglcontext_p.h" + QT_BEGIN_NAMESPACE diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index 87ed818..eb83002 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -53,13 +53,34 @@ // We mean it. // -#include -#include +QT_BEGIN_INCLUDE_NAMESPACE -#include +#if defined(QT_GLES_EGL) +#include +#else +#include +#endif -QT_BEGIN_INCLUDE_NAMESPACE +#if defined(Q_WS_X11) +// If included , then the global namespace +// may have been polluted with X #define's. The following makes sure +// the X11 headers were included properly and then cleans things up. +#include +#include +#undef Bool +#undef Status +#undef None +#undef KeyPress +#undef KeyRelease +#undef FocusIn +#undef FocusOut +#undef Type +#undef FontChange +#undef CursorShape +#endif +// Internally we use the EGL-prefixed native types which are used in EGL >= 1.3. +// For older versions of EGL, we have to define these types ourselves here: #if !defined(EGL_VERSION_1_3) && !defined(QEGL_NATIVE_TYPES_DEFINED) #undef EGLNativeWindowType #undef EGLNativePixmapType @@ -69,74 +90,27 @@ typedef NativePixmapType EGLNativePixmapType; typedef NativeDisplayType EGLNativeDisplayType; #define QEGL_NATIVE_TYPES_DEFINED 1 #endif -QT_END_INCLUDE_NAMESPACE - -QT_BEGIN_NAMESPACE - -class Q_GUI_EXPORT QEglContext -{ -public: - QEglContext(); - ~QEglContext(); - - bool isValid() const; - bool isCurrent() const; - bool isSharing() const { return sharing; } - - QEgl::API api() const { return apiType; } - void setApi(QEgl::API api) { apiType = api; } - - bool chooseConfig(const QEglProperties& properties, QEgl::PixelFormatMatch match = QEgl::ExactPixelFormat); - bool createContext(QEglContext *shareContext = 0, const QEglProperties *properties = 0); - void destroyContext(); - EGLSurface createSurface(QPaintDevice *device, const QEglProperties *properties = 0); - void destroySurface(EGLSurface surface); - - bool makeCurrent(EGLSurface surface); - bool doneCurrent(); - bool lazyDoneCurrent(); - bool swapBuffers(EGLSurface surface); - void waitNative(); - void waitClient(); - - bool configAttrib(int name, EGLint *value) const; - - static void clearError() { eglGetError(); } - static EGLint error() { return eglGetError(); } - static QString errorString(EGLint code); - - static EGLDisplay display(); - - EGLContext context() const { return ctx; } - void setContext(EGLContext context) { ctx = context; ownsContext = false;} - - EGLConfig config() const { return cfg; } - void setConfig(EGLConfig config) { cfg = config; } - - QEglProperties configProperties(EGLConfig cfg = 0) const; - - void dumpAllConfigs(); - - static QString extensions(); - static bool hasExtension(const char* extensionName); +QT_END_INCLUDE_NAMESPACE -private: - QEgl::API apiType; - EGLContext ctx; - EGLConfig cfg; - EGLSurface currentSurface; - bool current; - bool ownsContext; - bool sharing; - static EGLDisplay dpy; - static EGLNativeDisplayType nativeDisplay(); +QT_BEGIN_NAMESPACE - static QEglContext *currentContext(QEgl::API api); - static void setCurrentContext(QEgl::API api, QEglContext *context); +namespace QEgl { + enum API + { + OpenGL, + OpenVG + }; + + enum PixelFormatMatch + { + ExactPixelFormat, + BestPixelFormat + }; }; + QT_END_NAMESPACE -#endif // QEGL_P_H +#endif //QEGL_P_H diff --git a/src/gui/egl/qegl_qws.cpp b/src/gui/egl/qegl_qws.cpp index 2a61beb..a40c236 100644 --- a/src/gui/egl/qegl_qws.cpp +++ b/src/gui/egl/qegl_qws.cpp @@ -42,7 +42,9 @@ #include #include #include + #include "qegl_p.h" +#include "qeglcontext_p.h" #if !defined(QT_NO_EGL) diff --git a/src/gui/egl/qegl_symbian.cpp b/src/gui/egl/qegl_symbian.cpp index 5a010cd..0c91fd8 100644 --- a/src/gui/egl/qegl_symbian.cpp +++ b/src/gui/egl/qegl_symbian.cpp @@ -42,7 +42,9 @@ #include #include #include + #include "qegl_p.h" +#include "qeglcontext_p.h" #include diff --git a/src/gui/egl/qegl_wince.cpp b/src/gui/egl/qegl_wince.cpp index c9c9773..00341ba 100644 --- a/src/gui/egl/qegl_wince.cpp +++ b/src/gui/egl/qegl_wince.cpp @@ -42,7 +42,9 @@ #include #include #include + #include "qegl_p.h" +#include "qeglcontext_p.h" #include diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index 634ff13..cd55849 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -49,8 +49,9 @@ #include #include #include -#include "qegl_p.h" +#include "qegl_p.h" +#include "qeglcontext_p.h" QT_BEGIN_NAMESPACE diff --git a/src/gui/egl/qeglcontext_p.h b/src/gui/egl/qeglcontext_p.h new file mode 100644 index 0000000..3857fb7 --- /dev/null +++ b/src/gui/egl/qeglcontext_p.h @@ -0,0 +1,130 @@ +/**************************************************************************** +** +** 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 QtGui module 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$ +** +****************************************************************************/ + +#ifndef QEGLCONTEXT_P_H +#define QEGLCONTEXT_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience of +// the QtOpenGL and QtOpenVG modules. This header file may change from +// version to version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +#include +#include + +QT_BEGIN_NAMESPACE + +class Q_GUI_EXPORT QEglContext +{ +public: + QEglContext(); + ~QEglContext(); + + bool isValid() const; + bool isCurrent() const; + bool isSharing() const { return sharing; } + + QEgl::API api() const { return apiType; } + void setApi(QEgl::API api) { apiType = api; } + + bool chooseConfig(const QEglProperties& properties, QEgl::PixelFormatMatch match = QEgl::ExactPixelFormat); + bool createContext(QEglContext *shareContext = 0, const QEglProperties *properties = 0); + void destroyContext(); + EGLSurface createSurface(QPaintDevice *device, const QEglProperties *properties = 0); + void destroySurface(EGLSurface surface); + + bool makeCurrent(EGLSurface surface); + bool doneCurrent(); + bool lazyDoneCurrent(); + bool swapBuffers(EGLSurface surface); + + void waitNative(); + void waitClient(); + + bool configAttrib(int name, EGLint *value) const; + + static void clearError() { eglGetError(); } + static EGLint error() { return eglGetError(); } + static QString errorString(EGLint code); + + static EGLDisplay display(); + + EGLContext context() const { return ctx; } + void setContext(EGLContext context) { ctx = context; ownsContext = false;} + + EGLConfig config() const { return cfg; } + void setConfig(EGLConfig config) { cfg = config; } + + QEglProperties configProperties(EGLConfig cfg = 0) const; + + void dumpAllConfigs(); + + static QString extensions(); + static bool hasExtension(const char* extensionName); + +private: + QEgl::API apiType; + EGLContext ctx; + EGLConfig cfg; + EGLSurface currentSurface; + bool current; + bool ownsContext; + bool sharing; + + static EGLDisplay dpy; + static EGLNativeDisplayType nativeDisplay(); + + static QEglContext *currentContext(QEgl::API api); + static void setCurrentContext(QEgl::API api, QEglContext *context); +}; + +QT_END_NAMESPACE + +#endif // QEGLCONTEXT_P_H diff --git a/src/gui/egl/qeglproperties.cpp b/src/gui/egl/qeglproperties.cpp index 236ec37..b83ae4e 100644 --- a/src/gui/egl/qeglproperties.cpp +++ b/src/gui/egl/qeglproperties.cpp @@ -46,7 +46,8 @@ QT_BEGIN_NAMESPACE #include #include -#include "qegl_p.h" +#include "qeglproperties_p.h" +#include "qeglcontext_p.h" // Initialize a property block. diff --git a/src/gui/egl/qeglproperties_p.h b/src/gui/egl/qeglproperties_p.h index feed1d2..496847b 100644 --- a/src/gui/egl/qeglproperties_p.h +++ b/src/gui/egl/qeglproperties_p.h @@ -56,50 +56,10 @@ #include #include -QT_BEGIN_INCLUDE_NAMESPACE - -#if defined(QT_GLES_EGL) -#include -#else -#include -#endif - -#if defined(Q_WS_X11) -// If included , then the global namespace -// may have been polluted with X #define's. The following makes sure -// the X11 headers were included properly and then cleans things up. -#include -#include -#undef Bool -#undef Status -#undef None -#undef KeyPress -#undef KeyRelease -#undef FocusIn -#undef FocusOut -#undef Type -#undef FontChange -#undef CursorShape -#endif - -QT_END_INCLUDE_NAMESPACE +#include QT_BEGIN_NAMESPACE -namespace QEgl { - enum API - { - OpenGL, - OpenVG - }; - - enum PixelFormatMatch - { - ExactPixelFormat, - BestPixelFormat - }; -}; - class QX11Info; class QPaintDevice; diff --git a/src/opengl/qgl_egl_p.h b/src/opengl/qgl_egl_p.h index c503724..518b500 100644 --- a/src/opengl/qgl_egl_p.h +++ b/src/opengl/qgl_egl_p.h @@ -53,7 +53,8 @@ // We mean it. // -#include +#include +#include QT_BEGIN_NAMESPACE diff --git a/src/opengl/qgl_wince.cpp b/src/opengl/qgl_wince.cpp index f81115c..2b71201 100644 --- a/src/opengl/qgl_wince.cpp +++ b/src/opengl/qgl_wince.cpp @@ -54,7 +54,8 @@ #include -#include +#include +#include #include #include diff --git a/src/opengl/qpixmapdata_x11gl_egl.cpp b/src/opengl/qpixmapdata_x11gl_egl.cpp index 6a1d030..4f1543c 100644 --- a/src/opengl/qpixmapdata_x11gl_egl.cpp +++ b/src/opengl/qpixmapdata_x11gl_egl.cpp @@ -44,6 +44,7 @@ #include #include #include +#include #if !defined(QT_OPENGL_ES_1) #include diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 4ac4a3a..0334cbc 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -83,7 +83,7 @@ #endif #ifdef QT_OPENGL_ES -#include +#include #endif QT_BEGIN_NAMESPACE diff --git a/src/openvg/qpaintengine_vg.cpp b/src/openvg/qpaintengine_vg.cpp index 35f552e..47ce11c 100644 --- a/src/openvg/qpaintengine_vg.cpp +++ b/src/openvg/qpaintengine_vg.cpp @@ -45,7 +45,7 @@ #include "qvgcompositionhelper_p.h" #include "qvgimagepool_p.h" #if !defined(QT_NO_EGL) -#include +#include #include "qwindowsurface_vgegl_p.h" #endif #include diff --git a/src/openvg/qvg_p.h b/src/openvg/qvg_p.h index 7857bb6..51abbee 100644 --- a/src/openvg/qvg_p.h +++ b/src/openvg/qvg_p.h @@ -58,7 +58,7 @@ #include #if !defined(QT_NO_EGL) -#include +#include #endif QT_BEGIN_NAMESPACE diff --git a/src/openvg/qwindowsurface_vg.cpp b/src/openvg/qwindowsurface_vg.cpp index 83b0764..07d9209 100644 --- a/src/openvg/qwindowsurface_vg.cpp +++ b/src/openvg/qwindowsurface_vg.cpp @@ -47,7 +47,7 @@ #if !defined(QT_NO_EGL) -#include +#include #include QT_BEGIN_NAMESPACE diff --git a/src/openvg/qwindowsurface_vgegl_p.h b/src/openvg/qwindowsurface_vgegl_p.h index aa0c648..f6adbf3 100644 --- a/src/openvg/qwindowsurface_vgegl_p.h +++ b/src/openvg/qwindowsurface_vgegl_p.h @@ -58,7 +58,7 @@ #if !defined(QT_NO_EGL) -#include +#include QT_BEGIN_NAMESPACE -- cgit v0.12 From 28b85c76dd0ba4796ec519b890f6fab0fc813061 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 16 Feb 2010 13:29:36 +0100 Subject: Move static methods from QEglContext to QEgl namespace Reviewed-By: Aleksandar Sasha Babic --- src/gui/egl/qegl.cpp | 83 +++++++++++++++++++----------------- src/gui/egl/qegl_p.h | 18 ++++++++ src/gui/egl/qegl_wince.cpp | 6 +-- src/gui/egl/qegl_x11.cpp | 8 ++-- src/gui/egl/qeglcontext_p.h | 18 ++------ src/gui/egl/qeglproperties.cpp | 6 +-- src/opengl/qgl_egl.cpp | 2 +- src/opengl/qgl_x11egl.cpp | 20 ++++----- src/opengl/qglpixelbuffer_egl.cpp | 4 +- src/opengl/qpixmapdata_x11gl_egl.cpp | 20 ++++----- 10 files changed, 97 insertions(+), 88 deletions(-) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index 5052dfc..ef5eb67 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -57,8 +57,6 @@ QT_BEGIN_NAMESPACE static QEglContext * volatile currentGLContext = 0; static QEglContext * volatile currentVGContext = 0; -EGLDisplay QEglContext::dpy = EGL_NO_DISPLAY; - QEglContext::QEglContext() : apiType(QEgl::OpenGL) , ctx(EGL_NO_CONTEXT) @@ -98,7 +96,8 @@ bool QEglContext::chooseConfig do { // Get the number of matching configurations for this set of properties. EGLint matching = 0; - if (!eglChooseConfig(display(), props.properties(), 0, 0, &matching) || !matching) + EGLDisplay dpy = QEgl::display(); + if (!eglChooseConfig(dpy, props.properties(), 0, 0, &matching) || !matching) continue; // If we want the best pixel format, then return the first @@ -145,7 +144,7 @@ bool QEglContext::chooseConfig qWarning() << "QEglContext::chooseConfig(): Could not find a suitable EGL configuration"; qWarning() << "Requested:" << props.toString(); qWarning() << "Available:"; - dumpAllConfigs(); + QEgl::dumpAllConfigs(); } return false; } @@ -175,9 +174,9 @@ bool QEglContext::createContext(QEglContext *shareContext, const QEglProperties if (shareContext && shareContext->ctx == EGL_NO_CONTEXT) shareContext = 0; if (shareContext) { - ctx = eglCreateContext(display(), cfg, shareContext->ctx, contextProps.properties()); + ctx = eglCreateContext(QEgl::display(), cfg, shareContext->ctx, contextProps.properties()); if (ctx == EGL_NO_CONTEXT) { - qWarning() << "QEglContext::createContext(): Could not share context:" << errorString(eglGetError()); + qWarning() << "QEglContext::createContext(): Could not share context:" << QEgl::errorString(); shareContext = 0; } else { sharing = true; @@ -186,7 +185,7 @@ bool QEglContext::createContext(QEglContext *shareContext, const QEglProperties if (ctx == EGL_NO_CONTEXT) { ctx = eglCreateContext(display(), cfg, 0, contextProps.properties()); if (ctx == EGL_NO_CONTEXT) { - qWarning() << "QEglContext::createContext(): Unable to create EGL context:" << errorString(eglGetError()); + qWarning() << "QEglContext::createContext(): Unable to create EGL context:" << QEgl::errorString(); return false; } } @@ -243,9 +242,9 @@ bool QEglContext::makeCurrent(EGLSurface surface) eglBindAPI(EGL_OPENVG_API); #endif - bool ok = eglMakeCurrent(display(), surface, surface, ctx); + bool ok = eglMakeCurrent(QEgl::display(), surface, surface, ctx); if (!ok) - qWarning() << "QEglContext::makeCurrent():" << errorString(eglGetError()); + qWarning() << "QEglContext::makeCurrent():" << QEgl::errorString(); return ok; } @@ -272,9 +271,9 @@ bool QEglContext::doneCurrent() eglBindAPI(EGL_OPENVG_API); #endif - bool ok = eglMakeCurrent(display(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + bool ok = eglMakeCurrent(QEgl::display(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (!ok) - qWarning() << "QEglContext::doneCurrent():" << errorString(eglGetError()); + qWarning() << "QEglContext::doneCurrent():" << QEgl::errorString(); return ok; } @@ -294,9 +293,9 @@ bool QEglContext::swapBuffers(EGLSurface surface) if(ctx == EGL_NO_CONTEXT) return false; - bool ok = eglSwapBuffers(display(), surface); + bool ok = eglSwapBuffers(QEgl::display(), surface); if (!ok) - qWarning() << "QEglContext::swapBuffers():" << errorString(eglGetError()); + qWarning() << "QEglContext::swapBuffers():" << QEgl::errorString(); return ok; } @@ -333,43 +332,33 @@ void QEglContext::waitClient() // Query the value of a configuration attribute. bool QEglContext::configAttrib(int name, EGLint *value) const { - return eglGetConfigAttrib(display(), cfg, name, value); + return eglGetConfigAttrib(QEgl::display(), cfg, name, value); } -// Retrieve all of the properties on "cfg". If zero, return -// the context's configuration. -QEglProperties QEglContext::configProperties(EGLConfig cfg) const +QEglProperties QEglContext::configProperties() const { - if (!cfg) - cfg = config(); - QEglProperties props; - for (int name = 0x3020; name <= 0x304F; ++name) { - EGLint value; - if (name != EGL_NONE && eglGetConfigAttrib(display(), cfg, name, &value)) - props.setValue(name, value); - } - eglGetError(); // Clear the error state. - return props; + return QEglProperties(config()); } -EGLDisplay QEglContext::display() +EGLDisplay QEgl::display() { + static EGLDisplay dpy = EGL_NO_DISPLAY; static bool openedDisplay = false; if (!openedDisplay) { dpy = eglGetDisplay(nativeDisplay()); openedDisplay = true; if (dpy == EGL_NO_DISPLAY) { - qWarning("QEglContext::display(): Falling back to EGL_DEFAULT_DISPLAY"); + qWarning("QEgl::display(): Falling back to EGL_DEFAULT_DISPLAY"); dpy = eglGetDisplay(EGLNativeDisplayType(EGL_DEFAULT_DISPLAY)); } if (dpy == EGL_NO_DISPLAY) { - qWarning("QEglContext::display(): Can't even open the default display"); + qWarning("QEgl::display(): Can't even open the default display"); return EGL_NO_DISPLAY; } if (!eglInitialize(dpy, NULL, NULL)) { - qWarning() << "QEglContext::display(): Cannot initialize EGL display:" << errorString(eglGetError()); + qWarning() << "QEgl::display(): Cannot initialize EGL display:" << QEgl::errorString(); return EGL_NO_DISPLAY; } } @@ -378,14 +367,14 @@ EGLDisplay QEglContext::display() } #if !defined(Q_WS_X11) && !defined(Q_WS_WINCE) // WinCE & X11 implement this properly -EGLNativeDisplayType QEglContext::nativeDisplay() +EGLNativeDisplayType QEgl::nativeDisplay() { return EGL_DEFAULT_DISPLAY; } #endif // Return the error string associated with a specific code. -QString QEglContext::errorString(EGLint code) +QString QEgl::errorString(EGLint code) { static const char * const errors[] = { "Success (0x3000)", // No tr @@ -411,8 +400,24 @@ QString QEglContext::errorString(EGLint code) } } +QString QEgl::errorString() +{ + return errorString(error()); +} + +void QEgl::clearError() +{ + eglGetError(); +} + +EGLint QEgl::error() +{ + return eglGetError(); +} + + // Dump all of the EGL configurations supported by the system. -void QEglContext::dumpAllConfigs() +void QEgl::dumpAllConfigs() { QEglProperties props; EGLint count = 0; @@ -421,23 +426,23 @@ void QEglContext::dumpAllConfigs() EGLConfig *configs = new EGLConfig [count]; eglGetConfigs(display(), configs, count, &count); for (EGLint index = 0; index < count; ++index) { - props = configProperties(configs[index]); + props = QEglProperties(configs[index]); qWarning() << props.toString(); } delete [] configs; } -QString QEglContext::extensions() +QString QEgl::extensions() { - const char* exts = eglQueryString(QEglContext::display(), EGL_EXTENSIONS); + const char* exts = eglQueryString(QEgl::display(), EGL_EXTENSIONS); return QString(QLatin1String(exts)); } -bool QEglContext::hasExtension(const char* extensionName) +bool QEgl::hasExtension(const char* extensionName) { QList extensions = QByteArray(reinterpret_cast - (eglQueryString(QEglContext::display(), EGL_EXTENSIONS))).split(' '); + (eglQueryString(QEgl::display(), EGL_EXTENSIONS))).split(' '); return extensions.contains(extensionName); } diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index eb83002..e48e4a0 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -96,6 +96,8 @@ QT_END_INCLUDE_NAMESPACE QT_BEGIN_NAMESPACE +class QEglProperties; + namespace QEgl { enum API { @@ -108,6 +110,22 @@ namespace QEgl { ExactPixelFormat, BestPixelFormat }; + +// EGLConfig chooseConfig(const QEglProperties* properties, QEgl::PixelFormatMatch match = QEgl::ExactPixelFormat); +// EGLSurface createSurface(QPaintDevice *device, EGLConfig config, const QEglProperties *properties = 0); + + Q_GUI_EXPORT void dumpAllConfigs(); + + Q_GUI_EXPORT void clearError(); + Q_GUI_EXPORT EGLint error(); + Q_GUI_EXPORT QString errorString(EGLint code); + Q_GUI_EXPORT QString errorString(); + + Q_GUI_EXPORT QString extensions(); + Q_GUI_EXPORT bool hasExtension(const char* extensionName); + + Q_GUI_EXPORT EGLDisplay display(); + Q_GUI_EXPORT EGLNativeDisplayType nativeDisplay(); }; diff --git a/src/gui/egl/qegl_wince.cpp b/src/gui/egl/qegl_wince.cpp index 00341ba..2f79005 100644 --- a/src/gui/egl/qegl_wince.cpp +++ b/src/gui/egl/qegl_wince.cpp @@ -80,16 +80,16 @@ EGLSurface QEglContext::createSurface(QPaintDevice *device, const QEglProperties props = 0; EGLSurface surf; if (devType == QInternal::Widget) - surf = eglCreateWindowSurface(dpy, cfg, windowDrawable, props); + surf = eglCreateWindowSurface(QEgl::display(), cfg, windowDrawable, props); else - surf = eglCreatePixmapSurface(dpy, cfg, pixmapDrawable, props); + surf = eglCreatePixmapSurface(QEgl::display(), cfg, pixmapDrawable, props); if (surf == EGL_NO_SURFACE) { qWarning("QEglContext::createSurface(): Unable to create EGL surface, error = 0x%x", eglGetError()); } return surf; } -EGLNativeDisplayType QEglContext::nativeDisplay() +EGLNativeDisplayType QEgl::nativeDisplay() { HWND win = (static_cast(device))->winId(); HDC myDc = GetDC(win); diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index cd55849..4a813c6 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -84,17 +84,17 @@ EGLSurface QEglContext::createSurface(QPaintDevice *device, const QEglProperties props = 0; EGLSurface surf; if (devType == QInternal::Widget) - surf = eglCreateWindowSurface(dpy, cfg, windowDrawable, props); + surf = eglCreateWindowSurface(QEgl::display(), cfg, windowDrawable, props); else - surf = eglCreatePixmapSurface(dpy, cfg, pixmapDrawable, props); + surf = eglCreatePixmapSurface(QEgl::display(), cfg, pixmapDrawable, props); if (surf == EGL_NO_SURFACE) { qWarning() << "QEglContext::createSurface(): Unable to create EGL surface:" - << errorString(eglGetError()); + << QEgl::errorString(); } return surf; } -EGLNativeDisplayType QEglContext::nativeDisplay() +EGLNativeDisplayType QEgl::nativeDisplay() { Display *xdpy = QX11Info::display(); if (!xdpy) { diff --git a/src/gui/egl/qeglcontext_p.h b/src/gui/egl/qeglcontext_p.h index 3857fb7..c656d1d 100644 --- a/src/gui/egl/qeglcontext_p.h +++ b/src/gui/egl/qeglcontext_p.h @@ -90,24 +90,15 @@ public: bool configAttrib(int name, EGLint *value) const; - static void clearError() { eglGetError(); } - static EGLint error() { return eglGetError(); } - static QString errorString(EGLint code); - - static EGLDisplay display(); - EGLContext context() const { return ctx; } void setContext(EGLContext context) { ctx = context; ownsContext = false;} + EGLDisplay display() {return QEgl::display();} + EGLConfig config() const { return cfg; } void setConfig(EGLConfig config) { cfg = config; } - QEglProperties configProperties(EGLConfig cfg = 0) const; - - void dumpAllConfigs(); - - static QString extensions(); - static bool hasExtension(const char* extensionName); + QEglProperties configProperties() const; private: QEgl::API apiType; @@ -118,9 +109,6 @@ private: bool ownsContext; bool sharing; - static EGLDisplay dpy; - static EGLNativeDisplayType nativeDisplay(); - static QEglContext *currentContext(QEgl::API api); static void setCurrentContext(QEgl::API api, QEglContext *context); }; diff --git a/src/gui/egl/qeglproperties.cpp b/src/gui/egl/qeglproperties.cpp index b83ae4e..86e158b 100644 --- a/src/gui/egl/qeglproperties.cpp +++ b/src/gui/egl/qeglproperties.cpp @@ -61,7 +61,7 @@ QEglProperties::QEglProperties(EGLConfig cfg) props.append(EGL_NONE); for (int name = 0x3020; name <= 0x304F; ++name) { EGLint value; - if (name != EGL_NONE && eglGetConfigAttrib(QEglContext::display(), cfg, name, &value)) + if (name != EGL_NONE && eglGetConfigAttrib(QEgl::display(), cfg, name, &value)) setValue(name, value); } eglGetError(); // Clear the error state. @@ -274,12 +274,12 @@ static void addTag(QString& str, const QString& tag) void QEglProperties::dumpAllConfigs() { EGLint count = 0; - eglGetConfigs(QEglContext::display(), 0, 0, &count); + eglGetConfigs(QEgl::display(), 0, 0, &count); if (count < 1) return; EGLConfig *configs = new EGLConfig [count]; - eglGetConfigs(QEglContext::display(), configs, count, &count); + eglGetConfigs(QEgl::display(), configs, count, &count); for (EGLint index = 0; index < count; ++index) qWarning() << QEglProperties(configs[index]).toString(); delete [] configs; diff --git a/src/opengl/qgl_egl.cpp b/src/opengl/qgl_egl.cpp index 3addea1..90fb2bb 100644 --- a/src/opengl/qgl_egl.cpp +++ b/src/opengl/qgl_egl.cpp @@ -126,7 +126,7 @@ void qt_egl_update_format(const QEglContext& context, QGLFormat& format) // Clear the EGL error state because some of the above may // have errored out because the attribute is not applicable // to the surface type. Such errors don't matter. - context.clearError(); + QEgl::clearError(); } bool QGLFormat::hasOpenGL() diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 3d183ee..972a5f6 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -609,7 +609,7 @@ EGLConfig Q_OPENGL_EXPORT qt_chooseEGLConfigForPixmap(bool hasAlpha, bool readOn EGLint configCount = 0; do { - eglChooseConfig(QEglContext::display(), configAttribs.properties(), targetConfig, 1, &configCount); + eglChooseConfig(QEgl::display(), configAttribs.properties(), targetConfig, 1, &configCount); if (configCount > 0) { // Got one qDebug() << "Found an" << (hasAlpha ? "ARGB" : "RGB") << (readOnly ? "readonly" : "target" ) @@ -648,7 +648,7 @@ bool Q_OPENGL_EXPORT qt_createEGLSurfaceForPixmap(QPixmapData* pmd, bool readOnl pixmapAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGB); EGLSurface pixmapSurface; - pixmapSurface = eglCreatePixmapSurface(QEglContext::display(), + pixmapSurface = eglCreatePixmapSurface(QEgl::display(), pixmapConfig, (EGLNativePixmapType) pixmapData->handle(), pixmapAttribs.properties()); @@ -656,7 +656,7 @@ bool Q_OPENGL_EXPORT qt_createEGLSurfaceForPixmap(QPixmapData* pmd, bool readOnl // pixmapSurface, pixmapData->handle()); if (pixmapSurface == EGL_NO_SURFACE) { qWarning() << "Failed to create a pixmap surface using config" << (int)pixmapConfig - << ":" << QEglContext::errorString(eglGetError()); + << ":" << QEgl::errorString(); return false; } @@ -693,8 +693,8 @@ QGLTexture *QGLContextPrivate::bindTextureFromNativePixmap(QPixmapData* pd, cons if (!checkedForTFP) { // Check for texture_from_pixmap egl extension checkedForTFP = true; - if (eglContext->hasExtension("EGL_NOKIA_texture_from_pixmap") || - eglContext->hasExtension("EGL_EXT_texture_from_pixmap")) + if (QEgl::hasExtension("EGL_NOKIA_texture_from_pixmap") || + QEgl::hasExtension("EGL_EXT_texture_from_pixmap")) { qDebug("Found texture_from_pixmap EGL extension!"); haveTFP = true; @@ -734,7 +734,7 @@ QGLTexture *QGLContextPrivate::bindTextureFromNativePixmap(QPixmapData* pd, cons EGLBoolean success; success = eglBindTexImage(eglContext->display(), (EGLSurface)pixmapData->gl_surface, EGL_BACK_BUFFER); if (success == EGL_FALSE) { - qWarning() << "eglBindTexImage() failed:" << eglContext->errorString(eglGetError()); + qWarning() << "eglBindTexImage() failed:" << QEgl::errorString(); eglDestroySurface(eglContext->display(), (EGLSurface)pixmapData->gl_surface); pixmapData->gl_surface = (Qt::HANDLE)EGL_NO_SURFACE; haveTFP = false; @@ -757,10 +757,10 @@ void QGLContextPrivate::destroyGlSurfaceForPixmap(QPixmapData* pmd) QX11PixmapData *pixmapData = static_cast(pmd); if (pixmapData->gl_surface) { EGLBoolean success; - success = eglDestroySurface(QEglContext::display(), (EGLSurface)pixmapData->gl_surface); + success = eglDestroySurface(QEgl::display(), (EGLSurface)pixmapData->gl_surface); if (success == EGL_FALSE) { qWarning() << "destroyGlSurfaceForPixmap() - Error deleting surface: " - << QEglContext::errorString(eglGetError()); + << QEgl::errorString(); } pixmapData->gl_surface = 0; } @@ -772,12 +772,12 @@ void QGLContextPrivate::unbindPixmapFromTexture(QPixmapData* pmd) QX11PixmapData *pixmapData = static_cast(pmd); if (pixmapData->gl_surface) { EGLBoolean success; - success = eglReleaseTexImage(QEglContext::display(), + success = eglReleaseTexImage(QEgl::display(), (EGLSurface)pixmapData->gl_surface, EGL_BACK_BUFFER); if (success == EGL_FALSE) { qWarning() << "unbindPixmapFromTexture() - Unable to release bound texture: " - << QEglContext::errorString(eglGetError()); + << QEgl::errorString(); } } } diff --git a/src/opengl/qglpixelbuffer_egl.cpp b/src/opengl/qglpixelbuffer_egl.cpp index 954049d..cee5a1f 100644 --- a/src/opengl/qglpixelbuffer_egl.cpp +++ b/src/opengl/qglpixelbuffer_egl.cpp @@ -137,7 +137,7 @@ bool QGLPixelBufferPrivate::init(const QSize &size, const QGLFormat &f, QGLWidge } #endif if (pbuf == EGL_NO_SURFACE) { - qWarning() << "QGLPixelBufferPrivate::init(): Unable to create EGL pbuffer surface:" << QEglContext::errorString(eglGetError()); + qWarning() << "QGLPixelBufferPrivate::init(): Unable to create EGL pbuffer surface:" << QEgl::errorString(); return false; } @@ -204,7 +204,7 @@ GLuint QGLPixelBuffer::generateDynamicTexture() const bool QGLPixelBuffer::hasOpenGLPbuffers() { // See if we have at least 1 configuration that matches the default format. - EGLDisplay dpy = QEglContext::display(); + EGLDisplay dpy = QEgl::display(); if (dpy == EGL_NO_DISPLAY) return false; QEglProperties configProps; diff --git a/src/opengl/qpixmapdata_x11gl_egl.cpp b/src/opengl/qpixmapdata_x11gl_egl.cpp index 4f1543c..811e554 100644 --- a/src/opengl/qpixmapdata_x11gl_egl.cpp +++ b/src/opengl/qpixmapdata_x11gl_egl.cpp @@ -97,14 +97,14 @@ bool QX11GLPixmapData::hasX11GLPixmaps() #endif EGL_NONE }; - qPixmapARGBSharedEglContext = eglCreateContext(QEglContext::display(), + qPixmapARGBSharedEglContext = eglCreateContext(QEgl::display(), argbConfig, 0, contextAttribs); if (argbConfig == rgbConfig) { // If the configs are the same, we can re-use the same context. qPixmapRGBSharedEglContext = qPixmapARGBSharedEglContext; } else { - qPixmapRGBSharedEglContext = eglCreateContext(QEglContext::display(), + qPixmapRGBSharedEglContext = eglCreateContext(QEgl::display(), rgbConfig, 0, contextAttribs); } @@ -115,13 +115,12 @@ bool QX11GLPixmapData::hasX11GLPixmaps() if (!qt_createEGLSurfaceForPixmap(argbPixmapData, false)) break; - haveX11Pixmaps = eglMakeCurrent(QEglContext::display(), + haveX11Pixmaps = eglMakeCurrent(QEgl::display(), (EGLSurface)argbPixmapData->gl_surface, (EGLSurface)argbPixmapData->gl_surface, qPixmapARGBSharedEglContext); if (!haveX11Pixmaps) { - EGLint err = eglGetError(); - qWarning() << "Unable to make pixmap config current:" << err << QEglContext::errorString(err); + qWarning() << "Unable to make pixmap config current:" << QEgl::errorString(); break; } @@ -135,20 +134,19 @@ bool QX11GLPixmapData::hasX11GLPixmaps() if (!qt_createEGLSurfaceForPixmap(rgbPixmapData, false)) break; - haveX11Pixmaps = eglMakeCurrent(QEglContext::display(), + haveX11Pixmaps = eglMakeCurrent(QEgl::display(), (EGLSurface)rgbPixmapData->gl_surface, (EGLSurface)rgbPixmapData->gl_surface, qPixmapRGBSharedEglContext); if (!haveX11Pixmaps) { - EGLint err = eglGetError(); - qWarning() << "Unable to make pixmap config current:" << err << QEglContext::errorString(err); + qWarning() << "Unable to make pixmap config current:" << QEgl::errorString(); break; } } } while (0); if (qPixmapARGBSharedEglContext || qPixmapRGBSharedEglContext) { - eglMakeCurrent(QEglContext::display(), + eglMakeCurrent(QEgl::display(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } @@ -168,12 +166,12 @@ bool QX11GLPixmapData::hasX11GLPixmaps() if (!haveX11Pixmaps) { // Clean up the context(s) if we can't use X11GL pixmaps if (qPixmapARGBSharedEglContext != EGL_NO_CONTEXT) - eglDestroyContext(QEglContext::display(), qPixmapARGBSharedEglContext); + eglDestroyContext(QEgl::display(), qPixmapARGBSharedEglContext); if (qPixmapRGBSharedEglContext != qPixmapARGBSharedEglContext && qPixmapRGBSharedEglContext != EGL_NO_CONTEXT) { - eglDestroyContext(QEglContext::display(), qPixmapRGBSharedEglContext); + eglDestroyContext(QEgl::display(), qPixmapRGBSharedEglContext); } qPixmapRGBSharedEglContext = EGL_NO_CONTEXT; qPixmapARGBSharedEglContext = EGL_NO_CONTEXT; -- cgit v0.12 From 6378d3d0e851f6af3e518ff53351de3253368026 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 16 Feb 2010 16:15:04 +0100 Subject: Move chooseConfig and createSurface logic to QEgl functions We keep the methods in QEglContext, but these are useful helpers which wrap the QEgl version of the functions, which is where the bulk of the logic is (for these functions anyway). Reviewed-By: Aleksandar Sasha Babic --- src/gui/egl/qegl.cpp | 24 ++++++++++++++++++------ src/gui/egl/qegl_p.h | 7 +++++-- src/gui/egl/qegl_qws.cpp | 3 ++- src/gui/egl/qegl_symbian.cpp | 2 +- src/gui/egl/qegl_wince.cpp | 2 +- src/gui/egl/qegl_x11.cpp | 2 +- 6 files changed, 28 insertions(+), 12 deletions(-) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index ef5eb67..6d719ba 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -89,10 +89,10 @@ bool QEglContext::isCurrent() const } // Choose a configuration that matches "properties". -bool QEglContext::chooseConfig - (const QEglProperties& properties, QEgl::PixelFormatMatch match) +EGLConfig QEgl::chooseConfig(const QEglProperties* properties, QEgl::PixelFormatMatch match) { - QEglProperties props(properties); + QEglProperties props(*properties); + EGLConfig cfg = QEGL_NO_CONFIG; do { // Get the number of matching configurations for this set of properties. EGLint matching = 0; @@ -106,7 +106,7 @@ bool QEglContext::chooseConfig eglChooseConfig(display(), props.properties(), &cfg, 1, &matching); if (matching < 1) continue; - return true; + return cfg; } // Fetch all of the matching configurations and find the @@ -127,7 +127,7 @@ bool QEglContext::chooseConfig alpha == props.value(EGL_ALPHA_SIZE))) { cfg = configs[index]; delete [] configs; - return true; + return cfg; } } delete [] configs; @@ -146,9 +146,21 @@ bool QEglContext::chooseConfig qWarning() << "Available:"; QEgl::dumpAllConfigs(); } - return false; + return QEGL_NO_CONFIG; } +bool QEglContext::chooseConfig(const QEglProperties& properties, QEgl::PixelFormatMatch match) +{ + cfg = QEgl::chooseConfig(&properties, match); + return cfg != QEGL_NO_CONFIG; +} + +EGLSurface QEglContext::createSurface(QPaintDevice* device, const QEglProperties *properties) +{ + return QEgl::createSurface(device, cfg, properties); +} + + // Create the EGLContext. bool QEglContext::createContext(QEglContext *shareContext, const QEglProperties *properties) { diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index e48e4a0..a50e4e1 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -93,9 +93,12 @@ typedef NativeDisplayType EGLNativeDisplayType; QT_END_INCLUDE_NAMESPACE +#include QT_BEGIN_NAMESPACE +#define QEGL_NO_CONFIG ((EGLConfig)-1) + class QEglProperties; namespace QEgl { @@ -111,8 +114,8 @@ namespace QEgl { BestPixelFormat }; -// EGLConfig chooseConfig(const QEglProperties* properties, QEgl::PixelFormatMatch match = QEgl::ExactPixelFormat); -// EGLSurface createSurface(QPaintDevice *device, EGLConfig config, const QEglProperties *properties = 0); + Q_GUI_EXPORT EGLConfig chooseConfig(const QEglProperties* configAttribs, QEgl::PixelFormatMatch match = QEgl::ExactPixelFormat); + Q_GUI_EXPORT EGLSurface createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *surfaceAttribs = 0); Q_GUI_EXPORT void dumpAllConfigs(); diff --git a/src/gui/egl/qegl_qws.cpp b/src/gui/egl/qegl_qws.cpp index a40c236..935fe67 100644 --- a/src/gui/egl/qegl_qws.cpp +++ b/src/gui/egl/qegl_qws.cpp @@ -59,9 +59,10 @@ QT_BEGIN_NAMESPACE // We don't have QGLScreen to create EGL surfaces for us, // so surface creation needs to be done in QtOpenGL or // QtOpenVG for Qt/Embedded. -EGLSurface QEglContext::createSurface(QPaintDevice *device, const QEglProperties *properties) +EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) { Q_UNUSED(device); + Q_UNUSED(cfg); Q_UNUSED(properties); return EGL_NO_SURFACE; } diff --git a/src/gui/egl/qegl_symbian.cpp b/src/gui/egl/qegl_symbian.cpp index 0c91fd8..2276ce0 100644 --- a/src/gui/egl/qegl_symbian.cpp +++ b/src/gui/egl/qegl_symbian.cpp @@ -50,7 +50,7 @@ QT_BEGIN_NAMESPACE -EGLSurface QEglContext::createSurface(QPaintDevice *device, const QEglProperties *properties) +EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) { // Create the native drawable for the paint device. int devType = device->devType(); diff --git a/src/gui/egl/qegl_wince.cpp b/src/gui/egl/qegl_wince.cpp index 2f79005..fae491b 100644 --- a/src/gui/egl/qegl_wince.cpp +++ b/src/gui/egl/qegl_wince.cpp @@ -51,7 +51,7 @@ QT_BEGIN_NAMESPACE -EGLSurface QEglContext::createSurface(QPaintDevice *device, const QEglProperties *properties) +EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) { // Create the native drawable for the paint device. int devType = device->devType(); diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index 4a813c6..d24727a 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -55,7 +55,7 @@ QT_BEGIN_NAMESPACE -EGLSurface QEglContext::createSurface(QPaintDevice *device, const QEglProperties *properties) +EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) { // Create the native drawable for the paint device. int devType = device->devType(); -- cgit v0.12 From d0a2d10dfac7be20af78988a3351d374acfdd208 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 16 Feb 2010 17:38:25 +0100 Subject: Make QEgl::createSurface cross-platform and add native getters QEgl::createSurface was virtually identical for every platform apart from the line which returned the native window type. This patch just adds QEgl::nativePixmap and QEgl::nativeWindow which are platform specific (though the default widget->winId() works for everything apart from symbian). Reviewed-By: Aleksandar Sasha Babic --- src/gui/egl/qegl.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++++ src/gui/egl/qegl_p.h | 3 +++ src/gui/egl/qegl_qws.cpp | 12 ---------- src/gui/egl/qegl_symbian.cpp | 37 ++----------------------------- src/gui/egl/qegl_wince.cpp | 38 -------------------------------- src/gui/egl/qegl_x11.cpp | 38 -------------------------------- 6 files changed, 57 insertions(+), 123 deletions(-) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index 6d719ba..ef30029 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -385,6 +385,58 @@ EGLNativeDisplayType QEgl::nativeDisplay() } #endif +#if !defined(Q_OS_SYMBIAN) +EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) +{ + return (EGLNativeWindowType)(widget->winId()); +} +#endif + +EGLNativePixmapType QEgl::nativePixmap(QPixmap* pixmap) +{ + return (EGLNativePixmapType)(pixmap->handle()); +} + +EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) +{ + // Create the native drawable for the paint device. + int devType = device->devType(); + EGLNativePixmapType pixmapDrawable = 0; + EGLNativeWindowType windowDrawable = 0; + bool ok; + if (devType == QInternal::Pixmap) { + pixmapDrawable = nativePixmap(static_cast(device)); + ok = (pixmapDrawable != 0); + } else if (devType == QInternal::Widget) { + windowDrawable = nativeWindow(static_cast(device)); + ok = (windowDrawable != 0); + } else { + ok = false; + } + if (!ok) { + qWarning("QEglContext::createSurface(): Cannot create the native EGL drawable"); + return EGL_NO_SURFACE; + } + + // Create the EGL surface to draw into, based on the native drawable. + const int *props; + if (properties) + props = properties->properties(); + else + props = 0; + EGLSurface surf; + if (devType == QInternal::Widget) + surf = eglCreateWindowSurface(QEgl::display(), cfg, windowDrawable, props); + else + surf = eglCreatePixmapSurface(QEgl::display(), cfg, pixmapDrawable, props); + if (surf == EGL_NO_SURFACE) { + qWarning("QEglContext::createSurface(): Unable to create EGL surface, error = 0x%x", eglGetError()); + } + return surf; +} + + + // Return the error string associated with a specific code. QString QEgl::errorString(EGLint code) { diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index a50e4e1..8a9d815 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -128,7 +128,10 @@ namespace QEgl { Q_GUI_EXPORT bool hasExtension(const char* extensionName); Q_GUI_EXPORT EGLDisplay display(); + Q_GUI_EXPORT EGLNativeDisplayType nativeDisplay(); + Q_GUI_EXPORT EGLNativeWindowType nativeWindow(QWidget*); + Q_GUI_EXPORT EGLNativePixmapType nativePixmap(QPixmap*); }; diff --git a/src/gui/egl/qegl_qws.cpp b/src/gui/egl/qegl_qws.cpp index 935fe67..eb41bcc 100644 --- a/src/gui/egl/qegl_qws.cpp +++ b/src/gui/egl/qegl_qws.cpp @@ -55,18 +55,6 @@ QT_BEGIN_NAMESPACE -// Create the surface for a QPixmap, QImage, or QWidget. -// We don't have QGLScreen to create EGL surfaces for us, -// so surface creation needs to be done in QtOpenGL or -// QtOpenVG for Qt/Embedded. -EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) -{ - Q_UNUSED(device); - Q_UNUSED(cfg); - Q_UNUSED(properties); - return EGL_NO_SURFACE; -} - static QScreen *screenForDevice(QPaintDevice *device) { QScreen *screen = qt_screen; diff --git a/src/gui/egl/qegl_symbian.cpp b/src/gui/egl/qegl_symbian.cpp index 2276ce0..8833b42 100644 --- a/src/gui/egl/qegl_symbian.cpp +++ b/src/gui/egl/qegl_symbian.cpp @@ -50,42 +50,9 @@ QT_BEGIN_NAMESPACE -EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) +EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) { - // Create the native drawable for the paint device. - int devType = device->devType(); - EGLNativePixmapType pixmapDrawable = 0; - EGLNativeWindowType windowDrawable = 0; - bool ok; - if (devType == QInternal::Pixmap) { - pixmapDrawable = 0; - ok = (pixmapDrawable != 0); - } else if (devType == QInternal::Widget) { - QWidget *w = static_cast(device); - windowDrawable = (EGLNativeWindowType)(w->winId()->DrawableWindow()); - ok = (windowDrawable != 0); - } else { - ok = false; - } - if (!ok) { - qWarning("QEglContext::createSurface(): Cannot create the native EGL drawable"); - return EGL_NO_SURFACE; - } - - // Create the EGL surface to draw into, based on the native drawable. - const int *props; - if (properties) - props = properties->properties(); - else - props = 0; - EGLSurface surf; - if (devType == QInternal::Widget) - surf = eglCreateWindowSurface(dpy, cfg, windowDrawable, props); - else - surf = eglCreatePixmapSurface(dpy, cfg, pixmapDrawable, props); - if (surf == EGL_NO_SURFACE) - qWarning("QEglContext::createSurface(): Unable to create EGL surface, error = 0x%x", eglGetError()); - return surf; + return (EGLNativeWindowType)(widget->winId()->DrawableWindow()); } // Set pixel format and other properties based on a paint device. diff --git a/src/gui/egl/qegl_wince.cpp b/src/gui/egl/qegl_wince.cpp index fae491b..b201153 100644 --- a/src/gui/egl/qegl_wince.cpp +++ b/src/gui/egl/qegl_wince.cpp @@ -51,44 +51,6 @@ QT_BEGIN_NAMESPACE -EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) -{ - // Create the native drawable for the paint device. - int devType = device->devType(); - EGLNativePixmapType pixmapDrawable = 0; - EGLNativeWindowType windowDrawable = 0; - bool ok; - if (devType == QInternal::Pixmap) { - pixmapDrawable = 0; - ok = (pixmapDrawable != 0); - } else if (devType == QInternal::Widget) { - windowDrawable = (EGLNativeWindowType)(static_cast(device))->winId(); - ok = (windowDrawable != 0); - } else { - ok = false; - } - if (!ok) { - qWarning("QEglContext::createSurface(): Cannot create the native EGL drawable"); - return EGL_NO_SURFACE; - } - - // Create the EGL surface to draw into, based on the native drawable. - const int *props; - if (properties) - props = properties->properties(); - else - props = 0; - EGLSurface surf; - if (devType == QInternal::Widget) - surf = eglCreateWindowSurface(QEgl::display(), cfg, windowDrawable, props); - else - surf = eglCreatePixmapSurface(QEgl::display(), cfg, pixmapDrawable, props); - if (surf == EGL_NO_SURFACE) { - qWarning("QEglContext::createSurface(): Unable to create EGL surface, error = 0x%x", eglGetError()); - } - return surf; -} - EGLNativeDisplayType QEgl::nativeDisplay() { HWND win = (static_cast(device))->winId(); diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index d24727a..e8fb662 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -55,44 +55,6 @@ QT_BEGIN_NAMESPACE -EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) -{ - // Create the native drawable for the paint device. - int devType = device->devType(); - EGLNativePixmapType pixmapDrawable = 0; - EGLNativeWindowType windowDrawable = 0; - bool ok; - if (devType == QInternal::Pixmap) { - pixmapDrawable = (EGLNativePixmapType)(static_cast(device))->handle(); - ok = (pixmapDrawable != 0); - } else if (devType == QInternal::Widget) { - windowDrawable = (EGLNativeWindowType)(static_cast(device))->winId(); - ok = (windowDrawable != 0); - } else { - ok = false; - } - if (!ok) { - qWarning("QEglContext::createSurface(): Cannot create the native EGL drawable"); - return EGL_NO_SURFACE; - } - - // Create the EGL surface to draw into, based on the native drawable. - const int *props; - if (properties) - props = properties->properties(); - else - props = 0; - EGLSurface surf; - if (devType == QInternal::Widget) - surf = eglCreateWindowSurface(QEgl::display(), cfg, windowDrawable, props); - else - surf = eglCreatePixmapSurface(QEgl::display(), cfg, pixmapDrawable, props); - if (surf == EGL_NO_SURFACE) { - qWarning() << "QEglContext::createSurface(): Unable to create EGL surface:" - << QEgl::errorString(); - } - return surf; -} EGLNativeDisplayType QEgl::nativeDisplay() { -- cgit v0.12 From 551b41e20118b66edb37704a0cfbfe5d3a960067 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 18 Feb 2010 09:58:57 +0100 Subject: Add QEgl::defaultConfig method to select configs suitable for Qt Reviewed-By: TrustMe --- src/gui/egl/qegl.cpp | 163 +++++++++++++++++++++++++++++++++++++++++ src/gui/egl/qegl_p.h | 15 ++++ src/gui/egl/qeglproperties.cpp | 10 +++ 3 files changed, 188 insertions(+) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index ef30029..8bd4d7f 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -88,6 +88,169 @@ bool QEglContext::isCurrent() const return current; } +EGLConfig QEgl::defaultConfig(QPaintDevice* device, API api, ConfigOptions options) +{ + int devType = device->devType(); + + if ( (devType != QInternal::Pixmap) && ((options & Renderable) == 0)) + qWarning("QEgl::defaultConfig() - Only configs for pixmaps make sense to be read-only!"); + + EGLConfig* targetConfig = 0; + + static EGLConfig defaultVGConfigs[] = { + QEGL_NO_CONFIG, // 0 Window Renderable Translucent + QEGL_NO_CONFIG, // 1 Window Renderable Opaque + QEGL_NO_CONFIG, // 2 Pixmap Renderable Translucent + QEGL_NO_CONFIG, // 3 Pixmap Renderable Opaque + QEGL_NO_CONFIG, // 4 Pixmap ReadOnly Translucent + QEGL_NO_CONFIG // 5 Pixmap ReadOnly Opaque + }; + if (api == OpenVG) { + if (devType == QInternal::Widget) { + if (options & Translucent) + targetConfig = &(defaultVGConfigs[0]); + else + targetConfig = &(defaultVGConfigs[1]); + } else if (devType == QInternal::Pixmap) { + if (options & Renderable) { + if (options & Translucent) + targetConfig = &(defaultVGConfigs[2]); + else // Opaque + targetConfig = &(defaultVGConfigs[3]); + } else { // Read-only + if (options & Translucent) + targetConfig = &(defaultVGConfigs[4]); + else // Opaque + targetConfig = &(defaultVGConfigs[5]); + } + } + } + + + static EGLConfig defaultGLConfigs[] = { + QEGL_NO_CONFIG, // 0 Window Renderable Translucent + QEGL_NO_CONFIG, // 1 Window Renderable Opaque + QEGL_NO_CONFIG, // 2 PBuffer Renderable Translucent + QEGL_NO_CONFIG, // 3 PBuffer Renderable Opaque + QEGL_NO_CONFIG, // 4 Pixmap Renderable Translucent + QEGL_NO_CONFIG, // 5 Pixmap Renderable Opaque + QEGL_NO_CONFIG, // 6 Pixmap ReadOnly Translucent + QEGL_NO_CONFIG // 7 Pixmap ReadOnly Opaque + }; + if (api == OpenGL) { + if (devType == QInternal::Widget) { + if (options & Translucent) + targetConfig = &(defaultGLConfigs[0]); + else // Opaque + targetConfig = &(defaultGLConfigs[1]); + } else if (devType == QInternal::Pbuffer) { + if (options & Translucent) + targetConfig = &(defaultGLConfigs[2]); + else // Opaque + targetConfig = &(defaultGLConfigs[3]); + } else if (devType == QInternal::Pixmap) { + if (options & Renderable) { + if (options & Translucent) + targetConfig = &(defaultGLConfigs[4]); + else // Opaque + targetConfig = &(defaultGLConfigs[5]); + } else { // ReadOnly + if (options & Translucent) + targetConfig = &(defaultGLConfigs[6]); + else // Opaque + targetConfig = &(defaultGLConfigs[7]); + } + } + } + + if (!targetConfig) { + qWarning("QEgl::defaultConfig() - No default config for device/api/options combo"); + return QEGL_NO_CONFIG; + } + if (*targetConfig != QEGL_NO_CONFIG) + return *targetConfig; + + + // We haven't found an EGL config for the target config yet, so do it now: + + + // Allow overriding from an environment variable: + QByteArray configId; + if (api == OpenVG) + configId = qgetenv("QT_VG_EGL_CONFIG"); + else + configId = qgetenv("QT_GL_EGL_CONFIG"); + if (!configId.isEmpty()) { + // Overriden, so get the EGLConfig for the specified config ID: + EGLint properties[] = { + EGL_CONFIG_ID, (EGLint)configId.toInt(), + EGL_NONE + }; + EGLint configCount = 0; + eglChooseConfig(display(), properties, targetConfig, 1, &configCount); + if (configCount > 0) + return *targetConfig; + qWarning() << "QEgl::defaultConfig() -" << configId << "appears to be invalid"; + } + + QEglProperties configAttribs; + configAttribs.setRenderableType(api); + + EGLint surfaceType; + switch (devType) { + case QInternal::Widget: + surfaceType = EGL_WINDOW_BIT; + break; + case QInternal::Pixmap: + surfaceType = EGL_PIXMAP_BIT; + break; + case QInternal::Pbuffer: + surfaceType = EGL_PBUFFER_BIT; + break; + default: + qWarning("QEgl::defaultConfig() - Can't create EGL surface for %d device type", devType); + return QEGL_NO_CONFIG; + }; +#ifdef EGL_VG_ALPHA_FORMAT_PRE_BIT + // For OpenVG, we try to create a surface using a pre-multiplied format if + // the surface needs to have an alpha channel: + if (api == OpenVG && (options & Translucent)) + surfaceType |= EGL_VG_ALPHA_FORMAT_PRE_BIT; +#endif + configAttribs.setValue(EGL_SURFACE_TYPE, surfaceType); + +#ifdef EGL_BIND_TO_TEXTURE_RGBA + if (devType == QInternal::Pixmap || devType == QInternal::Pbuffer) { + if (options & Translucent) + configAttribs.setValue(EGL_BIND_TO_TEXTURE_RGBA, EGL_TRUE); + else + configAttribs.setValue(EGL_BIND_TO_TEXTURE_RGB, EGL_TRUE); + } +#endif + + // Add paint engine requirements + if (api == OpenVG) { +#ifndef QVG_SCISSOR_CLIP + configAttribs.setValue(EGL_ALPHA_MASK_SIZE, 1); +#endif + } else { + // Both OpenGL paint engines need to have stencil and sample buffers + configAttribs.setValue(EGL_STENCIL_SIZE, 1); + configAttribs.setValue(EGL_SAMPLE_BUFFERS, 1); +#ifndef QT_OPENGL_ES_2 + // Aditionally, the GL1 engine likes to have a depth buffer for clipping + configAttribs.setValue(EGL_DEPTH_SIZE, 1); +#endif + } + + // Finally, set the color format based on the device: + configAttribs.setPaintDeviceFormat(device); + + *targetConfig = chooseConfig(&configAttribs, QEgl::BestPixelFormat); + return *targetConfig; +} + + // Choose a configuration that matches "properties". EGLConfig QEgl::chooseConfig(const QEglProperties* properties, QEgl::PixelFormatMatch match) { diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index 8a9d815..1a5e4c0 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -114,6 +114,21 @@ namespace QEgl { BestPixelFormat }; + enum ConfigOptions + { + Opaque = 0x00, + Translucent = 0x01, + + ReadOnly = 0x00, + Renderable = 0x02 // Config will be compatable with the paint engines (VG or GL) + }; + + // Most of the time we use the same config for things like widgets & pixmaps, so rather than + // go through the eglChooseConfig loop every time, we use defaultConfig, which will return + // the config for a particular device/api/option combo. This function assumes that once a + // config is chosen for a particular combo, it's safe to always use that combo. + Q_GUI_EXPORT EGLConfig defaultConfig(QPaintDevice* device, API api, ConfigOptions options); + Q_GUI_EXPORT EGLConfig chooseConfig(const QEglProperties* configAttribs, QEgl::PixelFormatMatch match = QEgl::ExactPixelFormat); Q_GUI_EXPORT EGLSurface createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *surfaceAttribs = 0); diff --git a/src/gui/egl/qeglproperties.cpp b/src/gui/egl/qeglproperties.cpp index 86e158b..e0e8481 100644 --- a/src/gui/egl/qeglproperties.cpp +++ b/src/gui/egl/qeglproperties.cpp @@ -230,6 +230,16 @@ void QEglProperties::setRenderableType(QEgl::API api) // reductions in complexity are possible. bool QEglProperties::reduceConfiguration() { +#ifdef EGL_VG_ALPHA_FORMAT_PRE_BIT + // For OpenVG, we sometimes try to create a surface using a pre-multiplied format. If we can't + // find a config which supports pre-multiplied formats, remove the flag on the surface type: + EGLint surfaceType = value(EGL_SURFACE_TYPE); + if (surfaceType & EGL_VG_ALPHA_FORMAT_PRE_BIT) { + surfaceType ^= EGL_VG_ALPHA_FORMAT_PRE_BIT; + setValue(EGL_SURFACE_TYPE, surfaceType); + return true; + } +#endif // EGL chooses configs with the highest color depth over // those with smaller (but faster) lower color depths. One // way around this is to set EGL_BUFFER_SIZE to 16, which -- cgit v0.12 From 4c5549269144eae79bdcefc7119b2adf3044e000 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 19 Feb 2010 15:54:09 +0100 Subject: Add getCompatibleVisualId to QEgl on X11 This method takes an EGLConfig and hands back an X11 VisualID which can be used to create native windows/pixmaps which will have an EGL surface created for them using the given EGL config. Reviewed-By: TrustMe --- src/gui/egl/qegl_p.h | 4 ++ src/gui/egl/qegl_x11.cpp | 145 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index 1a5e4c0..7f753d0 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -147,6 +147,10 @@ namespace QEgl { Q_GUI_EXPORT EGLNativeDisplayType nativeDisplay(); Q_GUI_EXPORT EGLNativeWindowType nativeWindow(QWidget*); Q_GUI_EXPORT EGLNativePixmapType nativePixmap(QPixmap*); + +#ifdef Q_WS_X11 + Q_GUI_EXPORT VisualID getCompatibleVisualId(EGLConfig config); +#endif }; diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index e8fb662..2c0bbd3 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -116,4 +116,149 @@ void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev) setVisualFormat(qt_x11Info(dev)); } + +VisualID QEgl::getCompatibleVisualId(EGLConfig config) +{ + VisualID visualId = 0; + EGLint eglValue = 0; + + EGLint configRedSize = 0; + eglGetConfigAttrib(display(), config, EGL_RED_SIZE, &configRedSize); + + EGLint configGreenSize = 0; + eglGetConfigAttrib(display(), config, EGL_GREEN_SIZE, &configGreenSize); + + EGLint configBlueSize = 0; + eglGetConfigAttrib(display(), config, EGL_BLUE_SIZE, &configBlueSize); + + EGLint configAlphaSize = 0; + eglGetConfigAttrib(display(), config, EGL_ALPHA_SIZE, &configAlphaSize); + + eglGetConfigAttrib(display(), config, EGL_BUFFER_SIZE, &eglValue); + int configBitDepth = eglValue; + + // See if EGL provided a valid VisualID: + eglGetConfigAttrib(display(), config, EGL_NATIVE_VISUAL_ID, &eglValue); + visualId = (VisualID)eglValue; + if (visualId) { + // EGL has suggested a visual id, so get the rest of the visual info for that id: + XVisualInfo visualInfoTemplate; + memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); + visualInfoTemplate.visualid = visualId; + + XVisualInfo *chosenVisualInfo; + int matchingCount = 0; + chosenVisualInfo = XGetVisualInfo(X11->display, VisualIDMask, &visualInfoTemplate, &matchingCount); + if (chosenVisualInfo) { + if (configBitDepth == chosenVisualInfo->depth) { +#if !defined(QT_NO_XRENDER) + // If we have XRender, actually check the visual supplied by EGL is ARGB + if (configAlphaSize > 0) { + XRenderPictFormat *format; + format = XRenderFindVisualFormat(X11->display, chosenVisualInfo->visual); + if (!format || (format->type != PictTypeDirect) || (!format->direct.alphaMask)) { + qWarning("Warning: EGL suggested using X visual ID %d for config %d, but this is not ARGB", + (int)visualId, (int)config); + visualId = 0; + } + } +#endif + } else { + qWarning("Warning: EGL suggested using X visual ID %d (%d bpp) for config %d (%d bpp), but the depths do not match!", + (int)visualId, chosenVisualInfo->depth, (int)config, configBitDepth); + visualId = 0; + } + } + XFree(chosenVisualInfo); + } + + if (visualId) { +#ifdef QT_DEBUG_X11_VISUAL_SELECTION + if (configHasAlpha) + qDebug("Using ARGB Visual ID %d provided by EGL for config %d", (int)visualId, (int)config); + else + qDebug("Using Opaque Visual ID %d provided by EGL for config %d", (int)visualId, (int)config); +#endif + return visualId; + } + + + // If EGL didn't give us a valid visual ID, try XRender +#if !defined(QT_NO_XRENDER) + if (!visualId) { + XVisualInfo visualInfoTemplate; + memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); + + visualInfoTemplate.depth = configBitDepth; + visualInfoTemplate.c_class = TrueColor; + + XVisualInfo *matchingVisuals; + int matchingCount = 0; + matchingVisuals = XGetVisualInfo(X11->display, + VisualDepthMask|VisualClassMask, + &visualInfoTemplate, + &matchingCount); + + for (int i = 0; i < matchingCount; ++i) { + XRenderPictFormat *format; + format = XRenderFindVisualFormat(X11->display, matchingVisuals[i].visual); + + // Check the format for the visual matches the EGL config + if ( (countBits(format->direct.redMask) == configRedSize) && + (countBits(format->direct.greenMask) == configGreenSize) && + (countBits(format->direct.blueMask) == configBlueSize) && + (countBits(format->direct.alphaMask) == configAlphaSize) ) + { + visualId = matchingVisuals[i].visualid; + break; + } + } + if (matchingVisuals) + XFree(matchingVisuals); + + } + if (visualId) { +# ifdef QT_DEBUG_X11_VISUAL_SELECTION + if (configHasAlpha) + qDebug("Using ARGB Visual ID %d provided by XRender for EGL config %d", (int)visualId, (int)config); + else + qDebug("Using Opaque Visual ID %d provided by XRender for EGL config %d", (int)visualId, (int)config); +# endif // QT_DEBUG_X11_VISUAL_SELECTION + return visualId; + } +#endif //!defined(QT_NO_XRENDER) + + + // Finally, if XRender also failed to find a visual (or isn't present), try to + // use XGetVisualInfo and only use the bit depth to match on: + if (!visualId) { + XVisualInfo visualInfoTemplate; + memset(&visualInfoTemplate, 0, sizeof(XVisualInfo)); + + visualInfoTemplate.depth = configBitDepth; + + XVisualInfo *matchingVisuals; + int matchingCount = 0; + matchingVisuals = XGetVisualInfo(X11->display, + VisualDepthMask, + &visualInfoTemplate, + &matchingCount); + if (matchingVisuals) { + visualId = matchingVisuals[0].visualid; + XFree(matchingVisuals); + } + } + + if (visualId) { +#ifdef QT_DEBUG_X11_VISUAL_SELECTION + qDebug("Using Visual ID %d provided by XGetVisualInfo for EGL config %d", (int)visualId, (int)config); +#endif + return visualId; + } + + qWarning("Unable to find an X11 visual which matches EGL config %d", (int)config); + return (VisualID)0; +} + + QT_END_NAMESPACE -- cgit v0.12 From c993aef82eca9f5d5241093f407179e4189ab7f1 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 19 Feb 2010 18:17:08 +0100 Subject: Add QEglContext::configAttrib(int name) helper Reviewed-By: TrustMe --- src/gui/egl/qegl.cpp | 10 ++++++++++ src/gui/egl/qeglcontext_p.h | 1 + 2 files changed, 11 insertions(+) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index 8bd4d7f..d4c9913 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -510,6 +510,16 @@ bool QEglContext::configAttrib(int name, EGLint *value) const return eglGetConfigAttrib(QEgl::display(), cfg, name, value); } +int QEglContext::configAttrib(int name) const +{ + EGLint value; + EGLBoolean success = eglGetConfigAttrib(QEgl::display(), cfg, name, &value); + if (success) + return value; + else + return EGL_DONT_CARE; +} + QEglProperties QEglContext::configProperties() const { return QEglProperties(config()); diff --git a/src/gui/egl/qeglcontext_p.h b/src/gui/egl/qeglcontext_p.h index c656d1d..7eec7eb 100644 --- a/src/gui/egl/qeglcontext_p.h +++ b/src/gui/egl/qeglcontext_p.h @@ -89,6 +89,7 @@ public: void waitClient(); bool configAttrib(int name, EGLint *value) const; + int configAttrib(int name) const; EGLContext context() const { return ctx; } void setContext(EGLContext context) { ctx = context; ownsContext = false;} -- cgit v0.12 From 445b62cb432deb8aed3be766d3c37b9567e1d4ec Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 19 Feb 2010 18:29:42 +0100 Subject: Make QGLWidget use new QEgl::getCompatibleVisualId API Reviewed-By: TrustMe --- src/gui/egl/qegl_x11.cpp | 5 +++-- src/opengl/qgl_x11egl.cpp | 18 +++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index 2c0bbd3..49c8d60 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -116,6 +116,7 @@ void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev) setVisualFormat(qt_x11Info(dev)); } +//#define QT_DEBUG_X11_VISUAL_SELECTION 1 VisualID QEgl::getCompatibleVisualId(EGLConfig config) { @@ -174,7 +175,7 @@ VisualID QEgl::getCompatibleVisualId(EGLConfig config) if (visualId) { #ifdef QT_DEBUG_X11_VISUAL_SELECTION - if (configHasAlpha) + if (configAlphaSize > 0) qDebug("Using ARGB Visual ID %d provided by EGL for config %d", (int)visualId, (int)config); else qDebug("Using Opaque Visual ID %d provided by EGL for config %d", (int)visualId, (int)config); @@ -219,7 +220,7 @@ VisualID QEgl::getCompatibleVisualId(EGLConfig config) } if (visualId) { # ifdef QT_DEBUG_X11_VISUAL_SELECTION - if (configHasAlpha) + if (configAlphaSize > 0) qDebug("Using ARGB Visual ID %d provided by XRender for EGL config %d", (int)visualId, (int)config); else qDebug("Using Opaque Visual ID %d provided by XRender for EGL config %d", (int)visualId, (int)config); diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 972a5f6..b8da156 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -282,6 +282,7 @@ void QGLWidget::updateOverlayGL() } //#define QT_DEBUG_X11_VISUAL_SELECTION 1 +//#undef QT_DEBUG_X11_VISUAL_SELECTION bool qt_egl_setup_x11_visual(XVisualInfo &vi, EGLDisplay display, EGLConfig config, const QX11Info &x11Info, bool useArgbVisual) { @@ -471,10 +472,21 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, if (visible) hide(); - XVisualInfo vi; QEglContext *eglContext = d->glcx->d_func()->eglContext; - bool usingArgbVisual = qt_egl_setup_x11_visual(vi, eglContext->display(), eglContext->config(), - x11Info(), tryArgbVisual); + + XVisualInfo vi; + memset(&vi, 0, sizeof(XVisualInfo)); + vi.visualid = QEgl::getCompatibleVisualId(eglContext->config()); + + { + XVisualInfo *visualInfoPtr; + int matchingCount = 0; + visualInfoPtr = XGetVisualInfo(X11->display, VisualIDMask, &vi, &matchingCount); + vi = *visualInfoPtr; + XFree(visualInfoPtr); + } + + bool usingArgbVisual = eglContext->configAttrib(EGL_ALPHA_SIZE) > 0; XSetWindowAttributes a; -- cgit v0.12 From dbc62b34b54ec3294f1cf8248630fbd1eaad9cbc Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 23 Feb 2010 18:08:08 +0100 Subject: Remove qt_egl_setup_x11_visual This method has been re-written as QEgl::getCompatibleVisualId() which is much cleaner code. Reviewed-By: TrustMe --- src/opengl/qgl_x11egl.cpp | 150 +--------------------------------------------- 1 file changed, 1 insertion(+), 149 deletions(-) diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index b8da156..99ff5b8 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -53,9 +53,6 @@ QT_BEGIN_NAMESPACE -bool qt_egl_setup_x11_visual(XVisualInfo &vi, EGLDisplay display, EGLConfig config, - const QX11Info &x11Info, bool useArgbVisual); - /* QGLTemporaryContext implementation */ @@ -107,15 +104,7 @@ QGLTemporaryContext::QGLTemporaryContext(bool, QWidget *) int numVisuals; EGLint id = 0; - eglGetConfigAttrib(d->display, config, EGL_NATIVE_VISUAL_ID, &id); - if (id == 0) { - // EGL_NATIVE_VISUAL_ID is optional and might not be supported - // on some implementations - we'll have to do it the hard way - QX11Info xinfo; - qt_egl_setup_x11_visual(visualInfo, d->display, config, xinfo, false); - } else { - visualInfo.visualid = id; - } + visualInfo.visualid = QEgl::getCompatibleVisualId(config); vi = XGetVisualInfo(X11->display, VisualIDMask, &visualInfo, &numVisuals); if (!vi || numVisuals < 1) { qWarning("QGLTemporaryContext: Unable to get X11 visual info id."); @@ -281,143 +270,6 @@ void QGLWidget::updateOverlayGL() //handle overlay } -//#define QT_DEBUG_X11_VISUAL_SELECTION 1 -//#undef QT_DEBUG_X11_VISUAL_SELECTION - -bool qt_egl_setup_x11_visual(XVisualInfo &vi, EGLDisplay display, EGLConfig config, const QX11Info &x11Info, bool useArgbVisual) -{ - bool foundVisualIsArgb = useArgbVisual; - -#ifdef QT_DEBUG_X11_VISUAL_SELECTION - qDebug("qt_egl_setup_x11_visual() - useArgbVisual=%d", useArgbVisual); -#endif - - memset(&vi, 0, sizeof(XVisualInfo)); - - EGLint eglConfigColorSize; - eglGetConfigAttrib(display, config, EGL_BUFFER_SIZE, &eglConfigColorSize); - - // Check to see if EGL is suggesting an appropriate visual id: - EGLint nativeVisualId; - eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &nativeVisualId); - vi.visualid = nativeVisualId; - - if (vi.visualid) { - // EGL has suggested a visual id, so get the rest of the visual info for that id: - XVisualInfo *chosenVisualInfo; - int matchingCount = 0; - chosenVisualInfo = XGetVisualInfo(x11Info.display(), VisualIDMask, &vi, &matchingCount); - if (chosenVisualInfo) { -#if !defined(QT_NO_XRENDER) - if (useArgbVisual) { - // Check to make sure the visual provided by EGL is ARGB - XRenderPictFormat *format; - format = XRenderFindVisualFormat(x11Info.display(), chosenVisualInfo->visual); - if (format->type == PictTypeDirect && format->direct.alphaMask) { -#ifdef QT_DEBUG_X11_VISUAL_SELECTION - qDebug("Using ARGB X Visual ID (%d) provided by EGL", (int)vi.visualid); -#endif - foundVisualIsArgb = true; - vi = *chosenVisualInfo; - } - else { - qWarning("Warning: EGL suggested using X visual ID %d for config %d, but this is not ARGB", - nativeVisualId, (int)config); - vi.visualid = 0; - } - } else -#endif - { - if (eglConfigColorSize == chosenVisualInfo->depth) { -#ifdef QT_DEBUG_X11_VISUAL_SELECTION - qDebug("Using opaque X Visual ID (%d) provided by EGL", (int)vi.visualid); -#endif - vi = *chosenVisualInfo; - } else - qWarning("Warning: EGL suggested using X visual ID %d (%d bpp) for config %d (%d bpp), but the depths do not match!", - nativeVisualId, chosenVisualInfo->depth, (int)config, eglConfigColorSize); - } - XFree(chosenVisualInfo); - } - else { - qWarning("Warning: EGL suggested using X visual ID %d for config %d, but this seems to be invalid!", - nativeVisualId, (int)config); - vi.visualid = 0; - } - } - - // If EGL does not know the visual ID, so try to select an appropriate one ourselves, first - // using XRender if we're supposed to have an alpha, then falling back to XGetVisualInfo - -#if !defined(QT_NO_XRENDER) - if (vi.visualid == 0 && useArgbVisual) { - // Try to use XRender to find an ARGB visual we can use - vi.screen = x11Info.screen(); - vi.depth = 32; //### We might at some point (soon) get ARGB4444 - vi.c_class = TrueColor; - XVisualInfo *matchingVisuals; - int matchingCount = 0; - matchingVisuals = XGetVisualInfo(x11Info.display(), - VisualScreenMask|VisualDepthMask|VisualClassMask, - &vi, &matchingCount); - - for (int i = 0; i < matchingCount; ++i) { - XRenderPictFormat *format; - format = XRenderFindVisualFormat(x11Info.display(), matchingVisuals[i].visual); - if (format->type == PictTypeDirect && format->direct.alphaMask) { - vi = matchingVisuals[i]; - foundVisualIsArgb = true; -#ifdef QT_DEBUG_X11_VISUAL_SELECTION - qDebug("Using X Visual ID (%d) for ARGB visual as provided by XRender", (int)vi.visualid); -#endif - break; - } - } - XFree(matchingVisuals); - } -#endif - - if (vi.visualid == 0) { - EGLint depth; - eglGetConfigAttrib(display, config, EGL_BUFFER_SIZE, &depth); - int err; - err = XMatchVisualInfo(x11Info.display(), x11Info.screen(), depth, TrueColor, &vi); - if (err == 0) { - qWarning("Warning: Can't find an X visual which matches the EGL config(%d)'s depth (%d)!", - (int)config, depth); - depth = x11Info.depth(); - err = XMatchVisualInfo(x11Info.display(), x11Info.screen(), depth, TrueColor, &vi); - if (err == 0) { - qWarning("Error: Couldn't get any matching X visual!"); - return false; - } else - qWarning(" - Falling back to X11 suggested depth (%d)", depth); - } -#ifdef QT_DEBUG_X11_VISUAL_SELECTION - else - qDebug("Using X Visual ID (%d) for EGL provided depth (%d)", (int)vi.visualid, depth); -#endif - - // Don't try to use ARGB now unless the visual is 32-bit - even then it might stil fail :-( - if (useArgbVisual) - foundVisualIsArgb = vi.depth == 32; //### We might at some point (soon) get ARGB4444 - } - -#ifdef QT_DEBUG_X11_VISUAL_SELECTION - qDebug("Visual Info:"); - qDebug(" bits_per_rgb=%d", vi.bits_per_rgb); - qDebug(" red_mask=0x%x", vi.red_mask); - qDebug(" green_mask=0x%x", vi.green_mask); - qDebug(" blue_mask=0x%x", vi.blue_mask); - qDebug(" colormap_size=%d", vi.colormap_size); - qDebug(" c_class=%d", vi.c_class); - qDebug(" depth=%d", vi.depth); - qDebug(" screen=%d", vi.screen); - qDebug(" visualid=%d", vi.visualid); -#endif - return foundVisualIsArgb; -} - void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, bool deleteOldContext) { Q_D(QGLWidget); -- cgit v0.12 From ebdfa7270f67e4ce3b5034aa5144fdabeaecbbcd Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 24 Feb 2010 13:41:29 +0100 Subject: Use QEgl::display in QGLTemporaryContext so EGL is init'd only once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviewed-By: Trond Kjernåsen --- src/opengl/qgl_x11egl.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 99ff5b8..ff58fba 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -76,12 +76,7 @@ QGLTemporaryContext::QGLTemporaryContext(bool, QWidget *) d->surface = 0; int screen = 0; - d->display = eglGetDisplay(EGLNativeDisplayType(X11->display)); - - if (!eglInitialize(d->display, NULL, NULL)) { - qWarning("QGLTemporaryContext: Unable to initialize EGL display."); - return; - } + d->display = QEgl::display(); EGLConfig config; int numConfigs = 0; -- cgit v0.12 From a2eddea1432d6e558dcd620cd5100ce4531975e8 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 24 Feb 2010 17:26:11 +0100 Subject: Replace qt_egl_add_platform_config with existing QEglProperties API QEglProperties::setPaintDeviceFormat() seems to be a copy & paste of qt_egl_add_platform_config for every platform anyway. Reviewed-By: TrustMe --- src/opengl/qgl_egl_p.h | 1 - src/opengl/qgl_qws.cpp | 17 +---------------- src/opengl/qgl_wince.cpp | 12 +----------- src/opengl/qgl_x11egl.cpp | 8 +------- 4 files changed, 3 insertions(+), 35 deletions(-) diff --git a/src/opengl/qgl_egl_p.h b/src/opengl/qgl_egl_p.h index 518b500..1d8cbf1 100644 --- a/src/opengl/qgl_egl_p.h +++ b/src/opengl/qgl_egl_p.h @@ -62,7 +62,6 @@ class QGLFormat; void qt_egl_set_format(QEglProperties& props, int deviceType, const QGLFormat& f); void qt_egl_update_format(const QEglContext& context, QGLFormat& format); -void qt_egl_add_platform_config(QEglProperties& props, QPaintDevice *device); QT_END_NAMESPACE diff --git a/src/opengl/qgl_qws.cpp b/src/opengl/qgl_qws.cpp index fd17a27..c221134 100644 --- a/src/opengl/qgl_qws.cpp +++ b/src/opengl/qgl_qws.cpp @@ -119,21 +119,6 @@ bool QGLFormat::hasOpenGLOverlays() return false; } -void qt_egl_add_platform_config(QEglProperties& props, QPaintDevice *device) -{ - // Find the QGLScreen for this paint device. - QGLScreen *glScreen = glScreenForDevice(device); - if (!glScreen) { - qWarning("QGLContext::chooseContext(): The screen is not a QGLScreen"); - return; - } - int devType = device->devType(); - if (devType == QInternal::Image) - props.setPixelFormat(static_cast(device)->format()); - else - props.setPixelFormat(glScreen->pixelFormat()); -} - static EGLSurface qt_egl_create_surface (QEglContext *context, QPaintDevice *device, const QEglProperties *properties = 0) @@ -201,8 +186,8 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) // Construct the configuration we need for this surface. QEglProperties configProps; - qt_egl_add_platform_config(configProps, device()); qt_egl_set_format(configProps, devType, d->glFormat); + configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); // Search for a matching configuration, reducing the complexity diff --git a/src/opengl/qgl_wince.cpp b/src/opengl/qgl_wince.cpp index 2b71201..ed8b4f7 100644 --- a/src/opengl/qgl_wince.cpp +++ b/src/opengl/qgl_wince.cpp @@ -122,16 +122,6 @@ QGLTemporaryContext::~QGLTemporaryContext() QGLFormat Win32/WGL-specific code *****************************************************************************/ -void qt_egl_add_platform_config(QEglProperties& props, QPaintDevice *device) -{ - int devType = device->devType(); - if (devType == QInternal::Image) - props.setPixelFormat(static_cast(device)->format()); - else - props.setPixelFormat(QImage::Format_RGB16); -} - - static bool opengl32dll = false; bool QGLFormat::hasOpenGLOverlays() @@ -159,8 +149,8 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) // Construct the configuration we need for this surface. QEglProperties configProps; - qt_egl_add_platform_config(configProps, device()); qt_egl_set_format(configProps, devType, d->glFormat); + configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); // Search for a matching configuration, reducing the complexity diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index ff58fba..21ddfe3 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -154,12 +154,6 @@ bool QGLFormat::hasOpenGLOverlays() return false; } -void qt_egl_add_platform_config(QEglProperties& props, QPaintDevice *device) -{ - if (device->devType() == QInternal::Image) - props.setPixelFormat(static_cast(device)->format()); -} - // Chooses the EGL config and creates the EGL context bool QGLContext::chooseContext(const QGLContext* shareContext) { @@ -178,7 +172,7 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) // Construct the configuration we need for this surface. QEglProperties configProps; qt_egl_set_format(configProps, devType, d->glFormat); - qt_egl_add_platform_config(configProps, device()); + configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); #if We_have_an_EGL_library_which_bothers_to_check_EGL_BUFFER_SIZE -- cgit v0.12 From f936cc4e2a7b377981a626b1d45dbbb1c1df1cb8 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Mon, 1 Mar 2010 12:59:34 +0100 Subject: Move EGL surface type setting to new QEglProperties::setDeviceType Also renamed qt_egl_set_format->qt_eglproperties_set_glformat Reviewed-By: TrustMe --- src/gui/egl/qeglproperties.cpp | 11 +++++++ src/gui/egl/qeglproperties_p.h | 4 +-- src/opengl/qgl_egl.cpp | 62 ++++++++++++++++++--------------------- src/opengl/qgl_egl_p.h | 2 +- src/opengl/qgl_qws.cpp | 3 +- src/opengl/qgl_wince.cpp | 3 +- src/opengl/qgl_x11egl.cpp | 3 +- src/opengl/qglpixelbuffer_egl.cpp | 6 ++-- 8 files changed, 53 insertions(+), 41 deletions(-) diff --git a/src/gui/egl/qeglproperties.cpp b/src/gui/egl/qeglproperties.cpp index e0e8481..636f469 100644 --- a/src/gui/egl/qeglproperties.cpp +++ b/src/gui/egl/qeglproperties.cpp @@ -167,6 +167,17 @@ bool QEglProperties::removeValue(int name) return false; } +void QEglProperties::setDeviceType(int devType) +{ + if (devType == QInternal::Pixmap || devType == QInternal::Image) + setValue(EGL_SURFACE_TYPE, EGL_PIXMAP_BIT); + else if (devType == QInternal::Pbuffer) + setValue(EGL_SURFACE_TYPE, EGL_PBUFFER_BIT); + else + setValue(EGL_SURFACE_TYPE, EGL_WINDOW_BIT); +} + + // Sets the red, green, blue, and alpha sizes based on a pixel format. // Normally used to match a configuration request to the screen format. void QEglProperties::setPixelFormat(QImage::Format pixelFormat) diff --git a/src/gui/egl/qeglproperties_p.h b/src/gui/egl/qeglproperties_p.h index 496847b..eebcf72 100644 --- a/src/gui/egl/qeglproperties_p.h +++ b/src/gui/egl/qeglproperties_p.h @@ -82,9 +82,9 @@ public: #ifdef Q_WS_X11 void setVisualFormat(const QX11Info *xinfo); #endif - void setRenderableType(QEgl::API api); - + void setDeviceType(int devType); void setPaintDeviceFormat(QPaintDevice *dev); + void setRenderableType(QEgl::API api); bool reduceConfiguration(); diff --git a/src/opengl/qgl_egl.cpp b/src/opengl/qgl_egl.cpp index 90fb2bb..f1abab8 100644 --- a/src/opengl/qgl_egl.cpp +++ b/src/opengl/qgl_egl.cpp @@ -45,44 +45,40 @@ QT_BEGIN_NAMESPACE -// Set device configuration attributes from a QGLFormat instance. -void qt_egl_set_format(QEglProperties& props, int deviceType, const QGLFormat& f) +void qt_eglproperties_set_glformat(QEglProperties& eglProperties, const QGLFormat& glFormat) { - if (deviceType == QInternal::Pixmap || deviceType == QInternal::Image) - props.setValue(EGL_SURFACE_TYPE, EGL_PIXMAP_BIT); - else if (deviceType == QInternal::Pbuffer) - props.setValue(EGL_SURFACE_TYPE, EGL_PBUFFER_BIT); - else - props.setValue(EGL_SURFACE_TYPE, EGL_WINDOW_BIT); - - // Set the pixel format to that contained in the QGLFormat - // if the system hasn't already chosen a fixed format to - // match the pixmap, widget, etc. - if (props.value(EGL_RED_SIZE) == 0 || f.redBufferSize() != -1) - props.setValue(EGL_RED_SIZE, f.redBufferSize() == -1 ? 1 : f.redBufferSize()); - if (props.value(EGL_GREEN_SIZE) == 0 || f.greenBufferSize() != -1) - props.setValue(EGL_GREEN_SIZE, f.greenBufferSize() == -1 ? 1 : f.greenBufferSize()); - if (props.value(EGL_BLUE_SIZE) == 0 || f.blueBufferSize() != -1) - props.setValue(EGL_BLUE_SIZE, f.blueBufferSize() == -1 ? 1 : f.blueBufferSize()); - if (f.alpha()) { - if (props.value(EGL_ALPHA_SIZE) == 0 || f.alphaBufferSize() != -1) - props.setValue(EGL_ALPHA_SIZE, f.alphaBufferSize() == -1 ? 1 : f.alphaBufferSize()); + // NOTE: QGLFormat uses a magic value of -1 to indicate "don't care", even when a buffer of that + // type has been requested. + if (glFormat.depth()) { + int depthSize = glFormat.depthBufferSize(); + eglProperties.setValue(EGL_DEPTH_SIZE, depthSize == -1 ? 1 : depthSize); } - - if (f.depth()) - props.setValue(EGL_DEPTH_SIZE, f.depthBufferSize() == -1 ? 1 : f.depthBufferSize()); - if (f.stencil()) - props.setValue(EGL_STENCIL_SIZE, f.stencilBufferSize() == -1 ? 1 : f.stencilBufferSize()); - if (f.sampleBuffers()) { - props.setValue(EGL_SAMPLE_BUFFERS, 1); - props.setValue(EGL_SAMPLES, f.samples() == -1 ? 1 : f.samples()); - } else { - props.setValue(EGL_SAMPLE_BUFFERS, 0); + if (glFormat.stencil()) { + int stencilSize = glFormat.stencilBufferSize(); + eglProperties.setValue(EGL_STENCIL_SIZE, stencilSize == -1 ? 1 : stencilSize); + } + if (glFormat.sampleBuffers()) { + int sampleCount = glFormat.samples(); + eglProperties.setValue(EGL_SAMPLES, sampleCount == -1 ? 1 : sampleCount); + eglProperties.setValue(EGL_SAMPLE_BUFFERS, 1); + } + if (glFormat.alpha()) { + int alphaSize = glFormat.alphaBufferSize(); + eglProperties.setValue(EGL_ALPHA_SIZE, alphaSize == -1 ? 1 : alphaSize); } - if (deviceType == QInternal::Widget) - props.setValue(EGL_LEVEL, f.plane()); + + int redSize = glFormat.redBufferSize(); + int greenSize = glFormat.greenBufferSize(); + int blueSize = glFormat.blueBufferSize(); + int alphaSize = glFormat.alphaBufferSize(); + + eglProperties.setValue(EGL_RED_SIZE, redSize > 0 ? redSize : 1); + eglProperties.setValue(EGL_GREEN_SIZE, greenSize > 0 ? greenSize : 1); + eglProperties.setValue(EGL_BLUE_SIZE, blueSize > 0 ? blueSize : 1); + eglProperties.setValue(EGL_ALPHA_SIZE, alphaSize > 0 ? alphaSize : 0); } + // Updates "format" with the parameters of the selected configuration. void qt_egl_update_format(const QEglContext& context, QGLFormat& format) { diff --git a/src/opengl/qgl_egl_p.h b/src/opengl/qgl_egl_p.h index 1d8cbf1..6b65227 100644 --- a/src/opengl/qgl_egl_p.h +++ b/src/opengl/qgl_egl_p.h @@ -60,7 +60,7 @@ QT_BEGIN_NAMESPACE class QGLFormat; -void qt_egl_set_format(QEglProperties& props, int deviceType, const QGLFormat& f); +void qt_eglproperties_set_glformat(QEglProperties& props, const QGLFormat& format); void qt_egl_update_format(const QEglContext& context, QGLFormat& format); QT_END_NAMESPACE diff --git a/src/opengl/qgl_qws.cpp b/src/opengl/qgl_qws.cpp index c221134..f72f051 100644 --- a/src/opengl/qgl_qws.cpp +++ b/src/opengl/qgl_qws.cpp @@ -186,7 +186,8 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) // Construct the configuration we need for this surface. QEglProperties configProps; - qt_egl_set_format(configProps, devType, d->glFormat); + qt_eglproperties_set_glformat(configProps, d->glFormat); + configProps.setDeviceType(devType); configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); diff --git a/src/opengl/qgl_wince.cpp b/src/opengl/qgl_wince.cpp index ed8b4f7..3bf7f3a 100644 --- a/src/opengl/qgl_wince.cpp +++ b/src/opengl/qgl_wince.cpp @@ -149,7 +149,8 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) // Construct the configuration we need for this surface. QEglProperties configProps; - qt_egl_set_format(configProps, devType, d->glFormat); + qt_eglproperties_set_glformat(configProps, d->glFormat); + configProps.setDeviceType(devType); configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 21ddfe3..7be4973 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -171,7 +171,8 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) // Construct the configuration we need for this surface. QEglProperties configProps; - qt_egl_set_format(configProps, devType, d->glFormat); + qt_eglproperties_set_glformat(configProps, d->glFormat); + configProps.setDeviceType(devType); configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); diff --git a/src/opengl/qglpixelbuffer_egl.cpp b/src/opengl/qglpixelbuffer_egl.cpp index cee5a1f..ee0714f 100644 --- a/src/opengl/qglpixelbuffer_egl.cpp +++ b/src/opengl/qglpixelbuffer_egl.cpp @@ -82,7 +82,8 @@ bool QGLPixelBufferPrivate::init(const QSize &size, const QGLFormat &f, QGLWidge #endif } else { QEglProperties configProps; - qt_egl_set_format(configProps, QInternal::Pbuffer, f); + qt_eglproperties_set_glformat(configProps, f); + configProps.setDeviceType(QInternal::Pbuffer); configProps.setRenderableType(ctx->api()); bool ok = false; #if QGL_RENDER_TEXTURE @@ -208,7 +209,8 @@ bool QGLPixelBuffer::hasOpenGLPbuffers() if (dpy == EGL_NO_DISPLAY) return false; QEglProperties configProps; - qt_egl_set_format(configProps, QInternal::Pbuffer, QGLFormat::defaultFormat()); + qt_eglproperties_set_glformat(configProps, QGLFormat::defaultFormat()); + configProps.setDeviceType(QInternal::Pbuffer); configProps.setRenderableType(QEgl::OpenGL); do { EGLConfig cfg = 0; -- cgit v0.12 From b2cbb880273ae6516d68be5b5f3f9b614c31ca79 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Mon, 1 Mar 2010 14:12:23 +0100 Subject: Move QGLWidget::setContext logic into QEgl & QGLContext QEgl::createSurface() on X11 will now check to see if the device's X11 Visual is compatible with the EGLConfig passed in. If it is not compatible, the function will re-create the QPaintDevice's native drawable with a different Visual (one which is compatable with the EGLConfig). This represented the bulk of the QGLWidget::setContext method which is now much simpler. As a consequense of this change, QWidgets with graphicssystem opengl will behave much more like QGLWidget as most of the code is re-used. So things like WA_TranslucentBackground should now work with opengl graphicssystem too. Reviewed-By: TrustMe --- src/gui/egl/qegl.cpp | 3 +- src/gui/egl/qegl_x11.cpp | 121 +++++++++++++++++++++++++++ src/gui/image/qpixmap_x11_p.h | 1 + src/gui/kernel/qwidget.h | 1 + src/opengl/qgl_x11egl.cpp | 173 +++++++++++++-------------------------- src/opengl/qwindowsurface_gl.cpp | 12 --- 6 files changed, 180 insertions(+), 131 deletions(-) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index d4c9913..e2002ed 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -570,6 +570,7 @@ EGLNativePixmapType QEgl::nativePixmap(QPixmap* pixmap) return (EGLNativePixmapType)(pixmap->handle()); } +#ifndef Q_WS_X11 EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) { // Create the native drawable for the paint device. @@ -607,7 +608,7 @@ EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglPr } return surf; } - +#endif // Return the error string associated with a specific code. diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index 49c8d60..b710889 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -49,6 +49,7 @@ #include #include #include +#include #include "qegl_p.h" #include "qeglcontext_p.h" @@ -261,5 +262,125 @@ VisualID QEgl::getCompatibleVisualId(EGLConfig config) return (VisualID)0; } +void qt_set_winid_on_widget(QWidget* w, Qt::HANDLE id) +{ + w->create(id); +} + + +// NOTE: The X11 version of createSurface will re-create the native drawable if it's visual doesn't +// match the one for the passed in EGLConfig +EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig config, const QEglProperties *unusedProperties) +{ + Q_UNUSED(unusedProperties); + + int devType = device->devType(); + + if (devType == QInternal::Pbuffer) { + // TODO + return EGL_NO_SURFACE; + } + + QX11PixmapData *x11PixmapData = 0; + if (devType == QInternal::Pixmap) { + QPixmapData *pmd = static_cast(device)->data_ptr().data(); + if (pmd->classId() == QPixmapData::X11Class) + x11PixmapData = static_cast(pmd); + else { + // TODO: Replace the pixmap's data with a new QX11PixmapData + qWarning("WARNING: Creating an EGL surface on a QPixmap is only supported for QX11PixmapData"); + return EGL_NO_SURFACE; + } + } else if ((devType != QInternal::Widget) && (devType != QInternal::Pbuffer)) { + qWarning("WARNING: Creating an EGLSurface for device type %d isn't supported", devType); + return EGL_NO_SURFACE; + } + + VisualID visualId = QEgl::getCompatibleVisualId(config); + EGLint alphaSize; + eglGetConfigAttrib(QEgl::display(), config, EGL_ALPHA_SIZE, &alphaSize); + + if (devType == QInternal::Widget) { + QWidget *widget = static_cast(device); + + VisualID currentVisualId = 0; + if (widget->testAttribute(Qt::WA_WState_Created)) + currentVisualId = XVisualIDFromVisual((Visual*)widget->x11Info().visual()); + + if (currentVisualId != visualId) { + // The window is either not created or has the wrong visual. Either way, we need + // to create a window with the correct visual and call create() on the widget: + + bool visible = widget->isVisible(); + if (visible) + widget->hide(); + + XVisualInfo visualInfo; + visualInfo.visualid = visualId; + { + XVisualInfo *visualInfoPtr; + int matchingCount = 0; + visualInfoPtr = XGetVisualInfo(widget->x11Info().display(), VisualIDMask, + &visualInfo, &matchingCount); + Q_ASSERT(visualInfoPtr); // visualId really should be valid! + visualInfo = *visualInfoPtr; + XFree(visualInfoPtr); + } + + Window parentWindow = RootWindow(widget->x11Info().display(), widget->x11Info().screen()); + if (widget->parentWidget()) + parentWindow = widget->parentWidget()->winId(); + + XSetWindowAttributes windowAttribs; + QColormap colmap = QColormap::instance(widget->x11Info().screen()); + windowAttribs.background_pixel = colmap.pixel(widget->palette().color(widget->backgroundRole())); + windowAttribs.border_pixel = colmap.pixel(Qt::black); + + unsigned int valueMask = CWBackPixel|CWBorderPixel; + if (alphaSize > 0) { + windowAttribs.colormap = XCreateColormap(widget->x11Info().display(), parentWindow, + visualInfo.visual, AllocNone); + valueMask |= CWColormap; + } + + Window window = XCreateWindow(widget->x11Info().display(), parentWindow, + widget->x(), widget->y(), widget->width(), widget->height(), + 0, visualInfo.depth, InputOutput, visualInfo.visual, + valueMask, &windowAttribs); + + // This is a nasty hack to get round the fact that we can't be a friend of QWidget: + qt_set_winid_on_widget(widget, window); + + if (visible) + widget->show(); + } + + // At this point, the widget's window should be created and have the correct visual. Now we + // just need to create the EGL surface for it: + return eglCreateWindowSurface(QEgl::display(), config, (EGLNativeWindowType)widget->winId(), 0); + } + + if (x11PixmapData) { + VisualID currentVisualId = XVisualIDFromVisual((Visual*)qt_x11Info(device)->visual()); + if (visualId != currentVisualId) + qWarning("Error: The QPixmap's visual does not match the EGLConfig's visual!"); + + QEglProperties surfaceAttribs; + + // If the pixmap can't be bound to a texture, it's pretty useless + surfaceAttribs.setValue(EGL_TEXTURE_TARGET, EGL_TEXTURE_2D); + if (alphaSize > 0) + surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA); + else + surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGB); + + return eglCreatePixmapSurface(QEgl::display(), config, + (EGLNativePixmapType) x11PixmapData->handle(), + surfaceAttribs.properties()); + } + + return EGL_NO_SURFACE; +} + QT_END_NAMESPACE diff --git a/src/gui/image/qpixmap_x11_p.h b/src/gui/image/qpixmap_x11_p.h index 0c0a9bd..7bc586d 100644 --- a/src/gui/image/qpixmap_x11_p.h +++ b/src/gui/image/qpixmap_x11_p.h @@ -105,6 +105,7 @@ private: friend class QRasterWindowSurface; friend class QGLContextPrivate; // Needs to access xinfo, gl_surface & flags friend class QEglContext; // Needs gl_surface + friend class QGLContext; // Needs gl_surface friend class QX11GLPixmapData; // Needs gl_surface friend bool qt_createEGLSurfaceForPixmap(QPixmapData*, bool); // Needs gl_surface diff --git a/src/gui/kernel/qwidget.h b/src/gui/kernel/qwidget.h index 0d7475e9..e12148b 100644 --- a/src/gui/kernel/qwidget.h +++ b/src/gui/kernel/qwidget.h @@ -773,6 +773,7 @@ private: #ifdef Q_WS_X11 friend void qt_net_update_user_time(QWidget *tlw, unsigned long timestamp); friend void qt_net_remove_user_time(QWidget *tlw); + friend void qt_set_winid_on_widget(QWidget*, Qt::HANDLE); #endif friend Q_GUI_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget); diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 7be4973..18a2ee5 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -48,6 +48,7 @@ #include "qgl_egl_p.h" #include "qcolormap.h" #include +#include QT_BEGIN_NAMESPACE @@ -164,55 +165,53 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) int devType = device()->devType(); - // Get the display and initialize it. + QX11PixmapData *x11PixmapData = 0; + if (devType == QInternal::Pixmap) { + QPixmapData *pmd = static_cast(device())->data_ptr().data(); + if (pmd->classId() == QPixmapData::X11Class) + x11PixmapData = static_cast(pmd); + else { + // TODO: Replace the pixmap's data with a new QX11PixmapData + qWarning("WARNING: Creating a QGLContext on a QPixmap is only supported for X11 pixmap backend"); + return false; + } + } else if ((devType != QInternal::Widget) && (devType != QInternal::Pbuffer)) { + qWarning("WARNING: Creating a QGLContext not supported on device type %d", devType); + return false; + } + + // Only create the eglContext if we don't already have one: if (d->eglContext == 0) { d->eglContext = new QEglContext(); d->eglContext->setApi(QEgl::OpenGL); + // If the device is a widget with WA_TranslucentBackground set, make sure the glFormat + // has the alpha channel option set: + if (devType == QInternal::Widget) { + QWidget* widget = static_cast(device()); + if (widget->testAttribute(Qt::WA_TranslucentBackground)) + d->glFormat.setAlpha(true); + } + // Construct the configuration we need for this surface. QEglProperties configProps; - qt_eglproperties_set_glformat(configProps, d->glFormat); configProps.setDeviceType(devType); - configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); + qt_eglproperties_set_glformat(configProps, d->glFormat); -#if We_have_an_EGL_library_which_bothers_to_check_EGL_BUFFER_SIZE - if (device()->depth() == 16 && configProps.value(EGL_ALPHA_SIZE) <= 0) { - qDebug("Setting EGL_BUFFER_SIZE to 16"); + // Use EGL_BUFFER_SIZE to make sure we prefer a 16-bit config over a 32-bit config + if (device()->depth() == 16 && !d->glFormat.alpha()) configProps.setValue(EGL_BUFFER_SIZE, 16); - configProps.setValue(EGL_ALPHA_SIZE, 0); - } if (!d->eglContext->chooseConfig(configProps, QEgl::BestPixelFormat)) { delete d->eglContext; d->eglContext = 0; return false; } -#else - QEgl::PixelFormatMatch matchType = QEgl::BestPixelFormat; - if ((device()->depth() == 16) && configProps.value(EGL_ALPHA_SIZE) == 0) { - configProps.setValue(EGL_RED_SIZE, 5); - configProps.setValue(EGL_GREEN_SIZE, 6); - configProps.setValue(EGL_BLUE_SIZE, 5); - configProps.setValue(EGL_ALPHA_SIZE, 0); - matchType = QEgl::ExactPixelFormat; - } - - // Search for a matching configuration, reducing the complexity - // each time until we get something that matches. - if (!d->eglContext->chooseConfig(configProps, matchType)) { - delete d->eglContext; - d->eglContext = 0; - return false; - } -#endif - -// qDebug("QGLContext::chooseContext() - using EGL config %d:", d->eglContext->config()); -// qDebug() << QEglProperties(d->eglContext->config()).toString(); // Create a new context for the configuration. - if (!d->eglContext->createContext - (shareContext ? shareContext->d_func()->eglContext : 0)) { + QEglContext* eglSharedContext = shareContext ? shareContext->d_func()->eglContext : 0; + if (!d->eglContext->createContext(eglSharedContext)) { delete d->eglContext; d->eglContext = 0; return false; @@ -220,16 +219,34 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) d->sharing = d->eglContext->isSharing(); if (d->sharing && shareContext) const_cast(shareContext)->d_func()->sharing = true; - -#if defined(EGL_VERSION_1_1) - if (d->glFormat.swapInterval() != -1 && devType == QInternal::Widget) - eglSwapInterval(d->eglContext->display(), d->glFormat.swapInterval()); -#endif } // Inform the higher layers about the actual format properties. qt_egl_update_format(*(d->eglContext), d->glFormat); + + // Do don't create the EGLSurface for everything. + // QWidget - yes, create the EGLSurface and store it in QGLContextPrivate::eglSurface + // QGLWidget - yes, create the EGLSurface and store it in QGLContextPrivate::eglSurface + // QPixmap - yes, create the EGLSurface but store it in QX11PixmapData::gl_surface + // QGLPixelBuffer - no, it creates the surface itself + + if (devType == QInternal::Widget) { + if (d->eglSurface != EGL_NO_SURFACE) + eglDestroySurface(d->eglContext->display(), d->eglSurface); + d->eglSurface = QEgl::createSurface(device(), d->eglContext->config()); + XFlush(X11->display); + setWindowCreated(true); + } + + if (x11PixmapData) { + // TODO: Actually check to see if the existing surface can be re-used + if (x11PixmapData->gl_surface) + eglDestroySurface(d->eglContext->display(), (EGLSurface)x11PixmapData->gl_surface); + + x11PixmapData->gl_surface = (Qt::HANDLE)QEgl::createSurface(device(), d->eglContext->config()); + } + return true; } @@ -277,20 +294,6 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, QGLContext* oldcx = d->glcx; d->glcx = context; - if (parentWidget()) { - // force creation of delay-created widgets - parentWidget()->winId(); - if (parentWidget()->x11Info().screen() != x11Info().screen()) - d_func()->xinfo = parentWidget()->d_func()->xinfo; - } - - // If the application has set WA_TranslucentBackground and not explicitly set - // the alpha buffer size to zero, modify the format so it have an alpha channel - QGLFormat& fmt = d->glcx->d_func()->glFormat; - const bool tryArgbVisual = testAttribute(Qt::WA_TranslucentBackground) || fmt.alpha(); - if (tryArgbVisual && fmt.alphaBufferSize() == -1) - fmt.setAlphaBufferSize(1); - bool createFailed = false; if (!d->glcx->isValid()) { // Create the QGLContext here, which in turn chooses the EGL config @@ -304,74 +307,8 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, return; } - if (d->glcx->windowCreated() || d->glcx->deviceIsPixmap()) { - if (deleteOldContext) - delete oldcx; - return; - } - - bool visible = isVisible(); - if (visible) - hide(); - - QEglContext *eglContext = d->glcx->d_func()->eglContext; - - XVisualInfo vi; - memset(&vi, 0, sizeof(XVisualInfo)); - vi.visualid = QEgl::getCompatibleVisualId(eglContext->config()); - - { - XVisualInfo *visualInfoPtr; - int matchingCount = 0; - visualInfoPtr = XGetVisualInfo(X11->display, VisualIDMask, &vi, &matchingCount); - vi = *visualInfoPtr; - XFree(visualInfoPtr); - } - - bool usingArgbVisual = eglContext->configAttrib(EGL_ALPHA_SIZE) > 0; - - XSetWindowAttributes a; - - Window p = RootWindow(x11Info().display(), x11Info().screen()); - if (parentWidget()) - p = parentWidget()->winId(); - - QColormap colmap = QColormap::instance(vi.screen); - a.background_pixel = colmap.pixel(palette().color(backgroundRole())); - a.border_pixel = colmap.pixel(Qt::black); - - unsigned int valueMask = CWBackPixel|CWBorderPixel; - if (usingArgbVisual) { - a.colormap = XCreateColormap(x11Info().display(), p, vi.visual, AllocNone); - valueMask |= CWColormap; - } - - Window w = XCreateWindow(x11Info().display(), p, x(), y(), width(), height(), - 0, vi.depth, InputOutput, vi.visual, valueMask, &a); - - if (deleteOldContext) - delete oldcx; - oldcx = 0; - - create(w); // Create with the ID of the window we've just created - - - // Create the EGL surface to draw into. - QGLContextPrivate *ctxpriv = d->glcx->d_func(); - ctxpriv->eglSurface = ctxpriv->eglContext->createSurface(this); - if (ctxpriv->eglSurface == EGL_NO_SURFACE) { - delete ctxpriv->eglContext; - ctxpriv->eglContext = 0; - return; - } - - d->eglSurfaceWindowId = w; // Remember the window id we created the surface for - - if (visible) - show(); - XFlush(X11->display); - d->glcx->setWindowCreated(true); + d->eglSurfaceWindowId = winId(); // Remember the window id we created the surface for } void QGLWidgetPrivate::init(QGLContext *context, const QGLWidget* shareWidget) @@ -380,7 +317,7 @@ void QGLWidgetPrivate::init(QGLContext *context, const QGLWidget* shareWidget) initContext(context, shareWidget); - if(q->isValid() && glcx->format().hasOverlay()) { + if (q->isValid() && glcx->format().hasOverlay()) { //no overlay qWarning("QtOpenGL ES doesn't currently support overlays"); } diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 0334cbc..ca88de3 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -353,18 +353,6 @@ void QGLWindowSurface::hijackWindow(QWidget *widget) QGLContext *ctx = new QGLContext(surfaceFormat, widget); ctx->create(qt_gl_share_widget()->context()); -#if defined(Q_WS_X11) && defined(QT_OPENGL_ES) - // Create the EGL surface to draw into. QGLContext::chooseContext() - // does not do this for X11/EGL, but does do it for other platforms. - // This probably belongs in qgl_x11egl.cpp. - QGLContextPrivate *ctxpriv = ctx->d_func(); - ctxpriv->eglSurface = ctxpriv->eglContext->createSurface(widget); - if (ctxpriv->eglSurface == EGL_NO_SURFACE) { - qWarning() << "hijackWindow() could not create EGL surface"; - } - qDebug("QGLWindowSurface - using EGLConfig %d", reinterpret_cast(ctxpriv->eglContext->config())); -#endif - widgetPrivate->extraData()->glContext = ctx; union { QGLContext **ctxPtr; void **voidPtr; }; -- cgit v0.12 From 9c1ff07b427765beb71755e964b017d8258b834e Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Mon, 1 Mar 2010 16:53:17 +0100 Subject: Make bindTextureFromNativePixmap use new QEgl APIs The old qt_chooseEGLConfigForPixmap & qt_createEGLSurfaceForPixmap code will remain until QX11GLPixmapData can be re-written properly. Reviewed-By: TrustMe --- src/gui/egl/qegl.cpp | 8 +++----- src/gui/egl/qegl_p.h | 6 ++---- src/gui/egl/qegl_x11.cpp | 23 ++++++++++++++++++++--- src/gui/image/qpixmap_x11.cpp | 4 ++-- src/gui/image/qpixmap_x11_p.h | 9 +++++---- src/opengl/qgl_x11egl.cpp | 9 +++++++-- 6 files changed, 39 insertions(+), 20 deletions(-) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index e2002ed..1bfba10 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -88,10 +88,8 @@ bool QEglContext::isCurrent() const return current; } -EGLConfig QEgl::defaultConfig(QPaintDevice* device, API api, ConfigOptions options) +EGLConfig QEgl::defaultConfig(int devType, API api, ConfigOptions options) { - int devType = device->devType(); - if ( (devType != QInternal::Pixmap) && ((options & Renderable) == 0)) qWarning("QEgl::defaultConfig() - Only configs for pixmaps make sense to be read-only!"); @@ -243,8 +241,8 @@ EGLConfig QEgl::defaultConfig(QPaintDevice* device, API api, ConfigOptions optio #endif } - // Finally, set the color format based on the device: - configAttribs.setPaintDeviceFormat(device); + if (options & Translucent) + configAttribs.setValue(EGL_ALPHA_SIZE, 1); *targetConfig = chooseConfig(&configAttribs, QEgl::BestPixelFormat); return *targetConfig; diff --git a/src/gui/egl/qegl_p.h b/src/gui/egl/qegl_p.h index 7f753d0..aa89772 100644 --- a/src/gui/egl/qegl_p.h +++ b/src/gui/egl/qegl_p.h @@ -116,10 +116,8 @@ namespace QEgl { enum ConfigOptions { - Opaque = 0x00, + NoOptions = 0, Translucent = 0x01, - - ReadOnly = 0x00, Renderable = 0x02 // Config will be compatable with the paint engines (VG or GL) }; @@ -127,7 +125,7 @@ namespace QEgl { // go through the eglChooseConfig loop every time, we use defaultConfig, which will return // the config for a particular device/api/option combo. This function assumes that once a // config is chosen for a particular combo, it's safe to always use that combo. - Q_GUI_EXPORT EGLConfig defaultConfig(QPaintDevice* device, API api, ConfigOptions options); + Q_GUI_EXPORT EGLConfig defaultConfig(int devType, API api, ConfigOptions options); Q_GUI_EXPORT EGLConfig chooseConfig(const QEglProperties* configAttribs, QEgl::PixelFormatMatch match = QEgl::ExactPixelFormat); Q_GUI_EXPORT EGLSurface createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *surfaceAttribs = 0); diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index b710889..a4bfcac 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -361,9 +361,26 @@ EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig config, const QEg } if (x11PixmapData) { - VisualID currentVisualId = XVisualIDFromVisual((Visual*)qt_x11Info(device)->visual()); - if (visualId != currentVisualId) - qWarning("Error: The QPixmap's visual does not match the EGLConfig's visual!"); + // X11 Pixmaps are only created with a depth, so that's all we need to check + EGLint configDepth; + eglGetConfigAttrib(QEgl::display(), config, EGL_BUFFER_SIZE , &configDepth); + if (x11PixmapData->depth() != configDepth) { + // The bit depths are wrong which means the EGLConfig isn't compatable with + // this pixmap. So we need to replace the pixmap's existing data with a new + // one which is created with the correct depth: + +#ifndef QT_NO_XRENDER + if (configDepth == 32) { + qWarning("Warning: EGLConfig's depth (32) != pixmap's depth (%d), converting to ARGB32", + x11PixmapData->depth()); + x11PixmapData->convertToARGB32(true); + } else +#endif + { + qWarning("Warning: EGLConfig's depth (%d) != pixmap's depth (%d)", + configDepth, x11PixmapData->depth()); + } + } QEglProperties surfaceAttribs; diff --git a/src/gui/image/qpixmap_x11.cpp b/src/gui/image/qpixmap_x11.cpp index b976376..5a882af 100644 --- a/src/gui/image/qpixmap_x11.cpp +++ b/src/gui/image/qpixmap_x11.cpp @@ -314,8 +314,8 @@ static int qt_pixmap_serial = 0; int Q_GUI_EXPORT qt_x11_preferred_pixmap_depth = 0; QX11PixmapData::QX11PixmapData(PixelType type) - : QPixmapData(type, X11Class), hd(0), - flags(Uninitialized), x11_mask(0), picture(0), mask_picture(0), hd2(0), gl_surface(0), + : QPixmapData(type, X11Class), gl_surface(0), hd(0), + flags(Uninitialized), x11_mask(0), picture(0), mask_picture(0), hd2(0), share_mode(QPixmap::ImplicitlyShared), pengine(0) { } diff --git a/src/gui/image/qpixmap_x11_p.h b/src/gui/image/qpixmap_x11_p.h index 7bc586d..521a612 100644 --- a/src/gui/image/qpixmap_x11_p.h +++ b/src/gui/image/qpixmap_x11_p.h @@ -94,6 +94,11 @@ public: static Qt::HANDLE createBitmapFromImage(const QImage &image); + Qt::HANDLE gl_surface; +#ifndef QT_NO_XRENDER + void convertToARGB32(bool preserveContents = true); +#endif + protected: int metric(QPaintDevice::PaintDeviceMetric metric) const; @@ -131,10 +136,6 @@ private: Qt::HANDLE picture; Qt::HANDLE mask_picture; Qt::HANDLE hd2; // sorted in the default display depth - Qt::HANDLE gl_surface; -#ifndef QT_NO_XRENDER - void convertToARGB32(bool preserveContents = true); -#endif QPixmap::ShareMode share_mode; QX11PaintEngine *pengine; diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 18a2ee5..bcde8c4 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -508,8 +508,13 @@ QGLTexture *QGLContextPrivate::bindTextureFromNativePixmap(QPixmapData* pd, cons } if (pixmapData->gl_surface == 0) { - bool success = qt_createEGLSurfaceForPixmap(pixmapData, true); - if (!success) { + EGLConfig config = QEgl::defaultConfig(QInternal::Pixmap, + QEgl::OpenGL, + hasAlpha ? QEgl::Translucent : QEgl::NoOptions); + + QPixmap tmpPixmap(pixmapData); //### + pixmapData->gl_surface = (Qt::HANDLE)QEgl::createSurface(&tmpPixmap, config); + if (pixmapData->gl_surface == (Qt::HANDLE)EGL_NO_SURFACE) { haveTFP = false; return 0; } -- cgit v0.12 From 5363237c164667aa38433eefe8646aafee328b59 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 2 Mar 2010 09:40:55 +0100 Subject: qdoc: Second attempt, QML doc stuff. This change caused a crash on several platforms before, but not on mine, of course. It outputs a list of new QML elements on the What's New in 4.7 page, and it outputs the "Inherited by" list on each QML elemnent page for elements that are inherited by other elements. I can't see why it should crash anything, but I have included some debug output. I think the crash might have something to do with QList, which qdoc3 uses heavily. If it crashes for you, please get a stack trace and the debug output. --- tools/qdoc3/cppcodeparser.cpp | 2 +- tools/qdoc3/generator.cpp | 29 +++++++++++++++++++++ tools/qdoc3/generator.h | 7 +++++ tools/qdoc3/htmlgenerator.cpp | 60 +++++++++++++++++++++++-------------------- tools/qdoc3/htmlgenerator.h | 2 ++ tools/qdoc3/node.cpp | 9 ++++--- tools/qdoc3/node.h | 6 ++--- 7 files changed, 79 insertions(+), 36 deletions(-) diff --git a/tools/qdoc3/cppcodeparser.cpp b/tools/qdoc3/cppcodeparser.cpp index 021d64a..d9e9c3b 100644 --- a/tools/qdoc3/cppcodeparser.cpp +++ b/tools/qdoc3/cppcodeparser.cpp @@ -1034,7 +1034,7 @@ void CppCodeParser::processOtherMetaCommand(const Doc& doc, else if (command == COMMAND_QMLINHERITS) { setLink(node, Node::InheritsLink, arg); if (node->subType() == Node::QmlClass) { - QmlClassNode::addInheritedBy(arg,node->name()); + QmlClassNode::addInheritedBy(arg,node); } } else if (command == COMMAND_QMLDEFAULT) { diff --git a/tools/qdoc3/generator.cpp b/tools/qdoc3/generator.cpp index 6a8899a..40fd0e2 100644 --- a/tools/qdoc3/generator.cpp +++ b/tools/qdoc3/generator.cpp @@ -1186,6 +1186,35 @@ void Generator::appendSortedNames(Text& text, } } +void Generator::appendSortedQmlNames(Text& text, + const Node* base, + const NodeList& subs, + CodeMarker *marker) +{ + NodeList::ConstIterator r; + QMap classMap; + int index = 0; + + qDebug() << "Generator::appendSortedQmlNames():" << base->name() << "is inherited by..."; + + r = subs.begin(); + while (r != subs.end()) { + Text t; + qDebug() << " " << (*r)->name(); + appendFullName(t, (*r), base, marker); + classMap[t.toString().toLower()] = t; + ++r; + } + + QStringList names = classMap.keys(); + names.sort(); + + foreach (const QString &name, names) { + text << classMap[name]; + text << separator(index++, names.count()); + } +} + int Generator::skipAtoms(const Atom *atom, Atom::Type type) const { int skipAhead = 0; diff --git a/tools/qdoc3/generator.h b/tools/qdoc3/generator.h index 44f56e2..30d9af4 100644 --- a/tools/qdoc3/generator.h +++ b/tools/qdoc3/generator.h @@ -169,6 +169,13 @@ class Generator const QList &classes, CodeMarker *marker); + protected: + void appendSortedQmlNames(Text& text, + const Node* base, + const NodeList& subs, + CodeMarker *marker); + + private: QString amp; QString lt; QString gt; diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index e767460..411a886 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -73,6 +73,7 @@ QString HtmlGenerator::sinceTitles[] = " New Typedefs", " New Properties", " New Variables", + " New QML Elements", " New Qml Properties", " New Qml Signals", " New Qml Methods", @@ -687,6 +688,8 @@ int HtmlGenerator::generateAtom(const Atom *atom, nsmap = newSinceMaps.find(atom->string()); NewClassMaps::const_iterator ncmap; ncmap = newClassMaps.find(atom->string()); + NewClassMaps::const_iterator nqcmap; + nqcmap = newQmlClassMaps.find(atom->string()); if ((nsmap != newSinceMaps.constEnd()) && !nsmap.value().isEmpty()) { QList
sections; QList
::ConstIterator s; @@ -697,6 +700,13 @@ int HtmlGenerator::generateAtom(const Atom *atom, while (n != nsmap.value().constEnd()) { const Node* node = n.value(); switch (node->type()) { + case Node::Fake: + if (node->subType() == Node::QmlClass) { + sections[QmlClass].appendMember((Node*)node); + //qDebug() << "HtmlGenerator::generateAtom(): Atom::SinceList, append" + // << node->name(); + } + break; case Node::Namespace: sections[Namespace].appendMember((Node*)node); break; @@ -782,6 +792,8 @@ int HtmlGenerator::generateAtom(const Atom *atom, out() << "

" << protectEnc((*s).name) << "

\n"; if (idx == Class) generateCompactList(0, marker, ncmap.value(), QString("Q")); + else if (idx == QmlClass) + generateCompactList(0, marker, nqcmap.value(), QString("Q")); else if (idx == MemberFunction) { ParentMaps parentmaps; ParentMaps::iterator pmap; @@ -2332,7 +2344,11 @@ void HtmlGenerator::generateCompactList(const Node *relative, out() << ""; - QStringList pieces = fullName(it.value(), relative, marker).split("::"); + QStringList pieces; + if (it.value()->subType() == Node::QmlClass) + pieces << it.value()->name(); + else + pieces = fullName(it.value(), relative, marker).split("::"); out() << protectEnc(pieces.last()); out() << ""; if (pieces.size() > 1) { @@ -3723,6 +3739,9 @@ void HtmlGenerator::findAllSince(const InnerNode *node) NewClassMaps::iterator ncmap = newClassMaps.find(sinceVersion); if (ncmap == newClassMaps.end()) ncmap = newClassMaps.insert(sinceVersion,NodeMap()); + NewClassMaps::iterator nqcmap = newQmlClassMaps.find(sinceVersion); + if (nqcmap == newQmlClassMaps.end()) + nqcmap = newQmlClassMaps.insert(sinceVersion,NodeMap()); if ((*child)->type() == Node::Function) { FunctionNode *func = static_cast(*child); @@ -3742,6 +3761,16 @@ void HtmlGenerator::findAllSince(const InnerNode *node) nsmap.value().insert(className,(*child)); ncmap.value().insert(className,(*child)); } + else if ((*child)->subType() == Node::QmlClass) { + QString className = (*child)->name(); + if ((*child)->parent() && + (*child)->parent()->type() == Node::Namespace && + !(*child)->parent()->name().isEmpty()) + className = (*child)->parent()->name()+"::"+className; + nsmap.value().insert(className,(*child)); + nqcmap.value().insert(className,(*child)); + //qDebug() << "findAllSince(): insert" << className << sinceVersion; + } } else { QString name = (*child)->name(); @@ -4316,40 +4345,15 @@ void HtmlGenerator::generateQmlInheritedBy(const QmlClassNode* cn, CodeMarker* marker) { if (cn) { - QStringList subs; + NodeList subs; QmlClassNode::subclasses(cn->name(),subs); if (!subs.isEmpty()) { - subs.sort(); Text text; text << Atom::ParaLeft << "Inherited by "; - for (int i = 0; i < subs.size(); ++i) { - text << subs.at(i); - text << separator(i, subs.size()); - } + appendSortedQmlNames(text,cn,subs,marker); text << Atom::ParaRight; generateText(text, cn, marker); } -#if 0 - if (cn->links().contains(Node::InheritsLink)) { - QPair linkPair; - linkPair = cn->links()[Node::InheritsLink]; - QStringList strList(linkPair.first); - const Node* n = myTree->findNode(strList,Node::Fake); - if (n && n->subType() == Node::QmlClass) { - const QmlClassNode* qcn = static_cast(n); - out() << "

"; - Text text; - text << "[Inherits "; - text << Atom(Atom::LinkNode,CodeMarker::stringForNode(qcn)); - text << Atom(Atom::FormattingLeft, ATOM_FORMATTING_LINK); - text << Atom(Atom::String, linkPair.second); - text << Atom(Atom::FormattingRight, ATOM_FORMATTING_LINK); - text << "]"; - generateText(text, cn, marker); - out() << "

"; - } - } -#endif } } diff --git a/tools/qdoc3/htmlgenerator.h b/tools/qdoc3/htmlgenerator.h index 551bead..8fe0331 100644 --- a/tools/qdoc3/htmlgenerator.h +++ b/tools/qdoc3/htmlgenerator.h @@ -90,6 +90,7 @@ class HtmlGenerator : public PageGenerator Typedef, Property, Variable, + QmlClass, QmlProperty, QmlSignal, QmlMethod, @@ -326,6 +327,7 @@ class HtmlGenerator : public PageGenerator NewSinceMaps newSinceMaps; static QString sinceTitles[]; NewClassMaps newClassMaps; + NewClassMaps newQmlClassMaps; static int id; }; diff --git a/tools/qdoc3/node.cpp b/tools/qdoc3/node.cpp index 358fdd1..d2ffff5 100644 --- a/tools/qdoc3/node.cpp +++ b/tools/qdoc3/node.cpp @@ -1257,7 +1257,7 @@ bool TargetNode::isInnerNode() const #ifdef QDOC_QML bool QmlClassNode::qmlOnly = false; -QMultiMap QmlClassNode::inheritedBy; +QMultiMap QmlClassNode::inheritedBy; /*! Constructs a Qml class node (i.e. a Fake node with the @@ -1302,15 +1302,16 @@ QString QmlClassNode::fileBase() const Record the fact that QML class \a base is inherited by QML class \a sub. */ -void QmlClassNode::addInheritedBy(const QString& base, const QString& sub) +void QmlClassNode::addInheritedBy(const QString& base, Node* sub) { + //qDebug() << "QmlClassNode::addInheritedBy(): insert" << base << sub->name(); inheritedBy.insert(base,sub); } /*! - Loads the list \a subs with the names of all the subclasses of \a base. + Loads the list \a subs with the nodes of all the subclasses of \a base. */ -void QmlClassNode::subclasses(const QString& base, QStringList& subs) +void QmlClassNode::subclasses(const QString& base, NodeList& subs) { subs.clear(); if (inheritedBy.contains(base)) diff --git a/tools/qdoc3/node.h b/tools/qdoc3/node.h index ae5dcd7..fd39698 100644 --- a/tools/qdoc3/node.h +++ b/tools/qdoc3/node.h @@ -383,12 +383,12 @@ class QmlClassNode : public FakeNode const ClassNode* classNode() const { return cnode; } virtual QString fileBase() const; - static void addInheritedBy(const QString& base, const QString& sub); - static void subclasses(const QString& base, QStringList& subs); + static void addInheritedBy(const QString& base, Node* sub); + static void subclasses(const QString& base, NodeList& subs); public: static bool qmlOnly; - static QMultiMap inheritedBy; + static QMultiMap inheritedBy; private: const ClassNode* cnode; -- cgit v0.12 From d0c4433ca1aabab1a8fac1aae2ba65f25dae5f85 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 2 Mar 2010 10:19:21 +0100 Subject: doc: Fixed some qdoc errors. --- src/declarative/graphicsitems/qdeclarativeitem.cpp | 2 +- src/network/bearer/qnetworksession.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/graphicsitems/qdeclarativeitem.cpp b/src/declarative/graphicsitems/qdeclarativeitem.cpp index f48c761..5014fd8 100644 --- a/src/declarative/graphicsitems/qdeclarativeitem.cpp +++ b/src/declarative/graphicsitems/qdeclarativeitem.cpp @@ -1172,7 +1172,7 @@ QDeclarativeKeysAttached *QDeclarativeKeysAttached::qmlAttachedProperties(QObjec See the \l {Keys}{Keys} attached property for detailed documentation. - \section 1 Property Change Signals + \section1 Property Change Signals Most properties on Item and Item derivatives have a signal emitted when they change. By convention, the signals are diff --git a/src/network/bearer/qnetworksession.cpp b/src/network/bearer/qnetworksession.cpp index f0d7ede..047c8d3 100644 --- a/src/network/bearer/qnetworksession.cpp +++ b/src/network/bearer/qnetworksession.cpp @@ -527,7 +527,7 @@ QVariant QNetworkSession::sessionProperty(const QString& key) const \a key. Removing an already set property can be achieved by passing an invalid QVariant. - Note that the \i UserChoiceConfiguration and \i ActiveConfiguration + Note that the \e UserChoiceConfiguration and \e ActiveConfiguration properties are read only and cannot be changed using this method. */ void QNetworkSession::setSessionProperty(const QString& key, const QVariant& value) -- cgit v0.12 From f1412745126db129445a368525f7ec05b20a0885 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Mar 2010 18:45:02 +1000 Subject: Empty URL test --- src/declarative/qml/qdeclarativecomponent.cpp | 7 ++ tests/auto/declarative/declarative.pro | 1 + .../qdeclarativecomponent.pro | 8 +++ .../tst_qdeclarativecomponent.cpp | 75 ++++++++++++++++++++++ 4 files changed, 91 insertions(+) create mode 100644 tests/auto/declarative/qdeclarativecomponent/qdeclarativecomponent.pro create mode 100644 tests/auto/declarative/qdeclarativecomponent/tst_qdeclarativecomponent.cpp diff --git a/src/declarative/qml/qdeclarativecomponent.cpp b/src/declarative/qml/qdeclarativecomponent.cpp index 6a2d2d1..d6bb216 100644 --- a/src/declarative/qml/qdeclarativecomponent.cpp +++ b/src/declarative/qml/qdeclarativecomponent.cpp @@ -437,6 +437,13 @@ void QDeclarativeComponent::loadUrl(const QUrl &url) else d->url = url; + if (url.isEmpty()) { + QDeclarativeError error; + error.setDescription(tr("Invalid empty URL")); + d->state.errors << error; + return; + } + QDeclarativeCompositeTypeData *data = QDeclarativeEnginePrivate::get(d->engine)->typeManager.get(d->url); diff --git a/tests/auto/declarative/declarative.pro b/tests/auto/declarative/declarative.pro index 42ff523..4ee6d8c 100644 --- a/tests/auto/declarative/declarative.pro +++ b/tests/auto/declarative/declarative.pro @@ -7,6 +7,7 @@ SUBDIRS += \ qdeclarativeanimations \ # Cover qdeclarativebehaviors \ # Cover qdeclarativebinding \ # Cover + qdeclarativecomponent \ # Cover qdeclarativeconnection \ # Cover qdeclarativecontext \ # Cover qdeclarativedatetimeformatter \ # Cover diff --git a/tests/auto/declarative/qdeclarativecomponent/qdeclarativecomponent.pro b/tests/auto/declarative/qdeclarativecomponent/qdeclarativecomponent.pro new file mode 100644 index 0000000..c7affb7 --- /dev/null +++ b/tests/auto/declarative/qdeclarativecomponent/qdeclarativecomponent.pro @@ -0,0 +1,8 @@ +load(qttest_p4) +contains(QT_CONFIG,declarative): QT += declarative +QT += script network +macx:CONFIG -= app_bundle + +SOURCES += tst_qdeclarativecomponent.cpp + +DEFINES += SRCDIR=\\\"$$PWD\\\" diff --git a/tests/auto/declarative/qdeclarativecomponent/tst_qdeclarativecomponent.cpp b/tests/auto/declarative/qdeclarativecomponent/tst_qdeclarativecomponent.cpp new file mode 100644 index 0000000..c9e304c --- /dev/null +++ b/tests/auto/declarative/qdeclarativecomponent/tst_qdeclarativecomponent.cpp @@ -0,0 +1,75 @@ +/**************************************************************************** +** +** 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 + +#include +#include + +class tst_qdeclarativecomponent : public QObject +{ + Q_OBJECT +public: + tst_qdeclarativecomponent() { } + +private slots: + void loadEmptyUrl(); + +private: + QDeclarativeEngine engine; +}; + +void tst_qdeclarativecomponent::loadEmptyUrl() +{ + QDeclarativeComponent c(&engine); + c.loadUrl(QUrl()); + + QVERIFY(c.isError()); + QCOMPARE(c.errors().count(), 1); + QDeclarativeError error = c.errors().first(); + QCOMPARE(error.url(), QUrl()); + QCOMPARE(error.line(), -1); + QCOMPARE(error.column(), -1); + QCOMPARE(error.description(), QLatin1String("Invalid empty URL")); +} + +QTEST_MAIN(tst_qdeclarativecomponent) + +#include "tst_qdeclarativecomponent.moc" -- cgit v0.12 From 3b8cad8be96d7791e8ca8305609d1155ec093b80 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Mar 2010 19:35:30 +1000 Subject: Don't return QDeclarativeDeclarativeData for a deleting object This was causing crashes in the qmldesigner. --- src/declarative/qml/qdeclarativedeclarativedata_p.h | 5 ++++- src/declarative/qml/qdeclarativeengine_p.h | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/declarative/qml/qdeclarativedeclarativedata_p.h b/src/declarative/qml/qdeclarativedeclarativedata_p.h index 2c92419..a7a73bc 100644 --- a/src/declarative/qml/qdeclarativedeclarativedata_p.h +++ b/src/declarative/qml/qdeclarativedeclarativedata_p.h @@ -103,7 +103,10 @@ public: static QDeclarativeDeclarativeData *get(const QObject *object, bool create = false) { QObjectPrivate *priv = QObjectPrivate::get(const_cast(object)); - if (priv->declarativeData) { + if (priv->wasDeleted) { + Q_ASSERT(!create); + return 0; + } else if (priv->declarativeData) { return static_cast(priv->declarativeData); } else if (create) { priv->declarativeData = new QDeclarativeDeclarativeData; diff --git a/src/declarative/qml/qdeclarativeengine_p.h b/src/declarative/qml/qdeclarativeengine_p.h index 0359f98..d3eb583 100644 --- a/src/declarative/qml/qdeclarativeengine_p.h +++ b/src/declarative/qml/qdeclarativeengine_p.h @@ -238,7 +238,8 @@ public: QHash propertyCache; QDeclarativePropertyCache *cache(QObject *obj) { Q_Q(QDeclarativeEngine); - if (!obj || QObjectPrivate::get(obj)->metaObject) return 0; + if (!obj || QObjectPrivate::get(obj)->metaObject || + QObjectPrivate::get(obj)->wasDeleted) return 0; const QMetaObject *mo = obj->metaObject(); QDeclarativePropertyCache *rv = propertyCache.value(mo); if (!rv) { -- cgit v0.12 From 6e84a270c94376d24392d797f99bc7e95b217a34 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Mar 2010 19:48:54 +1000 Subject: Add "on" syntax to QmlChanges.txt --- src/declarative/QmlChanges.txt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/declarative/QmlChanges.txt b/src/declarative/QmlChanges.txt index c312abf..4951cb3 100644 --- a/src/declarative/QmlChanges.txt +++ b/src/declarative/QmlChanges.txt @@ -53,6 +53,16 @@ matchProperties and matchTargets have been renamed back to properties and target The semantics are explained in the PropertyAnimation::properties documentation and the animation overview documentation. +Behavior and Animation syntax +----------------------------- + +Previously animations and behaviors could be "assigned" to properties like this: + Item { x: Behavior {}; y: NumberAnimation {} } +To make it more obvious that these are not regular value assignments a new "on" +syntax has been introduced: + Item { Behavior on x {}; NumberAnimation on y {} } +Only the syntax has changed, the behavior is identical. + ============================================================================= The changes below are pre-4.6.0 release. -- cgit v0.12 From 2d99a28a583b099cc0281b39b88b0bda8f5e5f7f Mon Sep 17 00:00:00 2001 From: mae Date: Tue, 2 Mar 2010 11:36:05 +0100 Subject: Moved qdeclarativemodules to imports --- src/declarative/declarative.pro | 28 +- src/declarative/imports/imports.pro | 7 + src/declarative/imports/multimedia/multimedia.cpp | 63 + src/declarative/imports/multimedia/multimedia.pro | 15 + src/declarative/imports/qimportbase.pri | 16 + src/declarative/imports/webkit/plugin.cpp | 66 + .../imports/webkit/qdeclarativewebview.cpp | 1340 ++++++++++++++++++++ .../imports/webkit/qdeclarativewebview_p.h | 285 +++++ .../imports/webkit/qdeclarativewebview_p_p.h | 151 +++ src/declarative/imports/webkit/webkit.pro | 18 + .../imports/widgets/graphicslayouts.cpp | 260 ++++ .../imports/widgets/graphicslayouts_p.h | 226 ++++ .../imports/widgets/graphicswidgets.cpp | 40 + .../imports/widgets/graphicswidgets_p.h | 68 + src/declarative/imports/widgets/widgets.cpp | 138 ++ src/declarative/imports/widgets/widgets.pro | 20 + src/declarative/libdeclarative.pro | 29 + src/plugins/plugins.pro | 1 - .../qdeclarativemodules/multimedia/multimedia.cpp | 63 - .../qdeclarativemodules/multimedia/multimedia.pro | 15 - .../qdeclarativemodules/qdeclarativemodules.pro | 7 - .../qdeclarativemodules/webkitqmlplugin/plugin.cpp | 66 - .../webkitqmlplugin/qdeclarativewebview.cpp | 1340 -------------------- .../webkitqmlplugin/qdeclarativewebview_p.h | 285 ----- .../webkitqmlplugin/qdeclarativewebview_p_p.h | 151 --- .../webkitqmlplugin/webkitqmlplugin.pro | 18 - .../widgets/graphicslayouts.cpp | 260 ---- .../widgets/graphicslayouts_p.h | 226 ---- .../widgets/graphicswidgets.cpp | 40 - .../widgets/graphicswidgets_p.h | 68 - .../qdeclarativemodules/widgets/widgets.cpp | 138 -- .../qdeclarativemodules/widgets/widgets.pro | 20 - 32 files changed, 2744 insertions(+), 2724 deletions(-) create mode 100644 src/declarative/imports/imports.pro create mode 100644 src/declarative/imports/multimedia/multimedia.cpp create mode 100644 src/declarative/imports/multimedia/multimedia.pro create mode 100644 src/declarative/imports/qimportbase.pri create mode 100644 src/declarative/imports/webkit/plugin.cpp create mode 100644 src/declarative/imports/webkit/qdeclarativewebview.cpp create mode 100644 src/declarative/imports/webkit/qdeclarativewebview_p.h create mode 100644 src/declarative/imports/webkit/qdeclarativewebview_p_p.h create mode 100644 src/declarative/imports/webkit/webkit.pro create mode 100644 src/declarative/imports/widgets/graphicslayouts.cpp create mode 100644 src/declarative/imports/widgets/graphicslayouts_p.h create mode 100644 src/declarative/imports/widgets/graphicswidgets.cpp create mode 100644 src/declarative/imports/widgets/graphicswidgets_p.h create mode 100644 src/declarative/imports/widgets/widgets.cpp create mode 100644 src/declarative/imports/widgets/widgets.pro create mode 100644 src/declarative/libdeclarative.pro delete mode 100644 src/plugins/qdeclarativemodules/multimedia/multimedia.cpp delete mode 100644 src/plugins/qdeclarativemodules/multimedia/multimedia.pro delete mode 100644 src/plugins/qdeclarativemodules/qdeclarativemodules.pro delete mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp delete mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp delete mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h delete mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h delete mode 100644 src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro delete mode 100644 src/plugins/qdeclarativemodules/widgets/graphicslayouts.cpp delete mode 100644 src/plugins/qdeclarativemodules/widgets/graphicslayouts_p.h delete mode 100644 src/plugins/qdeclarativemodules/widgets/graphicswidgets.cpp delete mode 100644 src/plugins/qdeclarativemodules/widgets/graphicswidgets_p.h delete mode 100644 src/plugins/qdeclarativemodules/widgets/widgets.cpp delete mode 100644 src/plugins/qdeclarativemodules/widgets/widgets.pro diff --git a/src/declarative/declarative.pro b/src/declarative/declarative.pro index 4287e25..a7ec18e 100644 --- a/src/declarative/declarative.pro +++ b/src/declarative/declarative.pro @@ -1,29 +1,5 @@ -TARGET = QtDeclarative -QPRO_PWD = $$PWD -QT = core gui xml script network -contains(QT_CONFIG, svg): QT += svg -contains(QT_CONFIG, opengl): QT += opengl -DEFINES += QT_BUILD_DECLARATIVE_LIB QT_NO_URL_CAST_FROM_STRING -win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x66000000 -solaris-cc*:QMAKE_CXXFLAGS_RELEASE -= -O2 +TEMPLATE = subdirs -unix:QMAKE_PKGCONFIG_REQUIRES = QtCore QtGui QtXml +SUBDIRS = libdeclarative.pro imports -exists("qdeclarative_enable_gcov") { - QMAKE_CXXFLAGS = -fprofile-arcs -ftest-coverage -fno-elide-constructors - LIBS += -lgcov -} -include(../qbase.pri) - -#INCLUDEPATH -= $$QMAKE_INCDIR_QT/$$TARGET -#DESTDIR=. - -#modules -include(3rdparty/3rdparty.pri) -include(util/util.pri) -include(graphicsitems/graphicsitems.pri) -include(qml/qml.pri) -include(debugger/debugger.pri) - -symbian:TARGET.UID3=0x2001E623 diff --git a/src/declarative/imports/imports.pro b/src/declarative/imports/imports.pro new file mode 100644 index 0000000..f874644 --- /dev/null +++ b/src/declarative/imports/imports.pro @@ -0,0 +1,7 @@ +TEMPLATE = subdirs + +SUBDIRS += widgets + +contains(QT_CONFIG, multimedia): SUBDIRS += multimedia +contains(QT_CONFIG, webkit): SUBDIRS += webkit + diff --git a/src/declarative/imports/multimedia/multimedia.cpp b/src/declarative/imports/multimedia/multimedia.cpp new file mode 100644 index 0000000..8becbf3 --- /dev/null +++ b/src/declarative/imports/multimedia/multimedia.cpp @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the plugins 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 +#include +#include + +QT_BEGIN_NAMESPACE + +class QMultimediaQmlModule : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + virtual void registerTypes(const char *uri) + { + QtMultimedia::qRegisterDeclarativeElements(uri); + } +}; + +QT_END_NAMESPACE + +#include "multimedia.moc" + +Q_EXPORT_PLUGIN2(qmultimediaqmlmodule, QT_PREPEND_NAMESPACE(QMultimediaQmlModule)); + diff --git a/src/declarative/imports/multimedia/multimedia.pro b/src/declarative/imports/multimedia/multimedia.pro new file mode 100644 index 0000000..d601d2e --- /dev/null +++ b/src/declarative/imports/multimedia/multimedia.pro @@ -0,0 +1,15 @@ +TARGET = multimedia +include(../qimportbase.pri) + +QT += multimedia declarative + +SOURCES += multimedia.cpp + +QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/multimedia +target.path = $$[QT_INSTALL_IMPORTS]/Qt/multimedia + +qmldir.files += $$QT_BUILD_TREE/imports/Qt/multimedia/qmldir +qmldir.path += $$[QT_INSTALL_IMPORTS]/Qt/multimedia + +INSTALLS += target qmldir + diff --git a/src/declarative/imports/qimportbase.pri b/src/declarative/imports/qimportbase.pri new file mode 100644 index 0000000..5b0a4e2 --- /dev/null +++ b/src/declarative/imports/qimportbase.pri @@ -0,0 +1,16 @@ +TEMPLATE = lib +CONFIG += qt plugin + +win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release +TARGET = $$qtLibraryTarget($$TARGET) +contains(QT_CONFIG, reduce_exports):CONFIG += hide_symbols + +include(../../qt_targets.pri) + +wince*:LIBS += $$QMAKE_LIBS_GUI + +symbian: { + TARGET.EPOCALLOWDLLDATA=1 + TARGET.CAPABILITY = All -Tcb + load(armcc_warnings) +} diff --git a/src/declarative/imports/webkit/plugin.cpp b/src/declarative/imports/webkit/plugin.cpp new file mode 100644 index 0000000..2f6205d --- /dev/null +++ b/src/declarative/imports/webkit/plugin.cpp @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** 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 plugins 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 +#include + +#include "qdeclarativewebview_p.h" +#include "qdeclarativewebview_p_p.h" + +QT_BEGIN_NAMESPACE + +class WebKitQmlPlugin : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + virtual void registerTypes(const char *uri) + { + Q_ASSERT(QLatin1String(uri) == QLatin1String("org.webkit")); + qmlRegisterType(uri,1,0,"WebView"); + } +}; + +QT_END_NAMESPACE + +#include "plugin.moc" + +Q_EXPORT_PLUGIN2(webkitqmlplugin, QT_PREPEND_NAMESPACE(WebKitQmlPlugin)); + diff --git a/src/declarative/imports/webkit/qdeclarativewebview.cpp b/src/declarative/imports/webkit/qdeclarativewebview.cpp new file mode 100644 index 0000000..733ac86 --- /dev/null +++ b/src/declarative/imports/webkit/qdeclarativewebview.cpp @@ -0,0 +1,1340 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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 "qdeclarativewebview_p.h" +#include "qdeclarativewebview_p_p.h" + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system + +class QDeclarativeWebViewPrivate : public QDeclarativePaintedItemPrivate +{ + Q_DECLARE_PUBLIC(QDeclarativeWebView) + +public: + QDeclarativeWebViewPrivate() + : QDeclarativePaintedItemPrivate(), page(0), preferredwidth(0), preferredheight(0), + progress(1.0), status(QDeclarativeWebView::Null), pending(PendingNone), + newWindowComponent(0), newWindowParent(0), + pressTime(400), + rendering(true) + { + } + + QUrl url; // page url might be different if it has not loaded yet + QWebPage *page; + + int preferredwidth, preferredheight; + qreal progress; + QDeclarativeWebView::Status status; + QString statusText; + enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending; + QUrl pending_url; + QString pending_string; + QByteArray pending_data; + mutable QDeclarativeWebSettings settings; + QDeclarativeComponent *newWindowComponent; + QDeclarativeItem *newWindowParent; + + QBasicTimer pressTimer; + QPoint pressPoint; + int pressTime; // milliseconds before it's a "hold" + + + static void windowObjects_append(QDeclarativeListProperty *prop, QObject *o) { + static_cast(prop->data)->windowObjects.append(o); + static_cast(prop->data)->updateWindowObjects(); + } + + void updateWindowObjects(); + QObjectList windowObjects; + + bool rendering; +}; + +/*! + \qmlclass WebView QDeclarativeWebView + \since 4.7 + \brief The WebView item allows you to add web content to a canvas. + \inherits Item + + A WebView renders web content based on a URL. + + If the width and height of the item is not set, they will + dynamically adjust to a size appropriate for the content. + This width may be large for typical online web pages. + + If the preferredWidth is set, the width will be this amount or larger, + usually laying out the web content to fit the preferredWidth. + + \qml + import org.webkit 1.0 + + WebView { + url: "http://www.nokia.com" + width: 490 + height: 400 + scale: 0.5 + smooth: false + smoothCache: true + } + \endqml + + \image webview.png + + The item includes no scrolling, scaling, + toolbars, etc., those must be implemented around WebView. See the WebBrowser example + for a demonstration of this. +*/ + +/*! + \internal + \class QDeclarativeWebView + \brief The QDeclarativeWebView class allows you to add web content to a QDeclarativeView. + + A WebView renders web content base on a URL. + + \image webview.png + + The item includes no scrolling, scaling, + toolbars, etc., those must be implemented around WebView. See the WebBrowser example + for a demonstration of this. + + A QDeclarativeWebView object can be instantiated in Qml using the tag \l WebView. +*/ + +QDeclarativeWebView::QDeclarativeWebView(QDeclarativeItem *parent) + : QDeclarativePaintedItem(*(new QDeclarativeWebViewPrivate), parent) +{ + init(); +} + +QDeclarativeWebView::~QDeclarativeWebView() +{ + Q_D(QDeclarativeWebView); + delete d->page; +} + +void QDeclarativeWebView::init() +{ + Q_D(QDeclarativeWebView); + + QWebSettings::enablePersistentStorage(); + + setAcceptHoverEvents(true); + setAcceptedMouseButtons(Qt::LeftButton); + setFlag(QGraphicsItem::ItemHasNoContents, false); + + d->page = 0; +} + +void QDeclarativeWebView::componentComplete() +{ + QDeclarativePaintedItem::componentComplete(); + Q_D(QDeclarativeWebView); + switch (d->pending) { + case QDeclarativeWebViewPrivate::PendingUrl: + setUrl(d->pending_url); + break; + case QDeclarativeWebViewPrivate::PendingHtml: + setHtml(d->pending_string, d->pending_url); + break; + case QDeclarativeWebViewPrivate::PendingContent: + setContent(d->pending_data, d->pending_string, d->pending_url); + break; + default: + break; + } + d->pending = QDeclarativeWebViewPrivate::PendingNone; + d->updateWindowObjects(); +} + +QDeclarativeWebView::Status QDeclarativeWebView::status() const +{ + Q_D(const QDeclarativeWebView); + return d->status; +} + + +/*! + \qmlproperty real WebView::progress + This property holds the progress of loading the current URL, from 0 to 1. + + If you just want to know when progress gets to 1, use + WebView::onLoadFinished() or WebView::onLoadFailed() instead. +*/ +qreal QDeclarativeWebView::progress() const +{ + Q_D(const QDeclarativeWebView); + return d->progress; +} + +void QDeclarativeWebView::doLoadStarted() +{ + Q_D(QDeclarativeWebView); + + if (!d->url.isEmpty()) { + d->status = Loading; + emit statusChanged(d->status); + } + emit loadStarted(); +} + +void QDeclarativeWebView::doLoadProgress(int p) +{ + Q_D(QDeclarativeWebView); + if (d->progress == p/100.0) + return; + d->progress = p/100.0; + emit progressChanged(); +} + +void QDeclarativeWebView::pageUrlChanged() +{ + Q_D(QDeclarativeWebView); + + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + expandToWebPage(); + + if ((d->url.isEmpty() && page()->mainFrame()->url() != QUrl(QLatin1String("about:blank"))) + || (d->url != page()->mainFrame()->url() && !page()->mainFrame()->url().isEmpty())) + { + d->url = page()->mainFrame()->url(); + if (d->url == QUrl(QLatin1String("about:blank"))) + d->url = QUrl(); + emit urlChanged(); + } +} + +void QDeclarativeWebView::doLoadFinished(bool ok) +{ + Q_D(QDeclarativeWebView); + + if (title().isEmpty()) + pageUrlChanged(); // XXX bug 232556 - pages with no title never get urlChanged() + + if (ok) { + d->status = d->url.isEmpty() ? Null : Ready; + emit loadFinished(); + } else { + d->status = Error; + emit loadFailed(); + } + emit statusChanged(d->status); +} + +/*! + \qmlproperty url WebView::url + This property holds the URL to the page displayed in this item. It can be set, + but also can change spontaneously (eg. because of network redirection). + + If the url is empty, the page is blank. + + The url is always absolute (QML will resolve relative URL strings in the context + of the containing QML document). +*/ +QUrl QDeclarativeWebView::url() const +{ + Q_D(const QDeclarativeWebView); + return d->url; +} + +void QDeclarativeWebView::setUrl(const QUrl &url) +{ + Q_D(QDeclarativeWebView); + if (url == d->url) + return; + + if (isComponentComplete()) { + d->url = url; + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + QUrl seturl = url; + if (seturl.isEmpty()) + seturl = QUrl(QLatin1String("about:blank")); + + Q_ASSERT(!seturl.isRelative()); + + page()->mainFrame()->load(seturl); + + emit urlChanged(); + } else { + d->pending = d->PendingUrl; + d->pending_url = url; + } +} + +/*! + \qmlproperty int WebView::preferredWidth + This property holds the ideal width for displaying the current URL. +*/ +int QDeclarativeWebView::preferredWidth() const +{ + Q_D(const QDeclarativeWebView); + return d->preferredwidth; +} + +void QDeclarativeWebView::setPreferredWidth(int iw) +{ + Q_D(QDeclarativeWebView); + if (d->preferredwidth == iw) return; + d->preferredwidth = iw; + //expandToWebPage(); + emit preferredWidthChanged(); +} + +/*! + \qmlproperty int WebView::preferredHeight + This property holds the ideal height for displaying the current URL. + This only affects the area zoomed by heuristicZoom(). +*/ +int QDeclarativeWebView::preferredHeight() const +{ + Q_D(const QDeclarativeWebView); + return d->preferredheight; +} +void QDeclarativeWebView::setPreferredHeight(int ih) +{ + Q_D(QDeclarativeWebView); + if (d->preferredheight == ih) return; + d->preferredheight = ih; + emit preferredHeightChanged(); +} + +/*! + \qmlmethod bool WebView::evaluateJavaScript(string) + + Evaluates the \a scriptSource JavaScript inside the context of the + main web frame, and returns the result of the last executed statement. + + Note that this JavaScript does \e not have any access to QML objects + except as made available as windowObjects. +*/ +QVariant QDeclarativeWebView::evaluateJavaScript(const QString &scriptSource) +{ + return this->page()->mainFrame()->evaluateJavaScript(scriptSource); +} + +void QDeclarativeWebView::focusChanged(bool hasFocus) +{ + QFocusEvent e(hasFocus ? QEvent::FocusIn : QEvent::FocusOut); + page()->event(&e); + QDeclarativeItem::focusChanged(hasFocus); +} + +void QDeclarativeWebView::initialLayout() +{ + // nothing useful to do at this point +} + +void QDeclarativeWebView::noteContentsSizeChanged(const QSize&) +{ + expandToWebPage(); +} + +void QDeclarativeWebView::expandToWebPage() +{ + Q_D(QDeclarativeWebView); + QSize cs = page()->mainFrame()->contentsSize(); + if (cs.width() < d->preferredwidth) + cs.setWidth(d->preferredwidth); + if (cs.height() < d->preferredheight) + cs.setHeight(d->preferredheight); + if (widthValid()) + cs.setWidth(width()); + if (heightValid()) + cs.setHeight(height()); + if (cs != page()->viewportSize()) { + page()->setViewportSize(cs); + } + if (cs != contentsSize()) + setContentsSize(cs); +} + +void QDeclarativeWebView::geometryChanged(const QRectF &newGeometry, + const QRectF &oldGeometry) +{ + if (newGeometry.size() != oldGeometry.size()) + expandToWebPage(); + QDeclarativePaintedItem::geometryChanged(newGeometry, oldGeometry); +} + +void QDeclarativeWebView::paintPage(const QRect& r) +{ + dirtyCache(r); + update(); +} + +/*! + \qmlproperty list WebView::javaScriptWindowObjects + + This property is a list of object that are available from within + the webview's JavaScript context. + + The \a object will be inserted as a child of the frame's window + object, under the name given by the attached property \c WebView.windowObjectName. + + \qml + WebView { + javaScriptWindowObjects: Object { + WebView.windowObjectName: "coordinates" + } + } + \endqml + + Properties of the object will be exposed as JavaScript properties and slots as + JavaScript methods. + + If Javascript is not enabled for this page, then this property does nothing. +*/ +QDeclarativeListProperty QDeclarativeWebView::javaScriptWindowObjects() +{ + Q_D(QDeclarativeWebView); + return QDeclarativeListProperty(this, d, &QDeclarativeWebViewPrivate::windowObjects_append); +} + +QDeclarativeWebViewAttached *QDeclarativeWebView::qmlAttachedProperties(QObject *o) +{ + return new QDeclarativeWebViewAttached(o); +} + +void QDeclarativeWebViewPrivate::updateWindowObjects() +{ + Q_Q(QDeclarativeWebView); + if (!q->isComponentComplete() || !page) + return; + + for (int ii = 0; ii < windowObjects.count(); ++ii) { + QObject *object = windowObjects.at(ii); + QDeclarativeWebViewAttached *attached = static_cast(qmlAttachedPropertiesObject(object)); + if (attached && !attached->windowObjectName().isEmpty()) { + page->mainFrame()->addToJavaScriptWindowObject(attached->windowObjectName(), object); + } + } +} + +bool QDeclarativeWebView::renderingEnabled() const +{ + Q_D(const QDeclarativeWebView); + return d->rendering; +} + +void QDeclarativeWebView::setRenderingEnabled(bool enabled) +{ + Q_D(QDeclarativeWebView); + if (d->rendering == enabled) + return; + d->rendering = enabled; + emit renderingEnabledChanged(); + + setCacheFrozen(!enabled); + if (enabled) + clearCache(); +} + + +void QDeclarativeWebView::drawContents(QPainter *p, const QRect &r) +{ + Q_D(QDeclarativeWebView); + if (d->rendering) + page()->mainFrame()->render(p,r); +} + +QMouseEvent *QDeclarativeWebView::sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *e) +{ + QEvent::Type t; + switch(e->type()) { + default: + case QEvent::GraphicsSceneMousePress: + t = QEvent::MouseButtonPress; + break; + case QEvent::GraphicsSceneMouseRelease: + t = QEvent::MouseButtonRelease; + break; + case QEvent::GraphicsSceneMouseMove: + t = QEvent::MouseMove; + break; + case QGraphicsSceneEvent::GraphicsSceneMouseDoubleClick: + t = QEvent::MouseButtonDblClick; + break; + } + + QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), e->button(), e->buttons(), 0); + return me; +} + +QMouseEvent *QDeclarativeWebView::sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *e) +{ + QEvent::Type t = QEvent::MouseMove; + + QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), Qt::NoButton, Qt::NoButton, 0); + + return me; +} + + +/*! + \qmlsignal WebView::onDoubleClick(clickx,clicky) + + The WebView does not pass double-click events to the web engine, but rather + emits this signals. +*/ + +void QDeclarativeWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + emit doubleClick(me->x(),me->y()); + delete me; +} + +/*! + \qmlmethod bool WebView::heuristicZoom(clickX,clickY,maxzoom) + + Finds a zoom that: + \list + \i shows a whole item + \i includes (\a clickX, \a clickY) + \i fits into the preferredWidth and preferredHeight + \i zooms by no more than \a maxzoom + \i is more than 10% above the current zoom + \endlist + + If such a zoom exists, emits zoomTo(zoom,centerX,centerY) and returns true; otherwise, + no signal is emitted and returns false. +*/ +bool QDeclarativeWebView::heuristicZoom(int clickX, int clickY, qreal maxzoom) +{ + Q_D(QDeclarativeWebView); + if (contentsScale() >= maxzoom/zoomFactor()) + return false; + qreal ozf = contentsScale(); + QRect showarea = elementAreaAt(clickX, clickY, d->preferredwidth/maxzoom, d->preferredheight/maxzoom); + qreal z = qMin(qreal(d->preferredwidth)/showarea.width(),qreal(d->preferredheight)/showarea.height()); + if (z > maxzoom/zoomFactor()) + z = maxzoom/zoomFactor(); + if (z/ozf > 1.2) { + QRectF r(showarea.left()*z, showarea.top()*z, showarea.width()*z, showarea.height()*z); + emit zoomTo(z,r.x()+r.width()/2, r.y()+r.height()/2); + return true; + } else { + return false; + } +} + +/*! + \qmlproperty int WebView::pressGrabTime + + The number of milliseconds the user must press before the WebView + starts passing move events through to the web engine (rather than + letting other QML elements such as a Flickable take them). + + Defaults to 400ms. Set to 0 to always grab and pass move events to + the web engine. +*/ +int QDeclarativeWebView::pressGrabTime() const +{ + Q_D(const QDeclarativeWebView); + return d->pressTime; +} + +void QDeclarativeWebView::setPressGrabTime(int ms) +{ + Q_D(QDeclarativeWebView); + if (d->pressTime == ms) + return; + d->pressTime = ms; + emit pressGrabTimeChanged(); +} + +void QDeclarativeWebView::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + setFocus (true); + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + + d->pressPoint = me->pos(); + if (d->pressTime) { + d->pressTimer.start(d->pressTime,this); + setKeepMouseGrab(false); + } else { + grabMouse(); + setKeepMouseGrab(true); + } + + page()->event(me); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit + Might be a bug in WebKit, though + */ +#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) { + QDeclarativePaintedItem::mousePressEvent(event); + } +} + +void QDeclarativeWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + page()->event(me); + d->pressTimer.stop(); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send all the events to WebKit + */ +#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) { + QDeclarativePaintedItem::mouseReleaseEvent(event); + } + setKeepMouseGrab(false); + ungrabMouse(); +} + +void QDeclarativeWebView::timerEvent(QTimerEvent *event) +{ + Q_D(QDeclarativeWebView); + if (event->timerId() == d->pressTimer.timerId()) { + d->pressTimer.stop(); + grabMouse(); + setKeepMouseGrab(true); + } +} + +void QDeclarativeWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + if (d->pressTimer.isActive()) { + if ((me->pos() - d->pressPoint).manhattanLength() > QApplication::startDragDistance()) { + d->pressTimer.stop(); + } + } + if (keepMouseGrab()) { + page()->event(me); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit + Might be a bug in WebKit, though + */ +#if 1 // QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + } + delete me; + if (!event->isAccepted()) + QDeclarativePaintedItem::mouseMoveEvent(event); + +} +void QDeclarativeWebView::hoverMoveEvent (QGraphicsSceneHoverEvent * event) +{ + QMouseEvent *me = sceneHoverMoveEventToMouseEvent(event); + page()->event(me); + event->setAccepted( +#if QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) + QDeclarativePaintedItem::hoverMoveEvent(event); +} + +void QDeclarativeWebView::keyPressEvent(QKeyEvent* event) +{ + page()->event(event); + if (!event->isAccepted()) + QDeclarativePaintedItem::keyPressEvent(event); +} + +void QDeclarativeWebView::keyReleaseEvent(QKeyEvent* event) +{ + page()->event(event); + if (!event->isAccepted()) + QDeclarativePaintedItem::keyReleaseEvent(event); +} + +bool QDeclarativeWebView::sceneEvent(QEvent *event) +{ + if (event->type() == QEvent::KeyPress) { + QKeyEvent *k = static_cast(event); + if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) { + if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? + page()->event(event); + if (event->isAccepted()) + return true; + } + } + } + return QDeclarativePaintedItem::sceneEvent(event); +} + + +/*! + \qmlproperty action WebView::back + This property holds the action for causing the previous URL in the history to be displayed. +*/ +QAction *QDeclarativeWebView::backAction() const +{ + return page()->action(QWebPage::Back); +} + +/*! + \qmlproperty action WebView::forward + This property holds the action for causing the next URL in the history to be displayed. +*/ +QAction *QDeclarativeWebView::forwardAction() const +{ + return page()->action(QWebPage::Forward); +} + +/*! + \qmlproperty action WebView::reload + This property holds the action for reloading with the current URL +*/ +QAction *QDeclarativeWebView::reloadAction() const +{ + return page()->action(QWebPage::Reload); +} + +/*! + \qmlproperty action WebView::stop + This property holds the action for stopping loading with the current URL +*/ +QAction *QDeclarativeWebView::stopAction() const +{ + return page()->action(QWebPage::Stop); +} + +/*! + \qmlproperty real WebView::title + This property holds the title of the web page currently viewed + + By default, this property contains an empty string. +*/ +QString QDeclarativeWebView::title() const +{ + return page()->mainFrame()->title(); +} + + + +/*! + \qmlproperty pixmap WebView::icon + This property holds the icon associated with the web page currently viewed +*/ +QPixmap QDeclarativeWebView::icon() const +{ + return page()->mainFrame()->icon().pixmap(QSize(256,256)); +} + + +/*! + \qmlproperty real WebView::zoomFactor + This property holds the multiplier used to scale the contents of a Web page. +*/ +void QDeclarativeWebView::setZoomFactor(qreal factor) +{ + Q_D(QDeclarativeWebView); + if (factor == page()->mainFrame()->zoomFactor()) + return; + + page()->mainFrame()->setZoomFactor(factor); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth*factor : width()*factor, + d->preferredheight>0 ? d->preferredheight*factor : height()*factor)); + expandToWebPage(); + + emit zoomFactorChanged(); +} + +qreal QDeclarativeWebView::zoomFactor() const +{ + return page()->mainFrame()->zoomFactor(); +} + +/*! + \qmlproperty string WebView::statusText + + This property is the current status suggested by the current web page. In a web browser, + such status is often shown in some kind of status bar. +*/ +void QDeclarativeWebView::setStatusText(const QString& s) +{ + Q_D(QDeclarativeWebView); + d->statusText = s; + emit statusTextChanged(); +} + +void QDeclarativeWebView::windowObjectCleared() +{ + Q_D(QDeclarativeWebView); + d->updateWindowObjects(); +} + +QString QDeclarativeWebView::statusText() const +{ + Q_D(const QDeclarativeWebView); + return d->statusText; +} + +QWebPage *QDeclarativeWebView::page() const +{ + Q_D(const QDeclarativeWebView); + + if (!d->page) { + QDeclarativeWebView *self = const_cast(this); + QWebPage *wp = new QDeclarativeWebPage(self); + + // QML items don't default to having a background, + // even though most we pages will set one anyway. + QPalette pal = QApplication::palette(); + pal.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0)); + wp->setPalette(pal); + + wp->setNetworkAccessManager(qmlEngine(this)->networkAccessManager()); + + self->setPage(wp); + + return wp; + } + + return d->page; +} + + +// The QObject interface to settings(). +/*! + \qmlproperty string WebView::settings.standardFontFamily + \qmlproperty string WebView::settings.fixedFontFamily + \qmlproperty string WebView::settings.serifFontFamily + \qmlproperty string WebView::settings.sansSerifFontFamily + \qmlproperty string WebView::settings.cursiveFontFamily + \qmlproperty string WebView::settings.fantasyFontFamily + + \qmlproperty int WebView::settings.minimumFontSize + \qmlproperty int WebView::settings.minimumLogicalFontSize + \qmlproperty int WebView::settings.defaultFontSize + \qmlproperty int WebView::settings.defaultFixedFontSize + + \qmlproperty bool WebView::settings.autoLoadImages + \qmlproperty bool WebView::settings.javascriptEnabled + \qmlproperty bool WebView::settings.javaEnabled + \qmlproperty bool WebView::settings.pluginsEnabled + \qmlproperty bool WebView::settings.privateBrowsingEnabled + \qmlproperty bool WebView::settings.javascriptCanOpenWindows + \qmlproperty bool WebView::settings.javascriptCanAccessClipboard + \qmlproperty bool WebView::settings.developerExtrasEnabled + \qmlproperty bool WebView::settings.linksIncludedInFocusChain + \qmlproperty bool WebView::settings.zoomTextOnly + \qmlproperty bool WebView::settings.printElementBackgrounds + \qmlproperty bool WebView::settings.offlineStorageDatabaseEnabled + \qmlproperty bool WebView::settings.offlineWebApplicationCacheEnabled + \qmlproperty bool WebView::settings.localStorageDatabaseEnabled + \qmlproperty bool WebView::settings.localContentCanAccessRemoteUrls + + These properties give access to the settings controlling the web view. + + See QWebSettings for details of these properties. + + \qml + WebView { + settings.pluginsEnabled: true + settings.standardFontFamily: "Arial" + ... + } + \endqml +*/ +QObject *QDeclarativeWebView::settingsObject() const +{ + Q_D(const QDeclarativeWebView); + d->settings.s = page()->settings(); + return &d->settings; +} + +void QDeclarativeWebView::setPage(QWebPage *page) +{ + Q_D(QDeclarativeWebView); + if (d->page == page) + return; + if (d->page) { + if (d->page->parent() == this) { + delete d->page; + } else { + d->page->disconnect(this); + } + } + d->page = page; + d->page->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + d->page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff); + d->page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff); + connect(d->page,SIGNAL(repaintRequested(QRect)),this,SLOT(paintPage(QRect))); + connect(d->page->mainFrame(),SIGNAL(urlChanged(QUrl)),this,SLOT(pageUrlChanged())); + connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString))); + connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(iconChanged())); + connect(d->page->mainFrame(), SIGNAL(iconChanged()), this, SIGNAL(iconChanged())); + connect(d->page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), this, SLOT(noteContentsSizeChanged(QSize))); + connect(d->page->mainFrame(), SIGNAL(initialLayoutCompleted()), this, SLOT(initialLayout())); + + connect(d->page,SIGNAL(loadStarted()),this,SLOT(doLoadStarted())); + connect(d->page,SIGNAL(loadProgress(int)),this,SLOT(doLoadProgress(int))); + connect(d->page,SIGNAL(loadFinished(bool)),this,SLOT(doLoadFinished(bool))); + connect(d->page,SIGNAL(statusBarMessage(QString)),this,SLOT(setStatusText(QString))); + + connect(d->page->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(windowObjectCleared())); +} + +/*! + \qmlsignal WebView::onLoadStarted() + + This handler is called when the web engine begins loading + a page. Later, WebView::onLoadFinished() or WebView::onLoadFailed() + will be emitted. +*/ + +/*! + \qmlsignal WebView::onLoadFinished() + + This handler is called when the web engine \e successfully + finishes loading a page, including any component content + (WebView::onLoadFailed() will be emitted otherwise). + + \sa progress +*/ + +/*! + \qmlsignal WebView::onLoadFailed() + + This handler is called when the web engine fails loading + a page or any component content + (WebView::onLoadFinished() will be emitted on success). +*/ + +void QDeclarativeWebView::load(const QNetworkRequest &request, + QNetworkAccessManager::Operation operation, + const QByteArray &body) +{ + page()->mainFrame()->load(request, operation, body); +} + +QString QDeclarativeWebView::html() const +{ + return page()->mainFrame()->toHtml(); +} + +/*! + \qmlproperty string WebView::html + This property holds HTML text set directly + + The html property can be set as a string. + + \qml + WebView { + html: "

This is HTML." + } + \endqml +*/ +void QDeclarativeWebView::setHtml(const QString &html, const QUrl &baseUrl) +{ + Q_D(QDeclarativeWebView); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + if (isComponentComplete()) + page()->mainFrame()->setHtml(html, baseUrl); + else { + d->pending = d->PendingHtml; + d->pending_url = baseUrl; + d->pending_string = html; + } + emit htmlChanged(); +} + +void QDeclarativeWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) +{ + Q_D(QDeclarativeWebView); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + + if (isComponentComplete()) + page()->mainFrame()->setContent(data,mimeType,qmlContext(this)->resolvedUrl(baseUrl)); + else { + d->pending = d->PendingContent; + d->pending_url = baseUrl; + d->pending_string = mimeType; + d->pending_data = data; + } +} + +QWebHistory *QDeclarativeWebView::history() const +{ + return page()->history(); +} + +QWebSettings *QDeclarativeWebView::settings() const +{ + return page()->settings(); +} + +QDeclarativeWebView *QDeclarativeWebView::createWindow(QWebPage::WebWindowType type) +{ + Q_D(QDeclarativeWebView); + switch (type) { + case QWebPage::WebBrowserWindow: { + if (!d->newWindowComponent && d->newWindowParent) + qWarning("WebView::newWindowComponent not set - WebView::newWindowParent ignored"); + else if (d->newWindowComponent && !d->newWindowParent) + qWarning("WebView::newWindowParent not set - WebView::newWindowComponent ignored"); + else if (d->newWindowComponent && d->newWindowParent) { + QDeclarativeWebView *webview = 0; + QDeclarativeContext *windowContext = new QDeclarativeContext(qmlContext(this)); + + QObject *nobj = d->newWindowComponent->create(windowContext); + if (nobj) { + windowContext->setParent(nobj); + QDeclarativeItem *item = qobject_cast(nobj); + if (!item) { + delete nobj; + } else { + webview = item->findChild(); + if (!webview) { + delete item; + } else { + nobj->setParent(d->newWindowParent); + static_cast(item)->setParentItem(d->newWindowParent); + } + } + } else { + delete windowContext; + } + + return webview; + } + } + break; + case QWebPage::WebModalDialog: { + // Not supported + } + } + return 0; +} + +/*! + \qmlproperty component WebView::newWindowComponent + + This property holds the component to use for new windows. + The component must have a WebView somewhere in its structure. + + When the web engine requests a new window, it will be an instance of + this component. + + The parent of the new window is set by newWindowParent. It must be set. +*/ +QDeclarativeComponent *QDeclarativeWebView::newWindowComponent() const +{ + Q_D(const QDeclarativeWebView); + return d->newWindowComponent; +} + +void QDeclarativeWebView::setNewWindowComponent(QDeclarativeComponent *newWindow) +{ + Q_D(QDeclarativeWebView); + if (newWindow == d->newWindowComponent) + return; + d->newWindowComponent = newWindow; + emit newWindowComponentChanged(); +} + + +/*! + \qmlproperty item WebView::newWindowParent + + The parent item for new windows. + + \sa newWindowComponent +*/ +QDeclarativeItem *QDeclarativeWebView::newWindowParent() const +{ + Q_D(const QDeclarativeWebView); + return d->newWindowParent; +} + +void QDeclarativeWebView::setNewWindowParent(QDeclarativeItem *parent) +{ + Q_D(QDeclarativeWebView); + if (parent == d->newWindowParent) + return; + if (d->newWindowParent && parent) { + QList children = d->newWindowParent->childItems(); + for (int i = 0; i < children.count(); ++i) { + children.at(i)->setParentItem(parent); + } + } + d->newWindowParent = parent; + emit newWindowParentChanged(); +} + +/*! + Returns the area of the largest element at position (\a x,\a y) that is no larger + than \a maxwidth by \a maxheight pixels. + + May return an area larger in the case when no smaller element is at the position. +*/ +QRect QDeclarativeWebView::elementAreaAt(int x, int y, int maxwidth, int maxheight) const +{ + QWebHitTestResult hit = page()->mainFrame()->hitTestContent(QPoint(x,y)); + QRect rv = hit.boundingRect(); + QWebElement element = hit.enclosingBlockElement(); + if (maxwidth<=0) maxwidth = INT_MAX; + if (maxheight<=0) maxheight = INT_MAX; + while (!element.parent().isNull() && element.geometry().width() <= maxwidth && element.geometry().height() <= maxheight) { + rv = element.geometry(); + element = element.parent(); + } + return rv; +} + +/*! + \internal + \class QDeclarativeWebPage + \brief The QDeclarativeWebPage class is a QWebPage that can create QML plugins. + + \sa QDeclarativeWebView +*/ +QDeclarativeWebPage::QDeclarativeWebPage(QDeclarativeWebView *parent) : + QWebPage(parent) +{ +} + +QDeclarativeWebPage::~QDeclarativeWebPage() +{ +} + +void QDeclarativeWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) +{ + qWarning() << sourceID << ':' << lineNumber << ':' << message; +} + +QString QDeclarativeWebPage::chooseFile(QWebFrame *originatingFrame, const QString& oldFile) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(oldFile) + return oldFile; +} + +void QDeclarativeWebPage::javaScriptAlert(QWebFrame *originatingFrame, const QString& msg) +{ + Q_UNUSED(originatingFrame) + emit viewItem()->alert(msg); +} + +bool QDeclarativeWebPage::javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(msg) + return false; +} + +bool QDeclarativeWebPage::javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(msg) + Q_UNUSED(defaultValue) + Q_UNUSED(result) + return false; +} + + +/* + Qt WebKit does not understand non-QWidget plugins, so dummy widgets + are created, parented to a single dummy tool window. + + The requirements for QML object plugins are input to the Qt WebKit + non-QWidget plugin support, which will obsolete this kludge. +*/ +class QWidget_Dummy_Plugin : public QWidget +{ + Q_OBJECT +public: + static QWidget *dummy_shared_parent() + { + static QWidget *dsp = 0; + if (!dsp) { + dsp = new QWidget(0,Qt::Tool); + dsp->setGeometry(-10000,-10000,0,0); + dsp->show(); + } + return dsp; + } + QWidget_Dummy_Plugin(const QUrl& url, QDeclarativeWebView *view, const QStringList ¶mNames, const QStringList ¶mValues) : + QWidget(dummy_shared_parent()), + propertyNames(paramNames), + propertyValues(paramValues), + webview(view) + { + QDeclarativeEngine *engine = qmlEngine(webview); + component = new QDeclarativeComponent(engine, url, this); + item = 0; + if (component->isLoading()) + connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(qmlLoaded())); + else + qmlLoaded(); + } + +public Q_SLOTS: + void qmlLoaded() + { + if (component->isError()) { + // ### Could instead give these errors to the WebView to handle. + qWarning() << component->errors(); + return; + } + item = qobject_cast(component->create(qmlContext(webview))); + item->setParent(webview); + QString jsObjName; + for (int i=0; isetProperty(propertyNames[i].toUtf8(),propertyValues[i]); + if (propertyNames[i] == QLatin1String("objectname")) + jsObjName = propertyValues[i]; + } + } + if (!jsObjName.isNull()) { + QWebFrame *f = webview->page()->mainFrame(); + f->addToJavaScriptWindowObject(jsObjName, item); + } + resizeEvent(0); + delete component; + component = 0; + } + void resizeEvent(QResizeEvent*) + { + if (item) { + item->setX(x()); + item->setY(y()); + item->setWidth(width()); + item->setHeight(height()); + } + } + +private: + QDeclarativeComponent *component; + QDeclarativeItem *item; + QStringList propertyNames, propertyValues; + QDeclarativeWebView *webview; +}; + +QDeclarativeWebView *QDeclarativeWebPage::viewItem() +{ + return static_cast(parent()); +} + +QObject *QDeclarativeWebPage::createPlugin(const QString &, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) +{ + QUrl comp = qmlContext(viewItem())->resolvedUrl(url); + return new QWidget_Dummy_Plugin(comp,viewItem(),paramNames,paramValues); +} + +QWebPage *QDeclarativeWebPage::createWindow(WebWindowType type) +{ + QDeclarativeWebView *newView = viewItem()->createWindow(type); + if (newView) + return newView->page(); + return 0; +} + +QT_END_NAMESPACE + +#include diff --git a/src/declarative/imports/webkit/qdeclarativewebview_p.h b/src/declarative/imports/webkit/qdeclarativewebview_p.h new file mode 100644 index 0000000..0bb5d29 --- /dev/null +++ b/src/declarative/imports/webkit/qdeclarativewebview_p.h @@ -0,0 +1,285 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef QDECLARATIVEWEBVIEW_H +#define QDECLARATIVEWEBVIEW_H + +#include + +#include +#include +#include +#include + +QT_BEGIN_HEADER + +class QWebHistory; +class QWebSettings; + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) +class QDeclarativeWebViewPrivate; +class QNetworkRequest; +class QDeclarativeWebView; + +class Q_DECLARATIVE_EXPORT QDeclarativeWebPage : public QWebPage +{ + Q_OBJECT +public: + explicit QDeclarativeWebPage(QDeclarativeWebView *parent); + ~QDeclarativeWebPage(); +protected: + QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); + QWebPage *createWindow(WebWindowType type); + void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); + QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); + void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); + bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); + bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); + +private: + QDeclarativeWebView *viewItem(); +}; + + +class QDeclarativeWebViewAttached; + +//### TODO: browser plugins + +class Q_DECLARATIVE_EXPORT QDeclarativeWebView : public QDeclarativePaintedItem +{ + Q_OBJECT + + Q_ENUMS(Status SelectionMode) + + Q_PROPERTY(QString title READ title NOTIFY titleChanged) + Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged) + Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor NOTIFY zoomFactorChanged) + Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged) + + Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged) + + Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime NOTIFY pressGrabTimeChanged) + + Q_PROPERTY(int preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged) + Q_PROPERTY(int preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged) + Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) + Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) + Q_PROPERTY(Status status READ status NOTIFY statusChanged) + + Q_PROPERTY(QAction* reload READ reloadAction CONSTANT) + Q_PROPERTY(QAction* back READ backAction CONSTANT) + Q_PROPERTY(QAction* forward READ forwardAction CONSTANT) + Q_PROPERTY(QAction* stop READ stopAction CONSTANT) + + Q_PROPERTY(QObject* settings READ settingsObject CONSTANT) + + Q_PROPERTY(QDeclarativeListProperty javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT) + + Q_PROPERTY(QDeclarativeComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent NOTIFY newWindowComponentChanged) + Q_PROPERTY(QDeclarativeItem* newWindowParent READ newWindowParent WRITE setNewWindowParent NOTIFY newWindowParentChanged) + + Q_PROPERTY(bool renderingEnabled READ renderingEnabled WRITE setRenderingEnabled NOTIFY renderingEnabledChanged) + +public: + QDeclarativeWebView(QDeclarativeItem *parent=0); + ~QDeclarativeWebView(); + + QUrl url() const; + void setUrl(const QUrl &); + + QString title() const; + + QPixmap icon() const; + + qreal zoomFactor() const; + void setZoomFactor(qreal); + Q_INVOKABLE bool heuristicZoom(int clickX, int clickY, qreal maxzoom); + QRect elementAreaAt(int x, int y, int minwidth, int minheight) const; + + int pressGrabTime() const; + void setPressGrabTime(int); + + int preferredWidth() const; + void setPreferredWidth(int); + int preferredHeight() const; + void setPreferredHeight(int); + + enum Status { Null, Ready, Loading, Error }; + Status status() const; + qreal progress() const; + QString statusText() const; + + QAction *reloadAction() const; + QAction *backAction() const; + QAction *forwardAction() const; + QAction *stopAction() const; + + QWebPage *page() const; + void setPage(QWebPage *page); + + void load(const QNetworkRequest &request, + QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, + const QByteArray &body = QByteArray()); + + QString html() const; + + void setHtml(const QString &html, const QUrl &baseUrl = QUrl()); + void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl()); + + QWebHistory *history() const; + QWebSettings *settings() const; + QObject *settingsObject() const; + + bool renderingEnabled() const; + void setRenderingEnabled(bool); + + QDeclarativeListProperty javaScriptWindowObjects(); + + static QDeclarativeWebViewAttached *qmlAttachedProperties(QObject *); + + QDeclarativeComponent *newWindowComponent() const; + void setNewWindowComponent(QDeclarativeComponent *newWindow); + QDeclarativeItem *newWindowParent() const; + void setNewWindowParent(QDeclarativeItem *newWindow); + +Q_SIGNALS: + void preferredWidthChanged(); + void preferredHeightChanged(); + void urlChanged(); + void progressChanged(); + void statusChanged(Status); + void titleChanged(const QString&); + void iconChanged(); + void statusTextChanged(); + void htmlChanged(); + void pressGrabTimeChanged(); + void zoomFactorChanged(); + void newWindowComponentChanged(); + void newWindowParentChanged(); + void renderingEnabledChanged(); + + void loadStarted(); + void loadFinished(); + void loadFailed(); + + void doubleClick(int clickX, int clickY); + + void zoomTo(qreal zoom, int centerX, int centerY); + + void alert(const QString& message); + +public Q_SLOTS: + QVariant evaluateJavaScript(const QString&); + +private Q_SLOTS: + void expandToWebPage(); + void paintPage(const QRect&); + void doLoadStarted(); + void doLoadProgress(int p); + void doLoadFinished(bool ok); + void setStatusText(const QString&); + void windowObjectCleared(); + void pageUrlChanged(); + void noteContentsSizeChanged(const QSize&); + void initialLayout(); + +protected: + void drawContents(QPainter *, const QRect &); + + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void timerEvent(QTimerEvent *event); + void hoverMoveEvent (QGraphicsSceneHoverEvent * event); + void keyPressEvent(QKeyEvent* event); + void keyReleaseEvent(QKeyEvent* event); + virtual void geometryChanged(const QRectF &newGeometry, + const QRectF &oldGeometry); + virtual void focusChanged(bool); + virtual bool sceneEvent(QEvent *event); + QDeclarativeWebView *createWindow(QWebPage::WebWindowType type); + +private: + void init(); + virtual void componentComplete(); + Q_DISABLE_COPY(QDeclarativeWebView) + Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeWebView) + QMouseEvent *sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *); + QMouseEvent *sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *); + friend class QDeclarativeWebPage; +}; + +class QDeclarativeWebViewAttached : public QObject +{ + Q_OBJECT + Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName) +public: + QDeclarativeWebViewAttached(QObject *parent) + : QObject(parent) + { + } + + QString windowObjectName() const + { + return m_windowObjectName; + } + + void setWindowObjectName(const QString &n) + { + m_windowObjectName = n; + } + +private: + QString m_windowObjectName; +}; + + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QDeclarativeWebView) +QML_DECLARE_TYPEINFO(QDeclarativeWebView, QML_HAS_ATTACHED_PROPERTIES) + +QT_END_HEADER + +#endif diff --git a/src/declarative/imports/webkit/qdeclarativewebview_p_p.h b/src/declarative/imports/webkit/qdeclarativewebview_p_p.h new file mode 100644 index 0000000..258b472 --- /dev/null +++ b/src/declarative/imports/webkit/qdeclarativewebview_p_p.h @@ -0,0 +1,151 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef QDECLARATIVEWEBVIEW_P_H +#define QDECLARATIVEWEBVIEW_P_H + +#include + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +class QDeclarativeWebSettings : public QObject { + Q_OBJECT + + Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily) + Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily) + Q_PROPERTY(QString serifFontFamily READ serifFontFamily WRITE setSerifFontFamily) + Q_PROPERTY(QString sansSerifFontFamily READ sansSerifFontFamily WRITE setSansSerifFontFamily) + Q_PROPERTY(QString cursiveFontFamily READ cursiveFontFamily WRITE setCursiveFontFamily) + Q_PROPERTY(QString fantasyFontFamily READ fantasyFontFamily WRITE setFantasyFontFamily) + + Q_PROPERTY(int minimumFontSize READ minimumFontSize WRITE setMinimumFontSize) + Q_PROPERTY(int minimumLogicalFontSize READ minimumLogicalFontSize WRITE setMinimumLogicalFontSize) + Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize) + Q_PROPERTY(int defaultFixedFontSize READ defaultFixedFontSize WRITE setDefaultFixedFontSize) + + Q_PROPERTY(bool autoLoadImages READ autoLoadImages WRITE setAutoLoadImages) + Q_PROPERTY(bool javascriptEnabled READ javascriptEnabled WRITE setJavascriptEnabled) + Q_PROPERTY(bool javaEnabled READ javaEnabled WRITE setJavaEnabled) + Q_PROPERTY(bool pluginsEnabled READ pluginsEnabled WRITE setPluginsEnabled) + Q_PROPERTY(bool privateBrowsingEnabled READ privateBrowsingEnabled WRITE setPrivateBrowsingEnabled) + Q_PROPERTY(bool javascriptCanOpenWindows READ javascriptCanOpenWindows WRITE setJavascriptCanOpenWindows) + Q_PROPERTY(bool javascriptCanAccessClipboard READ javascriptCanAccessClipboard WRITE setJavascriptCanAccessClipboard) + Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled) + Q_PROPERTY(bool linksIncludedInFocusChain READ linksIncludedInFocusChain WRITE setLinksIncludedInFocusChain) + Q_PROPERTY(bool zoomTextOnly READ zoomTextOnly WRITE setZoomTextOnly) + Q_PROPERTY(bool printElementBackgrounds READ printElementBackgrounds WRITE setPrintElementBackgrounds) + Q_PROPERTY(bool offlineStorageDatabaseEnabled READ offlineStorageDatabaseEnabled WRITE setOfflineStorageDatabaseEnabled) + Q_PROPERTY(bool offlineWebApplicationCacheEnabled READ offlineWebApplicationCacheEnabled WRITE setOfflineWebApplicationCacheEnabled) + Q_PROPERTY(bool localStorageDatabaseEnabled READ localStorageDatabaseEnabled WRITE setLocalStorageDatabaseEnabled) + Q_PROPERTY(bool localContentCanAccessRemoteUrls READ localContentCanAccessRemoteUrls WRITE setLocalContentCanAccessRemoteUrls) + +public: + QDeclarativeWebSettings() {} + + QString standardFontFamily() const { return s->fontFamily(QWebSettings::StandardFont); } + void setStandardFontFamily(const QString& f) { s->setFontFamily(QWebSettings::StandardFont,f); } + QString fixedFontFamily() const { return s->fontFamily(QWebSettings::FixedFont); } + void setFixedFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FixedFont,f); } + QString serifFontFamily() const { return s->fontFamily(QWebSettings::SerifFont); } + void setSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SerifFont,f); } + QString sansSerifFontFamily() const { return s->fontFamily(QWebSettings::SansSerifFont); } + void setSansSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SansSerifFont,f); } + QString cursiveFontFamily() const { return s->fontFamily(QWebSettings::CursiveFont); } + void setCursiveFontFamily(const QString& f) { s->setFontFamily(QWebSettings::CursiveFont,f); } + QString fantasyFontFamily() const { return s->fontFamily(QWebSettings::FantasyFont); } + void setFantasyFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FantasyFont,f); } + + int minimumFontSize() const { return s->fontSize(QWebSettings::MinimumFontSize); } + void setMinimumFontSize(int size) { s->setFontSize(QWebSettings::MinimumFontSize,size); } + int minimumLogicalFontSize() const { return s->fontSize(QWebSettings::MinimumLogicalFontSize); } + void setMinimumLogicalFontSize(int size) { s->setFontSize(QWebSettings::MinimumLogicalFontSize,size); } + int defaultFontSize() const { return s->fontSize(QWebSettings::DefaultFontSize); } + void setDefaultFontSize(int size) { s->setFontSize(QWebSettings::DefaultFontSize,size); } + int defaultFixedFontSize() const { return s->fontSize(QWebSettings::DefaultFixedFontSize); } + void setDefaultFixedFontSize(int size) { s->setFontSize(QWebSettings::DefaultFixedFontSize,size); } + + bool autoLoadImages() const { return s->testAttribute(QWebSettings::AutoLoadImages); } + void setAutoLoadImages(bool on) { s->setAttribute(QWebSettings::AutoLoadImages, on); } + bool javascriptEnabled() const { return s->testAttribute(QWebSettings::JavascriptEnabled); } + void setJavascriptEnabled(bool on) { s->setAttribute(QWebSettings::JavascriptEnabled, on); } + bool javaEnabled() const { return s->testAttribute(QWebSettings::JavaEnabled); } + void setJavaEnabled(bool on) { s->setAttribute(QWebSettings::JavaEnabled, on); } + bool pluginsEnabled() const { return s->testAttribute(QWebSettings::PluginsEnabled); } + void setPluginsEnabled(bool on) { s->setAttribute(QWebSettings::PluginsEnabled, on); } + bool privateBrowsingEnabled() const { return s->testAttribute(QWebSettings::PrivateBrowsingEnabled); } + void setPrivateBrowsingEnabled(bool on) { s->setAttribute(QWebSettings::PrivateBrowsingEnabled, on); } + bool javascriptCanOpenWindows() const { return s->testAttribute(QWebSettings::JavascriptCanOpenWindows); } + void setJavascriptCanOpenWindows(bool on) { s->setAttribute(QWebSettings::JavascriptCanOpenWindows, on); } + bool javascriptCanAccessClipboard() const { return s->testAttribute(QWebSettings::JavascriptCanAccessClipboard); } + void setJavascriptCanAccessClipboard(bool on) { s->setAttribute(QWebSettings::JavascriptCanAccessClipboard, on); } + bool developerExtrasEnabled() const { return s->testAttribute(QWebSettings::DeveloperExtrasEnabled); } + void setDeveloperExtrasEnabled(bool on) { s->setAttribute(QWebSettings::DeveloperExtrasEnabled, on); } + bool linksIncludedInFocusChain() const { return s->testAttribute(QWebSettings::LinksIncludedInFocusChain); } + void setLinksIncludedInFocusChain(bool on) { s->setAttribute(QWebSettings::LinksIncludedInFocusChain, on); } + bool zoomTextOnly() const { return s->testAttribute(QWebSettings::ZoomTextOnly); } + void setZoomTextOnly(bool on) { s->setAttribute(QWebSettings::ZoomTextOnly, on); } + bool printElementBackgrounds() const { return s->testAttribute(QWebSettings::PrintElementBackgrounds); } + void setPrintElementBackgrounds(bool on) { s->setAttribute(QWebSettings::PrintElementBackgrounds, on); } + bool offlineStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled); } + void setOfflineStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, on); } + bool offlineWebApplicationCacheEnabled() const { return s->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled); } + void setOfflineWebApplicationCacheEnabled(bool on) { s->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, on); } + bool localStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::LocalStorageDatabaseEnabled); } + void setLocalStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, on); } + bool localContentCanAccessRemoteUrls() const { return s->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls); } + void setLocalContentCanAccessRemoteUrls(bool on) { s->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, on); } + + QWebSettings *s; +}; + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QDeclarativeWebSettings) + +QT_END_HEADER + +#endif diff --git a/src/declarative/imports/webkit/webkit.pro b/src/declarative/imports/webkit/webkit.pro new file mode 100644 index 0000000..7ad8564 --- /dev/null +++ b/src/declarative/imports/webkit/webkit.pro @@ -0,0 +1,18 @@ +TARGET = webkitqmlplugin +include(../qimportbase.pri) + +contains(QT_CONFIG, webkit) { + QT += webkit declarative + + SOURCES += qdeclarativewebview.cpp plugin.cpp + HEADERS += qdeclarativewebview_p.h + HEADERS += qdeclarativewebview_p_p.h + + QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/org/webkit + target.path = $$[QT_INSTALL_IMPORTS]/org/webkit + + qmldir.files += $$QT_BUILD_TREE/imports/org/webkit/qmldir + qmldir.path += $$[QT_INSTALL_IMPORTS]/org/webkit + + INSTALLS += target qmldir +} diff --git a/src/declarative/imports/widgets/graphicslayouts.cpp b/src/declarative/imports/widgets/graphicslayouts.cpp new file mode 100644 index 0000000..fc15ad2 --- /dev/null +++ b/src/declarative/imports/widgets/graphicslayouts.cpp @@ -0,0 +1,260 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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 "graphicslayouts_p.h" + +#include +#include + +QT_BEGIN_NAMESPACE + +LinearLayoutAttached::LinearLayoutAttached(QObject *parent) +: QObject(parent), _stretch(1), _alignment(Qt::AlignCenter) +{ +} + +void LinearLayoutAttached::setStretchFactor(int f) +{ + if (_stretch == f) + return; + + _stretch = f; + emit stretchChanged(reinterpret_cast(parent()), _stretch); +} + +void LinearLayoutAttached::setAlignment(Qt::Alignment a) +{ + if (_alignment == a) + return; + + _alignment = a; + emit alignmentChanged(reinterpret_cast(parent()), _alignment); +} + +QGraphicsLinearLayoutStretchItemObject::QGraphicsLinearLayoutStretchItemObject(QObject *parent) + : QObject(parent) +{ +} + +QSizeF QGraphicsLinearLayoutStretchItemObject::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const +{ +Q_UNUSED(which); +Q_UNUSED(constraint); +return QSizeF(); +} + + +QGraphicsLinearLayoutObject::QGraphicsLinearLayoutObject(QObject *parent) +: QObject(parent) +{ +} + +QGraphicsLinearLayoutObject::~QGraphicsLinearLayoutObject() +{ +} + +void QGraphicsLinearLayoutObject::insertLayoutItem(int index, QGraphicsLayoutItem *item) +{ +insertItem(index, item); + +//connect attached properties +if (LinearLayoutAttached *obj = attachedProperties.value(item)) { + setStretchFactor(item, obj->stretchFactor()); + setAlignment(item, obj->alignment()); + QObject::connect(obj, SIGNAL(stretchChanged(QGraphicsLayoutItem*,int)), + this, SLOT(updateStretch(QGraphicsLayoutItem*,int))); + QObject::connect(obj, SIGNAL(alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment)), + this, SLOT(updateAlignment(QGraphicsLayoutItem*,Qt::Alignment))); + //### need to disconnect when widget is removed? +} +} + +//### is there a better way to do this? +void QGraphicsLinearLayoutObject::clearChildren() +{ +for (int i = 0; i < count(); ++i) + removeAt(i); +} + +void QGraphicsLinearLayoutObject::updateStretch(QGraphicsLayoutItem *item, int stretch) +{ +QGraphicsLinearLayout::setStretchFactor(item, stretch); +} + +void QGraphicsLinearLayoutObject::updateAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment) +{ +QGraphicsLinearLayout::setAlignment(item, alignment); +} + +QHash QGraphicsLinearLayoutObject::attachedProperties; +LinearLayoutAttached *QGraphicsLinearLayoutObject::qmlAttachedProperties(QObject *obj) +{ +// ### This is not allowed - you must attach to any object +if (!qobject_cast(obj)) + return 0; +LinearLayoutAttached *rv = new LinearLayoutAttached(obj); +attachedProperties.insert(qobject_cast(obj), rv); +return rv; +} + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// QGraphicsGridLayout-related classes +////////////////////////////////////////////////////////////////////////////////////////////////////// +GridLayoutAttached::GridLayoutAttached(QObject *parent) +: QObject(parent), _row(-1), _column(-1), _rowspan(1), _colspan(1), _alignment(-1) +{ +} + +void GridLayoutAttached::setRow(int r) +{ + if (_row == r) + return; + + _row = r; + //emit rowChanged(reinterpret_cast(parent()), _row); +} + +void GridLayoutAttached::setColumn(int c) +{ + if (_column == c) + return; + + _column = c; + //emit columnChanged(reinterpret_cast(parent()), _column); +} + +void GridLayoutAttached::setRowSpan(int rs) +{ + if (_rowspan == rs) + return; + + _rowspan = rs; + //emit rowSpanChanged(reinterpret_cast(parent()), _rowSpan); +} + +void GridLayoutAttached::setColumnSpan(int cs) +{ + if (_colspan == cs) + return; + + _colspan = cs; + //emit columnSpanChanged(reinterpret_cast(parent()), _columnSpan); +} + +void GridLayoutAttached::setAlignment(Qt::Alignment a) +{ + if (_alignment == a) + return; + + _alignment = a; + //emit alignmentChanged(reinterpret_cast(parent()), _alignment); +} + +QGraphicsGridLayoutObject::QGraphicsGridLayoutObject(QObject *parent) +: QObject(parent) +{ +} + +QGraphicsGridLayoutObject::~QGraphicsGridLayoutObject() +{ +} + +void QGraphicsGridLayoutObject::addWidget(QGraphicsWidget *wid) +{ +//use attached properties +if (QObject *obj = attachedProperties.value(qobject_cast(wid))) { + int row = static_cast(obj)->row(); + int column = static_cast(obj)->column(); + int rowSpan = static_cast(obj)->rowSpan(); + int columnSpan = static_cast(obj)->columnSpan(); + if (row == -1 || column == -1) { + qWarning() << "Must set row and column for an item in a grid layout"; + return; + } + addItem(wid, row, column, rowSpan, columnSpan); +} +} + +void QGraphicsGridLayoutObject::addLayoutItem(QGraphicsLayoutItem *item) +{ +//use attached properties +if (GridLayoutAttached *obj = attachedProperties.value(item)) { + int row = obj->row(); + int column = obj->column(); + int rowSpan = obj->rowSpan(); + int columnSpan = obj->columnSpan(); + Qt::Alignment alignment = obj->alignment(); + if (row == -1 || column == -1) { + qWarning() << "Must set row and column for an item in a grid layout"; + return; + } + addItem(item, row, column, rowSpan, columnSpan); + if (alignment != -1) + setAlignment(item,alignment); +} +} + +//### is there a better way to do this? +void QGraphicsGridLayoutObject::clearChildren() +{ +for (int i = 0; i < count(); ++i) + removeAt(i); +} + +qreal QGraphicsGridLayoutObject::spacing() const +{ +if (verticalSpacing() == horizontalSpacing()) + return verticalSpacing(); +return -1; //### +} + +QHash QGraphicsGridLayoutObject::attachedProperties; +GridLayoutAttached *QGraphicsGridLayoutObject::qmlAttachedProperties(QObject *obj) +{ +// ### This is not allowed - you must attach to any object +if (!qobject_cast(obj)) + return 0; +GridLayoutAttached *rv = new GridLayoutAttached(obj); +attachedProperties.insert(qobject_cast(obj), rv); +return rv; +} + +QT_END_NAMESPACE diff --git a/src/declarative/imports/widgets/graphicslayouts_p.h b/src/declarative/imports/widgets/graphicslayouts_p.h new file mode 100644 index 0000000..f9b9ae8 --- /dev/null +++ b/src/declarative/imports/widgets/graphicslayouts_p.h @@ -0,0 +1,226 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef GRAPHICSLAYOUTS_H +#define GRAPHICSLAYOUTS_H + +#include "graphicswidgets_p.h" + +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +class QGraphicsLinearLayoutStretchItemObject : public QObject, public QGraphicsLayoutItem +{ + Q_OBJECT + Q_INTERFACES(QGraphicsLayoutItem) +public: + QGraphicsLinearLayoutStretchItemObject(QObject *parent = 0); + + virtual QSizeF sizeHint(Qt::SizeHint, const QSizeF &) const; +}; + +class LinearLayoutAttached; +class QGraphicsLinearLayoutObject : public QObject, public QGraphicsLinearLayout +{ + Q_OBJECT + Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation) + Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsLinearLayoutObject(QObject * = 0); + ~QGraphicsLinearLayoutObject(); + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } + + static LinearLayoutAttached *qmlAttachedProperties(QObject *); + +private Q_SLOTS: + void updateStretch(QGraphicsLayoutItem*,int); + void updateAlignment(QGraphicsLayoutItem*,Qt::Alignment); + +private: + friend class LinearLayoutAttached; + void clearChildren(); + void insertLayoutItem(int, QGraphicsLayoutItem *); + static QHash attachedProperties; + + static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { + static_cast(prop->object)->insertLayoutItem(-1, item); + } + + static void children_clear(QDeclarativeListProperty *prop) { + static_cast(prop->object)->clearChildren(); + } + + static int children_count(QDeclarativeListProperty *prop) { + return static_cast(prop->object)->count(); + } + + static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { + return static_cast(prop->object)->itemAt(index); + } +}; + +class GridLayoutAttached; +class QGraphicsGridLayoutObject : public QObject, public QGraphicsGridLayout +{ + Q_OBJECT + Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) + Q_PROPERTY(qreal verticalSpacing READ verticalSpacing WRITE setVerticalSpacing) + Q_PROPERTY(qreal horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsGridLayoutObject(QObject * = 0); + ~QGraphicsGridLayoutObject(); + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } + + qreal spacing() const; + + static GridLayoutAttached *qmlAttachedProperties(QObject *); + +private: + friend class GraphicsLayoutAttached; + void addWidget(QGraphicsWidget *); + void clearChildren(); + void addLayoutItem(QGraphicsLayoutItem *); + static QHash attachedProperties; + + static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { + static_cast(prop->object)->addLayoutItem(item); + } + + static void children_clear(QDeclarativeListProperty *prop) { + static_cast(prop->object)->clearChildren(); + } + + static int children_count(QDeclarativeListProperty *prop) { + return static_cast(prop->object)->count(); + } + + static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { + return static_cast(prop->object)->itemAt(index); + } +}; + +class LinearLayoutAttached : public QObject +{ + Q_OBJECT + + Q_PROPERTY(int stretchFactor READ stretchFactor WRITE setStretchFactor NOTIFY stretchChanged) + Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) +public: + LinearLayoutAttached(QObject *parent); + + int stretchFactor() const { return _stretch; } + void setStretchFactor(int f); + Qt::Alignment alignment() const { return _alignment; } + void setAlignment(Qt::Alignment a); + +Q_SIGNALS: + void stretchChanged(QGraphicsLayoutItem*,int); + void alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment); + +private: + int _stretch; + Qt::Alignment _alignment; +}; + +class GridLayoutAttached : public QObject +{ + Q_OBJECT + + Q_PROPERTY(int row READ row WRITE setRow) + Q_PROPERTY(int column READ column WRITE setColumn) + Q_PROPERTY(int rowSpan READ rowSpan WRITE setRowSpan) + Q_PROPERTY(int columnSpan READ columnSpan WRITE setColumnSpan) + Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment) +public: + GridLayoutAttached(QObject *parent); + + int row() const { return _row; } + void setRow(int r); + + int column() const { return _column; } + void setColumn(int c); + + int rowSpan() const { return _rowspan; } + void setRowSpan(int rs); + + int columnSpan() const { return _colspan; } + void setColumnSpan(int cs); + + Qt::Alignment alignment() const { return _alignment; } + void setAlignment(Qt::Alignment a); + +private: + int _row; + int _column; + int _rowspan; + int _colspan; + Qt::Alignment _alignment; +}; + +QT_END_NAMESPACE + +QML_DECLARE_INTERFACE(QGraphicsLayoutItem) +QML_DECLARE_INTERFACE(QGraphicsLayout) +QML_DECLARE_TYPE(QGraphicsLinearLayoutStretchItemObject) +QML_DECLARE_TYPE(QGraphicsLinearLayoutObject) +QML_DECLARE_TYPEINFO(QGraphicsLinearLayoutObject, QML_HAS_ATTACHED_PROPERTIES) +QML_DECLARE_TYPE(QGraphicsGridLayoutObject) +QML_DECLARE_TYPEINFO(QGraphicsGridLayoutObject, QML_HAS_ATTACHED_PROPERTIES) + +QT_END_HEADER + +#endif // GRAPHICSLAYOUTS_H diff --git a/src/declarative/imports/widgets/graphicswidgets.cpp b/src/declarative/imports/widgets/graphicswidgets.cpp new file mode 100644 index 0000000..062e516 --- /dev/null +++ b/src/declarative/imports/widgets/graphicswidgets.cpp @@ -0,0 +1,40 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ diff --git a/src/declarative/imports/widgets/graphicswidgets_p.h b/src/declarative/imports/widgets/graphicswidgets_p.h new file mode 100644 index 0000000..2c2b707 --- /dev/null +++ b/src/declarative/imports/widgets/graphicswidgets_p.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef GRAPHICSWIDGETS_H +#define GRAPHICSWIDGETS_H + +#include + +#include +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QGraphicsView) +QML_DECLARE_TYPE_HASMETATYPE(QGraphicsScene) +QML_DECLARE_TYPE(QGraphicsWidget) +QML_DECLARE_TYPE(QGraphicsObject) +QML_DECLARE_INTERFACE_HASMETATYPE(QGraphicsItem) + +QT_END_HEADER + +#endif // GRAPHICSWIDGETS_H diff --git a/src/declarative/imports/widgets/widgets.cpp b/src/declarative/imports/widgets/widgets.cpp new file mode 100644 index 0000000..ec21cc4 --- /dev/null +++ b/src/declarative/imports/widgets/widgets.cpp @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the plugins 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 +#include + +#include "graphicslayouts_p.h" +#include "graphicswidgets_p.h" + +QT_BEGIN_NAMESPACE + +class QGraphicsViewDeclarativeUI : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QGraphicsScene *scene READ scene WRITE setScene) + Q_CLASSINFO("DefaultProperty", "scene") +public: + QGraphicsViewDeclarativeUI(QObject *other) : QObject(other) {} + + QGraphicsScene *scene() const { return static_cast(parent())->scene(); } + void setScene(QGraphicsScene *scene) + { + static_cast(parent())->setScene(scene); + } +}; + +class QGraphicsSceneDeclarativeUI : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsSceneDeclarativeUI(QObject *other) : QObject(other) {} + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this->parent(), 0, children_append); } + +private: + static void children_append(QDeclarativeListProperty *prop, QObject *o) { + if (QGraphicsObject *go = qobject_cast(o)) + static_cast(prop->object)->addItem(go); + } +}; + +class QGraphicsWidgetDeclarativeUI : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_PROPERTY(QGraphicsLayout *layout READ layout WRITE setLayout) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsWidgetDeclarativeUI(QObject *other) : QObject(other) {} + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append); } + + QGraphicsLayout *layout() const { return static_cast(parent())->layout(); } + void setLayout(QGraphicsLayout *lo) + { + static_cast(parent())->setLayout(lo); + } + +private: + void setItemParent(QGraphicsItem *wid) + { + wid->setParentItem(static_cast(parent())); + } + + static void children_append(QDeclarativeListProperty *prop, QGraphicsItem *i) { + static_cast(prop->object)->setItemParent(i); + } +}; + +class QWidgetsQmlModule : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + virtual void registerTypes(const char *uri) + { + Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.widgets")); + + QML_REGISTER_INTERFACE(QGraphicsLayoutItem); + QML_REGISTER_INTERFACE(QGraphicsLayout); + qmlRegisterType(uri,4,6,"QGraphicsLinearLayoutStretchItem"); + qmlRegisterType(uri,4,6,"QGraphicsLinearLayout"); + qmlRegisterType(uri,4,6,"QGraphicsGridLayout"); + qmlRegisterExtendedType(uri,4,6,"QGraphicsView"); + qmlRegisterExtendedType(uri,4,6,"QGraphicsScene"); + qmlRegisterExtendedType(uri,4,6,"QGraphicsWidget"); + QML_REGISTER_INTERFACE(QGraphicsItem); + } +}; + +QT_END_NAMESPACE + +#include "widgets.moc" + +Q_EXPORT_PLUGIN2(qtwidgetsqmlmodule, QT_PREPEND_NAMESPACE(QWidgetsQmlModule)); + diff --git a/src/declarative/imports/widgets/widgets.pro b/src/declarative/imports/widgets/widgets.pro new file mode 100644 index 0000000..230d398 --- /dev/null +++ b/src/declarative/imports/widgets/widgets.pro @@ -0,0 +1,20 @@ +TARGET = widgets +include(../qimportbase.pri) + +QT += declarative + +SOURCES += \ + graphicslayouts.cpp \ + widgets.cpp + +HEADERS += \ + graphicswidgets_p.h \ + graphicslayouts_p.h + +QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/widgets +target.path = $$[QT_INSTALL_IMPORTS]/Qt/widgets + +qmldir.files += $$QT_BUILD_TREE/imports/Qt/widgets/qmldir +qmldir.path += $$[QT_INSTALL_IMPORTS]/Qt/widgets + +INSTALLS += target qmldir diff --git a/src/declarative/libdeclarative.pro b/src/declarative/libdeclarative.pro new file mode 100644 index 0000000..4287e25 --- /dev/null +++ b/src/declarative/libdeclarative.pro @@ -0,0 +1,29 @@ +TARGET = QtDeclarative +QPRO_PWD = $$PWD +QT = core gui xml script network +contains(QT_CONFIG, svg): QT += svg +contains(QT_CONFIG, opengl): QT += opengl +DEFINES += QT_BUILD_DECLARATIVE_LIB QT_NO_URL_CAST_FROM_STRING +win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x66000000 +solaris-cc*:QMAKE_CXXFLAGS_RELEASE -= -O2 + +unix:QMAKE_PKGCONFIG_REQUIRES = QtCore QtGui QtXml + +exists("qdeclarative_enable_gcov") { + QMAKE_CXXFLAGS = -fprofile-arcs -ftest-coverage -fno-elide-constructors + LIBS += -lgcov +} + +include(../qbase.pri) + +#INCLUDEPATH -= $$QMAKE_INCDIR_QT/$$TARGET +#DESTDIR=. + +#modules +include(3rdparty/3rdparty.pri) +include(util/util.pri) +include(graphicsitems/graphicsitems.pri) +include(qml/qml.pri) +include(debugger/debugger.pri) + +symbian:TARGET.UID3=0x2001E623 diff --git a/src/plugins/plugins.pro b/src/plugins/plugins.pro index 418fd81..730fdc5 100644 --- a/src/plugins/plugins.pro +++ b/src/plugins/plugins.pro @@ -12,6 +12,5 @@ embedded:SUBDIRS *= gfxdrivers decorations mousedrivers kbddrivers symbian:SUBDIRS += s60 contains(QT_CONFIG, phonon): SUBDIRS *= phonon contains(QT_CONFIG, multimedia): SUBDIRS *= audio mediaservices -contains(QT_CONFIG, declarative): SUBDIRS *= qdeclarativemodules diff --git a/src/plugins/qdeclarativemodules/multimedia/multimedia.cpp b/src/plugins/qdeclarativemodules/multimedia/multimedia.cpp deleted file mode 100644 index 8becbf3..0000000 --- a/src/plugins/qdeclarativemodules/multimedia/multimedia.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the plugins 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 -#include -#include - -QT_BEGIN_NAMESPACE - -class QMultimediaQmlModule : public QDeclarativeExtensionPlugin -{ - Q_OBJECT -public: - virtual void registerTypes(const char *uri) - { - QtMultimedia::qRegisterDeclarativeElements(uri); - } -}; - -QT_END_NAMESPACE - -#include "multimedia.moc" - -Q_EXPORT_PLUGIN2(qmultimediaqmlmodule, QT_PREPEND_NAMESPACE(QMultimediaQmlModule)); - diff --git a/src/plugins/qdeclarativemodules/multimedia/multimedia.pro b/src/plugins/qdeclarativemodules/multimedia/multimedia.pro deleted file mode 100644 index d8ad18e..0000000 --- a/src/plugins/qdeclarativemodules/multimedia/multimedia.pro +++ /dev/null @@ -1,15 +0,0 @@ -TARGET = multimedia -include(../../qpluginbase.pri) - -QT += multimedia declarative - -SOURCES += multimedia.cpp - -QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/multimedia -target.path = $$[QT_INSTALL_IMPORTS]/Qt/multimedia - -qmldir.files += $$QT_BUILD_TREE/imports/Qt/multimedia/qmldir -qmldir.path += $$[QT_INSTALL_IMPORTS]/Qt/multimedia - -INSTALLS += target qmldir - diff --git a/src/plugins/qdeclarativemodules/qdeclarativemodules.pro b/src/plugins/qdeclarativemodules/qdeclarativemodules.pro deleted file mode 100644 index ae53578..0000000 --- a/src/plugins/qdeclarativemodules/qdeclarativemodules.pro +++ /dev/null @@ -1,7 +0,0 @@ -TEMPLATE = subdirs - -SUBDIRS += widgets - -contains(QT_CONFIG, multimedia): SUBDIRS += multimedia -contains(QT_CONFIG, webkit): SUBDIRS += webkitqmlplugin - diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp b/src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp deleted file mode 100644 index 2f6205d..0000000 --- a/src/plugins/qdeclarativemodules/webkitqmlplugin/plugin.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** 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 plugins 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 -#include - -#include "qdeclarativewebview_p.h" -#include "qdeclarativewebview_p_p.h" - -QT_BEGIN_NAMESPACE - -class WebKitQmlPlugin : public QDeclarativeExtensionPlugin -{ - Q_OBJECT -public: - virtual void registerTypes(const char *uri) - { - Q_ASSERT(QLatin1String(uri) == QLatin1String("org.webkit")); - qmlRegisterType(uri,1,0,"WebView"); - } -}; - -QT_END_NAMESPACE - -#include "plugin.moc" - -Q_EXPORT_PLUGIN2(webkitqmlplugin, QT_PREPEND_NAMESPACE(WebKitQmlPlugin)); - diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp deleted file mode 100644 index 733ac86..0000000 --- a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview.cpp +++ /dev/null @@ -1,1340 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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 "qdeclarativewebview_p.h" -#include "qdeclarativewebview_p_p.h" - -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system - -class QDeclarativeWebViewPrivate : public QDeclarativePaintedItemPrivate -{ - Q_DECLARE_PUBLIC(QDeclarativeWebView) - -public: - QDeclarativeWebViewPrivate() - : QDeclarativePaintedItemPrivate(), page(0), preferredwidth(0), preferredheight(0), - progress(1.0), status(QDeclarativeWebView::Null), pending(PendingNone), - newWindowComponent(0), newWindowParent(0), - pressTime(400), - rendering(true) - { - } - - QUrl url; // page url might be different if it has not loaded yet - QWebPage *page; - - int preferredwidth, preferredheight; - qreal progress; - QDeclarativeWebView::Status status; - QString statusText; - enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending; - QUrl pending_url; - QString pending_string; - QByteArray pending_data; - mutable QDeclarativeWebSettings settings; - QDeclarativeComponent *newWindowComponent; - QDeclarativeItem *newWindowParent; - - QBasicTimer pressTimer; - QPoint pressPoint; - int pressTime; // milliseconds before it's a "hold" - - - static void windowObjects_append(QDeclarativeListProperty *prop, QObject *o) { - static_cast(prop->data)->windowObjects.append(o); - static_cast(prop->data)->updateWindowObjects(); - } - - void updateWindowObjects(); - QObjectList windowObjects; - - bool rendering; -}; - -/*! - \qmlclass WebView QDeclarativeWebView - \since 4.7 - \brief The WebView item allows you to add web content to a canvas. - \inherits Item - - A WebView renders web content based on a URL. - - If the width and height of the item is not set, they will - dynamically adjust to a size appropriate for the content. - This width may be large for typical online web pages. - - If the preferredWidth is set, the width will be this amount or larger, - usually laying out the web content to fit the preferredWidth. - - \qml - import org.webkit 1.0 - - WebView { - url: "http://www.nokia.com" - width: 490 - height: 400 - scale: 0.5 - smooth: false - smoothCache: true - } - \endqml - - \image webview.png - - The item includes no scrolling, scaling, - toolbars, etc., those must be implemented around WebView. See the WebBrowser example - for a demonstration of this. -*/ - -/*! - \internal - \class QDeclarativeWebView - \brief The QDeclarativeWebView class allows you to add web content to a QDeclarativeView. - - A WebView renders web content base on a URL. - - \image webview.png - - The item includes no scrolling, scaling, - toolbars, etc., those must be implemented around WebView. See the WebBrowser example - for a demonstration of this. - - A QDeclarativeWebView object can be instantiated in Qml using the tag \l WebView. -*/ - -QDeclarativeWebView::QDeclarativeWebView(QDeclarativeItem *parent) - : QDeclarativePaintedItem(*(new QDeclarativeWebViewPrivate), parent) -{ - init(); -} - -QDeclarativeWebView::~QDeclarativeWebView() -{ - Q_D(QDeclarativeWebView); - delete d->page; -} - -void QDeclarativeWebView::init() -{ - Q_D(QDeclarativeWebView); - - QWebSettings::enablePersistentStorage(); - - setAcceptHoverEvents(true); - setAcceptedMouseButtons(Qt::LeftButton); - setFlag(QGraphicsItem::ItemHasNoContents, false); - - d->page = 0; -} - -void QDeclarativeWebView::componentComplete() -{ - QDeclarativePaintedItem::componentComplete(); - Q_D(QDeclarativeWebView); - switch (d->pending) { - case QDeclarativeWebViewPrivate::PendingUrl: - setUrl(d->pending_url); - break; - case QDeclarativeWebViewPrivate::PendingHtml: - setHtml(d->pending_string, d->pending_url); - break; - case QDeclarativeWebViewPrivate::PendingContent: - setContent(d->pending_data, d->pending_string, d->pending_url); - break; - default: - break; - } - d->pending = QDeclarativeWebViewPrivate::PendingNone; - d->updateWindowObjects(); -} - -QDeclarativeWebView::Status QDeclarativeWebView::status() const -{ - Q_D(const QDeclarativeWebView); - return d->status; -} - - -/*! - \qmlproperty real WebView::progress - This property holds the progress of loading the current URL, from 0 to 1. - - If you just want to know when progress gets to 1, use - WebView::onLoadFinished() or WebView::onLoadFailed() instead. -*/ -qreal QDeclarativeWebView::progress() const -{ - Q_D(const QDeclarativeWebView); - return d->progress; -} - -void QDeclarativeWebView::doLoadStarted() -{ - Q_D(QDeclarativeWebView); - - if (!d->url.isEmpty()) { - d->status = Loading; - emit statusChanged(d->status); - } - emit loadStarted(); -} - -void QDeclarativeWebView::doLoadProgress(int p) -{ - Q_D(QDeclarativeWebView); - if (d->progress == p/100.0) - return; - d->progress = p/100.0; - emit progressChanged(); -} - -void QDeclarativeWebView::pageUrlChanged() -{ - Q_D(QDeclarativeWebView); - - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - expandToWebPage(); - - if ((d->url.isEmpty() && page()->mainFrame()->url() != QUrl(QLatin1String("about:blank"))) - || (d->url != page()->mainFrame()->url() && !page()->mainFrame()->url().isEmpty())) - { - d->url = page()->mainFrame()->url(); - if (d->url == QUrl(QLatin1String("about:blank"))) - d->url = QUrl(); - emit urlChanged(); - } -} - -void QDeclarativeWebView::doLoadFinished(bool ok) -{ - Q_D(QDeclarativeWebView); - - if (title().isEmpty()) - pageUrlChanged(); // XXX bug 232556 - pages with no title never get urlChanged() - - if (ok) { - d->status = d->url.isEmpty() ? Null : Ready; - emit loadFinished(); - } else { - d->status = Error; - emit loadFailed(); - } - emit statusChanged(d->status); -} - -/*! - \qmlproperty url WebView::url - This property holds the URL to the page displayed in this item. It can be set, - but also can change spontaneously (eg. because of network redirection). - - If the url is empty, the page is blank. - - The url is always absolute (QML will resolve relative URL strings in the context - of the containing QML document). -*/ -QUrl QDeclarativeWebView::url() const -{ - Q_D(const QDeclarativeWebView); - return d->url; -} - -void QDeclarativeWebView::setUrl(const QUrl &url) -{ - Q_D(QDeclarativeWebView); - if (url == d->url) - return; - - if (isComponentComplete()) { - d->url = url; - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - QUrl seturl = url; - if (seturl.isEmpty()) - seturl = QUrl(QLatin1String("about:blank")); - - Q_ASSERT(!seturl.isRelative()); - - page()->mainFrame()->load(seturl); - - emit urlChanged(); - } else { - d->pending = d->PendingUrl; - d->pending_url = url; - } -} - -/*! - \qmlproperty int WebView::preferredWidth - This property holds the ideal width for displaying the current URL. -*/ -int QDeclarativeWebView::preferredWidth() const -{ - Q_D(const QDeclarativeWebView); - return d->preferredwidth; -} - -void QDeclarativeWebView::setPreferredWidth(int iw) -{ - Q_D(QDeclarativeWebView); - if (d->preferredwidth == iw) return; - d->preferredwidth = iw; - //expandToWebPage(); - emit preferredWidthChanged(); -} - -/*! - \qmlproperty int WebView::preferredHeight - This property holds the ideal height for displaying the current URL. - This only affects the area zoomed by heuristicZoom(). -*/ -int QDeclarativeWebView::preferredHeight() const -{ - Q_D(const QDeclarativeWebView); - return d->preferredheight; -} -void QDeclarativeWebView::setPreferredHeight(int ih) -{ - Q_D(QDeclarativeWebView); - if (d->preferredheight == ih) return; - d->preferredheight = ih; - emit preferredHeightChanged(); -} - -/*! - \qmlmethod bool WebView::evaluateJavaScript(string) - - Evaluates the \a scriptSource JavaScript inside the context of the - main web frame, and returns the result of the last executed statement. - - Note that this JavaScript does \e not have any access to QML objects - except as made available as windowObjects. -*/ -QVariant QDeclarativeWebView::evaluateJavaScript(const QString &scriptSource) -{ - return this->page()->mainFrame()->evaluateJavaScript(scriptSource); -} - -void QDeclarativeWebView::focusChanged(bool hasFocus) -{ - QFocusEvent e(hasFocus ? QEvent::FocusIn : QEvent::FocusOut); - page()->event(&e); - QDeclarativeItem::focusChanged(hasFocus); -} - -void QDeclarativeWebView::initialLayout() -{ - // nothing useful to do at this point -} - -void QDeclarativeWebView::noteContentsSizeChanged(const QSize&) -{ - expandToWebPage(); -} - -void QDeclarativeWebView::expandToWebPage() -{ - Q_D(QDeclarativeWebView); - QSize cs = page()->mainFrame()->contentsSize(); - if (cs.width() < d->preferredwidth) - cs.setWidth(d->preferredwidth); - if (cs.height() < d->preferredheight) - cs.setHeight(d->preferredheight); - if (widthValid()) - cs.setWidth(width()); - if (heightValid()) - cs.setHeight(height()); - if (cs != page()->viewportSize()) { - page()->setViewportSize(cs); - } - if (cs != contentsSize()) - setContentsSize(cs); -} - -void QDeclarativeWebView::geometryChanged(const QRectF &newGeometry, - const QRectF &oldGeometry) -{ - if (newGeometry.size() != oldGeometry.size()) - expandToWebPage(); - QDeclarativePaintedItem::geometryChanged(newGeometry, oldGeometry); -} - -void QDeclarativeWebView::paintPage(const QRect& r) -{ - dirtyCache(r); - update(); -} - -/*! - \qmlproperty list WebView::javaScriptWindowObjects - - This property is a list of object that are available from within - the webview's JavaScript context. - - The \a object will be inserted as a child of the frame's window - object, under the name given by the attached property \c WebView.windowObjectName. - - \qml - WebView { - javaScriptWindowObjects: Object { - WebView.windowObjectName: "coordinates" - } - } - \endqml - - Properties of the object will be exposed as JavaScript properties and slots as - JavaScript methods. - - If Javascript is not enabled for this page, then this property does nothing. -*/ -QDeclarativeListProperty QDeclarativeWebView::javaScriptWindowObjects() -{ - Q_D(QDeclarativeWebView); - return QDeclarativeListProperty(this, d, &QDeclarativeWebViewPrivate::windowObjects_append); -} - -QDeclarativeWebViewAttached *QDeclarativeWebView::qmlAttachedProperties(QObject *o) -{ - return new QDeclarativeWebViewAttached(o); -} - -void QDeclarativeWebViewPrivate::updateWindowObjects() -{ - Q_Q(QDeclarativeWebView); - if (!q->isComponentComplete() || !page) - return; - - for (int ii = 0; ii < windowObjects.count(); ++ii) { - QObject *object = windowObjects.at(ii); - QDeclarativeWebViewAttached *attached = static_cast(qmlAttachedPropertiesObject(object)); - if (attached && !attached->windowObjectName().isEmpty()) { - page->mainFrame()->addToJavaScriptWindowObject(attached->windowObjectName(), object); - } - } -} - -bool QDeclarativeWebView::renderingEnabled() const -{ - Q_D(const QDeclarativeWebView); - return d->rendering; -} - -void QDeclarativeWebView::setRenderingEnabled(bool enabled) -{ - Q_D(QDeclarativeWebView); - if (d->rendering == enabled) - return; - d->rendering = enabled; - emit renderingEnabledChanged(); - - setCacheFrozen(!enabled); - if (enabled) - clearCache(); -} - - -void QDeclarativeWebView::drawContents(QPainter *p, const QRect &r) -{ - Q_D(QDeclarativeWebView); - if (d->rendering) - page()->mainFrame()->render(p,r); -} - -QMouseEvent *QDeclarativeWebView::sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *e) -{ - QEvent::Type t; - switch(e->type()) { - default: - case QEvent::GraphicsSceneMousePress: - t = QEvent::MouseButtonPress; - break; - case QEvent::GraphicsSceneMouseRelease: - t = QEvent::MouseButtonRelease; - break; - case QEvent::GraphicsSceneMouseMove: - t = QEvent::MouseMove; - break; - case QGraphicsSceneEvent::GraphicsSceneMouseDoubleClick: - t = QEvent::MouseButtonDblClick; - break; - } - - QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), e->button(), e->buttons(), 0); - return me; -} - -QMouseEvent *QDeclarativeWebView::sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *e) -{ - QEvent::Type t = QEvent::MouseMove; - - QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), Qt::NoButton, Qt::NoButton, 0); - - return me; -} - - -/*! - \qmlsignal WebView::onDoubleClick(clickx,clicky) - - The WebView does not pass double-click events to the web engine, but rather - emits this signals. -*/ - -void QDeclarativeWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) -{ - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - emit doubleClick(me->x(),me->y()); - delete me; -} - -/*! - \qmlmethod bool WebView::heuristicZoom(clickX,clickY,maxzoom) - - Finds a zoom that: - \list - \i shows a whole item - \i includes (\a clickX, \a clickY) - \i fits into the preferredWidth and preferredHeight - \i zooms by no more than \a maxzoom - \i is more than 10% above the current zoom - \endlist - - If such a zoom exists, emits zoomTo(zoom,centerX,centerY) and returns true; otherwise, - no signal is emitted and returns false. -*/ -bool QDeclarativeWebView::heuristicZoom(int clickX, int clickY, qreal maxzoom) -{ - Q_D(QDeclarativeWebView); - if (contentsScale() >= maxzoom/zoomFactor()) - return false; - qreal ozf = contentsScale(); - QRect showarea = elementAreaAt(clickX, clickY, d->preferredwidth/maxzoom, d->preferredheight/maxzoom); - qreal z = qMin(qreal(d->preferredwidth)/showarea.width(),qreal(d->preferredheight)/showarea.height()); - if (z > maxzoom/zoomFactor()) - z = maxzoom/zoomFactor(); - if (z/ozf > 1.2) { - QRectF r(showarea.left()*z, showarea.top()*z, showarea.width()*z, showarea.height()*z); - emit zoomTo(z,r.x()+r.width()/2, r.y()+r.height()/2); - return true; - } else { - return false; - } -} - -/*! - \qmlproperty int WebView::pressGrabTime - - The number of milliseconds the user must press before the WebView - starts passing move events through to the web engine (rather than - letting other QML elements such as a Flickable take them). - - Defaults to 400ms. Set to 0 to always grab and pass move events to - the web engine. -*/ -int QDeclarativeWebView::pressGrabTime() const -{ - Q_D(const QDeclarativeWebView); - return d->pressTime; -} - -void QDeclarativeWebView::setPressGrabTime(int ms) -{ - Q_D(QDeclarativeWebView); - if (d->pressTime == ms) - return; - d->pressTime = ms; - emit pressGrabTimeChanged(); -} - -void QDeclarativeWebView::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - setFocus (true); - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - - d->pressPoint = me->pos(); - if (d->pressTime) { - d->pressTimer.start(d->pressTime,this); - setKeepMouseGrab(false); - } else { - grabMouse(); - setKeepMouseGrab(true); - } - - page()->event(me); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit - Might be a bug in WebKit, though - */ -#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) { - QDeclarativePaintedItem::mousePressEvent(event); - } -} - -void QDeclarativeWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - page()->event(me); - d->pressTimer.stop(); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send all the events to WebKit - */ -#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) { - QDeclarativePaintedItem::mouseReleaseEvent(event); - } - setKeepMouseGrab(false); - ungrabMouse(); -} - -void QDeclarativeWebView::timerEvent(QTimerEvent *event) -{ - Q_D(QDeclarativeWebView); - if (event->timerId() == d->pressTimer.timerId()) { - d->pressTimer.stop(); - grabMouse(); - setKeepMouseGrab(true); - } -} - -void QDeclarativeWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - if (d->pressTimer.isActive()) { - if ((me->pos() - d->pressPoint).manhattanLength() > QApplication::startDragDistance()) { - d->pressTimer.stop(); - } - } - if (keepMouseGrab()) { - page()->event(me); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit - Might be a bug in WebKit, though - */ -#if 1 // QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - } - delete me; - if (!event->isAccepted()) - QDeclarativePaintedItem::mouseMoveEvent(event); - -} -void QDeclarativeWebView::hoverMoveEvent (QGraphicsSceneHoverEvent * event) -{ - QMouseEvent *me = sceneHoverMoveEventToMouseEvent(event); - page()->event(me); - event->setAccepted( -#if QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) - QDeclarativePaintedItem::hoverMoveEvent(event); -} - -void QDeclarativeWebView::keyPressEvent(QKeyEvent* event) -{ - page()->event(event); - if (!event->isAccepted()) - QDeclarativePaintedItem::keyPressEvent(event); -} - -void QDeclarativeWebView::keyReleaseEvent(QKeyEvent* event) -{ - page()->event(event); - if (!event->isAccepted()) - QDeclarativePaintedItem::keyReleaseEvent(event); -} - -bool QDeclarativeWebView::sceneEvent(QEvent *event) -{ - if (event->type() == QEvent::KeyPress) { - QKeyEvent *k = static_cast(event); - if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) { - if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? - page()->event(event); - if (event->isAccepted()) - return true; - } - } - } - return QDeclarativePaintedItem::sceneEvent(event); -} - - -/*! - \qmlproperty action WebView::back - This property holds the action for causing the previous URL in the history to be displayed. -*/ -QAction *QDeclarativeWebView::backAction() const -{ - return page()->action(QWebPage::Back); -} - -/*! - \qmlproperty action WebView::forward - This property holds the action for causing the next URL in the history to be displayed. -*/ -QAction *QDeclarativeWebView::forwardAction() const -{ - return page()->action(QWebPage::Forward); -} - -/*! - \qmlproperty action WebView::reload - This property holds the action for reloading with the current URL -*/ -QAction *QDeclarativeWebView::reloadAction() const -{ - return page()->action(QWebPage::Reload); -} - -/*! - \qmlproperty action WebView::stop - This property holds the action for stopping loading with the current URL -*/ -QAction *QDeclarativeWebView::stopAction() const -{ - return page()->action(QWebPage::Stop); -} - -/*! - \qmlproperty real WebView::title - This property holds the title of the web page currently viewed - - By default, this property contains an empty string. -*/ -QString QDeclarativeWebView::title() const -{ - return page()->mainFrame()->title(); -} - - - -/*! - \qmlproperty pixmap WebView::icon - This property holds the icon associated with the web page currently viewed -*/ -QPixmap QDeclarativeWebView::icon() const -{ - return page()->mainFrame()->icon().pixmap(QSize(256,256)); -} - - -/*! - \qmlproperty real WebView::zoomFactor - This property holds the multiplier used to scale the contents of a Web page. -*/ -void QDeclarativeWebView::setZoomFactor(qreal factor) -{ - Q_D(QDeclarativeWebView); - if (factor == page()->mainFrame()->zoomFactor()) - return; - - page()->mainFrame()->setZoomFactor(factor); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth*factor : width()*factor, - d->preferredheight>0 ? d->preferredheight*factor : height()*factor)); - expandToWebPage(); - - emit zoomFactorChanged(); -} - -qreal QDeclarativeWebView::zoomFactor() const -{ - return page()->mainFrame()->zoomFactor(); -} - -/*! - \qmlproperty string WebView::statusText - - This property is the current status suggested by the current web page. In a web browser, - such status is often shown in some kind of status bar. -*/ -void QDeclarativeWebView::setStatusText(const QString& s) -{ - Q_D(QDeclarativeWebView); - d->statusText = s; - emit statusTextChanged(); -} - -void QDeclarativeWebView::windowObjectCleared() -{ - Q_D(QDeclarativeWebView); - d->updateWindowObjects(); -} - -QString QDeclarativeWebView::statusText() const -{ - Q_D(const QDeclarativeWebView); - return d->statusText; -} - -QWebPage *QDeclarativeWebView::page() const -{ - Q_D(const QDeclarativeWebView); - - if (!d->page) { - QDeclarativeWebView *self = const_cast(this); - QWebPage *wp = new QDeclarativeWebPage(self); - - // QML items don't default to having a background, - // even though most we pages will set one anyway. - QPalette pal = QApplication::palette(); - pal.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0)); - wp->setPalette(pal); - - wp->setNetworkAccessManager(qmlEngine(this)->networkAccessManager()); - - self->setPage(wp); - - return wp; - } - - return d->page; -} - - -// The QObject interface to settings(). -/*! - \qmlproperty string WebView::settings.standardFontFamily - \qmlproperty string WebView::settings.fixedFontFamily - \qmlproperty string WebView::settings.serifFontFamily - \qmlproperty string WebView::settings.sansSerifFontFamily - \qmlproperty string WebView::settings.cursiveFontFamily - \qmlproperty string WebView::settings.fantasyFontFamily - - \qmlproperty int WebView::settings.minimumFontSize - \qmlproperty int WebView::settings.minimumLogicalFontSize - \qmlproperty int WebView::settings.defaultFontSize - \qmlproperty int WebView::settings.defaultFixedFontSize - - \qmlproperty bool WebView::settings.autoLoadImages - \qmlproperty bool WebView::settings.javascriptEnabled - \qmlproperty bool WebView::settings.javaEnabled - \qmlproperty bool WebView::settings.pluginsEnabled - \qmlproperty bool WebView::settings.privateBrowsingEnabled - \qmlproperty bool WebView::settings.javascriptCanOpenWindows - \qmlproperty bool WebView::settings.javascriptCanAccessClipboard - \qmlproperty bool WebView::settings.developerExtrasEnabled - \qmlproperty bool WebView::settings.linksIncludedInFocusChain - \qmlproperty bool WebView::settings.zoomTextOnly - \qmlproperty bool WebView::settings.printElementBackgrounds - \qmlproperty bool WebView::settings.offlineStorageDatabaseEnabled - \qmlproperty bool WebView::settings.offlineWebApplicationCacheEnabled - \qmlproperty bool WebView::settings.localStorageDatabaseEnabled - \qmlproperty bool WebView::settings.localContentCanAccessRemoteUrls - - These properties give access to the settings controlling the web view. - - See QWebSettings for details of these properties. - - \qml - WebView { - settings.pluginsEnabled: true - settings.standardFontFamily: "Arial" - ... - } - \endqml -*/ -QObject *QDeclarativeWebView::settingsObject() const -{ - Q_D(const QDeclarativeWebView); - d->settings.s = page()->settings(); - return &d->settings; -} - -void QDeclarativeWebView::setPage(QWebPage *page) -{ - Q_D(QDeclarativeWebView); - if (d->page == page) - return; - if (d->page) { - if (d->page->parent() == this) { - delete d->page; - } else { - d->page->disconnect(this); - } - } - d->page = page; - d->page->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - d->page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff); - d->page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff); - connect(d->page,SIGNAL(repaintRequested(QRect)),this,SLOT(paintPage(QRect))); - connect(d->page->mainFrame(),SIGNAL(urlChanged(QUrl)),this,SLOT(pageUrlChanged())); - connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString))); - connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(iconChanged())); - connect(d->page->mainFrame(), SIGNAL(iconChanged()), this, SIGNAL(iconChanged())); - connect(d->page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), this, SLOT(noteContentsSizeChanged(QSize))); - connect(d->page->mainFrame(), SIGNAL(initialLayoutCompleted()), this, SLOT(initialLayout())); - - connect(d->page,SIGNAL(loadStarted()),this,SLOT(doLoadStarted())); - connect(d->page,SIGNAL(loadProgress(int)),this,SLOT(doLoadProgress(int))); - connect(d->page,SIGNAL(loadFinished(bool)),this,SLOT(doLoadFinished(bool))); - connect(d->page,SIGNAL(statusBarMessage(QString)),this,SLOT(setStatusText(QString))); - - connect(d->page->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(windowObjectCleared())); -} - -/*! - \qmlsignal WebView::onLoadStarted() - - This handler is called when the web engine begins loading - a page. Later, WebView::onLoadFinished() or WebView::onLoadFailed() - will be emitted. -*/ - -/*! - \qmlsignal WebView::onLoadFinished() - - This handler is called when the web engine \e successfully - finishes loading a page, including any component content - (WebView::onLoadFailed() will be emitted otherwise). - - \sa progress -*/ - -/*! - \qmlsignal WebView::onLoadFailed() - - This handler is called when the web engine fails loading - a page or any component content - (WebView::onLoadFinished() will be emitted on success). -*/ - -void QDeclarativeWebView::load(const QNetworkRequest &request, - QNetworkAccessManager::Operation operation, - const QByteArray &body) -{ - page()->mainFrame()->load(request, operation, body); -} - -QString QDeclarativeWebView::html() const -{ - return page()->mainFrame()->toHtml(); -} - -/*! - \qmlproperty string WebView::html - This property holds HTML text set directly - - The html property can be set as a string. - - \qml - WebView { - html: "

This is HTML." - } - \endqml -*/ -void QDeclarativeWebView::setHtml(const QString &html, const QUrl &baseUrl) -{ - Q_D(QDeclarativeWebView); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - if (isComponentComplete()) - page()->mainFrame()->setHtml(html, baseUrl); - else { - d->pending = d->PendingHtml; - d->pending_url = baseUrl; - d->pending_string = html; - } - emit htmlChanged(); -} - -void QDeclarativeWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) -{ - Q_D(QDeclarativeWebView); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - - if (isComponentComplete()) - page()->mainFrame()->setContent(data,mimeType,qmlContext(this)->resolvedUrl(baseUrl)); - else { - d->pending = d->PendingContent; - d->pending_url = baseUrl; - d->pending_string = mimeType; - d->pending_data = data; - } -} - -QWebHistory *QDeclarativeWebView::history() const -{ - return page()->history(); -} - -QWebSettings *QDeclarativeWebView::settings() const -{ - return page()->settings(); -} - -QDeclarativeWebView *QDeclarativeWebView::createWindow(QWebPage::WebWindowType type) -{ - Q_D(QDeclarativeWebView); - switch (type) { - case QWebPage::WebBrowserWindow: { - if (!d->newWindowComponent && d->newWindowParent) - qWarning("WebView::newWindowComponent not set - WebView::newWindowParent ignored"); - else if (d->newWindowComponent && !d->newWindowParent) - qWarning("WebView::newWindowParent not set - WebView::newWindowComponent ignored"); - else if (d->newWindowComponent && d->newWindowParent) { - QDeclarativeWebView *webview = 0; - QDeclarativeContext *windowContext = new QDeclarativeContext(qmlContext(this)); - - QObject *nobj = d->newWindowComponent->create(windowContext); - if (nobj) { - windowContext->setParent(nobj); - QDeclarativeItem *item = qobject_cast(nobj); - if (!item) { - delete nobj; - } else { - webview = item->findChild(); - if (!webview) { - delete item; - } else { - nobj->setParent(d->newWindowParent); - static_cast(item)->setParentItem(d->newWindowParent); - } - } - } else { - delete windowContext; - } - - return webview; - } - } - break; - case QWebPage::WebModalDialog: { - // Not supported - } - } - return 0; -} - -/*! - \qmlproperty component WebView::newWindowComponent - - This property holds the component to use for new windows. - The component must have a WebView somewhere in its structure. - - When the web engine requests a new window, it will be an instance of - this component. - - The parent of the new window is set by newWindowParent. It must be set. -*/ -QDeclarativeComponent *QDeclarativeWebView::newWindowComponent() const -{ - Q_D(const QDeclarativeWebView); - return d->newWindowComponent; -} - -void QDeclarativeWebView::setNewWindowComponent(QDeclarativeComponent *newWindow) -{ - Q_D(QDeclarativeWebView); - if (newWindow == d->newWindowComponent) - return; - d->newWindowComponent = newWindow; - emit newWindowComponentChanged(); -} - - -/*! - \qmlproperty item WebView::newWindowParent - - The parent item for new windows. - - \sa newWindowComponent -*/ -QDeclarativeItem *QDeclarativeWebView::newWindowParent() const -{ - Q_D(const QDeclarativeWebView); - return d->newWindowParent; -} - -void QDeclarativeWebView::setNewWindowParent(QDeclarativeItem *parent) -{ - Q_D(QDeclarativeWebView); - if (parent == d->newWindowParent) - return; - if (d->newWindowParent && parent) { - QList children = d->newWindowParent->childItems(); - for (int i = 0; i < children.count(); ++i) { - children.at(i)->setParentItem(parent); - } - } - d->newWindowParent = parent; - emit newWindowParentChanged(); -} - -/*! - Returns the area of the largest element at position (\a x,\a y) that is no larger - than \a maxwidth by \a maxheight pixels. - - May return an area larger in the case when no smaller element is at the position. -*/ -QRect QDeclarativeWebView::elementAreaAt(int x, int y, int maxwidth, int maxheight) const -{ - QWebHitTestResult hit = page()->mainFrame()->hitTestContent(QPoint(x,y)); - QRect rv = hit.boundingRect(); - QWebElement element = hit.enclosingBlockElement(); - if (maxwidth<=0) maxwidth = INT_MAX; - if (maxheight<=0) maxheight = INT_MAX; - while (!element.parent().isNull() && element.geometry().width() <= maxwidth && element.geometry().height() <= maxheight) { - rv = element.geometry(); - element = element.parent(); - } - return rv; -} - -/*! - \internal - \class QDeclarativeWebPage - \brief The QDeclarativeWebPage class is a QWebPage that can create QML plugins. - - \sa QDeclarativeWebView -*/ -QDeclarativeWebPage::QDeclarativeWebPage(QDeclarativeWebView *parent) : - QWebPage(parent) -{ -} - -QDeclarativeWebPage::~QDeclarativeWebPage() -{ -} - -void QDeclarativeWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) -{ - qWarning() << sourceID << ':' << lineNumber << ':' << message; -} - -QString QDeclarativeWebPage::chooseFile(QWebFrame *originatingFrame, const QString& oldFile) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(oldFile) - return oldFile; -} - -void QDeclarativeWebPage::javaScriptAlert(QWebFrame *originatingFrame, const QString& msg) -{ - Q_UNUSED(originatingFrame) - emit viewItem()->alert(msg); -} - -bool QDeclarativeWebPage::javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(msg) - return false; -} - -bool QDeclarativeWebPage::javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(msg) - Q_UNUSED(defaultValue) - Q_UNUSED(result) - return false; -} - - -/* - Qt WebKit does not understand non-QWidget plugins, so dummy widgets - are created, parented to a single dummy tool window. - - The requirements for QML object plugins are input to the Qt WebKit - non-QWidget plugin support, which will obsolete this kludge. -*/ -class QWidget_Dummy_Plugin : public QWidget -{ - Q_OBJECT -public: - static QWidget *dummy_shared_parent() - { - static QWidget *dsp = 0; - if (!dsp) { - dsp = new QWidget(0,Qt::Tool); - dsp->setGeometry(-10000,-10000,0,0); - dsp->show(); - } - return dsp; - } - QWidget_Dummy_Plugin(const QUrl& url, QDeclarativeWebView *view, const QStringList ¶mNames, const QStringList ¶mValues) : - QWidget(dummy_shared_parent()), - propertyNames(paramNames), - propertyValues(paramValues), - webview(view) - { - QDeclarativeEngine *engine = qmlEngine(webview); - component = new QDeclarativeComponent(engine, url, this); - item = 0; - if (component->isLoading()) - connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(qmlLoaded())); - else - qmlLoaded(); - } - -public Q_SLOTS: - void qmlLoaded() - { - if (component->isError()) { - // ### Could instead give these errors to the WebView to handle. - qWarning() << component->errors(); - return; - } - item = qobject_cast(component->create(qmlContext(webview))); - item->setParent(webview); - QString jsObjName; - for (int i=0; isetProperty(propertyNames[i].toUtf8(),propertyValues[i]); - if (propertyNames[i] == QLatin1String("objectname")) - jsObjName = propertyValues[i]; - } - } - if (!jsObjName.isNull()) { - QWebFrame *f = webview->page()->mainFrame(); - f->addToJavaScriptWindowObject(jsObjName, item); - } - resizeEvent(0); - delete component; - component = 0; - } - void resizeEvent(QResizeEvent*) - { - if (item) { - item->setX(x()); - item->setY(y()); - item->setWidth(width()); - item->setHeight(height()); - } - } - -private: - QDeclarativeComponent *component; - QDeclarativeItem *item; - QStringList propertyNames, propertyValues; - QDeclarativeWebView *webview; -}; - -QDeclarativeWebView *QDeclarativeWebPage::viewItem() -{ - return static_cast(parent()); -} - -QObject *QDeclarativeWebPage::createPlugin(const QString &, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) -{ - QUrl comp = qmlContext(viewItem())->resolvedUrl(url); - return new QWidget_Dummy_Plugin(comp,viewItem(),paramNames,paramValues); -} - -QWebPage *QDeclarativeWebPage::createWindow(WebWindowType type) -{ - QDeclarativeWebView *newView = viewItem()->createWindow(type); - if (newView) - return newView->page(); - return 0; -} - -QT_END_NAMESPACE - -#include diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h deleted file mode 100644 index 0bb5d29..0000000 --- a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p.h +++ /dev/null @@ -1,285 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef QDECLARATIVEWEBVIEW_H -#define QDECLARATIVEWEBVIEW_H - -#include - -#include -#include -#include -#include - -QT_BEGIN_HEADER - -class QWebHistory; -class QWebSettings; - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) -class QDeclarativeWebViewPrivate; -class QNetworkRequest; -class QDeclarativeWebView; - -class Q_DECLARATIVE_EXPORT QDeclarativeWebPage : public QWebPage -{ - Q_OBJECT -public: - explicit QDeclarativeWebPage(QDeclarativeWebView *parent); - ~QDeclarativeWebPage(); -protected: - QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); - QWebPage *createWindow(WebWindowType type); - void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); - QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); - void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); - bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); - bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); - -private: - QDeclarativeWebView *viewItem(); -}; - - -class QDeclarativeWebViewAttached; - -//### TODO: browser plugins - -class Q_DECLARATIVE_EXPORT QDeclarativeWebView : public QDeclarativePaintedItem -{ - Q_OBJECT - - Q_ENUMS(Status SelectionMode) - - Q_PROPERTY(QString title READ title NOTIFY titleChanged) - Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged) - Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor NOTIFY zoomFactorChanged) - Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged) - - Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged) - - Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime NOTIFY pressGrabTimeChanged) - - Q_PROPERTY(int preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged) - Q_PROPERTY(int preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged) - Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) - Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) - Q_PROPERTY(Status status READ status NOTIFY statusChanged) - - Q_PROPERTY(QAction* reload READ reloadAction CONSTANT) - Q_PROPERTY(QAction* back READ backAction CONSTANT) - Q_PROPERTY(QAction* forward READ forwardAction CONSTANT) - Q_PROPERTY(QAction* stop READ stopAction CONSTANT) - - Q_PROPERTY(QObject* settings READ settingsObject CONSTANT) - - Q_PROPERTY(QDeclarativeListProperty javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT) - - Q_PROPERTY(QDeclarativeComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent NOTIFY newWindowComponentChanged) - Q_PROPERTY(QDeclarativeItem* newWindowParent READ newWindowParent WRITE setNewWindowParent NOTIFY newWindowParentChanged) - - Q_PROPERTY(bool renderingEnabled READ renderingEnabled WRITE setRenderingEnabled NOTIFY renderingEnabledChanged) - -public: - QDeclarativeWebView(QDeclarativeItem *parent=0); - ~QDeclarativeWebView(); - - QUrl url() const; - void setUrl(const QUrl &); - - QString title() const; - - QPixmap icon() const; - - qreal zoomFactor() const; - void setZoomFactor(qreal); - Q_INVOKABLE bool heuristicZoom(int clickX, int clickY, qreal maxzoom); - QRect elementAreaAt(int x, int y, int minwidth, int minheight) const; - - int pressGrabTime() const; - void setPressGrabTime(int); - - int preferredWidth() const; - void setPreferredWidth(int); - int preferredHeight() const; - void setPreferredHeight(int); - - enum Status { Null, Ready, Loading, Error }; - Status status() const; - qreal progress() const; - QString statusText() const; - - QAction *reloadAction() const; - QAction *backAction() const; - QAction *forwardAction() const; - QAction *stopAction() const; - - QWebPage *page() const; - void setPage(QWebPage *page); - - void load(const QNetworkRequest &request, - QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, - const QByteArray &body = QByteArray()); - - QString html() const; - - void setHtml(const QString &html, const QUrl &baseUrl = QUrl()); - void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl()); - - QWebHistory *history() const; - QWebSettings *settings() const; - QObject *settingsObject() const; - - bool renderingEnabled() const; - void setRenderingEnabled(bool); - - QDeclarativeListProperty javaScriptWindowObjects(); - - static QDeclarativeWebViewAttached *qmlAttachedProperties(QObject *); - - QDeclarativeComponent *newWindowComponent() const; - void setNewWindowComponent(QDeclarativeComponent *newWindow); - QDeclarativeItem *newWindowParent() const; - void setNewWindowParent(QDeclarativeItem *newWindow); - -Q_SIGNALS: - void preferredWidthChanged(); - void preferredHeightChanged(); - void urlChanged(); - void progressChanged(); - void statusChanged(Status); - void titleChanged(const QString&); - void iconChanged(); - void statusTextChanged(); - void htmlChanged(); - void pressGrabTimeChanged(); - void zoomFactorChanged(); - void newWindowComponentChanged(); - void newWindowParentChanged(); - void renderingEnabledChanged(); - - void loadStarted(); - void loadFinished(); - void loadFailed(); - - void doubleClick(int clickX, int clickY); - - void zoomTo(qreal zoom, int centerX, int centerY); - - void alert(const QString& message); - -public Q_SLOTS: - QVariant evaluateJavaScript(const QString&); - -private Q_SLOTS: - void expandToWebPage(); - void paintPage(const QRect&); - void doLoadStarted(); - void doLoadProgress(int p); - void doLoadFinished(bool ok); - void setStatusText(const QString&); - void windowObjectCleared(); - void pageUrlChanged(); - void noteContentsSizeChanged(const QSize&); - void initialLayout(); - -protected: - void drawContents(QPainter *, const QRect &); - - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - void timerEvent(QTimerEvent *event); - void hoverMoveEvent (QGraphicsSceneHoverEvent * event); - void keyPressEvent(QKeyEvent* event); - void keyReleaseEvent(QKeyEvent* event); - virtual void geometryChanged(const QRectF &newGeometry, - const QRectF &oldGeometry); - virtual void focusChanged(bool); - virtual bool sceneEvent(QEvent *event); - QDeclarativeWebView *createWindow(QWebPage::WebWindowType type); - -private: - void init(); - virtual void componentComplete(); - Q_DISABLE_COPY(QDeclarativeWebView) - Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeWebView) - QMouseEvent *sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *); - QMouseEvent *sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *); - friend class QDeclarativeWebPage; -}; - -class QDeclarativeWebViewAttached : public QObject -{ - Q_OBJECT - Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName) -public: - QDeclarativeWebViewAttached(QObject *parent) - : QObject(parent) - { - } - - QString windowObjectName() const - { - return m_windowObjectName; - } - - void setWindowObjectName(const QString &n) - { - m_windowObjectName = n; - } - -private: - QString m_windowObjectName; -}; - - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QDeclarativeWebView) -QML_DECLARE_TYPEINFO(QDeclarativeWebView, QML_HAS_ATTACHED_PROPERTIES) - -QT_END_HEADER - -#endif diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h b/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h deleted file mode 100644 index 258b472..0000000 --- a/src/plugins/qdeclarativemodules/webkitqmlplugin/qdeclarativewebview_p_p.h +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef QDECLARATIVEWEBVIEW_P_H -#define QDECLARATIVEWEBVIEW_P_H - -#include - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) - -class QDeclarativeWebSettings : public QObject { - Q_OBJECT - - Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily) - Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily) - Q_PROPERTY(QString serifFontFamily READ serifFontFamily WRITE setSerifFontFamily) - Q_PROPERTY(QString sansSerifFontFamily READ sansSerifFontFamily WRITE setSansSerifFontFamily) - Q_PROPERTY(QString cursiveFontFamily READ cursiveFontFamily WRITE setCursiveFontFamily) - Q_PROPERTY(QString fantasyFontFamily READ fantasyFontFamily WRITE setFantasyFontFamily) - - Q_PROPERTY(int minimumFontSize READ minimumFontSize WRITE setMinimumFontSize) - Q_PROPERTY(int minimumLogicalFontSize READ minimumLogicalFontSize WRITE setMinimumLogicalFontSize) - Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize) - Q_PROPERTY(int defaultFixedFontSize READ defaultFixedFontSize WRITE setDefaultFixedFontSize) - - Q_PROPERTY(bool autoLoadImages READ autoLoadImages WRITE setAutoLoadImages) - Q_PROPERTY(bool javascriptEnabled READ javascriptEnabled WRITE setJavascriptEnabled) - Q_PROPERTY(bool javaEnabled READ javaEnabled WRITE setJavaEnabled) - Q_PROPERTY(bool pluginsEnabled READ pluginsEnabled WRITE setPluginsEnabled) - Q_PROPERTY(bool privateBrowsingEnabled READ privateBrowsingEnabled WRITE setPrivateBrowsingEnabled) - Q_PROPERTY(bool javascriptCanOpenWindows READ javascriptCanOpenWindows WRITE setJavascriptCanOpenWindows) - Q_PROPERTY(bool javascriptCanAccessClipboard READ javascriptCanAccessClipboard WRITE setJavascriptCanAccessClipboard) - Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled) - Q_PROPERTY(bool linksIncludedInFocusChain READ linksIncludedInFocusChain WRITE setLinksIncludedInFocusChain) - Q_PROPERTY(bool zoomTextOnly READ zoomTextOnly WRITE setZoomTextOnly) - Q_PROPERTY(bool printElementBackgrounds READ printElementBackgrounds WRITE setPrintElementBackgrounds) - Q_PROPERTY(bool offlineStorageDatabaseEnabled READ offlineStorageDatabaseEnabled WRITE setOfflineStorageDatabaseEnabled) - Q_PROPERTY(bool offlineWebApplicationCacheEnabled READ offlineWebApplicationCacheEnabled WRITE setOfflineWebApplicationCacheEnabled) - Q_PROPERTY(bool localStorageDatabaseEnabled READ localStorageDatabaseEnabled WRITE setLocalStorageDatabaseEnabled) - Q_PROPERTY(bool localContentCanAccessRemoteUrls READ localContentCanAccessRemoteUrls WRITE setLocalContentCanAccessRemoteUrls) - -public: - QDeclarativeWebSettings() {} - - QString standardFontFamily() const { return s->fontFamily(QWebSettings::StandardFont); } - void setStandardFontFamily(const QString& f) { s->setFontFamily(QWebSettings::StandardFont,f); } - QString fixedFontFamily() const { return s->fontFamily(QWebSettings::FixedFont); } - void setFixedFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FixedFont,f); } - QString serifFontFamily() const { return s->fontFamily(QWebSettings::SerifFont); } - void setSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SerifFont,f); } - QString sansSerifFontFamily() const { return s->fontFamily(QWebSettings::SansSerifFont); } - void setSansSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SansSerifFont,f); } - QString cursiveFontFamily() const { return s->fontFamily(QWebSettings::CursiveFont); } - void setCursiveFontFamily(const QString& f) { s->setFontFamily(QWebSettings::CursiveFont,f); } - QString fantasyFontFamily() const { return s->fontFamily(QWebSettings::FantasyFont); } - void setFantasyFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FantasyFont,f); } - - int minimumFontSize() const { return s->fontSize(QWebSettings::MinimumFontSize); } - void setMinimumFontSize(int size) { s->setFontSize(QWebSettings::MinimumFontSize,size); } - int minimumLogicalFontSize() const { return s->fontSize(QWebSettings::MinimumLogicalFontSize); } - void setMinimumLogicalFontSize(int size) { s->setFontSize(QWebSettings::MinimumLogicalFontSize,size); } - int defaultFontSize() const { return s->fontSize(QWebSettings::DefaultFontSize); } - void setDefaultFontSize(int size) { s->setFontSize(QWebSettings::DefaultFontSize,size); } - int defaultFixedFontSize() const { return s->fontSize(QWebSettings::DefaultFixedFontSize); } - void setDefaultFixedFontSize(int size) { s->setFontSize(QWebSettings::DefaultFixedFontSize,size); } - - bool autoLoadImages() const { return s->testAttribute(QWebSettings::AutoLoadImages); } - void setAutoLoadImages(bool on) { s->setAttribute(QWebSettings::AutoLoadImages, on); } - bool javascriptEnabled() const { return s->testAttribute(QWebSettings::JavascriptEnabled); } - void setJavascriptEnabled(bool on) { s->setAttribute(QWebSettings::JavascriptEnabled, on); } - bool javaEnabled() const { return s->testAttribute(QWebSettings::JavaEnabled); } - void setJavaEnabled(bool on) { s->setAttribute(QWebSettings::JavaEnabled, on); } - bool pluginsEnabled() const { return s->testAttribute(QWebSettings::PluginsEnabled); } - void setPluginsEnabled(bool on) { s->setAttribute(QWebSettings::PluginsEnabled, on); } - bool privateBrowsingEnabled() const { return s->testAttribute(QWebSettings::PrivateBrowsingEnabled); } - void setPrivateBrowsingEnabled(bool on) { s->setAttribute(QWebSettings::PrivateBrowsingEnabled, on); } - bool javascriptCanOpenWindows() const { return s->testAttribute(QWebSettings::JavascriptCanOpenWindows); } - void setJavascriptCanOpenWindows(bool on) { s->setAttribute(QWebSettings::JavascriptCanOpenWindows, on); } - bool javascriptCanAccessClipboard() const { return s->testAttribute(QWebSettings::JavascriptCanAccessClipboard); } - void setJavascriptCanAccessClipboard(bool on) { s->setAttribute(QWebSettings::JavascriptCanAccessClipboard, on); } - bool developerExtrasEnabled() const { return s->testAttribute(QWebSettings::DeveloperExtrasEnabled); } - void setDeveloperExtrasEnabled(bool on) { s->setAttribute(QWebSettings::DeveloperExtrasEnabled, on); } - bool linksIncludedInFocusChain() const { return s->testAttribute(QWebSettings::LinksIncludedInFocusChain); } - void setLinksIncludedInFocusChain(bool on) { s->setAttribute(QWebSettings::LinksIncludedInFocusChain, on); } - bool zoomTextOnly() const { return s->testAttribute(QWebSettings::ZoomTextOnly); } - void setZoomTextOnly(bool on) { s->setAttribute(QWebSettings::ZoomTextOnly, on); } - bool printElementBackgrounds() const { return s->testAttribute(QWebSettings::PrintElementBackgrounds); } - void setPrintElementBackgrounds(bool on) { s->setAttribute(QWebSettings::PrintElementBackgrounds, on); } - bool offlineStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled); } - void setOfflineStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, on); } - bool offlineWebApplicationCacheEnabled() const { return s->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled); } - void setOfflineWebApplicationCacheEnabled(bool on) { s->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, on); } - bool localStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::LocalStorageDatabaseEnabled); } - void setLocalStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, on); } - bool localContentCanAccessRemoteUrls() const { return s->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls); } - void setLocalContentCanAccessRemoteUrls(bool on) { s->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, on); } - - QWebSettings *s; -}; - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QDeclarativeWebSettings) - -QT_END_HEADER - -#endif diff --git a/src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro b/src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro deleted file mode 100644 index 37fe37c..0000000 --- a/src/plugins/qdeclarativemodules/webkitqmlplugin/webkitqmlplugin.pro +++ /dev/null @@ -1,18 +0,0 @@ -TARGET = webkitqmlplugin -include(../../qpluginbase.pri) - -contains(QT_CONFIG, webkit) { - QT += webkit declarative - - SOURCES += qdeclarativewebview.cpp plugin.cpp - HEADERS += qdeclarativewebview_p.h - HEADERS += qdeclarativewebview_p_p.h - - QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/org/webkit - target.path = $$[QT_INSTALL_IMPORTS]/org/webkit - - qmldir.files += $$QT_BUILD_TREE/imports/org/webkit/qmldir - qmldir.path += $$[QT_INSTALL_IMPORTS]/org/webkit - - INSTALLS += target qmldir -} diff --git a/src/plugins/qdeclarativemodules/widgets/graphicslayouts.cpp b/src/plugins/qdeclarativemodules/widgets/graphicslayouts.cpp deleted file mode 100644 index fc15ad2..0000000 --- a/src/plugins/qdeclarativemodules/widgets/graphicslayouts.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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 "graphicslayouts_p.h" - -#include -#include - -QT_BEGIN_NAMESPACE - -LinearLayoutAttached::LinearLayoutAttached(QObject *parent) -: QObject(parent), _stretch(1), _alignment(Qt::AlignCenter) -{ -} - -void LinearLayoutAttached::setStretchFactor(int f) -{ - if (_stretch == f) - return; - - _stretch = f; - emit stretchChanged(reinterpret_cast(parent()), _stretch); -} - -void LinearLayoutAttached::setAlignment(Qt::Alignment a) -{ - if (_alignment == a) - return; - - _alignment = a; - emit alignmentChanged(reinterpret_cast(parent()), _alignment); -} - -QGraphicsLinearLayoutStretchItemObject::QGraphicsLinearLayoutStretchItemObject(QObject *parent) - : QObject(parent) -{ -} - -QSizeF QGraphicsLinearLayoutStretchItemObject::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const -{ -Q_UNUSED(which); -Q_UNUSED(constraint); -return QSizeF(); -} - - -QGraphicsLinearLayoutObject::QGraphicsLinearLayoutObject(QObject *parent) -: QObject(parent) -{ -} - -QGraphicsLinearLayoutObject::~QGraphicsLinearLayoutObject() -{ -} - -void QGraphicsLinearLayoutObject::insertLayoutItem(int index, QGraphicsLayoutItem *item) -{ -insertItem(index, item); - -//connect attached properties -if (LinearLayoutAttached *obj = attachedProperties.value(item)) { - setStretchFactor(item, obj->stretchFactor()); - setAlignment(item, obj->alignment()); - QObject::connect(obj, SIGNAL(stretchChanged(QGraphicsLayoutItem*,int)), - this, SLOT(updateStretch(QGraphicsLayoutItem*,int))); - QObject::connect(obj, SIGNAL(alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment)), - this, SLOT(updateAlignment(QGraphicsLayoutItem*,Qt::Alignment))); - //### need to disconnect when widget is removed? -} -} - -//### is there a better way to do this? -void QGraphicsLinearLayoutObject::clearChildren() -{ -for (int i = 0; i < count(); ++i) - removeAt(i); -} - -void QGraphicsLinearLayoutObject::updateStretch(QGraphicsLayoutItem *item, int stretch) -{ -QGraphicsLinearLayout::setStretchFactor(item, stretch); -} - -void QGraphicsLinearLayoutObject::updateAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment) -{ -QGraphicsLinearLayout::setAlignment(item, alignment); -} - -QHash QGraphicsLinearLayoutObject::attachedProperties; -LinearLayoutAttached *QGraphicsLinearLayoutObject::qmlAttachedProperties(QObject *obj) -{ -// ### This is not allowed - you must attach to any object -if (!qobject_cast(obj)) - return 0; -LinearLayoutAttached *rv = new LinearLayoutAttached(obj); -attachedProperties.insert(qobject_cast(obj), rv); -return rv; -} - -////////////////////////////////////////////////////////////////////////////////////////////////////// -// QGraphicsGridLayout-related classes -////////////////////////////////////////////////////////////////////////////////////////////////////// -GridLayoutAttached::GridLayoutAttached(QObject *parent) -: QObject(parent), _row(-1), _column(-1), _rowspan(1), _colspan(1), _alignment(-1) -{ -} - -void GridLayoutAttached::setRow(int r) -{ - if (_row == r) - return; - - _row = r; - //emit rowChanged(reinterpret_cast(parent()), _row); -} - -void GridLayoutAttached::setColumn(int c) -{ - if (_column == c) - return; - - _column = c; - //emit columnChanged(reinterpret_cast(parent()), _column); -} - -void GridLayoutAttached::setRowSpan(int rs) -{ - if (_rowspan == rs) - return; - - _rowspan = rs; - //emit rowSpanChanged(reinterpret_cast(parent()), _rowSpan); -} - -void GridLayoutAttached::setColumnSpan(int cs) -{ - if (_colspan == cs) - return; - - _colspan = cs; - //emit columnSpanChanged(reinterpret_cast(parent()), _columnSpan); -} - -void GridLayoutAttached::setAlignment(Qt::Alignment a) -{ - if (_alignment == a) - return; - - _alignment = a; - //emit alignmentChanged(reinterpret_cast(parent()), _alignment); -} - -QGraphicsGridLayoutObject::QGraphicsGridLayoutObject(QObject *parent) -: QObject(parent) -{ -} - -QGraphicsGridLayoutObject::~QGraphicsGridLayoutObject() -{ -} - -void QGraphicsGridLayoutObject::addWidget(QGraphicsWidget *wid) -{ -//use attached properties -if (QObject *obj = attachedProperties.value(qobject_cast(wid))) { - int row = static_cast(obj)->row(); - int column = static_cast(obj)->column(); - int rowSpan = static_cast(obj)->rowSpan(); - int columnSpan = static_cast(obj)->columnSpan(); - if (row == -1 || column == -1) { - qWarning() << "Must set row and column for an item in a grid layout"; - return; - } - addItem(wid, row, column, rowSpan, columnSpan); -} -} - -void QGraphicsGridLayoutObject::addLayoutItem(QGraphicsLayoutItem *item) -{ -//use attached properties -if (GridLayoutAttached *obj = attachedProperties.value(item)) { - int row = obj->row(); - int column = obj->column(); - int rowSpan = obj->rowSpan(); - int columnSpan = obj->columnSpan(); - Qt::Alignment alignment = obj->alignment(); - if (row == -1 || column == -1) { - qWarning() << "Must set row and column for an item in a grid layout"; - return; - } - addItem(item, row, column, rowSpan, columnSpan); - if (alignment != -1) - setAlignment(item,alignment); -} -} - -//### is there a better way to do this? -void QGraphicsGridLayoutObject::clearChildren() -{ -for (int i = 0; i < count(); ++i) - removeAt(i); -} - -qreal QGraphicsGridLayoutObject::spacing() const -{ -if (verticalSpacing() == horizontalSpacing()) - return verticalSpacing(); -return -1; //### -} - -QHash QGraphicsGridLayoutObject::attachedProperties; -GridLayoutAttached *QGraphicsGridLayoutObject::qmlAttachedProperties(QObject *obj) -{ -// ### This is not allowed - you must attach to any object -if (!qobject_cast(obj)) - return 0; -GridLayoutAttached *rv = new GridLayoutAttached(obj); -attachedProperties.insert(qobject_cast(obj), rv); -return rv; -} - -QT_END_NAMESPACE diff --git a/src/plugins/qdeclarativemodules/widgets/graphicslayouts_p.h b/src/plugins/qdeclarativemodules/widgets/graphicslayouts_p.h deleted file mode 100644 index f9b9ae8..0000000 --- a/src/plugins/qdeclarativemodules/widgets/graphicslayouts_p.h +++ /dev/null @@ -1,226 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef GRAPHICSLAYOUTS_H -#define GRAPHICSLAYOUTS_H - -#include "graphicswidgets_p.h" - -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) - -class QGraphicsLinearLayoutStretchItemObject : public QObject, public QGraphicsLayoutItem -{ - Q_OBJECT - Q_INTERFACES(QGraphicsLayoutItem) -public: - QGraphicsLinearLayoutStretchItemObject(QObject *parent = 0); - - virtual QSizeF sizeHint(Qt::SizeHint, const QSizeF &) const; -}; - -class LinearLayoutAttached; -class QGraphicsLinearLayoutObject : public QObject, public QGraphicsLinearLayout -{ - Q_OBJECT - Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation) - Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsLinearLayoutObject(QObject * = 0); - ~QGraphicsLinearLayoutObject(); - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } - - static LinearLayoutAttached *qmlAttachedProperties(QObject *); - -private Q_SLOTS: - void updateStretch(QGraphicsLayoutItem*,int); - void updateAlignment(QGraphicsLayoutItem*,Qt::Alignment); - -private: - friend class LinearLayoutAttached; - void clearChildren(); - void insertLayoutItem(int, QGraphicsLayoutItem *); - static QHash attachedProperties; - - static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { - static_cast(prop->object)->insertLayoutItem(-1, item); - } - - static void children_clear(QDeclarativeListProperty *prop) { - static_cast(prop->object)->clearChildren(); - } - - static int children_count(QDeclarativeListProperty *prop) { - return static_cast(prop->object)->count(); - } - - static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { - return static_cast(prop->object)->itemAt(index); - } -}; - -class GridLayoutAttached; -class QGraphicsGridLayoutObject : public QObject, public QGraphicsGridLayout -{ - Q_OBJECT - Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) - Q_PROPERTY(qreal verticalSpacing READ verticalSpacing WRITE setVerticalSpacing) - Q_PROPERTY(qreal horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsGridLayoutObject(QObject * = 0); - ~QGraphicsGridLayoutObject(); - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } - - qreal spacing() const; - - static GridLayoutAttached *qmlAttachedProperties(QObject *); - -private: - friend class GraphicsLayoutAttached; - void addWidget(QGraphicsWidget *); - void clearChildren(); - void addLayoutItem(QGraphicsLayoutItem *); - static QHash attachedProperties; - - static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { - static_cast(prop->object)->addLayoutItem(item); - } - - static void children_clear(QDeclarativeListProperty *prop) { - static_cast(prop->object)->clearChildren(); - } - - static int children_count(QDeclarativeListProperty *prop) { - return static_cast(prop->object)->count(); - } - - static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { - return static_cast(prop->object)->itemAt(index); - } -}; - -class LinearLayoutAttached : public QObject -{ - Q_OBJECT - - Q_PROPERTY(int stretchFactor READ stretchFactor WRITE setStretchFactor NOTIFY stretchChanged) - Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) -public: - LinearLayoutAttached(QObject *parent); - - int stretchFactor() const { return _stretch; } - void setStretchFactor(int f); - Qt::Alignment alignment() const { return _alignment; } - void setAlignment(Qt::Alignment a); - -Q_SIGNALS: - void stretchChanged(QGraphicsLayoutItem*,int); - void alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment); - -private: - int _stretch; - Qt::Alignment _alignment; -}; - -class GridLayoutAttached : public QObject -{ - Q_OBJECT - - Q_PROPERTY(int row READ row WRITE setRow) - Q_PROPERTY(int column READ column WRITE setColumn) - Q_PROPERTY(int rowSpan READ rowSpan WRITE setRowSpan) - Q_PROPERTY(int columnSpan READ columnSpan WRITE setColumnSpan) - Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment) -public: - GridLayoutAttached(QObject *parent); - - int row() const { return _row; } - void setRow(int r); - - int column() const { return _column; } - void setColumn(int c); - - int rowSpan() const { return _rowspan; } - void setRowSpan(int rs); - - int columnSpan() const { return _colspan; } - void setColumnSpan(int cs); - - Qt::Alignment alignment() const { return _alignment; } - void setAlignment(Qt::Alignment a); - -private: - int _row; - int _column; - int _rowspan; - int _colspan; - Qt::Alignment _alignment; -}; - -QT_END_NAMESPACE - -QML_DECLARE_INTERFACE(QGraphicsLayoutItem) -QML_DECLARE_INTERFACE(QGraphicsLayout) -QML_DECLARE_TYPE(QGraphicsLinearLayoutStretchItemObject) -QML_DECLARE_TYPE(QGraphicsLinearLayoutObject) -QML_DECLARE_TYPEINFO(QGraphicsLinearLayoutObject, QML_HAS_ATTACHED_PROPERTIES) -QML_DECLARE_TYPE(QGraphicsGridLayoutObject) -QML_DECLARE_TYPEINFO(QGraphicsGridLayoutObject, QML_HAS_ATTACHED_PROPERTIES) - -QT_END_HEADER - -#endif // GRAPHICSLAYOUTS_H diff --git a/src/plugins/qdeclarativemodules/widgets/graphicswidgets.cpp b/src/plugins/qdeclarativemodules/widgets/graphicswidgets.cpp deleted file mode 100644 index 062e516..0000000 --- a/src/plugins/qdeclarativemodules/widgets/graphicswidgets.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ diff --git a/src/plugins/qdeclarativemodules/widgets/graphicswidgets_p.h b/src/plugins/qdeclarativemodules/widgets/graphicswidgets_p.h deleted file mode 100644 index 2c2b707..0000000 --- a/src/plugins/qdeclarativemodules/widgets/graphicswidgets_p.h +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef GRAPHICSWIDGETS_H -#define GRAPHICSWIDGETS_H - -#include - -#include -#include -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QGraphicsView) -QML_DECLARE_TYPE_HASMETATYPE(QGraphicsScene) -QML_DECLARE_TYPE(QGraphicsWidget) -QML_DECLARE_TYPE(QGraphicsObject) -QML_DECLARE_INTERFACE_HASMETATYPE(QGraphicsItem) - -QT_END_HEADER - -#endif // GRAPHICSWIDGETS_H diff --git a/src/plugins/qdeclarativemodules/widgets/widgets.cpp b/src/plugins/qdeclarativemodules/widgets/widgets.cpp deleted file mode 100644 index ec21cc4..0000000 --- a/src/plugins/qdeclarativemodules/widgets/widgets.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the plugins 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 -#include - -#include "graphicslayouts_p.h" -#include "graphicswidgets_p.h" - -QT_BEGIN_NAMESPACE - -class QGraphicsViewDeclarativeUI : public QObject -{ - Q_OBJECT - - Q_PROPERTY(QGraphicsScene *scene READ scene WRITE setScene) - Q_CLASSINFO("DefaultProperty", "scene") -public: - QGraphicsViewDeclarativeUI(QObject *other) : QObject(other) {} - - QGraphicsScene *scene() const { return static_cast(parent())->scene(); } - void setScene(QGraphicsScene *scene) - { - static_cast(parent())->setScene(scene); - } -}; - -class QGraphicsSceneDeclarativeUI : public QObject -{ - Q_OBJECT - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsSceneDeclarativeUI(QObject *other) : QObject(other) {} - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this->parent(), 0, children_append); } - -private: - static void children_append(QDeclarativeListProperty *prop, QObject *o) { - if (QGraphicsObject *go = qobject_cast(o)) - static_cast(prop->object)->addItem(go); - } -}; - -class QGraphicsWidgetDeclarativeUI : public QObject -{ - Q_OBJECT - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_PROPERTY(QGraphicsLayout *layout READ layout WRITE setLayout) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsWidgetDeclarativeUI(QObject *other) : QObject(other) {} - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append); } - - QGraphicsLayout *layout() const { return static_cast(parent())->layout(); } - void setLayout(QGraphicsLayout *lo) - { - static_cast(parent())->setLayout(lo); - } - -private: - void setItemParent(QGraphicsItem *wid) - { - wid->setParentItem(static_cast(parent())); - } - - static void children_append(QDeclarativeListProperty *prop, QGraphicsItem *i) { - static_cast(prop->object)->setItemParent(i); - } -}; - -class QWidgetsQmlModule : public QDeclarativeExtensionPlugin -{ - Q_OBJECT -public: - virtual void registerTypes(const char *uri) - { - Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.widgets")); - - QML_REGISTER_INTERFACE(QGraphicsLayoutItem); - QML_REGISTER_INTERFACE(QGraphicsLayout); - qmlRegisterType(uri,4,6,"QGraphicsLinearLayoutStretchItem"); - qmlRegisterType(uri,4,6,"QGraphicsLinearLayout"); - qmlRegisterType(uri,4,6,"QGraphicsGridLayout"); - qmlRegisterExtendedType(uri,4,6,"QGraphicsView"); - qmlRegisterExtendedType(uri,4,6,"QGraphicsScene"); - qmlRegisterExtendedType(uri,4,6,"QGraphicsWidget"); - QML_REGISTER_INTERFACE(QGraphicsItem); - } -}; - -QT_END_NAMESPACE - -#include "widgets.moc" - -Q_EXPORT_PLUGIN2(qtwidgetsqmlmodule, QT_PREPEND_NAMESPACE(QWidgetsQmlModule)); - diff --git a/src/plugins/qdeclarativemodules/widgets/widgets.pro b/src/plugins/qdeclarativemodules/widgets/widgets.pro deleted file mode 100644 index 3ec38da..0000000 --- a/src/plugins/qdeclarativemodules/widgets/widgets.pro +++ /dev/null @@ -1,20 +0,0 @@ -TARGET = widgets -include(../../qpluginbase.pri) - -QT += declarative - -SOURCES += \ - graphicslayouts.cpp \ - widgets.cpp - -HEADERS += \ - graphicswidgets_p.h \ - graphicslayouts_p.h - -QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/widgets -target.path = $$[QT_INSTALL_IMPORTS]/Qt/widgets - -qmldir.files += $$QT_BUILD_TREE/imports/Qt/widgets/qmldir -qmldir.path += $$[QT_INSTALL_IMPORTS]/Qt/widgets - -INSTALLS += target qmldir -- cgit v0.12 From b277a6932c32ce4bae015cce6e1c00c322b4a63b Mon Sep 17 00:00:00 2001 From: mae Date: Tue, 2 Mar 2010 12:13:44 +0100 Subject: Let the 'qml' runtime use its applicationDirPath as importsPath The is analog to the plugin system in Qt. It makes it possible to ship an executable with extra plugins resp. qml import modules without creating a qt.conf. --- tools/qml/main.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/qml/main.cpp b/tools/qml/main.cpp index 6339813..a4de339 100644 --- a/tools/qml/main.cpp +++ b/tools/qml/main.cpp @@ -311,8 +311,11 @@ int main(int argc, char ** argv) usage(); } + viewer.addLibraryPath(QCoreApplication::applicationDirPath()); + foreach (QString lib, libraries) viewer.addLibraryPath(lib); + viewer.setNetworkCacheSize(cache); viewer.setRecordFile(recordfile); if (resizeview) -- cgit v0.12 From e0a9e34b6e776be1df3b3fae68d20f242aa07e6a Mon Sep 17 00:00:00 2001 From: mae Date: Tue, 2 Mar 2010 12:39:38 +0100 Subject: Fix qml import modules loading on Windows On windows, when importing a declarative plugin by name, extend with "d.dll" in the debug case, then with ".dll". This is in sync with qmake's behaviour for libraries. --- src/declarative/qml/qdeclarativeengine.cpp | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/declarative/qml/qdeclarativeengine.cpp b/src/declarative/qml/qdeclarativeengine.cpp index af75e98..277c602 100644 --- a/src/declarative/qml/qdeclarativeengine.cpp +++ b/src/declarative/qml/qdeclarativeengine.cpp @@ -1687,6 +1687,7 @@ QString QDeclarativeEngine::offlineStoragePath() const \internal Returns the result of the merge of \a baseName with \a dir, \a suffixes, and \a prefix. + The \a prefix must contain the dot. */ QString QDeclarativeEnginePrivate::resolvePlugin(const QDir &dir, const QString &baseName, const QStringList &suffixes, @@ -1696,7 +1697,6 @@ QString QDeclarativeEnginePrivate::resolvePlugin(const QDir &dir, const QString QString pluginFileName = prefix; pluginFileName += baseName; - pluginFileName += QLatin1Char('.'); pluginFileName += suffix; QFileInfo fileInfo(dir, pluginFileName); @@ -1728,14 +1728,26 @@ QString QDeclarativeEnginePrivate::resolvePlugin(const QDir &dir, const QString QString QDeclarativeEnginePrivate::resolvePlugin(const QDir &dir, const QString &baseName) { #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE) - return resolvePlugin(dir, baseName, QStringList(QLatin1String("dll"))); + return resolvePlugin(dir, baseName, + QStringList() +# ifdef QT_DEBUG + << QLatin1String("d.dll") // try a qmake-style debug build first +# endif + << QLatin1String(".dll"); #elif defined(Q_OS_SYMBIAN) - return resolvePlugin(dir, baseName, QStringList() << QLatin1String("dll") << QLatin1String("qtplugin")); + return resolvePlugin(dir, baseName, + QStringList() + << QLatin1String(".dll") + << QLatin1String(".qtplugin")); #else # if defined(Q_OS_DARWIN) - return resolvePlugin(dir, baseName, QStringList() << QLatin1String("dylib") << QLatin1String("so") << QLatin1String("bundle"), + return resolvePlugin(dir, baseName, + QStringList() + << QLatin1String(".dylib") + << QLatin1String(".so") + << QLatin1String(".bundle"), QLatin1String("lib")); # else // Generic Unix QStringList validSuffixList; @@ -1746,14 +1758,14 @@ QString QDeclarativeEnginePrivate::resolvePlugin(const QDir &dir, const QString "In PA-RISC (PA-32 and PA-64) shared libraries are suffixed with .sl. In IPF (32-bit and 64-bit), the shared libraries are suffixed with .so. For compatibility, the IPF linker also supports the .sl suffix." */ - validSuffixList << QLatin1String("sl"); + validSuffixList << QLatin1String(".sl"); # if defined __ia64 - validSuffixList << QLatin1String("so"); + validSuffixList << QLatin1String(".so"); # endif # elif defined(Q_OS_AIX) - validSuffixList << QLatin1String("a") << QLatin1String("so"); + validSuffixList << QLatin1String(".a") << QLatin1String(".so"); # elif defined(Q_OS_UNIX) - validSuffixList << QLatin1String("so"); + validSuffixList << QLatin1String(".so"); # endif // Examples of valid library names: -- cgit v0.12 From 3708ff474a987ddb82f7b66d8c686f499b65eeb6 Mon Sep 17 00:00:00 2001 From: aavit Date: Tue, 2 Mar 2010 13:36:55 +0100 Subject: Updates to changes file Reviewed-by: trustme --- dist/changes-4.7.0 | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/dist/changes-4.7.0 b/dist/changes-4.7.0 index 013f1ce..4d776ee 100644 --- a/dist/changes-4.7.0 +++ b/dist/changes-4.7.0 @@ -30,6 +30,12 @@ General Improvements Third party components ---------------------- + - Updated libpng to version 1.4.0 + + - Updated libjpeg to version 8 + + - Updated libtiff to version 3.9.2 + **************************************************************************** * Library * -- cgit v0.12 From 2afda558815bc29c1f54e7b9bcc0312369dd7d79 Mon Sep 17 00:00:00 2001 From: Tobias Hunger Date: Tue, 2 Mar 2010 13:41:05 +0100 Subject: Build fix on windows --- src/declarative/qml/qdeclarativeengine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/qml/qdeclarativeengine.cpp b/src/declarative/qml/qdeclarativeengine.cpp index 277c602..ecaea61 100644 --- a/src/declarative/qml/qdeclarativeengine.cpp +++ b/src/declarative/qml/qdeclarativeengine.cpp @@ -1733,7 +1733,7 @@ QString QDeclarativeEnginePrivate::resolvePlugin(const QDir &dir, const QString # ifdef QT_DEBUG << QLatin1String("d.dll") // try a qmake-style debug build first # endif - << QLatin1String(".dll"); + << QLatin1String(".dll")); #elif defined(Q_OS_SYMBIAN) return resolvePlugin(dir, baseName, QStringList() -- cgit v0.12 From a140e37fab6a1d028fd1b751a98774dacb4f1a89 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 2 Mar 2010 13:42:05 +0100 Subject: Fix & move QEgl::native* to platform-specific files This should fix build on Symbian & WinCE Reviewed-By: TrustMe --- src/gui/egl/qegl.cpp | 19 ------------------- src/gui/egl/qegl_qws.cpp | 17 +++++++++++++++++ src/gui/egl/qegl_symbian.cpp | 11 +++++++++++ src/gui/egl/qegl_wince.cpp | 11 +++++++++++ src/gui/egl/qegl_x11.cpp | 11 ++++++++++- 5 files changed, 49 insertions(+), 20 deletions(-) diff --git a/src/gui/egl/qegl.cpp b/src/gui/egl/qegl.cpp index 1bfba10..485bfbf 100644 --- a/src/gui/egl/qegl.cpp +++ b/src/gui/egl/qegl.cpp @@ -549,25 +549,6 @@ EGLDisplay QEgl::display() return dpy; } -#if !defined(Q_WS_X11) && !defined(Q_WS_WINCE) // WinCE & X11 implement this properly -EGLNativeDisplayType QEgl::nativeDisplay() -{ - return EGL_DEFAULT_DISPLAY; -} -#endif - -#if !defined(Q_OS_SYMBIAN) -EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) -{ - return (EGLNativeWindowType)(widget->winId()); -} -#endif - -EGLNativePixmapType QEgl::nativePixmap(QPixmap* pixmap) -{ - return (EGLNativePixmapType)(pixmap->handle()); -} - #ifndef Q_WS_X11 EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig cfg, const QEglProperties *properties) { diff --git a/src/gui/egl/qegl_qws.cpp b/src/gui/egl/qegl_qws.cpp index eb41bcc..56383a5 100644 --- a/src/gui/egl/qegl_qws.cpp +++ b/src/gui/egl/qegl_qws.cpp @@ -92,6 +92,23 @@ void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev) setPixelFormat(screen->pixelFormat()); } +EGLNativeDisplayType QEgl::nativeDisplay() +{ + return EGL_DEFAULT_DISPLAY; +} + +EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) +{ + return (EGLNativeWindowType)(widget->winId()); // Might work +} + +EGLNativePixmapType QEgl::nativePixmap(QPixmap*) +{ + qWarning("QEgl: EGL pixmap surfaces not supported on QWS"); + return (EGLNativePixmapType)0; +} + + QT_END_NAMESPACE #endif // !QT_NO_EGL diff --git a/src/gui/egl/qegl_symbian.cpp b/src/gui/egl/qegl_symbian.cpp index 8833b42..9744ed0 100644 --- a/src/gui/egl/qegl_symbian.cpp +++ b/src/gui/egl/qegl_symbian.cpp @@ -50,11 +50,22 @@ QT_BEGIN_NAMESPACE +EGLNativeDisplayType QEgl::nativeDisplay() +{ + return EGL_DEFAULT_DISPLAY; +} + EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) { return (EGLNativeWindowType)(widget->winId()->DrawableWindow()); } +EGLNativePixmapType QEgl::nativePixmap(QPixmap*) +{ + qWarning("QEgl: EGL pixmap surfaces not implemented yet on Symbian"); + return (EGLNativePixmapType)0; +} + // Set pixel format and other properties based on a paint device. void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev) { diff --git a/src/gui/egl/qegl_wince.cpp b/src/gui/egl/qegl_wince.cpp index b201153..c07b20b 100644 --- a/src/gui/egl/qegl_wince.cpp +++ b/src/gui/egl/qegl_wince.cpp @@ -62,6 +62,17 @@ EGLNativeDisplayType QEgl::nativeDisplay() return EGLNativeDisplayType(myDc); } +EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) +{ + return (EGLNativeWindowType)(widget->winId()); +} + +EGLNativePixmapType QEgl::nativePixmap(QPixmap*) +{ + qWarning("QEgl: EGL pixmap surfaces not supported on WinCE"); + return (EGLNativePixmapType)0; +} + // Set pixel format and other properties based on a paint device. void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev) { diff --git a/src/gui/egl/qegl_x11.cpp b/src/gui/egl/qegl_x11.cpp index a4bfcac..339bd57 100644 --- a/src/gui/egl/qegl_x11.cpp +++ b/src/gui/egl/qegl_x11.cpp @@ -67,6 +67,16 @@ EGLNativeDisplayType QEgl::nativeDisplay() return EGLNativeDisplayType(xdpy); } +EGLNativeWindowType QEgl::nativeWindow(QWidget* widget) +{ + return (EGLNativeWindowType)(widget->winId()); +} + +EGLNativePixmapType QEgl::nativePixmap(QPixmap* pixmap) +{ + return (EGLNativePixmapType)(pixmap->handle()); +} + static int countBits(unsigned long mask) { int count = 0; @@ -399,5 +409,4 @@ EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig config, const QEg return EGL_NO_SURFACE; } - QT_END_NAMESPACE -- cgit v0.12 From 89429d192dc14044f6d27c9dde06811f1f23b954 Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Tue, 2 Mar 2010 14:17:08 +0100 Subject: Compile fix on Windows --- src/declarative/qml/qdeclarativelist.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/qml/qdeclarativelist.h b/src/declarative/qml/qdeclarativelist.h index 8d59384..eac4967 100644 --- a/src/declarative/qml/qdeclarativelist.h +++ b/src/declarative/qml/qdeclarativelist.h @@ -53,7 +53,7 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) class QObject; -class QMetaObject; +struct QMetaObject; template struct QDeclarativeListProperty { typedef void (*AppendFunction)(QDeclarativeListProperty *, T*); -- cgit v0.12 From 7fd5ade07bd05ff6cb6f4e7cfa7a74081b803809 Mon Sep 17 00:00:00 2001 From: mae Date: Tue, 2 Mar 2010 15:00:23 +0100 Subject: Adapted example to use the import mechanism --- .../imageprovider/ImageProviderCore/qmldir | 2 + .../declarative/imageprovider/imageprovider.cpp | 107 +++++++++++++++++++++ .../declarative/imageprovider/imageprovider.pro | 14 +-- .../declarative/imageprovider/imageprovider.qml | 23 +++++ .../declarative/imageprovider/imageprovider.qrc | 5 - examples/declarative/imageprovider/main.cpp | 98 ------------------- examples/declarative/imageprovider/view.qml | 22 ----- 7 files changed, 140 insertions(+), 131 deletions(-) create mode 100644 examples/declarative/imageprovider/ImageProviderCore/qmldir create mode 100644 examples/declarative/imageprovider/imageprovider.cpp create mode 100644 examples/declarative/imageprovider/imageprovider.qml delete mode 100644 examples/declarative/imageprovider/imageprovider.qrc delete mode 100644 examples/declarative/imageprovider/main.cpp delete mode 100644 examples/declarative/imageprovider/view.qml diff --git a/examples/declarative/imageprovider/ImageProviderCore/qmldir b/examples/declarative/imageprovider/ImageProviderCore/qmldir new file mode 100644 index 0000000..1028590 --- /dev/null +++ b/examples/declarative/imageprovider/ImageProviderCore/qmldir @@ -0,0 +1,2 @@ +plugin imageprovider + diff --git a/examples/declarative/imageprovider/imageprovider.cpp b/examples/declarative/imageprovider/imageprovider.cpp new file mode 100644 index 0000000..253dbf5 --- /dev/null +++ b/examples/declarative/imageprovider/imageprovider.cpp @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** 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 demonstration applications 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 + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + This example illustrates using a QDeclarativeImageProvider to serve + images asynchronously. +*/ + +//![0] +class ColorImageProvider : public QDeclarativeImageProvider +{ +public: + // This is run in a low priority thread. + QImage request(const QString &id) { + QImage image(100, 50, QImage::Format_RGB32); + image.fill(QColor(id).rgba()); + QPainter p(&image); + p.setPen(Qt::black); + p.drawText(QRectF(0,0,100,50),Qt::AlignCenter,id); + return image; + } +}; + + +class ImageProviderExtensionPlugin : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + void registerTypes(const char *uri) { + Q_UNUSED(uri); + + } + + void initializeEngine(QDeclarativeEngine *engine, const char *uri) { + Q_UNUSED(uri); + + engine->addImageProvider("colors", new ColorImageProvider); + + QStringList dataList; + dataList.append("image://colors/red"); + dataList.append("image://colors/green"); + dataList.append("image://colors/blue"); + dataList.append("image://colors/brown"); + dataList.append("image://colors/orange"); + dataList.append("image://colors/purple"); + dataList.append("image://colors/yellow"); + + QDeclarativeContext *ctxt = engine->rootContext(); + ctxt->setContextProperty("myModel", QVariant::fromValue(dataList)); + } + +}; + +#include "imageprovider.moc" + +Q_EXPORT_PLUGIN(ImageProviderExtensionPlugin); + diff --git a/examples/declarative/imageprovider/imageprovider.pro b/examples/declarative/imageprovider/imageprovider.pro index 60423ab..e403bf8 100644 --- a/examples/declarative/imageprovider/imageprovider.pro +++ b/examples/declarative/imageprovider/imageprovider.pro @@ -1,9 +1,11 @@ -TEMPLATE = app -TARGET = imageprovider -DEPENDPATH += . -INCLUDEPATH += . +TEMPLATE = lib +TARGET = imageprovider QT += declarative +CONFIG += qt plugin + +TARGET = $$qtLibraryTarget($$TARGET) +DESTDIR = ImageProviderCore # Input -SOURCES += main.cpp -RESOURCES += imageprovider.qrc +SOURCES += imageprovider.cpp + diff --git a/examples/declarative/imageprovider/imageprovider.qml b/examples/declarative/imageprovider/imageprovider.qml new file mode 100644 index 0000000..a1f2794 --- /dev/null +++ b/examples/declarative/imageprovider/imageprovider.qml @@ -0,0 +1,23 @@ +import Qt 4.6 +import ImageProviderCore 1.0 +//![0] +ListView { + width: 100 + height: 100 + anchors.fill: parent + model: myModel + delegate: Component { + Item { + width: 100 + height: 50 + Text { + text: "Loading..." + anchors.centerIn: parent + } + Image { + source: modelData + } + } + } +} +//![0] diff --git a/examples/declarative/imageprovider/imageprovider.qrc b/examples/declarative/imageprovider/imageprovider.qrc deleted file mode 100644 index 17e9301..0000000 --- a/examples/declarative/imageprovider/imageprovider.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - view.qml - - diff --git a/examples/declarative/imageprovider/main.cpp b/examples/declarative/imageprovider/main.cpp deleted file mode 100644 index d9d4c1a..0000000 --- a/examples/declarative/imageprovider/main.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** 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 demonstration applications 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 - -#include -#include -#include -#include -#include -#include -#include -#include - -/* - This example illustrates using a QDeclarativeImageProvider to serve - images asynchronously. -*/ - -//![0] -class ColorImageProvider : public QDeclarativeImageProvider -{ -public: - // This is run in a low priority thread. - QImage request(const QString &id) { - QImage image(100, 50, QImage::Format_RGB32); - image.fill(QColor(id).rgba()); - QPainter p(&image); - p.setPen(Qt::black); - p.drawText(QRectF(0,0,100,50),Qt::AlignCenter,id); - return image; - } -}; - -int main(int argc, char ** argv) -{ - QApplication app(argc, argv); - - QDeclarativeView view; - - view.engine()->addImageProvider("colors", new ColorImageProvider); - - QStringList dataList; - dataList.append("image://colors/red"); - dataList.append("image://colors/green"); - dataList.append("image://colors/blue"); - dataList.append("image://colors/brown"); - dataList.append("image://colors/orange"); - dataList.append("image://colors/purple"); - dataList.append("image://colors/yellow"); - - QDeclarativeContext *ctxt = view.rootContext(); - ctxt->setContextProperty("myModel", QVariant::fromValue(dataList)); - - view.setSource(QUrl("qrc:view.qml")); - view.show(); - - return app.exec(); -} -//![0] diff --git a/examples/declarative/imageprovider/view.qml b/examples/declarative/imageprovider/view.qml deleted file mode 100644 index 2ab729d..0000000 --- a/examples/declarative/imageprovider/view.qml +++ /dev/null @@ -1,22 +0,0 @@ -import Qt 4.6 -//![0] -ListView { - width: 100 - height: 100 - anchors.fill: parent - model: myModel - delegate: Component { - Item { - width: 100 - height: 50 - Text { - text: "Loading..." - anchors.centerIn: parent - } - Image { - source: modelData - } - } - } -} -//![0] -- cgit v0.12 From f56893bbffd5eb26dd77e56707615cbb11a26c9b Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Tue, 2 Mar 2010 15:41:16 +0100 Subject: Rewrite Minehunt demo to use the runtime. --- demos/declarative/minehunt/Description.qml | 34 -- demos/declarative/minehunt/Explosion.qml | 26 -- .../minehunt/MinehuntCore/Explosion.qml | 26 ++ .../MinehuntCore/pics/No-Ones-Laughing-3.jpg | Bin 0 -> 30730 bytes .../minehunt/MinehuntCore/pics/back.png | Bin 0 -> 558 bytes .../minehunt/MinehuntCore/pics/bomb-color.png | Bin 0 -> 284 bytes .../minehunt/MinehuntCore/pics/bomb.png | Bin 0 -> 535 bytes .../minehunt/MinehuntCore/pics/face-sad.png | Bin 0 -> 14844 bytes .../minehunt/MinehuntCore/pics/face-smile-big.png | Bin 0 -> 13810 bytes .../minehunt/MinehuntCore/pics/face-smile.png | Bin 0 -> 15408 bytes .../minehunt/MinehuntCore/pics/flag-color.png | Bin 0 -> 219 bytes .../minehunt/MinehuntCore/pics/flag.png | Bin 0 -> 196 bytes .../minehunt/MinehuntCore/pics/front.png | Bin 0 -> 580 bytes .../minehunt/MinehuntCore/pics/star.png | Bin 0 -> 2677 bytes demos/declarative/minehunt/MinehuntCore/qmldir | 2 + demos/declarative/minehunt/main.cpp | 351 --------------------- demos/declarative/minehunt/minehunt.cpp | 314 ++++++++++++++++++ demos/declarative/minehunt/minehunt.pro | 16 +- demos/declarative/minehunt/minehunt.qml | 24 +- .../minehunt/pics/No-Ones-Laughing-3.jpg | Bin 30730 -> 0 bytes demos/declarative/minehunt/pics/back.png | Bin 558 -> 0 bytes demos/declarative/minehunt/pics/bomb-color.png | Bin 284 -> 0 bytes demos/declarative/minehunt/pics/bomb.png | Bin 535 -> 0 bytes demos/declarative/minehunt/pics/face-sad.png | Bin 14844 -> 0 bytes demos/declarative/minehunt/pics/face-smile-big.png | Bin 13810 -> 0 bytes demos/declarative/minehunt/pics/face-smile.png | Bin 15408 -> 0 bytes demos/declarative/minehunt/pics/flag-color.png | Bin 219 -> 0 bytes demos/declarative/minehunt/pics/flag.png | Bin 196 -> 0 bytes demos/declarative/minehunt/pics/front.png | Bin 580 -> 0 bytes demos/declarative/minehunt/pics/star.png | Bin 2677 -> 0 bytes demos/declarative/minehunt/test.qml | 13 - 31 files changed, 360 insertions(+), 446 deletions(-) delete mode 100644 demos/declarative/minehunt/Description.qml delete mode 100644 demos/declarative/minehunt/Explosion.qml create mode 100644 demos/declarative/minehunt/MinehuntCore/Explosion.qml create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/No-Ones-Laughing-3.jpg create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/back.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/bomb-color.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/bomb.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/face-sad.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/face-smile-big.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/face-smile.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/flag-color.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/flag.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/front.png create mode 100644 demos/declarative/minehunt/MinehuntCore/pics/star.png create mode 100644 demos/declarative/minehunt/MinehuntCore/qmldir delete mode 100644 demos/declarative/minehunt/main.cpp create mode 100644 demos/declarative/minehunt/minehunt.cpp delete mode 100644 demos/declarative/minehunt/pics/No-Ones-Laughing-3.jpg delete mode 100644 demos/declarative/minehunt/pics/back.png delete mode 100644 demos/declarative/minehunt/pics/bomb-color.png delete mode 100644 demos/declarative/minehunt/pics/bomb.png delete mode 100644 demos/declarative/minehunt/pics/face-sad.png delete mode 100644 demos/declarative/minehunt/pics/face-smile-big.png delete mode 100644 demos/declarative/minehunt/pics/face-smile.png delete mode 100644 demos/declarative/minehunt/pics/flag-color.png delete mode 100644 demos/declarative/minehunt/pics/flag.png delete mode 100644 demos/declarative/minehunt/pics/front.png delete mode 100644 demos/declarative/minehunt/pics/star.png delete mode 100644 demos/declarative/minehunt/test.qml diff --git a/demos/declarative/minehunt/Description.qml b/demos/declarative/minehunt/Description.qml deleted file mode 100644 index cc4d3b2..0000000 --- a/demos/declarative/minehunt/Description.qml +++ /dev/null @@ -1,34 +0,0 @@ -import Qt 4.6 - -Item { - id: page - height: myText.height + 20 - property var text - MouseArea { - anchors.fill: parent - drag.target: page - drag.axis: "XandYAxis" - drag.minimumX: 0 - drag.maximumX: 1000 - drag.minimumY: 0 - drag.maximumY: 1000 - } - Rectangle { - radius: 10 - anchors.fill: parent - color: "lightsteelblue" - } - Item { - x: 10 - y: 10 - width: parent.width - 20 - height: parent.height - 20 - Text { - id: myText - text: page.text - width: parent.width - clip: true - wrap: true - } - } -} diff --git a/demos/declarative/minehunt/Explosion.qml b/demos/declarative/minehunt/Explosion.qml deleted file mode 100644 index e337c46..0000000 --- a/demos/declarative/minehunt/Explosion.qml +++ /dev/null @@ -1,26 +0,0 @@ -import Qt 4.6 - -Item { - property bool explode : false - - Particles { - id: particles - width: 40 - height: 40 - lifeSpan: 1000 - lifeSpanDeviation: 0 - source: "pics/star.png" - count: 0 - angle: 270 - angleDeviation: 360 - velocity: 100 - velocityDeviation: 20 - z: 100 - opacity: 1 - } - states: [ State { name: "exploding"; when: explode == true - StateChangeScript {script: particles.burst(200); } - } - ] - -} diff --git a/demos/declarative/minehunt/MinehuntCore/Explosion.qml b/demos/declarative/minehunt/MinehuntCore/Explosion.qml new file mode 100644 index 0000000..e337c46 --- /dev/null +++ b/demos/declarative/minehunt/MinehuntCore/Explosion.qml @@ -0,0 +1,26 @@ +import Qt 4.6 + +Item { + property bool explode : false + + Particles { + id: particles + width: 40 + height: 40 + lifeSpan: 1000 + lifeSpanDeviation: 0 + source: "pics/star.png" + count: 0 + angle: 270 + angleDeviation: 360 + velocity: 100 + velocityDeviation: 20 + z: 100 + opacity: 1 + } + states: [ State { name: "exploding"; when: explode == true + StateChangeScript {script: particles.burst(200); } + } + ] + +} diff --git a/demos/declarative/minehunt/MinehuntCore/pics/No-Ones-Laughing-3.jpg b/demos/declarative/minehunt/MinehuntCore/pics/No-Ones-Laughing-3.jpg new file mode 100644 index 0000000..445567f Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/No-Ones-Laughing-3.jpg differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/back.png b/demos/declarative/minehunt/MinehuntCore/pics/back.png new file mode 100644 index 0000000..f6b3f0b Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/back.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/bomb-color.png b/demos/declarative/minehunt/MinehuntCore/pics/bomb-color.png new file mode 100644 index 0000000..61ad0a9 Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/bomb-color.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/bomb.png b/demos/declarative/minehunt/MinehuntCore/pics/bomb.png new file mode 100644 index 0000000..a992575 Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/bomb.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/face-sad.png b/demos/declarative/minehunt/MinehuntCore/pics/face-sad.png new file mode 100644 index 0000000..cf00aaf Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/face-sad.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/face-smile-big.png b/demos/declarative/minehunt/MinehuntCore/pics/face-smile-big.png new file mode 100644 index 0000000..f9c2335 Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/face-smile-big.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/face-smile.png b/demos/declarative/minehunt/MinehuntCore/pics/face-smile.png new file mode 100644 index 0000000..3d66d72 Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/face-smile.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/flag-color.png b/demos/declarative/minehunt/MinehuntCore/pics/flag-color.png new file mode 100644 index 0000000..aadad0f Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/flag-color.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/flag.png b/demos/declarative/minehunt/MinehuntCore/pics/flag.png new file mode 100644 index 0000000..39cde4d Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/flag.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/front.png b/demos/declarative/minehunt/MinehuntCore/pics/front.png new file mode 100644 index 0000000..834331b Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/front.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/pics/star.png b/demos/declarative/minehunt/MinehuntCore/pics/star.png new file mode 100644 index 0000000..3772359 Binary files /dev/null and b/demos/declarative/minehunt/MinehuntCore/pics/star.png differ diff --git a/demos/declarative/minehunt/MinehuntCore/qmldir b/demos/declarative/minehunt/MinehuntCore/qmldir new file mode 100644 index 0000000..862c396 --- /dev/null +++ b/demos/declarative/minehunt/MinehuntCore/qmldir @@ -0,0 +1,2 @@ +plugin minehunt +Explosion 1.0 Explosion.qml diff --git a/demos/declarative/minehunt/main.cpp b/demos/declarative/minehunt/main.cpp deleted file mode 100644 index 99856ed..0000000 --- a/demos/declarative/minehunt/main.cpp +++ /dev/null @@ -1,351 +0,0 @@ -/**************************************************************************** -** -** 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 demonstration applications 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 "qdeclarativeengine.h" -#include "qdeclarativecontext.h" -#include "qdeclarative.h" -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -QString fileName = "minehunt.qml"; - -class Tile : public QObject -{ - Q_OBJECT -public: - Tile() : _hasFlag(false), _hasMine(false), _hint(-1), _flipped(false) {} - - Q_PROPERTY(bool hasFlag READ hasFlag WRITE setHasFlag NOTIFY hasFlagChanged); - bool hasFlag() const { return _hasFlag; } - - Q_PROPERTY(bool hasMine READ hasMine NOTIFY hasMineChanged); - bool hasMine() const { return _hasMine; } - - Q_PROPERTY(int hint READ hint NOTIFY hintChanged); - int hint() const { return _hint; } - - Q_PROPERTY(bool flipped READ flipped NOTIFY flippedChanged()); - bool flipped() const { return _flipped; } - - void setHasFlag(bool flag) {if(flag==_hasFlag) return; _hasFlag = flag; emit hasFlagChanged();} - void setHasMine(bool mine) {if(mine==_hasMine) return; _hasMine = mine; emit hasMineChanged();} - void setHint(int hint) { if(hint == _hint) return; _hint = hint; emit hintChanged(); } - void flip() { if (_flipped) return; _flipped = true; emit flippedChanged(); } - void unflip() { if(!_flipped) return; _flipped = false; emit flippedChanged(); } - -signals: - void flippedChanged(); - void hasFlagChanged(); - void hintChanged(); - void hasMineChanged(); - -private: - bool _hasFlag; - bool _hasMine; - int _hint; - bool _flipped; -}; - -QML_DECLARE_TYPE(Tile); - -class MyWidget : public QWidget -{ -Q_OBJECT -public: - MyWidget(int = 370, int = 480, QWidget *parent=0, Qt::WindowFlags flags=0); - ~MyWidget(); - - Q_PROPERTY(QDeclarativeListProperty tiles READ tiles CONSTANT); - QDeclarativeListProperty tiles() { return QDeclarativeListProperty(this, _tiles); } - - Q_PROPERTY(bool isPlaying READ isPlaying NOTIFY isPlayingChanged); - bool isPlaying() {return playing;} - - Q_PROPERTY(bool hasWon READ hasWon NOTIFY hasWonChanged); - bool hasWon() {return won;} - - Q_PROPERTY(int numMines READ numMines NOTIFY numMinesChanged); - int numMines() const{return nMines;} - - Q_PROPERTY(int numFlags READ numFlags NOTIFY numFlagsChanged); - int numFlags() const{return nFlags;} - -public slots: - Q_INVOKABLE bool flip(int row, int col); - Q_INVOKABLE bool flag(int row, int col); - void setBoard(); - void reset(); - -signals: - void isPlayingChanged(); - void hasWonChanged(); - void numMinesChanged(); - void numFlagsChanged(); - -private: - bool onBoard( int r, int c ) const { return r >= 0 && r < numRows && c >= 0 && c < numCols; } - Tile *tile( int row, int col ) { return onBoard(row, col) ? _tiles[col+numRows*row] : 0; } - int getHint(int row, int col); - void setPlaying(bool b){if(b==playing) return; playing=b; emit isPlayingChanged();} - - QDeclarativeView *canvas; - - QList _tiles; - int numCols; - int numRows; - bool playing; - bool won; - int remaining; - int nMines; - int nFlags; -}; - -Q_DECLARE_METATYPE(QList) -MyWidget::MyWidget(int width, int height, QWidget *parent, Qt::WindowFlags flags) -: QWidget(parent, flags), canvas(0), numCols(9), numRows(9), playing(true), won(false) -{ - setObjectName("mainWidget"); - srand(QTime(0,0,0).secsTo(QTime::currentTime())); - - //initialize array - for(int ii = 0; ii < numRows * numCols; ++ii) { - _tiles << new Tile; - } - reset(); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->setMargin(0); - setLayout(vbox); - - canvas = new QDeclarativeView(this); - canvas->setFixedSize(width, height); - vbox->addWidget(canvas); - - QDeclarativeContext *ctxt = canvas->rootContext(); - ctxt->addDefaultObject(this); - - canvas->setSource(QUrl::fromLocalFile(fileName)); -} - -MyWidget::~MyWidget() -{ -} - -void MyWidget::setBoard() -{ - foreach(Tile* t, _tiles){ - t->setHasMine(false); - t->setHint(-1); - } - //place mines - int mines = nMines; - remaining = numRows*numCols-mines; - while ( mines ) { - int col = int((double(rand()) / double(RAND_MAX)) * numCols); - int row = int((double(rand()) / double(RAND_MAX)) * numRows); - - Tile* t = tile( row, col ); - - if (t && !t->hasMine()) { - t->setHasMine( true ); - mines--; - } - } - - //set hints - for (int r = 0; r < numRows; r++) - for (int c = 0; c < numCols; c++) { - Tile* t = tile(r, c); - if (t && !t->hasMine()) { - int hint = getHint(r,c); - t->setHint(hint); - } - } - - setPlaying(true); -} - -void MyWidget::reset() -{ - foreach(Tile* t, _tiles){ - t->unflip(); - t->setHasFlag(false); - } - nMines = 12; - nFlags = 0; - setPlaying(false); - QTimer::singleShot(600,this, SLOT(setBoard())); -} - -int MyWidget::getHint(int row, int col) -{ - int hint = 0; - for (int c = col-1; c <= col+1; c++) - for (int r = row-1; r <= row+1; r++) { - Tile* t = tile(r, c); - if (t && t->hasMine()) - hint++; - } - return hint; -} - -bool MyWidget::flip(int row, int col) -{ - if(!playing) - return false; - - Tile *t = tile(row, col); - if (!t || t->hasFlag()) - return false; - - if(t->flipped()){ - int flags = 0; - for (int c = col-1; c <= col+1; c++) - for (int r = row-1; r <= row+1; r++) { - Tile *nearT = tile(r, c); - if(!nearT || nearT == t) - continue; - if(nearT->hasFlag()) - flags++; - } - if(!t->hint() || t->hint() != flags) - return false; - for (int c = col-1; c <= col+1; c++) - for (int r = row-1; r <= row+1; r++) { - Tile *nearT = tile(r, c); - if (nearT && !nearT->flipped() && !nearT->hasFlag()) { - flip( r, c ); - } - } - return true; - } - - t->flip(); - - if (t->hint() == 0) { - for (int c = col-1; c <= col+1; c++) - for (int r = row-1; r <= row+1; r++) { - Tile* t = tile(r, c); - if (t && !t->flipped()) { - flip( r, c ); - } - } - } - - if(t->hasMine()){ - for (int r = 0; r < numRows; r++)//Flip all other mines - for (int c = 0; c < numCols; c++) { - Tile* t = tile(r, c); - if (t && t->hasMine()) { - flip(r, c); - } - } - won = false; - hasWonChanged(); - setPlaying(false); - } - - remaining--; - if(!remaining){ - won = true; - hasWonChanged(); - setPlaying(false); - } - return true; -} - -bool MyWidget::flag(int row, int col) -{ - Tile *t = tile(row, col); - if(!t) - return false; - - t->setHasFlag(!t->hasFlag()); - nFlags += (t->hasFlag()?1:-1); - emit numFlagsChanged(); - return true; -} -///////////////////////////////////////////////////////// - -int main(int argc, char ** argv) -{ -#ifdef Q_WS_X11 - // native on X11 is terrible for this demo. - QApplication::setGraphicsSystem("raster"); -#endif - QApplication app(argc, argv); - - bool frameless = false; - - int width = 370; - int height = 480; - - QML_REGISTER_TYPE(0,0,0,Tile,Tile); - - for (int i = 1; i < argc; ++i) { - QString arg = argv[i]; - if (arg == "-frameless") { - frameless = true; - } else if(arg == "-width" && i < (argc - 1)) { - ++i; - width = ::atoi(argv[i]); - } else if(arg == "-height" && i < (argc - 1)) { - ++i; - height = ::atoi(argv[i]); - } else if (arg[0] != '-') { - fileName = arg; - } - } - - MyWidget wid(width, height, 0, frameless ? Qt::FramelessWindowHint : Qt::Widget); - wid.show(); - - return app.exec(); -} - -#include "main.moc" diff --git a/demos/declarative/minehunt/minehunt.cpp b/demos/declarative/minehunt/minehunt.cpp new file mode 100644 index 0000000..89845ef --- /dev/null +++ b/demos/declarative/minehunt/minehunt.cpp @@ -0,0 +1,314 @@ +/**************************************************************************** +** +** 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 demonstration applications 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 +#include +#include +#include +#include + +#include +#include + +class Tile : public QObject +{ + Q_OBJECT +public: + Tile() : _hasFlag(false), _hasMine(false), _hint(-1), _flipped(false) {} + + Q_PROPERTY(bool hasFlag READ hasFlag WRITE setHasFlag NOTIFY hasFlagChanged); + bool hasFlag() const { return _hasFlag; } + + Q_PROPERTY(bool hasMine READ hasMine NOTIFY hasMineChanged); + bool hasMine() const { return _hasMine; } + + Q_PROPERTY(int hint READ hint NOTIFY hintChanged); + int hint() const { return _hint; } + + Q_PROPERTY(bool flipped READ flipped NOTIFY flippedChanged()); + bool flipped() const { return _flipped; } + + void setHasFlag(bool flag) {if(flag==_hasFlag) return; _hasFlag = flag; emit hasFlagChanged();} + void setHasMine(bool mine) {if(mine==_hasMine) return; _hasMine = mine; emit hasMineChanged();} + void setHint(int hint) { if(hint == _hint) return; _hint = hint; emit hintChanged(); } + void flip() { if (_flipped) return; _flipped = true; emit flippedChanged(); } + void unflip() { if(!_flipped) return; _flipped = false; emit flippedChanged(); } + +signals: + void flippedChanged(); + void hasFlagChanged(); + void hintChanged(); + void hasMineChanged(); + +private: + bool _hasFlag; + bool _hasMine; + int _hint; + bool _flipped; +}; + +class MinehuntGame : public QObject +{ + Q_OBJECT +public: + MinehuntGame(); + + Q_PROPERTY(QDeclarativeListProperty tiles READ tiles CONSTANT); + QDeclarativeListProperty tiles() { return QDeclarativeListProperty(this, _tiles); } + + Q_PROPERTY(bool isPlaying READ isPlaying NOTIFY isPlayingChanged); + bool isPlaying() {return playing;} + + Q_PROPERTY(bool hasWon READ hasWon NOTIFY hasWonChanged); + bool hasWon() {return won;} + + Q_PROPERTY(int numMines READ numMines NOTIFY numMinesChanged); + int numMines() const{return nMines;} + + Q_PROPERTY(int numFlags READ numFlags NOTIFY numFlagsChanged); + int numFlags() const{return nFlags;} + +public slots: + Q_INVOKABLE bool flip(int row, int col); + Q_INVOKABLE bool flag(int row, int col); + void setBoard(); + void reset(); + +signals: + void isPlayingChanged(); + void hasWonChanged(); + void numMinesChanged(); + void numFlagsChanged(); + +private: + bool onBoard( int r, int c ) const { return r >= 0 && r < numRows && c >= 0 && c < numCols; } + Tile *tile( int row, int col ) { return onBoard(row, col) ? _tiles[col+numRows*row] : 0; } + int getHint(int row, int col); + void setPlaying(bool b){if(b==playing) return; playing=b; emit isPlayingChanged();} + + QList _tiles; + int numCols; + int numRows; + bool playing; + bool won; + int remaining; + int nMines; + int nFlags; +}; + +MinehuntGame::MinehuntGame() +: numCols(9), numRows(9), playing(true), won(false) +{ + setObjectName("mainObject"); + srand(QTime(0,0,0).secsTo(QTime::currentTime())); + + //initialize array + for(int ii = 0; ii < numRows * numCols; ++ii) { + _tiles << new Tile; + } + reset(); + +} + +void MinehuntGame::setBoard() +{ + foreach(Tile* t, _tiles){ + t->setHasMine(false); + t->setHint(-1); + } + //place mines + int mines = nMines; + remaining = numRows*numCols-mines; + while ( mines ) { + int col = int((double(rand()) / double(RAND_MAX)) * numCols); + int row = int((double(rand()) / double(RAND_MAX)) * numRows); + + Tile* t = tile( row, col ); + + if (t && !t->hasMine()) { + t->setHasMine( true ); + mines--; + } + } + + //set hints + for (int r = 0; r < numRows; r++) + for (int c = 0; c < numCols; c++) { + Tile* t = tile(r, c); + if (t && !t->hasMine()) { + int hint = getHint(r,c); + t->setHint(hint); + } + } + + setPlaying(true); +} + +void MinehuntGame::reset() +{ + foreach(Tile* t, _tiles){ + t->unflip(); + t->setHasFlag(false); + } + nMines = 12; + nFlags = 0; + setPlaying(false); + QTimer::singleShot(600,this, SLOT(setBoard())); +} + +int MinehuntGame::getHint(int row, int col) +{ + int hint = 0; + for (int c = col-1; c <= col+1; c++) + for (int r = row-1; r <= row+1; r++) { + Tile* t = tile(r, c); + if (t && t->hasMine()) + hint++; + } + return hint; +} + +bool MinehuntGame::flip(int row, int col) +{ + if(!playing) + return false; + + Tile *t = tile(row, col); + if (!t || t->hasFlag()) + return false; + + if(t->flipped()){ + int flags = 0; + for (int c = col-1; c <= col+1; c++) + for (int r = row-1; r <= row+1; r++) { + Tile *nearT = tile(r, c); + if(!nearT || nearT == t) + continue; + if(nearT->hasFlag()) + flags++; + } + if(!t->hint() || t->hint() != flags) + return false; + for (int c = col-1; c <= col+1; c++) + for (int r = row-1; r <= row+1; r++) { + Tile *nearT = tile(r, c); + if (nearT && !nearT->flipped() && !nearT->hasFlag()) { + flip( r, c ); + } + } + return true; + } + + t->flip(); + + if (t->hint() == 0) { + for (int c = col-1; c <= col+1; c++) + for (int r = row-1; r <= row+1; r++) { + Tile* t = tile(r, c); + if (t && !t->flipped()) { + flip( r, c ); + } + } + } + + if(t->hasMine()){ + for (int r = 0; r < numRows; r++)//Flip all other mines + for (int c = 0; c < numCols; c++) { + Tile* t = tile(r, c); + if (t && t->hasMine()) { + flip(r, c); + } + } + won = false; + hasWonChanged(); + setPlaying(false); + } + + remaining--; + if(!remaining){ + won = true; + hasWonChanged(); + setPlaying(false); + } + return true; +} + +bool MinehuntGame::flag(int row, int col) +{ + Tile *t = tile(row, col); + if(!t) + return false; + + t->setHasFlag(!t->hasFlag()); + nFlags += (t->hasFlag()?1:-1); + emit numFlagsChanged(); + return true; +} + +QML_DECLARE_TYPE(Tile); +QML_DECLARE_TYPE(MinehuntGame); + +class MinehuntExtensionPlugin : public QDeclarativeExtensionPlugin +{ + Q_OBJECT + + public: + void registerTypes(const char *uri) { + Q_UNUSED(uri); + QML_REGISTER_TYPE(SameGameCore, 0, 1, Tile, Tile); + QML_REGISTER_TYPE(SameGameCore, 0, 1, Game, MinehuntGame); + } + + void initializeEngine(QDeclarativeEngine *engine, const char *uri) { + Q_UNUSED(uri); + + srand(QTime(0,0,0).secsTo(QTime::currentTime())); + + MinehuntGame* game = new MinehuntGame(); + + engine->rootContext()->addDefaultObject(game); + } +}; + +#include "minehunt.moc" + +Q_EXPORT_PLUGIN(MinehuntExtensionPlugin); + diff --git a/demos/declarative/minehunt/minehunt.pro b/demos/declarative/minehunt/minehunt.pro index 01791b1..a497b0f 100644 --- a/demos/declarative/minehunt/minehunt.pro +++ b/demos/declarative/minehunt/minehunt.pro @@ -1,9 +1,11 @@ -SOURCES = main.cpp +TEMPLATE = lib +TARGET = minehunt +QT += declarative +CONFIG += qt plugin -QT += script declarative -contains(QT_CONFIG, opengles2)|contains(QT_CONFIG, opengles1): QT += opengl +TARGET = $$qtLibraryTarget($$TARGET) +DESTDIR = MinehuntCore + +# Input +SOURCES += minehunt.cpp -target.path = $$[QT_INSTALL_EXAMPLES]/declarative/minehunt -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS minehunt.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/declarative/minehunt -INSTALLS += target sources diff --git a/demos/declarative/minehunt/minehunt.qml b/demos/declarative/minehunt/minehunt.qml index 456f25b..9e99706 100644 --- a/demos/declarative/minehunt/minehunt.qml +++ b/demos/declarative/minehunt/minehunt.qml @@ -1,4 +1,5 @@ import Qt 4.6 +import MinehuntCore 1.0 Item { id: field @@ -24,13 +25,13 @@ Item { angle: flipable.angle; } front: Image { - source: "pics/front.png" + source: "MinehuntCore/pics/front.png" width: 40 height: 40 Image { anchors.horizontalCenter: parent.horizontalCenter anchors.verticalCenter: parent.verticalCenter - source: "pics/flag.png" + source: "MinehuntCore/pics/flag.png" opacity: modelData.hasFlag Behavior on opacity { NumberAnimation { @@ -41,7 +42,7 @@ Item { } } back: Image { - source: "pics/back.png" + source: "MinehuntCore/pics/back.png" width: 40 height: 40 Text { @@ -55,7 +56,7 @@ Item { Image { anchors.horizontalCenter: parent.horizontalCenter anchors.verticalCenter: parent.verticalCenter - source: "pics/bomb.png" + source: "MinehuntCore/pics/bomb.png" opacity: modelData.hasMine } Explosion { @@ -120,16 +121,9 @@ Item { } ] Image { - source: "pics/No-Ones-Laughing-3.jpg" + source: "MinehuntCore/pics/No-Ones-Laughing-3.jpg" fillMode: Image.Tile } - Description { - text: "Use the 'minehunt' executable to run this demo!" - width: 300 - opacity: tiles?0:1 - anchors.horizontalCenter: parent.horizontalCenter - anchors.verticalCenter: parent.verticalCenter - } Repeater { id: repeater model: tiles @@ -156,7 +150,7 @@ Item { Image { // x: 100 // y: 20 - source: "pics/bomb-color.png" + source: "MinehuntCore/pics/bomb-color.png" } Text { // x: 100 @@ -172,7 +166,7 @@ Item { Image { // x: 140 // y: 20 - source: "pics/flag-color.png" + source: "MinehuntCore/pics/flag-color.png" } Text { // x: 140 @@ -187,7 +181,7 @@ Item { y: 390 anchors.right: field.right anchors.rightMargin: 20 - source: isPlaying ? 'pics/face-smile.png' : hasWon ? 'pics/face-smile-big.png': 'pics/face-sad.png' + source: isPlaying ? 'MinehuntCore/pics/face-smile.png' : hasWon ? 'MinehuntCore/pics/face-smile-big.png': 'MinehuntCore/pics/face-sad.png' MouseArea { anchors.fill: parent onPressed: { reset() } diff --git a/demos/declarative/minehunt/pics/No-Ones-Laughing-3.jpg b/demos/declarative/minehunt/pics/No-Ones-Laughing-3.jpg deleted file mode 100644 index 445567f..0000000 Binary files a/demos/declarative/minehunt/pics/No-Ones-Laughing-3.jpg and /dev/null differ diff --git a/demos/declarative/minehunt/pics/back.png b/demos/declarative/minehunt/pics/back.png deleted file mode 100644 index f6b3f0b..0000000 Binary files a/demos/declarative/minehunt/pics/back.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/bomb-color.png b/demos/declarative/minehunt/pics/bomb-color.png deleted file mode 100644 index 61ad0a9..0000000 Binary files a/demos/declarative/minehunt/pics/bomb-color.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/bomb.png b/demos/declarative/minehunt/pics/bomb.png deleted file mode 100644 index a992575..0000000 Binary files a/demos/declarative/minehunt/pics/bomb.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/face-sad.png b/demos/declarative/minehunt/pics/face-sad.png deleted file mode 100644 index cf00aaf..0000000 Binary files a/demos/declarative/minehunt/pics/face-sad.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/face-smile-big.png b/demos/declarative/minehunt/pics/face-smile-big.png deleted file mode 100644 index f9c2335..0000000 Binary files a/demos/declarative/minehunt/pics/face-smile-big.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/face-smile.png b/demos/declarative/minehunt/pics/face-smile.png deleted file mode 100644 index 3d66d72..0000000 Binary files a/demos/declarative/minehunt/pics/face-smile.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/flag-color.png b/demos/declarative/minehunt/pics/flag-color.png deleted file mode 100644 index aadad0f..0000000 Binary files a/demos/declarative/minehunt/pics/flag-color.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/flag.png b/demos/declarative/minehunt/pics/flag.png deleted file mode 100644 index 39cde4d..0000000 Binary files a/demos/declarative/minehunt/pics/flag.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/front.png b/demos/declarative/minehunt/pics/front.png deleted file mode 100644 index 834331b..0000000 Binary files a/demos/declarative/minehunt/pics/front.png and /dev/null differ diff --git a/demos/declarative/minehunt/pics/star.png b/demos/declarative/minehunt/pics/star.png deleted file mode 100644 index 3772359..0000000 Binary files a/demos/declarative/minehunt/pics/star.png and /dev/null differ diff --git a/demos/declarative/minehunt/test.qml b/demos/declarative/minehunt/test.qml deleted file mode 100644 index 11ed182..0000000 --- a/demos/declarative/minehunt/test.qml +++ /dev/null @@ -1,13 +0,0 @@ -import Qt 4.6 - - Image { - source: "pics/front.png" - width: 40 - height: 40 - Image { - anchors.horizontalCenter: parent.horizontalCenter - anchors.verticalCenter: parent.verticalCenter - source: "pics/flag.png" - opacity: 1 - } - } -- cgit v0.12 From e16b33eefa365986f8e0d26c710cb7568bf9abff Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Tue, 2 Mar 2010 15:54:38 +0100 Subject: Refactor demos Samegame and Twitter are now trying the new naming convention. --- .../samegame/SamegameCore/BoomBlock.qml | 55 +++++ demos/declarative/samegame/SamegameCore/Button.qml | 25 +++ demos/declarative/samegame/SamegameCore/Dialog.qml | 22 ++ .../samegame/SamegameCore/pics/background.png | Bin 0 -> 313930 bytes .../samegame/SamegameCore/pics/blueStar.png | Bin 0 -> 278 bytes .../samegame/SamegameCore/pics/blueStone.png | Bin 0 -> 3054 bytes .../samegame/SamegameCore/pics/greenStar.png | Bin 0 -> 273 bytes .../samegame/SamegameCore/pics/greenStone.png | Bin 0 -> 2932 bytes .../samegame/SamegameCore/pics/redStar.png | Bin 0 -> 274 bytes .../samegame/SamegameCore/pics/redStone.png | Bin 0 -> 2902 bytes .../samegame/SamegameCore/pics/star.png | Bin 0 -> 262 bytes .../samegame/SamegameCore/pics/yellowStone.png | Bin 0 -> 3056 bytes demos/declarative/samegame/SamegameCore/qmldir | 3 + .../declarative/samegame/SamegameCore/samegame.js | 250 +++++++++++++++++++++ demos/declarative/samegame/content/BoomBlock.qml | 55 ----- demos/declarative/samegame/content/Button.qml | 25 --- demos/declarative/samegame/content/Dialog.qml | 22 -- .../samegame/content/pics/background.png | Bin 313930 -> 0 bytes .../declarative/samegame/content/pics/blueStar.png | Bin 278 -> 0 bytes .../samegame/content/pics/blueStone.png | Bin 3054 -> 0 bytes .../samegame/content/pics/greenStar.png | Bin 273 -> 0 bytes .../samegame/content/pics/greenStone.png | Bin 2932 -> 0 bytes .../declarative/samegame/content/pics/redStar.png | Bin 274 -> 0 bytes .../declarative/samegame/content/pics/redStone.png | Bin 2902 -> 0 bytes demos/declarative/samegame/content/pics/star.png | Bin 262 -> 0 bytes .../samegame/content/pics/yellowStone.png | Bin 3056 -> 0 bytes demos/declarative/samegame/content/qmldir | 3 - demos/declarative/samegame/content/samegame.js | 250 --------------------- demos/declarative/samegame/samegame.qml | 6 +- demos/declarative/twitter/TwitterCore/AuthView.qml | 99 ++++++++ demos/declarative/twitter/TwitterCore/Button.qml | 49 ++++ .../twitter/TwitterCore/FatDelegate.qml | 46 ++++ .../twitter/TwitterCore/HomeTitleBar.qml | 121 ++++++++++ demos/declarative/twitter/TwitterCore/Loading.qml | 8 + .../twitter/TwitterCore/MultiTitleBar.qml | 24 ++ demos/declarative/twitter/TwitterCore/RssModel.qml | 44 ++++ demos/declarative/twitter/TwitterCore/TitleBar.qml | 77 +++++++ demos/declarative/twitter/TwitterCore/ToolBar.qml | 24 ++ .../declarative/twitter/TwitterCore/UserModel.qml | 26 +++ .../twitter/TwitterCore/images/gloss.png | Bin 0 -> 1236 bytes .../twitter/TwitterCore/images/lineedit.png | Bin 0 -> 1415 bytes .../twitter/TwitterCore/images/lineedit.sci | 5 + .../twitter/TwitterCore/images/loading.png | Bin 0 -> 813 bytes .../twitter/TwitterCore/images/stripes.png | Bin 0 -> 257 bytes .../twitter/TwitterCore/images/titlebar.png | Bin 0 -> 1436 bytes .../twitter/TwitterCore/images/titlebar.sci | 5 + .../twitter/TwitterCore/images/toolbutton.png | Bin 0 -> 2550 bytes .../twitter/TwitterCore/images/toolbutton.sci | 5 + demos/declarative/twitter/TwitterCore/qmldir | 10 + demos/declarative/twitter/content/AuthView.qml | 99 -------- demos/declarative/twitter/content/Button.qml | 49 ---- demos/declarative/twitter/content/FatDelegate.qml | 46 ---- demos/declarative/twitter/content/HomeTitleBar.qml | 121 ---------- demos/declarative/twitter/content/Loading.qml | 8 - .../declarative/twitter/content/MultiTitleBar.qml | 24 -- demos/declarative/twitter/content/RssModel.qml | 44 ---- demos/declarative/twitter/content/TitleBar.qml | 77 ------- demos/declarative/twitter/content/ToolBar.qml | 24 -- demos/declarative/twitter/content/UserModel.qml | 26 --- demos/declarative/twitter/content/images/gloss.png | Bin 1236 -> 0 bytes .../twitter/content/images/lineedit.png | Bin 1415 -> 0 bytes .../twitter/content/images/lineedit.sci | 5 - .../declarative/twitter/content/images/loading.png | Bin 813 -> 0 bytes .../declarative/twitter/content/images/stripes.png | Bin 257 -> 0 bytes .../twitter/content/images/titlebar.png | Bin 1436 -> 0 bytes .../twitter/content/images/titlebar.sci | 5 - .../twitter/content/images/toolbutton.png | Bin 2550 -> 0 bytes .../twitter/content/images/toolbutton.sci | 5 - demos/declarative/twitter/twitter.qml | 4 +- 69 files changed, 903 insertions(+), 893 deletions(-) create mode 100644 demos/declarative/samegame/SamegameCore/BoomBlock.qml create mode 100644 demos/declarative/samegame/SamegameCore/Button.qml create mode 100644 demos/declarative/samegame/SamegameCore/Dialog.qml create mode 100644 demos/declarative/samegame/SamegameCore/pics/background.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/blueStar.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/blueStone.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/greenStar.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/greenStone.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/redStar.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/redStone.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/star.png create mode 100644 demos/declarative/samegame/SamegameCore/pics/yellowStone.png create mode 100644 demos/declarative/samegame/SamegameCore/qmldir create mode 100755 demos/declarative/samegame/SamegameCore/samegame.js delete mode 100644 demos/declarative/samegame/content/BoomBlock.qml delete mode 100644 demos/declarative/samegame/content/Button.qml delete mode 100644 demos/declarative/samegame/content/Dialog.qml delete mode 100644 demos/declarative/samegame/content/pics/background.png delete mode 100644 demos/declarative/samegame/content/pics/blueStar.png delete mode 100644 demos/declarative/samegame/content/pics/blueStone.png delete mode 100644 demos/declarative/samegame/content/pics/greenStar.png delete mode 100644 demos/declarative/samegame/content/pics/greenStone.png delete mode 100644 demos/declarative/samegame/content/pics/redStar.png delete mode 100644 demos/declarative/samegame/content/pics/redStone.png delete mode 100644 demos/declarative/samegame/content/pics/star.png delete mode 100644 demos/declarative/samegame/content/pics/yellowStone.png delete mode 100644 demos/declarative/samegame/content/qmldir delete mode 100755 demos/declarative/samegame/content/samegame.js create mode 100644 demos/declarative/twitter/TwitterCore/AuthView.qml create mode 100644 demos/declarative/twitter/TwitterCore/Button.qml create mode 100644 demos/declarative/twitter/TwitterCore/FatDelegate.qml create mode 100644 demos/declarative/twitter/TwitterCore/HomeTitleBar.qml create mode 100644 demos/declarative/twitter/TwitterCore/Loading.qml create mode 100644 demos/declarative/twitter/TwitterCore/MultiTitleBar.qml create mode 100644 demos/declarative/twitter/TwitterCore/RssModel.qml create mode 100644 demos/declarative/twitter/TwitterCore/TitleBar.qml create mode 100644 demos/declarative/twitter/TwitterCore/ToolBar.qml create mode 100644 demos/declarative/twitter/TwitterCore/UserModel.qml create mode 100644 demos/declarative/twitter/TwitterCore/images/gloss.png create mode 100644 demos/declarative/twitter/TwitterCore/images/lineedit.png create mode 100644 demos/declarative/twitter/TwitterCore/images/lineedit.sci create mode 100644 demos/declarative/twitter/TwitterCore/images/loading.png create mode 100644 demos/declarative/twitter/TwitterCore/images/stripes.png create mode 100644 demos/declarative/twitter/TwitterCore/images/titlebar.png create mode 100644 demos/declarative/twitter/TwitterCore/images/titlebar.sci create mode 100644 demos/declarative/twitter/TwitterCore/images/toolbutton.png create mode 100644 demos/declarative/twitter/TwitterCore/images/toolbutton.sci create mode 100644 demos/declarative/twitter/TwitterCore/qmldir delete mode 100644 demos/declarative/twitter/content/AuthView.qml delete mode 100644 demos/declarative/twitter/content/Button.qml delete mode 100644 demos/declarative/twitter/content/FatDelegate.qml delete mode 100644 demos/declarative/twitter/content/HomeTitleBar.qml delete mode 100644 demos/declarative/twitter/content/Loading.qml delete mode 100644 demos/declarative/twitter/content/MultiTitleBar.qml delete mode 100644 demos/declarative/twitter/content/RssModel.qml delete mode 100644 demos/declarative/twitter/content/TitleBar.qml delete mode 100644 demos/declarative/twitter/content/ToolBar.qml delete mode 100644 demos/declarative/twitter/content/UserModel.qml delete mode 100644 demos/declarative/twitter/content/images/gloss.png delete mode 100644 demos/declarative/twitter/content/images/lineedit.png delete mode 100644 demos/declarative/twitter/content/images/lineedit.sci delete mode 100644 demos/declarative/twitter/content/images/loading.png delete mode 100644 demos/declarative/twitter/content/images/stripes.png delete mode 100644 demos/declarative/twitter/content/images/titlebar.png delete mode 100644 demos/declarative/twitter/content/images/titlebar.sci delete mode 100644 demos/declarative/twitter/content/images/toolbutton.png delete mode 100644 demos/declarative/twitter/content/images/toolbutton.sci diff --git a/demos/declarative/samegame/SamegameCore/BoomBlock.qml b/demos/declarative/samegame/SamegameCore/BoomBlock.qml new file mode 100644 index 0000000..e48194a --- /dev/null +++ b/demos/declarative/samegame/SamegameCore/BoomBlock.qml @@ -0,0 +1,55 @@ +import Qt 4.6 + +Item { id:block + property bool dying: false + property bool spawned: false + property int type: 0 + property int targetX: 0 + property int targetY: 0 + + SpringFollow on x { enabled: spawned; source: targetX; spring: 2; damping: 0.2 } + SpringFollow on y { source: targetY; spring: 2; damping: 0.2 } + + Image { id: img + source: { + if(type == 0){ + "pics/redStone.png"; + } else if(type == 1) { + "pics/blueStone.png"; + } else { + "pics/greenStone.png"; + } + } + opacity: 0 + Behavior on opacity { NumberAnimation { duration: 200 } } + anchors.fill: parent + } + + Particles { id: particles + width:1; height:1; anchors.centerIn: parent; + emissionRate: 0; + lifeSpan: 700; lifeSpanDeviation: 600; + angle: 0; angleDeviation: 360; + velocity: 100; velocityDeviation:30; + source: { + if(type == 0){ + "pics/redStar.png"; + } else if (type == 1) { + "pics/blueStar.png"; + } else { + "pics/greenStar.png"; + } + } + } + + states: [ + State{ name: "AliveState"; when: spawned == true && dying == false + PropertyChanges { target: img; opacity: 1 } + }, + State{ name: "DeathState"; when: dying == true + StateChangeScript { script: particles.burst(50); } + PropertyChanges { target: img; opacity: 0 } + StateChangeScript { script: block.destroy(1000); } + } + ] +} diff --git a/demos/declarative/samegame/SamegameCore/Button.qml b/demos/declarative/samegame/SamegameCore/Button.qml new file mode 100644 index 0000000..6629302 --- /dev/null +++ b/demos/declarative/samegame/SamegameCore/Button.qml @@ -0,0 +1,25 @@ +import Qt 4.6 + +Rectangle { + id: container + + signal clicked + property string text: "Button" + + color: activePalette.button; smooth: true + width: txtItem.width + 20; height: txtItem.height + 6 + border.width: 1; border.color: Qt.darker(activePalette.button); radius: 8; + + gradient: Gradient { + GradientStop { + id: topGrad; position: 0.0 + color: if (mr.pressed) { activePalette.dark } else { activePalette.light } } + GradientStop { position: 1.0; color: activePalette.button } + } + + MouseArea { id: mr; anchors.fill: parent; onClicked: container.clicked() } + + Text { + id: txtItem; text: container.text; anchors.centerIn: container; color: activePalette.buttonText + } +} diff --git a/demos/declarative/samegame/SamegameCore/Dialog.qml b/demos/declarative/samegame/SamegameCore/Dialog.qml new file mode 100644 index 0000000..6d5d6b5 --- /dev/null +++ b/demos/declarative/samegame/SamegameCore/Dialog.qml @@ -0,0 +1,22 @@ +import Qt 4.6 + +Rectangle { + id: page + function forceClose() { + page.closed(); + page.opacity = 0; + } + function show(txt) { + myText.text = txt; + page.opacity = 1; + } + signal closed(); + property Item text: myText + color: "white"; border.width: 1; width: myText.width + 20; height: myText.height + 40; + opacity: 0 + Behavior on opacity { + NumberAnimation { duration: 1000 } + } + Text { id: myText; anchors.centerIn: parent; text: "Hello World!" } + MouseArea { id: mr; anchors.fill: parent; onClicked: forceClose(); } +} diff --git a/demos/declarative/samegame/SamegameCore/pics/background.png b/demos/declarative/samegame/SamegameCore/pics/background.png new file mode 100644 index 0000000..3734a27 Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/background.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/blueStar.png b/demos/declarative/samegame/SamegameCore/pics/blueStar.png new file mode 100644 index 0000000..ff9588f Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/blueStar.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/blueStone.png b/demos/declarative/samegame/SamegameCore/pics/blueStone.png new file mode 100644 index 0000000..20e43c7 Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/blueStone.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/greenStar.png b/demos/declarative/samegame/SamegameCore/pics/greenStar.png new file mode 100644 index 0000000..cd06854 Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/greenStar.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/greenStone.png b/demos/declarative/samegame/SamegameCore/pics/greenStone.png new file mode 100644 index 0000000..b568a19 Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/greenStone.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/redStar.png b/demos/declarative/samegame/SamegameCore/pics/redStar.png new file mode 100644 index 0000000..0a4dffe Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/redStar.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/redStone.png b/demos/declarative/samegame/SamegameCore/pics/redStone.png new file mode 100644 index 0000000..36b09a2 Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/redStone.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/star.png b/demos/declarative/samegame/SamegameCore/pics/star.png new file mode 100644 index 0000000..defbde5 Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/star.png differ diff --git a/demos/declarative/samegame/SamegameCore/pics/yellowStone.png b/demos/declarative/samegame/SamegameCore/pics/yellowStone.png new file mode 100644 index 0000000..b1ce762 Binary files /dev/null and b/demos/declarative/samegame/SamegameCore/pics/yellowStone.png differ diff --git a/demos/declarative/samegame/SamegameCore/qmldir b/demos/declarative/samegame/SamegameCore/qmldir new file mode 100644 index 0000000..a8f8a98 --- /dev/null +++ b/demos/declarative/samegame/SamegameCore/qmldir @@ -0,0 +1,3 @@ +BoomBlock 0.0 BoomBlock.qml +Button 0.0 Button.qml +Dialog 0.0 Dialog.qml diff --git a/demos/declarative/samegame/SamegameCore/samegame.js b/demos/declarative/samegame/SamegameCore/samegame.js new file mode 100755 index 0000000..c0f10bd --- /dev/null +++ b/demos/declarative/samegame/SamegameCore/samegame.js @@ -0,0 +1,250 @@ +/* This script file handles the game logic */ +//Note that X/Y referred to here are in game coordinates +var maxX = 10;//Nums are for gameCanvas.tileSize 40 +var maxY = 15; +var maxIndex = maxX*maxY; +var board = new Array(maxIndex); +var tileSrc = "content/BoomBlock.qml"; +var scoresURL = "http://qtfx-nokia.trolltech.com.au/samegame/scores.php"; +var scoresURL = ""; +var timer; +var component = createComponent(tileSrc); + +//Index function used instead of a 2D array +function index(xIdx,yIdx) { + return xIdx + (yIdx * maxX); +} + +function timeStr(msecs) { + var secs = Math.floor(msecs/1000); + var m = Math.floor(secs/60); + var ret = "" + m + "m " + (secs%60) + "s"; + return ret; +} + +function getTileSize() +{ + return tileSize; +} + +function initBoard() +{ + for(var i = 0; i= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0) + return; + if(board[index(xIdx, yIdx)] == null) + return; + //If it's a valid tile, remove it and all connected (does nothing if it's not connected) + floodFill(xIdx,yIdx, -1); + if(fillFound <= 0) + return; + gameCanvas.score += (fillFound - 1) * (fillFound - 1); + shuffleDown(); + victoryCheck(); +} + +function floodFill(xIdx,yIdx,type) +{ + if(board[index(xIdx, yIdx)] == null) + return; + var first = false; + if(type == -1){ + first = true; + type = board[index(xIdx,yIdx)].type; + + //Flood fill initialization + fillFound = 0; + floodBoard = new Array(maxIndex); + } + if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0) + return; + if(floodBoard[index(xIdx, yIdx)] == 1 || (!first && type != board[index(xIdx,yIdx)].type)) + return; + floodBoard[index(xIdx, yIdx)] = 1; + floodFill(xIdx+1,yIdx,type); + floodFill(xIdx-1,yIdx,type); + floodFill(xIdx,yIdx+1,type); + floodFill(xIdx,yIdx-1,type); + if(first==true && fillFound == 0) + return;//Can't remove single tiles + board[index(xIdx,yIdx)].dying = true; + board[index(xIdx,yIdx)] = null; + fillFound += 1; +} + +function shuffleDown() +{ + //Fall down + for(var xIdx=0; xIdx=0; yIdx--){ + if(board[index(xIdx,yIdx)] == null){ + fallDist += 1; + }else{ + if(fallDist > 0){ + var obj = board[index(xIdx,yIdx)]; + obj.targetY += fallDist * gameCanvas.tileSize; + board[index(xIdx,yIdx+fallDist)] = obj; + board[index(xIdx,yIdx)] = null; + } + } + } + } + //Fall to the left + fallDist = 0; + for(xIdx=0; xIdx 0){ + for(yIdx=0; yIdx=0; xIdx--) + if(board[index(xIdx, maxY - 1)] != null) + deservesBonus = false; + if(deservesBonus) + gameCanvas.score += 500; + //Checks for game over + if(deservesBonus || !(floodMoveCheck(0,maxY-1, -1))){ + timer = new Date() - timer; + //scoreName.show("You won! Please enter your name: "); + scoreName.show("You won! Please enter your name: "); + scoreName.initialWidth = scoreName.text.width + 20; + scoreName.width = scoreName.initialWidth; + scoreName.text.opacity = 0;//Just a spacer + //dialog.show("Game Over. Your score is " + gameCanvas.score); + } +} + +//only floods up and right, to see if it can find adjacent same-typed tiles +function floodMoveCheck(xIdx, yIdx, type) +{ + if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0) + return false; + if(board[index(xIdx, yIdx)] == null) + return false; + var myType = board[index(xIdx, yIdx)].type; + if(type == myType) + return true; + return floodMoveCheck(xIdx + 1, yIdx, myType) || + floodMoveCheck(xIdx, yIdx - 1, board[index(xIdx,yIdx)].type); +} + +function createBlock(xIdx,yIdx){ + // Note that we don't wait for the component to become ready. This will + // only work if the block QML is a local file. Otherwise the component will + // not be ready immediately. There is a statusChanged signal on the + // component you could use if you want to wait to load remote files. + if(component.isReady){ + var dynamicObject = component.createObject(); + if(dynamicObject == null){ + print("error creating block"); + print(component.errorsString()); + return false; + } + dynamicObject.type = Math.floor(Math.random() * 3); + dynamicObject.parent = gameCanvas; + dynamicObject.x = xIdx*gameCanvas.tileSize; + dynamicObject.targetX = xIdx*gameCanvas.tileSize; + dynamicObject.targetY = yIdx*gameCanvas.tileSize; + dynamicObject.width = gameCanvas.tileSize; + dynamicObject.height = gameCanvas.tileSize; + dynamicObject.spawned = true; + board[index(xIdx,yIdx)] = dynamicObject; + }else{//isError or isLoading + print("error loading block component"); + print(component.errorsString()); + return false; + } + return true; +} + +function saveHighScore(name) { + if(scoresURL!="") + sendHighScore(name); + //OfflineStorage + var db = openDatabaseSync("SameGameScores", "1.0", "Local SameGame High Scores",100); + var dataStr = "INSERT INTO Scores VALUES(?, ?, ?, ?)"; + var data = [name, gameCanvas.score, maxX+"x"+maxY ,Math.floor(timer/1000)]; + db.transaction( + function(tx) { + tx.executeSql('CREATE TABLE IF NOT EXISTS Scores(name TEXT, score NUMBER, gridSize TEXT, time NUMBER)'); + tx.executeSql(dataStr, data); + + //Only show results for the current grid size + var rs = tx.executeSql('SELECT * FROM Scores WHERE gridSize = "'+maxX+"x"+maxY+'" ORDER BY score desc LIMIT 10'); + var r = "\nHIGH SCORES for this grid size\n\n" + for(var i = 0; i < rs.rows.length; i++){ + r += (i+1)+". " + rs.rows.item(i).name +' got ' + + rs.rows.item(i).score + ' points in ' + + rs.rows.item(i).time + ' seconds.\n'; + } + dialog.show(r); + } + ); +} + +function sendHighScore(name) { + var postman = new XMLHttpRequest() + var postData = "name="+name+"&score="+gameCanvas.score + +"&gridSize="+maxX+"x"+maxY +"&time="+Math.floor(timer/1000); + postman.open("POST", scoresURL, true); + postman.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + postman.onreadystatechange = function() { + if (postman.readyState == postman.DONE) { + dialog.show("Your score has been uploaded."); + } + } + postman.send(postData); +} diff --git a/demos/declarative/samegame/content/BoomBlock.qml b/demos/declarative/samegame/content/BoomBlock.qml deleted file mode 100644 index e48194a..0000000 --- a/demos/declarative/samegame/content/BoomBlock.qml +++ /dev/null @@ -1,55 +0,0 @@ -import Qt 4.6 - -Item { id:block - property bool dying: false - property bool spawned: false - property int type: 0 - property int targetX: 0 - property int targetY: 0 - - SpringFollow on x { enabled: spawned; source: targetX; spring: 2; damping: 0.2 } - SpringFollow on y { source: targetY; spring: 2; damping: 0.2 } - - Image { id: img - source: { - if(type == 0){ - "pics/redStone.png"; - } else if(type == 1) { - "pics/blueStone.png"; - } else { - "pics/greenStone.png"; - } - } - opacity: 0 - Behavior on opacity { NumberAnimation { duration: 200 } } - anchors.fill: parent - } - - Particles { id: particles - width:1; height:1; anchors.centerIn: parent; - emissionRate: 0; - lifeSpan: 700; lifeSpanDeviation: 600; - angle: 0; angleDeviation: 360; - velocity: 100; velocityDeviation:30; - source: { - if(type == 0){ - "pics/redStar.png"; - } else if (type == 1) { - "pics/blueStar.png"; - } else { - "pics/greenStar.png"; - } - } - } - - states: [ - State{ name: "AliveState"; when: spawned == true && dying == false - PropertyChanges { target: img; opacity: 1 } - }, - State{ name: "DeathState"; when: dying == true - StateChangeScript { script: particles.burst(50); } - PropertyChanges { target: img; opacity: 0 } - StateChangeScript { script: block.destroy(1000); } - } - ] -} diff --git a/demos/declarative/samegame/content/Button.qml b/demos/declarative/samegame/content/Button.qml deleted file mode 100644 index 6629302..0000000 --- a/demos/declarative/samegame/content/Button.qml +++ /dev/null @@ -1,25 +0,0 @@ -import Qt 4.6 - -Rectangle { - id: container - - signal clicked - property string text: "Button" - - color: activePalette.button; smooth: true - width: txtItem.width + 20; height: txtItem.height + 6 - border.width: 1; border.color: Qt.darker(activePalette.button); radius: 8; - - gradient: Gradient { - GradientStop { - id: topGrad; position: 0.0 - color: if (mr.pressed) { activePalette.dark } else { activePalette.light } } - GradientStop { position: 1.0; color: activePalette.button } - } - - MouseArea { id: mr; anchors.fill: parent; onClicked: container.clicked() } - - Text { - id: txtItem; text: container.text; anchors.centerIn: container; color: activePalette.buttonText - } -} diff --git a/demos/declarative/samegame/content/Dialog.qml b/demos/declarative/samegame/content/Dialog.qml deleted file mode 100644 index 6d5d6b5..0000000 --- a/demos/declarative/samegame/content/Dialog.qml +++ /dev/null @@ -1,22 +0,0 @@ -import Qt 4.6 - -Rectangle { - id: page - function forceClose() { - page.closed(); - page.opacity = 0; - } - function show(txt) { - myText.text = txt; - page.opacity = 1; - } - signal closed(); - property Item text: myText - color: "white"; border.width: 1; width: myText.width + 20; height: myText.height + 40; - opacity: 0 - Behavior on opacity { - NumberAnimation { duration: 1000 } - } - Text { id: myText; anchors.centerIn: parent; text: "Hello World!" } - MouseArea { id: mr; anchors.fill: parent; onClicked: forceClose(); } -} diff --git a/demos/declarative/samegame/content/pics/background.png b/demos/declarative/samegame/content/pics/background.png deleted file mode 100644 index 3734a27..0000000 Binary files a/demos/declarative/samegame/content/pics/background.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/blueStar.png b/demos/declarative/samegame/content/pics/blueStar.png deleted file mode 100644 index ff9588f..0000000 Binary files a/demos/declarative/samegame/content/pics/blueStar.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/blueStone.png b/demos/declarative/samegame/content/pics/blueStone.png deleted file mode 100644 index 20e43c7..0000000 Binary files a/demos/declarative/samegame/content/pics/blueStone.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/greenStar.png b/demos/declarative/samegame/content/pics/greenStar.png deleted file mode 100644 index cd06854..0000000 Binary files a/demos/declarative/samegame/content/pics/greenStar.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/greenStone.png b/demos/declarative/samegame/content/pics/greenStone.png deleted file mode 100644 index b568a19..0000000 Binary files a/demos/declarative/samegame/content/pics/greenStone.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/redStar.png b/demos/declarative/samegame/content/pics/redStar.png deleted file mode 100644 index 0a4dffe..0000000 Binary files a/demos/declarative/samegame/content/pics/redStar.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/redStone.png b/demos/declarative/samegame/content/pics/redStone.png deleted file mode 100644 index 36b09a2..0000000 Binary files a/demos/declarative/samegame/content/pics/redStone.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/star.png b/demos/declarative/samegame/content/pics/star.png deleted file mode 100644 index defbde5..0000000 Binary files a/demos/declarative/samegame/content/pics/star.png and /dev/null differ diff --git a/demos/declarative/samegame/content/pics/yellowStone.png b/demos/declarative/samegame/content/pics/yellowStone.png deleted file mode 100644 index b1ce762..0000000 Binary files a/demos/declarative/samegame/content/pics/yellowStone.png and /dev/null differ diff --git a/demos/declarative/samegame/content/qmldir b/demos/declarative/samegame/content/qmldir deleted file mode 100644 index a8f8a98..0000000 --- a/demos/declarative/samegame/content/qmldir +++ /dev/null @@ -1,3 +0,0 @@ -BoomBlock 0.0 BoomBlock.qml -Button 0.0 Button.qml -Dialog 0.0 Dialog.qml diff --git a/demos/declarative/samegame/content/samegame.js b/demos/declarative/samegame/content/samegame.js deleted file mode 100755 index c0f10bd..0000000 --- a/demos/declarative/samegame/content/samegame.js +++ /dev/null @@ -1,250 +0,0 @@ -/* This script file handles the game logic */ -//Note that X/Y referred to here are in game coordinates -var maxX = 10;//Nums are for gameCanvas.tileSize 40 -var maxY = 15; -var maxIndex = maxX*maxY; -var board = new Array(maxIndex); -var tileSrc = "content/BoomBlock.qml"; -var scoresURL = "http://qtfx-nokia.trolltech.com.au/samegame/scores.php"; -var scoresURL = ""; -var timer; -var component = createComponent(tileSrc); - -//Index function used instead of a 2D array -function index(xIdx,yIdx) { - return xIdx + (yIdx * maxX); -} - -function timeStr(msecs) { - var secs = Math.floor(msecs/1000); - var m = Math.floor(secs/60); - var ret = "" + m + "m " + (secs%60) + "s"; - return ret; -} - -function getTileSize() -{ - return tileSize; -} - -function initBoard() -{ - for(var i = 0; i= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0) - return; - if(board[index(xIdx, yIdx)] == null) - return; - //If it's a valid tile, remove it and all connected (does nothing if it's not connected) - floodFill(xIdx,yIdx, -1); - if(fillFound <= 0) - return; - gameCanvas.score += (fillFound - 1) * (fillFound - 1); - shuffleDown(); - victoryCheck(); -} - -function floodFill(xIdx,yIdx,type) -{ - if(board[index(xIdx, yIdx)] == null) - return; - var first = false; - if(type == -1){ - first = true; - type = board[index(xIdx,yIdx)].type; - - //Flood fill initialization - fillFound = 0; - floodBoard = new Array(maxIndex); - } - if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0) - return; - if(floodBoard[index(xIdx, yIdx)] == 1 || (!first && type != board[index(xIdx,yIdx)].type)) - return; - floodBoard[index(xIdx, yIdx)] = 1; - floodFill(xIdx+1,yIdx,type); - floodFill(xIdx-1,yIdx,type); - floodFill(xIdx,yIdx+1,type); - floodFill(xIdx,yIdx-1,type); - if(first==true && fillFound == 0) - return;//Can't remove single tiles - board[index(xIdx,yIdx)].dying = true; - board[index(xIdx,yIdx)] = null; - fillFound += 1; -} - -function shuffleDown() -{ - //Fall down - for(var xIdx=0; xIdx=0; yIdx--){ - if(board[index(xIdx,yIdx)] == null){ - fallDist += 1; - }else{ - if(fallDist > 0){ - var obj = board[index(xIdx,yIdx)]; - obj.targetY += fallDist * gameCanvas.tileSize; - board[index(xIdx,yIdx+fallDist)] = obj; - board[index(xIdx,yIdx)] = null; - } - } - } - } - //Fall to the left - fallDist = 0; - for(xIdx=0; xIdx 0){ - for(yIdx=0; yIdx=0; xIdx--) - if(board[index(xIdx, maxY - 1)] != null) - deservesBonus = false; - if(deservesBonus) - gameCanvas.score += 500; - //Checks for game over - if(deservesBonus || !(floodMoveCheck(0,maxY-1, -1))){ - timer = new Date() - timer; - //scoreName.show("You won! Please enter your name: "); - scoreName.show("You won! Please enter your name: "); - scoreName.initialWidth = scoreName.text.width + 20; - scoreName.width = scoreName.initialWidth; - scoreName.text.opacity = 0;//Just a spacer - //dialog.show("Game Over. Your score is " + gameCanvas.score); - } -} - -//only floods up and right, to see if it can find adjacent same-typed tiles -function floodMoveCheck(xIdx, yIdx, type) -{ - if(xIdx >= maxX || xIdx < 0 || yIdx >= maxY || yIdx < 0) - return false; - if(board[index(xIdx, yIdx)] == null) - return false; - var myType = board[index(xIdx, yIdx)].type; - if(type == myType) - return true; - return floodMoveCheck(xIdx + 1, yIdx, myType) || - floodMoveCheck(xIdx, yIdx - 1, board[index(xIdx,yIdx)].type); -} - -function createBlock(xIdx,yIdx){ - // Note that we don't wait for the component to become ready. This will - // only work if the block QML is a local file. Otherwise the component will - // not be ready immediately. There is a statusChanged signal on the - // component you could use if you want to wait to load remote files. - if(component.isReady){ - var dynamicObject = component.createObject(); - if(dynamicObject == null){ - print("error creating block"); - print(component.errorsString()); - return false; - } - dynamicObject.type = Math.floor(Math.random() * 3); - dynamicObject.parent = gameCanvas; - dynamicObject.x = xIdx*gameCanvas.tileSize; - dynamicObject.targetX = xIdx*gameCanvas.tileSize; - dynamicObject.targetY = yIdx*gameCanvas.tileSize; - dynamicObject.width = gameCanvas.tileSize; - dynamicObject.height = gameCanvas.tileSize; - dynamicObject.spawned = true; - board[index(xIdx,yIdx)] = dynamicObject; - }else{//isError or isLoading - print("error loading block component"); - print(component.errorsString()); - return false; - } - return true; -} - -function saveHighScore(name) { - if(scoresURL!="") - sendHighScore(name); - //OfflineStorage - var db = openDatabaseSync("SameGameScores", "1.0", "Local SameGame High Scores",100); - var dataStr = "INSERT INTO Scores VALUES(?, ?, ?, ?)"; - var data = [name, gameCanvas.score, maxX+"x"+maxY ,Math.floor(timer/1000)]; - db.transaction( - function(tx) { - tx.executeSql('CREATE TABLE IF NOT EXISTS Scores(name TEXT, score NUMBER, gridSize TEXT, time NUMBER)'); - tx.executeSql(dataStr, data); - - //Only show results for the current grid size - var rs = tx.executeSql('SELECT * FROM Scores WHERE gridSize = "'+maxX+"x"+maxY+'" ORDER BY score desc LIMIT 10'); - var r = "\nHIGH SCORES for this grid size\n\n" - for(var i = 0; i < rs.rows.length; i++){ - r += (i+1)+". " + rs.rows.item(i).name +' got ' - + rs.rows.item(i).score + ' points in ' - + rs.rows.item(i).time + ' seconds.\n'; - } - dialog.show(r); - } - ); -} - -function sendHighScore(name) { - var postman = new XMLHttpRequest() - var postData = "name="+name+"&score="+gameCanvas.score - +"&gridSize="+maxX+"x"+maxY +"&time="+Math.floor(timer/1000); - postman.open("POST", scoresURL, true); - postman.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - postman.onreadystatechange = function() { - if (postman.readyState == postman.DONE) { - dialog.show("Your score has been uploaded."); - } - } - postman.send(postData); -} diff --git a/demos/declarative/samegame/samegame.qml b/demos/declarative/samegame/samegame.qml index c81f292..3b19cbe 100644 --- a/demos/declarative/samegame/samegame.qml +++ b/demos/declarative/samegame/samegame.qml @@ -1,5 +1,5 @@ import Qt 4.6 -import "content" +import SamegameCore 1.0 Rectangle { id: screen @@ -12,7 +12,7 @@ Rectangle { Image { id: background - anchors.fill: parent; source: "content/pics/background.png" + anchors.fill: parent; source: "SamegameCore/pics/background.png" fillMode: Image.PreserveAspectCrop smooth: true } @@ -22,7 +22,7 @@ Rectangle { property int score: 0 property int tileSize: 40 - Script { source: "content/samegame.js" } + Script { source: "SamegameCore/samegame.js" } z: 20; anchors.centerIn: parent width: parent.width - (parent.width % getTileSize()); diff --git a/demos/declarative/twitter/TwitterCore/AuthView.qml b/demos/declarative/twitter/TwitterCore/AuthView.qml new file mode 100644 index 0000000..bcf4646 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/AuthView.qml @@ -0,0 +1,99 @@ +import Qt 4.6 + +Item { + id: wrapper + Column { + anchors.centerIn: parent + spacing: 20 + Column{ + spacing: 4 + Text { + text: "Screen name:" + font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" + horizontalAlignment: Qt.AlignRight + } + Item { + width: 220 + height: 28 + BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } + TextInput{ + id: nameIn + width: parent.width - 8 + anchors.centerIn: parent + maximumLength:21 + font.pixelSize: 16; + font.bold: true + color: "#151515"; selectionColor: "green" + KeyNavigation.down: passIn + focus: true + } + } + } + Column{ + spacing: 4 + Text { + text: "Password:" + font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" + horizontalAlignment: Qt.AlignRight + } + Item { + width: 220 + height: 28 + BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } + TextInput{ + id: passIn + width: parent.width - 8 + anchors.centerIn: parent + maximumLength:21 + echoMode: TextInput.Password + font.pixelSize: 16; + font.bold: true + color: "#151515"; selectionColor: "green" + KeyNavigation.down: login + KeyNavigation.up: nameIn + } + } + } + Row{ + spacing: 10 + Button { + width: 100 + height: 32 + id: login + keyUsing: true; + function doLogin(){ + rssModel.authName=nameIn.text; + rssModel.authPass=passIn.text; + rssModel.tags='my timeline'; + screen.focus = true; + } + text: "Log in" + KeyNavigation.right: guest + KeyNavigation.up: passIn + Keys.onReturnPressed: login.doLogin(); + Keys.onSelectPressed: login.doLogin(); + Keys.onSpacePressed: login.doLogin(); + onClicked: login.doLogin(); + } + Button { + width: 100 + height: 32 + id: guest + keyUsing: true; + function doGuest() + { + rssModel.authName='-'; + screen.focus = true; + screen.setMode(true); + } + text: "Guest" + KeyNavigation.left: login + KeyNavigation.up: passIn + Keys.onReturnPressed: guest.doGuest(); + Keys.onSelectPressed: guest.doGuest(); + Keys.onSpacePressed: guest.doGuest(); + onClicked: guest.doGuest(); + } + } + } +} diff --git a/demos/declarative/twitter/TwitterCore/Button.qml b/demos/declarative/twitter/TwitterCore/Button.qml new file mode 100644 index 0000000..4cba8c3 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/Button.qml @@ -0,0 +1,49 @@ +import Qt 4.6 + +Item { + id: container + + signal clicked + + property string text + property bool keyUsing: false + + BorderImage { + id: buttonImage + source: "images/toolbutton.sci" + width: container.width; height: container.height + } + BorderImage { + id: pressed + opacity: 0 + source: "images/toolbutton.sci" + width: container.width; height: container.height + } + MouseArea { + id: mouseRegion + anchors.fill: buttonImage + onClicked: { container.clicked(); } + } + Text { + id: btnText + color: if(container.keyUsing){"#DDDDDD";} else {"#FFFFFF";} + anchors.centerIn: buttonImage; font.bold: true + text: container.text; style: Text.Raised; styleColor: "black" + font.pixelSize: 12 + } + states: [ + State { + name: "Pressed" + when: mouseRegion.pressed == true + PropertyChanges { target: pressed; opacity: 1 } + }, + State { + name: "Focused" + when: container.focus == true + PropertyChanges { target: btnText; color: "#FFFFFF" } + } + ] + transitions: Transition { + ColorAnimation { target: btnText; } + } +} diff --git a/demos/declarative/twitter/TwitterCore/FatDelegate.qml b/demos/declarative/twitter/TwitterCore/FatDelegate.qml new file mode 100644 index 0000000..0f013e6 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/FatDelegate.qml @@ -0,0 +1,46 @@ +import Qt 4.6 + +Component { + id: listDelegate + Item { + id: wrapper; width: wrapper.ListView.view.width; height: if(txt.height > 58){txt.height+8}else{58}//50+4+4 + Script { + function handleLink(link){ + if(link.slice(0,3) == 'app'){ + setUser(link.slice(7)); + screen.setMode(true); + }else if(link.slice(0,4) == 'http'){ + Qt.openUrlExternally(link); + } + } + function addTags(str){ + var ret = str.replace(/@[a-zA-Z0-9_]+/g, '$&');//click to jump to user? + var ret2 = ret.replace(/http:\/\/[^ \n\t]+/g, '$&');//surrounds http links with html link tags + return ret2; + } + } + Item { + id: moveMe; height: parent.height + Rectangle { + id: blackRect + color: "black"; opacity: wrapper.ListView.index % 2 ? 0.2 : 0.3; height: wrapper.height-2; width: wrapper.width; y: 1 + } + Rectangle { + id: whiteRect; x: 6; width: 50; height: 50; color: "white"; smooth: true + anchors.verticalCenter: parent.verticalCenter + + Loading { x: 1; y: 1; width: 48; height: 48; visible: realImage.status != 1 } + Image { id: realImage; source: userImage; x: 1; y: 1; width:48; height:48 } + } + Text { id:txt; y:4; x: 56 + text: '' + + ''+userScreenName + " from " +source + + "
" + addTags(statusText) + ""; + textFormat: Qt.RichText + color: "#cccccc"; style: Text.Raised; styleColor: "black"; wrap: true + anchors.left: whiteRect.right; anchors.right: blackRect.right; anchors.leftMargin: 6; anchors.rightMargin: 6 + onLinkActivated: handleLink(link) + } + } + } +} diff --git a/demos/declarative/twitter/TwitterCore/HomeTitleBar.qml b/demos/declarative/twitter/TwitterCore/HomeTitleBar.qml new file mode 100644 index 0000000..a206c87 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/HomeTitleBar.qml @@ -0,0 +1,121 @@ +import Qt 4.6 + +Item { + id: titleBar + + signal update() + onYChanged: state="" //When switching titlebars + + BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } + Item { + id: container + width: (parent.width * 2) - 55 ; height: parent.height + + Script { + function accept() { + if(rssModel.authName == '' || rssModel.authPass == '') + return false;//Can't login like that + + var postData = "status=" + editor.text; + var postman = new XMLHttpRequest(); + postman.open("POST", "http://twitter.com/statuses/update.xml", true, rssModel.authName, rssModel.authPass); + postman.onreadystatechange = function() { + if (postman.readyState == postman.DONE) { + titleBar.update(); + } + } + postman.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + postman.send(postData); + + editor.text = "" + titleBar.state = "" + } + } + + Rectangle { + x: 6; width: 50; height: 50; color: "white"; smooth: true + anchors.verticalCenter: parent.verticalCenter + + UserModel { user: rssModel.authName; id: userModel } + Component { id: imgDelegate; + Item { + Loading { width:48; height:48; visible: realImage.status != 1 } + Image { source: image; width:48; height:48; id: realImage } + } + } + ListView { model: userModel.model; x:1; y:1; delegate: imgDelegate } + } + + Text { + id: categoryText + anchors.left: parent.left; anchors.right: tagButton.left + anchors.leftMargin: 58; anchors.rightMargin: 10 + anchors.verticalCenter: parent.verticalCenter + elide: Text.ElideLeft + text: "Timeline for " + rssModel.authName + font.pixelSize: 12; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" + } + + Button { + id: tagButton; x: titleBar.width - 90; width: 85; height: 32; text: "New Post..." + anchors.verticalCenter: parent.verticalCenter; + onClicked: if (titleBar.state == "Posting") accept(); else titleBar.state = "Posting" + } + + Text { + id: charsLeftText; anchors.horizontalCenter: tagButton.horizontalCenter; + anchors.top: tagButton.bottom; anchors.topMargin: 2 + text: {140 - editor.text.length;} visible: titleBar.state == "Posting" + font.pointSize: 10; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" + } + Item { + id: txtEdit; + anchors.left: tagButton.right; anchors.leftMargin: 5; y: 4 + anchors.right: parent.right; anchors.rightMargin: 40; height: parent.height - 9 + BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } + + Binding {//TODO: Can this be a function, which also resets the cursor? And flashes? + when: editor.text.length > 140 + target: editor + property: "text" + value: editor.text.slice(0,140) + } + TextEdit { + id: editor + anchors.left: parent.left; + anchors.leftMargin: 8; + anchors.bottom: parent.bottom + anchors.bottomMargin: 4; + cursorVisible: true; font.bold: true + width: parent.width - 12 + height: parent.height - 8 + font.pointSize: 10 + wrap: true + color: "#151515"; selectionColor: "green" + } + Keys.forwardTo: [(returnKey), (editor)] + Item { + id: returnKey + Keys.onReturnPressed: accept() + Keys.onEscapePressed: titleBar.state = "" + } + } + } + states: [ + State { + name: "Posting" + PropertyChanges { target: container; x: -tagButton.x + 5 } + PropertyChanges { target: titleBar; height: 80 } + PropertyChanges { target: tagButton; text: "OK" } + PropertyChanges { target: tagButton; width: 28 } + PropertyChanges { target: tagButton; height: 24 } + PropertyChanges { target: txtEdit; focus: true } + } + ] + transitions: [ + Transition { + from: "*"; to: "*" + NumberAnimation { properties: "x,y,width,height"; easing.type: "InOutQuad" } + } + ] +} diff --git a/demos/declarative/twitter/TwitterCore/Loading.qml b/demos/declarative/twitter/TwitterCore/Loading.qml new file mode 100644 index 0000000..76bf64b --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/Loading.qml @@ -0,0 +1,8 @@ +import Qt 4.6 + +Image { + id: loading; source: "images/loading.png"; transformOrigin: "Center" + NumberAnimation on rotation { + from: 0; to: 360; running: loading.visible == true; repeat: true; duration: 900 + } +} diff --git a/demos/declarative/twitter/TwitterCore/MultiTitleBar.qml b/demos/declarative/twitter/TwitterCore/MultiTitleBar.qml new file mode 100644 index 0000000..e0205b8 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/MultiTitleBar.qml @@ -0,0 +1,24 @@ +import Qt 4.6 + +Item { + height: homeBar.height + HomeTitleBar { id: homeBar; width: parent.width; height: 60; + onUpdate: rssModel.reload() + } + TitleBar { id: titleBar; width: parent.width; height: 60; + y: -80 + untaggedString: "Latest tweets from everyone" + taggedString: "Latest tweets from " + } + states: [ + State { + name: "search"; when: screen.userView + PropertyChanges { target: titleBar; y: 0 } + PropertyChanges { target: homeBar; y: -80 } + } + ] + transitions: [ + Transition { NumberAnimation { properties: "x,y"; duration: 500; easing.type: "InOutQuad" } } + ] +} + diff --git a/demos/declarative/twitter/TwitterCore/RssModel.qml b/demos/declarative/twitter/TwitterCore/RssModel.qml new file mode 100644 index 0000000..9d88bb7 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/RssModel.qml @@ -0,0 +1,44 @@ +import Qt 4.6 + +Item { id: wrapper + property var model: xmlModel + property string tags : "" + property string authName : "" + property string authPass : "" + property string mode : "everyone" + property int status: xmlModel.status + function reload() { xmlModel.reload(); } +XmlListModel { + id: xmlModel + + source:{ + if (wrapper.authName == ""){ + ""; //Avoid worthless calls to twitter servers + }else if(wrapper.mode == 'user'){ + "https://"+ ((wrapper.authName!="" && wrapper.authPass!="")? (wrapper.authName+":"+wrapper.authPass+"@") : "" )+"twitter.com/statuses/user_timeline.xml?screen_name="+wrapper.tags; + }else if(wrapper.mode == 'self'){ + "https://"+ ((wrapper.authName!="" && wrapper.authPass!="")? (wrapper.authName+":"+wrapper.authPass+"@") : "" )+"twitter.com/statuses/friends_timeline.xml"; + }else{//everyone/public + "http://twitter.com/statuses/public_timeline.xml"; + } + } + query: "/statuses/status" + + XmlRole { name: "statusText"; query: "text/string()" } + XmlRole { name: "timestamp"; query: "created_at/string()" } + XmlRole { name: "source"; query: "source/string()" } + XmlRole { name: "userName"; query: "user/name/string()" } + XmlRole { name: "userScreenName"; query: "user/screen_name/string()" } + XmlRole { name: "userImage"; query: "user/profile_image_url/string()" } + XmlRole { name: "userLocation"; query: "user/location/string()" } + XmlRole { name: "userDescription"; query: "user/description/string()" } + XmlRole { name: "userFollowers"; query: "user/followers_count/string()" } + XmlRole { name: "userStatuses"; query: "user/statuses_count/string()" } + //TODO: Could also get the user's color scheme, timezone and a few other things +} +Binding { + property: "mode" + target: wrapper + value: {if(wrapper.tags==''){"everyone";}else if(wrapper.tags=='my timeline'){"self";}else{"user";}} +} +} diff --git a/demos/declarative/twitter/TwitterCore/TitleBar.qml b/demos/declarative/twitter/TwitterCore/TitleBar.qml new file mode 100644 index 0000000..149aa82 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/TitleBar.qml @@ -0,0 +1,77 @@ +import Qt 4.6 + +Item { + id: titleBar + property string untaggedString: "Uploads from everyone" + property string taggedString: "Recent uploads tagged " + + BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } + + Item { + id: container + width: (parent.width * 2) - 55 ; height: parent.height + + Script { + function accept() { + titleBar.state = "" + background.state = "" + rssModel.tags = editor.text + } + } + + Text { + id: categoryText + anchors { + left: parent.left; right: tagButton.left; leftMargin: 10; rightMargin: 10 + verticalCenter: parent.verticalCenter + } + elide: Text.ElideLeft + text: (rssModel.tags=="" ? untaggedString : taggedString + rssModel.tags) + font.bold: true; color: "White"; style: Text.Raised; styleColor: "Black" + font.pixelSize: 12 + } + + Button { + id: tagButton; x: titleBar.width - 50; width: 45; height: 32; text: "..." + onClicked: if (titleBar.state == "Tags") accept(); else titleBar.state = "Tags" + anchors.verticalCenter: parent.verticalCenter + } + + Item { + id: lineEdit + y: 4; height: parent.height - 9 + anchors { left: tagButton.right; leftMargin: 5; right: parent.right; rightMargin: 5 } + + BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } + + TextInput { + id: editor + anchors { + left: parent.left; right: parent.right; leftMargin: 10; rightMargin: 10 + verticalCenter: parent.verticalCenter + } + cursorVisible: true; font.bold: true + color: "#151515"; selectionColor: "Green" + } + + Keys.forwardTo: [ (returnKey), (editor)] + + Item { + id: returnKey + Keys.onReturnPressed: accept() + Keys.onEscapePressed: titleBar.state = "" + } + } + } + + states: State { + name: "Tags" + PropertyChanges { target: container; x: -tagButton.x + 5 } + PropertyChanges { target: tagButton; text: "OK" } + PropertyChanges { target: lineEdit; focus: true } + } + + transitions: Transition { + NumberAnimation { properties: "x"; easing.type: "InOutQuad" } + } +} diff --git a/demos/declarative/twitter/TwitterCore/ToolBar.qml b/demos/declarative/twitter/TwitterCore/ToolBar.qml new file mode 100644 index 0000000..f96c767 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/ToolBar.qml @@ -0,0 +1,24 @@ +import Qt 4.6 + +Item { + id: toolbar + + property alias button1Label: button1.text + property alias button2Label: button2.text + signal button1Clicked + signal button2Clicked + + BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } + + Button { + id: button1 + anchors.left: parent.left; anchors.leftMargin: 5; y: 3; width: 140; height: 32 + onClicked: toolbar.button1Clicked() + } + + Button { + id: button2 + anchors.right: parent.right; anchors.rightMargin: 5; y: 3; width: 140; height: 32 + onClicked: toolbar.button2Clicked() + } +} diff --git a/demos/declarative/twitter/TwitterCore/UserModel.qml b/demos/declarative/twitter/TwitterCore/UserModel.qml new file mode 100644 index 0000000..c146b84 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/UserModel.qml @@ -0,0 +1,26 @@ +import Qt 4.6 + +//This "model" gets the user information about the searched user. Mainly for the icon. +//Copied from RssModel + +Item { id: wrapper + property var model: xmlModel + property string user : "" + property int status: xmlModel.status + function reload() { xmlModel.reload(); } +XmlListModel { + id: xmlModel + + source: {if(user!="") {"http://twitter.com/users/show.xml?screen_name="+user;}else{"";}} + query: "/user" + + XmlRole { name: "name"; query: "name/string()" } + XmlRole { name: "screenName"; query: "screen_name/string()" } + XmlRole { name: "image"; query: "profile_image_url/string()" } + XmlRole { name: "location"; query: "location/string()" } + XmlRole { name: "description"; query: "description/string()" } + XmlRole { name: "followers"; query: "followers_count/string()" } + //XmlRole { name: "protected"; query: "protected/bool()" } + //TODO: Could also get the user's color scheme, timezone and a few other things +} +} diff --git a/demos/declarative/twitter/TwitterCore/images/gloss.png b/demos/declarative/twitter/TwitterCore/images/gloss.png new file mode 100644 index 0000000..5d370cd Binary files /dev/null and b/demos/declarative/twitter/TwitterCore/images/gloss.png differ diff --git a/demos/declarative/twitter/TwitterCore/images/lineedit.png b/demos/declarative/twitter/TwitterCore/images/lineedit.png new file mode 100644 index 0000000..2cc38dc Binary files /dev/null and b/demos/declarative/twitter/TwitterCore/images/lineedit.png differ diff --git a/demos/declarative/twitter/TwitterCore/images/lineedit.sci b/demos/declarative/twitter/TwitterCore/images/lineedit.sci new file mode 100644 index 0000000..054bff7 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/images/lineedit.sci @@ -0,0 +1,5 @@ +border.left: 10 +border.top: 10 +border.bottom: 10 +border.right: 10 +source: lineedit.png diff --git a/demos/declarative/twitter/TwitterCore/images/loading.png b/demos/declarative/twitter/TwitterCore/images/loading.png new file mode 100644 index 0000000..47a1589 Binary files /dev/null and b/demos/declarative/twitter/TwitterCore/images/loading.png differ diff --git a/demos/declarative/twitter/TwitterCore/images/stripes.png b/demos/declarative/twitter/TwitterCore/images/stripes.png new file mode 100644 index 0000000..9f36727 Binary files /dev/null and b/demos/declarative/twitter/TwitterCore/images/stripes.png differ diff --git a/demos/declarative/twitter/TwitterCore/images/titlebar.png b/demos/declarative/twitter/TwitterCore/images/titlebar.png new file mode 100644 index 0000000..51c9008 Binary files /dev/null and b/demos/declarative/twitter/TwitterCore/images/titlebar.png differ diff --git a/demos/declarative/twitter/TwitterCore/images/titlebar.sci b/demos/declarative/twitter/TwitterCore/images/titlebar.sci new file mode 100644 index 0000000..0418d94 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/images/titlebar.sci @@ -0,0 +1,5 @@ +border.left: 10 +border.top: 12 +border.bottom: 12 +border.right: 10 +source: titlebar.png diff --git a/demos/declarative/twitter/TwitterCore/images/toolbutton.png b/demos/declarative/twitter/TwitterCore/images/toolbutton.png new file mode 100644 index 0000000..1131001 Binary files /dev/null and b/demos/declarative/twitter/TwitterCore/images/toolbutton.png differ diff --git a/demos/declarative/twitter/TwitterCore/images/toolbutton.sci b/demos/declarative/twitter/TwitterCore/images/toolbutton.sci new file mode 100644 index 0000000..9e4f965 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/images/toolbutton.sci @@ -0,0 +1,5 @@ +border.left: 15 +border.top: 4 +border.bottom: 4 +border.right: 15 +source: toolbutton.png diff --git a/demos/declarative/twitter/TwitterCore/qmldir b/demos/declarative/twitter/TwitterCore/qmldir new file mode 100644 index 0000000..8b56c56 --- /dev/null +++ b/demos/declarative/twitter/TwitterCore/qmldir @@ -0,0 +1,10 @@ +AuthView 1.0 AuthView.qml +Button 1.0 Button.qml +FatDelegate 1.0 FatDelegate.qml +HomeTitleBar 1.0 HomeTitleBar.qml +Loading 1.0 Loading.qml +MultiTitleBar 1.0 MultiTitleBar.qml +TitleBar 1.0 TitleBar.qml +RssModel 1.0 RssModel.qml +UserModel 1.0 UserModel.qml +ToolBar 1.0 ToolBar.qml diff --git a/demos/declarative/twitter/content/AuthView.qml b/demos/declarative/twitter/content/AuthView.qml deleted file mode 100644 index bcf4646..0000000 --- a/demos/declarative/twitter/content/AuthView.qml +++ /dev/null @@ -1,99 +0,0 @@ -import Qt 4.6 - -Item { - id: wrapper - Column { - anchors.centerIn: parent - spacing: 20 - Column{ - spacing: 4 - Text { - text: "Screen name:" - font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - horizontalAlignment: Qt.AlignRight - } - Item { - width: 220 - height: 28 - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - TextInput{ - id: nameIn - width: parent.width - 8 - anchors.centerIn: parent - maximumLength:21 - font.pixelSize: 16; - font.bold: true - color: "#151515"; selectionColor: "green" - KeyNavigation.down: passIn - focus: true - } - } - } - Column{ - spacing: 4 - Text { - text: "Password:" - font.pixelSize: 16; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - horizontalAlignment: Qt.AlignRight - } - Item { - width: 220 - height: 28 - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - TextInput{ - id: passIn - width: parent.width - 8 - anchors.centerIn: parent - maximumLength:21 - echoMode: TextInput.Password - font.pixelSize: 16; - font.bold: true - color: "#151515"; selectionColor: "green" - KeyNavigation.down: login - KeyNavigation.up: nameIn - } - } - } - Row{ - spacing: 10 - Button { - width: 100 - height: 32 - id: login - keyUsing: true; - function doLogin(){ - rssModel.authName=nameIn.text; - rssModel.authPass=passIn.text; - rssModel.tags='my timeline'; - screen.focus = true; - } - text: "Log in" - KeyNavigation.right: guest - KeyNavigation.up: passIn - Keys.onReturnPressed: login.doLogin(); - Keys.onSelectPressed: login.doLogin(); - Keys.onSpacePressed: login.doLogin(); - onClicked: login.doLogin(); - } - Button { - width: 100 - height: 32 - id: guest - keyUsing: true; - function doGuest() - { - rssModel.authName='-'; - screen.focus = true; - screen.setMode(true); - } - text: "Guest" - KeyNavigation.left: login - KeyNavigation.up: passIn - Keys.onReturnPressed: guest.doGuest(); - Keys.onSelectPressed: guest.doGuest(); - Keys.onSpacePressed: guest.doGuest(); - onClicked: guest.doGuest(); - } - } - } -} diff --git a/demos/declarative/twitter/content/Button.qml b/demos/declarative/twitter/content/Button.qml deleted file mode 100644 index 4cba8c3..0000000 --- a/demos/declarative/twitter/content/Button.qml +++ /dev/null @@ -1,49 +0,0 @@ -import Qt 4.6 - -Item { - id: container - - signal clicked - - property string text - property bool keyUsing: false - - BorderImage { - id: buttonImage - source: "images/toolbutton.sci" - width: container.width; height: container.height - } - BorderImage { - id: pressed - opacity: 0 - source: "images/toolbutton.sci" - width: container.width; height: container.height - } - MouseArea { - id: mouseRegion - anchors.fill: buttonImage - onClicked: { container.clicked(); } - } - Text { - id: btnText - color: if(container.keyUsing){"#DDDDDD";} else {"#FFFFFF";} - anchors.centerIn: buttonImage; font.bold: true - text: container.text; style: Text.Raised; styleColor: "black" - font.pixelSize: 12 - } - states: [ - State { - name: "Pressed" - when: mouseRegion.pressed == true - PropertyChanges { target: pressed; opacity: 1 } - }, - State { - name: "Focused" - when: container.focus == true - PropertyChanges { target: btnText; color: "#FFFFFF" } - } - ] - transitions: Transition { - ColorAnimation { target: btnText; } - } -} diff --git a/demos/declarative/twitter/content/FatDelegate.qml b/demos/declarative/twitter/content/FatDelegate.qml deleted file mode 100644 index 0f013e6..0000000 --- a/demos/declarative/twitter/content/FatDelegate.qml +++ /dev/null @@ -1,46 +0,0 @@ -import Qt 4.6 - -Component { - id: listDelegate - Item { - id: wrapper; width: wrapper.ListView.view.width; height: if(txt.height > 58){txt.height+8}else{58}//50+4+4 - Script { - function handleLink(link){ - if(link.slice(0,3) == 'app'){ - setUser(link.slice(7)); - screen.setMode(true); - }else if(link.slice(0,4) == 'http'){ - Qt.openUrlExternally(link); - } - } - function addTags(str){ - var ret = str.replace(/@[a-zA-Z0-9_]+/g, '$&');//click to jump to user? - var ret2 = ret.replace(/http:\/\/[^ \n\t]+/g, '$&');//surrounds http links with html link tags - return ret2; - } - } - Item { - id: moveMe; height: parent.height - Rectangle { - id: blackRect - color: "black"; opacity: wrapper.ListView.index % 2 ? 0.2 : 0.3; height: wrapper.height-2; width: wrapper.width; y: 1 - } - Rectangle { - id: whiteRect; x: 6; width: 50; height: 50; color: "white"; smooth: true - anchors.verticalCenter: parent.verticalCenter - - Loading { x: 1; y: 1; width: 48; height: 48; visible: realImage.status != 1 } - Image { id: realImage; source: userImage; x: 1; y: 1; width:48; height:48 } - } - Text { id:txt; y:4; x: 56 - text: '' - + ''+userScreenName + " from " +source - + "
" + addTags(statusText) + ""; - textFormat: Qt.RichText - color: "#cccccc"; style: Text.Raised; styleColor: "black"; wrap: true - anchors.left: whiteRect.right; anchors.right: blackRect.right; anchors.leftMargin: 6; anchors.rightMargin: 6 - onLinkActivated: handleLink(link) - } - } - } -} diff --git a/demos/declarative/twitter/content/HomeTitleBar.qml b/demos/declarative/twitter/content/HomeTitleBar.qml deleted file mode 100644 index a206c87..0000000 --- a/demos/declarative/twitter/content/HomeTitleBar.qml +++ /dev/null @@ -1,121 +0,0 @@ -import Qt 4.6 - -Item { - id: titleBar - - signal update() - onYChanged: state="" //When switching titlebars - - BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } - Item { - id: container - width: (parent.width * 2) - 55 ; height: parent.height - - Script { - function accept() { - if(rssModel.authName == '' || rssModel.authPass == '') - return false;//Can't login like that - - var postData = "status=" + editor.text; - var postman = new XMLHttpRequest(); - postman.open("POST", "http://twitter.com/statuses/update.xml", true, rssModel.authName, rssModel.authPass); - postman.onreadystatechange = function() { - if (postman.readyState == postman.DONE) { - titleBar.update(); - } - } - postman.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - postman.send(postData); - - editor.text = "" - titleBar.state = "" - } - } - - Rectangle { - x: 6; width: 50; height: 50; color: "white"; smooth: true - anchors.verticalCenter: parent.verticalCenter - - UserModel { user: rssModel.authName; id: userModel } - Component { id: imgDelegate; - Item { - Loading { width:48; height:48; visible: realImage.status != 1 } - Image { source: image; width:48; height:48; id: realImage } - } - } - ListView { model: userModel.model; x:1; y:1; delegate: imgDelegate } - } - - Text { - id: categoryText - anchors.left: parent.left; anchors.right: tagButton.left - anchors.leftMargin: 58; anchors.rightMargin: 10 - anchors.verticalCenter: parent.verticalCenter - elide: Text.ElideLeft - text: "Timeline for " + rssModel.authName - font.pixelSize: 12; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - } - - Button { - id: tagButton; x: titleBar.width - 90; width: 85; height: 32; text: "New Post..." - anchors.verticalCenter: parent.verticalCenter; - onClicked: if (titleBar.state == "Posting") accept(); else titleBar.state = "Posting" - } - - Text { - id: charsLeftText; anchors.horizontalCenter: tagButton.horizontalCenter; - anchors.top: tagButton.bottom; anchors.topMargin: 2 - text: {140 - editor.text.length;} visible: titleBar.state == "Posting" - font.pointSize: 10; font.bold: true; color: "white"; style: Text.Raised; styleColor: "black" - } - Item { - id: txtEdit; - anchors.left: tagButton.right; anchors.leftMargin: 5; y: 4 - anchors.right: parent.right; anchors.rightMargin: 40; height: parent.height - 9 - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - - Binding {//TODO: Can this be a function, which also resets the cursor? And flashes? - when: editor.text.length > 140 - target: editor - property: "text" - value: editor.text.slice(0,140) - } - TextEdit { - id: editor - anchors.left: parent.left; - anchors.leftMargin: 8; - anchors.bottom: parent.bottom - anchors.bottomMargin: 4; - cursorVisible: true; font.bold: true - width: parent.width - 12 - height: parent.height - 8 - font.pointSize: 10 - wrap: true - color: "#151515"; selectionColor: "green" - } - Keys.forwardTo: [(returnKey), (editor)] - Item { - id: returnKey - Keys.onReturnPressed: accept() - Keys.onEscapePressed: titleBar.state = "" - } - } - } - states: [ - State { - name: "Posting" - PropertyChanges { target: container; x: -tagButton.x + 5 } - PropertyChanges { target: titleBar; height: 80 } - PropertyChanges { target: tagButton; text: "OK" } - PropertyChanges { target: tagButton; width: 28 } - PropertyChanges { target: tagButton; height: 24 } - PropertyChanges { target: txtEdit; focus: true } - } - ] - transitions: [ - Transition { - from: "*"; to: "*" - NumberAnimation { properties: "x,y,width,height"; easing.type: "InOutQuad" } - } - ] -} diff --git a/demos/declarative/twitter/content/Loading.qml b/demos/declarative/twitter/content/Loading.qml deleted file mode 100644 index 76bf64b..0000000 --- a/demos/declarative/twitter/content/Loading.qml +++ /dev/null @@ -1,8 +0,0 @@ -import Qt 4.6 - -Image { - id: loading; source: "images/loading.png"; transformOrigin: "Center" - NumberAnimation on rotation { - from: 0; to: 360; running: loading.visible == true; repeat: true; duration: 900 - } -} diff --git a/demos/declarative/twitter/content/MultiTitleBar.qml b/demos/declarative/twitter/content/MultiTitleBar.qml deleted file mode 100644 index e0205b8..0000000 --- a/demos/declarative/twitter/content/MultiTitleBar.qml +++ /dev/null @@ -1,24 +0,0 @@ -import Qt 4.6 - -Item { - height: homeBar.height - HomeTitleBar { id: homeBar; width: parent.width; height: 60; - onUpdate: rssModel.reload() - } - TitleBar { id: titleBar; width: parent.width; height: 60; - y: -80 - untaggedString: "Latest tweets from everyone" - taggedString: "Latest tweets from " - } - states: [ - State { - name: "search"; when: screen.userView - PropertyChanges { target: titleBar; y: 0 } - PropertyChanges { target: homeBar; y: -80 } - } - ] - transitions: [ - Transition { NumberAnimation { properties: "x,y"; duration: 500; easing.type: "InOutQuad" } } - ] -} - diff --git a/demos/declarative/twitter/content/RssModel.qml b/demos/declarative/twitter/content/RssModel.qml deleted file mode 100644 index 9d88bb7..0000000 --- a/demos/declarative/twitter/content/RssModel.qml +++ /dev/null @@ -1,44 +0,0 @@ -import Qt 4.6 - -Item { id: wrapper - property var model: xmlModel - property string tags : "" - property string authName : "" - property string authPass : "" - property string mode : "everyone" - property int status: xmlModel.status - function reload() { xmlModel.reload(); } -XmlListModel { - id: xmlModel - - source:{ - if (wrapper.authName == ""){ - ""; //Avoid worthless calls to twitter servers - }else if(wrapper.mode == 'user'){ - "https://"+ ((wrapper.authName!="" && wrapper.authPass!="")? (wrapper.authName+":"+wrapper.authPass+"@") : "" )+"twitter.com/statuses/user_timeline.xml?screen_name="+wrapper.tags; - }else if(wrapper.mode == 'self'){ - "https://"+ ((wrapper.authName!="" && wrapper.authPass!="")? (wrapper.authName+":"+wrapper.authPass+"@") : "" )+"twitter.com/statuses/friends_timeline.xml"; - }else{//everyone/public - "http://twitter.com/statuses/public_timeline.xml"; - } - } - query: "/statuses/status" - - XmlRole { name: "statusText"; query: "text/string()" } - XmlRole { name: "timestamp"; query: "created_at/string()" } - XmlRole { name: "source"; query: "source/string()" } - XmlRole { name: "userName"; query: "user/name/string()" } - XmlRole { name: "userScreenName"; query: "user/screen_name/string()" } - XmlRole { name: "userImage"; query: "user/profile_image_url/string()" } - XmlRole { name: "userLocation"; query: "user/location/string()" } - XmlRole { name: "userDescription"; query: "user/description/string()" } - XmlRole { name: "userFollowers"; query: "user/followers_count/string()" } - XmlRole { name: "userStatuses"; query: "user/statuses_count/string()" } - //TODO: Could also get the user's color scheme, timezone and a few other things -} -Binding { - property: "mode" - target: wrapper - value: {if(wrapper.tags==''){"everyone";}else if(wrapper.tags=='my timeline'){"self";}else{"user";}} -} -} diff --git a/demos/declarative/twitter/content/TitleBar.qml b/demos/declarative/twitter/content/TitleBar.qml deleted file mode 100644 index 149aa82..0000000 --- a/demos/declarative/twitter/content/TitleBar.qml +++ /dev/null @@ -1,77 +0,0 @@ -import Qt 4.6 - -Item { - id: titleBar - property string untaggedString: "Uploads from everyone" - property string taggedString: "Recent uploads tagged " - - BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } - - Item { - id: container - width: (parent.width * 2) - 55 ; height: parent.height - - Script { - function accept() { - titleBar.state = "" - background.state = "" - rssModel.tags = editor.text - } - } - - Text { - id: categoryText - anchors { - left: parent.left; right: tagButton.left; leftMargin: 10; rightMargin: 10 - verticalCenter: parent.verticalCenter - } - elide: Text.ElideLeft - text: (rssModel.tags=="" ? untaggedString : taggedString + rssModel.tags) - font.bold: true; color: "White"; style: Text.Raised; styleColor: "Black" - font.pixelSize: 12 - } - - Button { - id: tagButton; x: titleBar.width - 50; width: 45; height: 32; text: "..." - onClicked: if (titleBar.state == "Tags") accept(); else titleBar.state = "Tags" - anchors.verticalCenter: parent.verticalCenter - } - - Item { - id: lineEdit - y: 4; height: parent.height - 9 - anchors { left: tagButton.right; leftMargin: 5; right: parent.right; rightMargin: 5 } - - BorderImage { source: "images/lineedit.sci"; anchors.fill: parent } - - TextInput { - id: editor - anchors { - left: parent.left; right: parent.right; leftMargin: 10; rightMargin: 10 - verticalCenter: parent.verticalCenter - } - cursorVisible: true; font.bold: true - color: "#151515"; selectionColor: "Green" - } - - Keys.forwardTo: [ (returnKey), (editor)] - - Item { - id: returnKey - Keys.onReturnPressed: accept() - Keys.onEscapePressed: titleBar.state = "" - } - } - } - - states: State { - name: "Tags" - PropertyChanges { target: container; x: -tagButton.x + 5 } - PropertyChanges { target: tagButton; text: "OK" } - PropertyChanges { target: lineEdit; focus: true } - } - - transitions: Transition { - NumberAnimation { properties: "x"; easing.type: "InOutQuad" } - } -} diff --git a/demos/declarative/twitter/content/ToolBar.qml b/demos/declarative/twitter/content/ToolBar.qml deleted file mode 100644 index f96c767..0000000 --- a/demos/declarative/twitter/content/ToolBar.qml +++ /dev/null @@ -1,24 +0,0 @@ -import Qt 4.6 - -Item { - id: toolbar - - property alias button1Label: button1.text - property alias button2Label: button2.text - signal button1Clicked - signal button2Clicked - - BorderImage { source: "images/titlebar.sci"; width: parent.width; height: parent.height + 14; y: -7 } - - Button { - id: button1 - anchors.left: parent.left; anchors.leftMargin: 5; y: 3; width: 140; height: 32 - onClicked: toolbar.button1Clicked() - } - - Button { - id: button2 - anchors.right: parent.right; anchors.rightMargin: 5; y: 3; width: 140; height: 32 - onClicked: toolbar.button2Clicked() - } -} diff --git a/demos/declarative/twitter/content/UserModel.qml b/demos/declarative/twitter/content/UserModel.qml deleted file mode 100644 index c146b84..0000000 --- a/demos/declarative/twitter/content/UserModel.qml +++ /dev/null @@ -1,26 +0,0 @@ -import Qt 4.6 - -//This "model" gets the user information about the searched user. Mainly for the icon. -//Copied from RssModel - -Item { id: wrapper - property var model: xmlModel - property string user : "" - property int status: xmlModel.status - function reload() { xmlModel.reload(); } -XmlListModel { - id: xmlModel - - source: {if(user!="") {"http://twitter.com/users/show.xml?screen_name="+user;}else{"";}} - query: "/user" - - XmlRole { name: "name"; query: "name/string()" } - XmlRole { name: "screenName"; query: "screen_name/string()" } - XmlRole { name: "image"; query: "profile_image_url/string()" } - XmlRole { name: "location"; query: "location/string()" } - XmlRole { name: "description"; query: "description/string()" } - XmlRole { name: "followers"; query: "followers_count/string()" } - //XmlRole { name: "protected"; query: "protected/bool()" } - //TODO: Could also get the user's color scheme, timezone and a few other things -} -} diff --git a/demos/declarative/twitter/content/images/gloss.png b/demos/declarative/twitter/content/images/gloss.png deleted file mode 100644 index 5d370cd..0000000 Binary files a/demos/declarative/twitter/content/images/gloss.png and /dev/null differ diff --git a/demos/declarative/twitter/content/images/lineedit.png b/demos/declarative/twitter/content/images/lineedit.png deleted file mode 100644 index 2cc38dc..0000000 Binary files a/demos/declarative/twitter/content/images/lineedit.png and /dev/null differ diff --git a/demos/declarative/twitter/content/images/lineedit.sci b/demos/declarative/twitter/content/images/lineedit.sci deleted file mode 100644 index 054bff7..0000000 --- a/demos/declarative/twitter/content/images/lineedit.sci +++ /dev/null @@ -1,5 +0,0 @@ -border.left: 10 -border.top: 10 -border.bottom: 10 -border.right: 10 -source: lineedit.png diff --git a/demos/declarative/twitter/content/images/loading.png b/demos/declarative/twitter/content/images/loading.png deleted file mode 100644 index 47a1589..0000000 Binary files a/demos/declarative/twitter/content/images/loading.png and /dev/null differ diff --git a/demos/declarative/twitter/content/images/stripes.png b/demos/declarative/twitter/content/images/stripes.png deleted file mode 100644 index 9f36727..0000000 Binary files a/demos/declarative/twitter/content/images/stripes.png and /dev/null differ diff --git a/demos/declarative/twitter/content/images/titlebar.png b/demos/declarative/twitter/content/images/titlebar.png deleted file mode 100644 index 51c9008..0000000 Binary files a/demos/declarative/twitter/content/images/titlebar.png and /dev/null differ diff --git a/demos/declarative/twitter/content/images/titlebar.sci b/demos/declarative/twitter/content/images/titlebar.sci deleted file mode 100644 index 0418d94..0000000 --- a/demos/declarative/twitter/content/images/titlebar.sci +++ /dev/null @@ -1,5 +0,0 @@ -border.left: 10 -border.top: 12 -border.bottom: 12 -border.right: 10 -source: titlebar.png diff --git a/demos/declarative/twitter/content/images/toolbutton.png b/demos/declarative/twitter/content/images/toolbutton.png deleted file mode 100644 index 1131001..0000000 Binary files a/demos/declarative/twitter/content/images/toolbutton.png and /dev/null differ diff --git a/demos/declarative/twitter/content/images/toolbutton.sci b/demos/declarative/twitter/content/images/toolbutton.sci deleted file mode 100644 index 9e4f965..0000000 --- a/demos/declarative/twitter/content/images/toolbutton.sci +++ /dev/null @@ -1,5 +0,0 @@ -border.left: 15 -border.top: 4 -border.bottom: 4 -border.right: 15 -source: toolbutton.png diff --git a/demos/declarative/twitter/twitter.qml b/demos/declarative/twitter/twitter.qml index 0ea1309..259f79a 100644 --- a/demos/declarative/twitter/twitter.qml +++ b/demos/declarative/twitter/twitter.qml @@ -1,5 +1,5 @@ import Qt 4.6 -import "content" as Twitter +import TwitterCore 1.0 as Twitter Item { id: screen; width: 320; height: 480 @@ -28,7 +28,7 @@ Item { id: background anchors.fill: parent; color: "#343434"; - Image { source: "content/images/stripes.png"; fillMode: Image.Tile; anchors.fill: parent; opacity: 0.3 } + Image { source: "TwitterCore/images/stripes.png"; fillMode: Image.Tile; anchors.fill: parent; opacity: 0.3 } Twitter.RssModel { id: rssModel } Twitter.Loading { anchors.centerIn: parent; visible: rssModel.status==XmlListModel.Loading && state!='unauthed'} -- cgit v0.12 From 4eaa7599be17d0838f98e2bafb0f0c8a0787530e Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Tue, 2 Mar 2010 15:55:17 +0100 Subject: Add minehunt README --- demos/declarative/minehunt/README | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 demos/declarative/minehunt/README diff --git a/demos/declarative/minehunt/README b/demos/declarative/minehunt/README new file mode 100644 index 0000000..7379dcf --- /dev/null +++ b/demos/declarative/minehunt/README @@ -0,0 +1,3 @@ +To run, simply load the minehunt.qml file with the qml runtime. + +Note that on X11, this demo has problems with the native graphicssystem. If you are using the X11 window system, please pass -graphicssystem raster to the qml binary. -- cgit v0.12 From b0b19d286e10d307db4b9e477d4463eabc2b319d Mon Sep 17 00:00:00 2001 From: Tobias Hunger Date: Tue, 2 Mar 2010 17:56:17 +0100 Subject: Fix build of imports * Fix export macro used in webkit * Fix dependencies on declarative/mutlimedia * Copy qmldir files into the build tree --- imports/Qt/multimedia/qmldir | 1 - imports/Qt/widgets/qmldir | 1 - imports/org/webkit/qmldir | 1 - src/declarative/declarative.pro | 28 +- src/declarative/imports/imports.pro | 7 - src/declarative/imports/multimedia/multimedia.cpp | 63 - src/declarative/imports/multimedia/multimedia.pro | 15 - src/declarative/imports/qimportbase.pri | 16 - src/declarative/imports/webkit/plugin.cpp | 66 - .../imports/webkit/qdeclarativewebview.cpp | 1340 -------------------- .../imports/webkit/qdeclarativewebview_p.h | 285 ----- .../imports/webkit/qdeclarativewebview_p_p.h | 151 --- src/declarative/imports/webkit/webkit.pro | 18 - .../imports/widgets/graphicslayouts.cpp | 260 ---- .../imports/widgets/graphicslayouts_p.h | 226 ---- .../imports/widgets/graphicswidgets.cpp | 40 - .../imports/widgets/graphicswidgets_p.h | 68 - src/declarative/imports/widgets/widgets.cpp | 138 -- src/declarative/imports/widgets/widgets.pro | 20 - src/declarative/libdeclarative.pro | 29 - src/imports/imports.pro | 7 + src/imports/multimedia/multimedia.cpp | 63 + src/imports/multimedia/multimedia.pro | 15 + src/imports/multimedia/qmldir | 1 + src/imports/qimportbase.pri | 33 + src/imports/webkit/plugin.cpp | 66 + src/imports/webkit/qdeclarativewebview.cpp | 1340 ++++++++++++++++++++ src/imports/webkit/qdeclarativewebview_p.h | 287 +++++ src/imports/webkit/qdeclarativewebview_p_p.h | 151 +++ src/imports/webkit/qmldir | 1 + src/imports/webkit/webkit.pro | 19 + src/imports/webkit/webkitqmlplugin_export.h | 53 + src/imports/widgets/graphicslayouts.cpp | 260 ++++ src/imports/widgets/graphicslayouts_p.h | 226 ++++ src/imports/widgets/graphicswidgets.cpp | 40 + src/imports/widgets/graphicswidgets_p.h | 68 + src/imports/widgets/qmldir | 1 + src/imports/widgets/widgets.cpp | 138 ++ src/imports/widgets/widgets.pro | 22 + src/src.pro | 6 + 40 files changed, 2823 insertions(+), 2747 deletions(-) delete mode 100644 imports/Qt/multimedia/qmldir delete mode 100644 imports/Qt/widgets/qmldir delete mode 100644 imports/org/webkit/qmldir delete mode 100644 src/declarative/imports/imports.pro delete mode 100644 src/declarative/imports/multimedia/multimedia.cpp delete mode 100644 src/declarative/imports/multimedia/multimedia.pro delete mode 100644 src/declarative/imports/qimportbase.pri delete mode 100644 src/declarative/imports/webkit/plugin.cpp delete mode 100644 src/declarative/imports/webkit/qdeclarativewebview.cpp delete mode 100644 src/declarative/imports/webkit/qdeclarativewebview_p.h delete mode 100644 src/declarative/imports/webkit/qdeclarativewebview_p_p.h delete mode 100644 src/declarative/imports/webkit/webkit.pro delete mode 100644 src/declarative/imports/widgets/graphicslayouts.cpp delete mode 100644 src/declarative/imports/widgets/graphicslayouts_p.h delete mode 100644 src/declarative/imports/widgets/graphicswidgets.cpp delete mode 100644 src/declarative/imports/widgets/graphicswidgets_p.h delete mode 100644 src/declarative/imports/widgets/widgets.cpp delete mode 100644 src/declarative/imports/widgets/widgets.pro delete mode 100644 src/declarative/libdeclarative.pro create mode 100644 src/imports/imports.pro create mode 100644 src/imports/multimedia/multimedia.cpp create mode 100644 src/imports/multimedia/multimedia.pro create mode 100644 src/imports/multimedia/qmldir create mode 100644 src/imports/qimportbase.pri create mode 100644 src/imports/webkit/plugin.cpp create mode 100644 src/imports/webkit/qdeclarativewebview.cpp create mode 100644 src/imports/webkit/qdeclarativewebview_p.h create mode 100644 src/imports/webkit/qdeclarativewebview_p_p.h create mode 100644 src/imports/webkit/qmldir create mode 100644 src/imports/webkit/webkit.pro create mode 100644 src/imports/webkit/webkitqmlplugin_export.h create mode 100644 src/imports/widgets/graphicslayouts.cpp create mode 100644 src/imports/widgets/graphicslayouts_p.h create mode 100644 src/imports/widgets/graphicswidgets.cpp create mode 100644 src/imports/widgets/graphicswidgets_p.h create mode 100644 src/imports/widgets/qmldir create mode 100644 src/imports/widgets/widgets.cpp create mode 100644 src/imports/widgets/widgets.pro diff --git a/imports/Qt/multimedia/qmldir b/imports/Qt/multimedia/qmldir deleted file mode 100644 index 0e6f656..0000000 --- a/imports/Qt/multimedia/qmldir +++ /dev/null @@ -1 +0,0 @@ -plugin multimedia diff --git a/imports/Qt/widgets/qmldir b/imports/Qt/widgets/qmldir deleted file mode 100644 index 6f19878..0000000 --- a/imports/Qt/widgets/qmldir +++ /dev/null @@ -1 +0,0 @@ -plugin widgets diff --git a/imports/org/webkit/qmldir b/imports/org/webkit/qmldir deleted file mode 100644 index 258aa2c..0000000 --- a/imports/org/webkit/qmldir +++ /dev/null @@ -1 +0,0 @@ -plugin webkitqmlplugin diff --git a/src/declarative/declarative.pro b/src/declarative/declarative.pro index a7ec18e..4287e25 100644 --- a/src/declarative/declarative.pro +++ b/src/declarative/declarative.pro @@ -1,5 +1,29 @@ -TEMPLATE = subdirs +TARGET = QtDeclarative +QPRO_PWD = $$PWD +QT = core gui xml script network +contains(QT_CONFIG, svg): QT += svg +contains(QT_CONFIG, opengl): QT += opengl +DEFINES += QT_BUILD_DECLARATIVE_LIB QT_NO_URL_CAST_FROM_STRING +win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x66000000 +solaris-cc*:QMAKE_CXXFLAGS_RELEASE -= -O2 -SUBDIRS = libdeclarative.pro imports +unix:QMAKE_PKGCONFIG_REQUIRES = QtCore QtGui QtXml +exists("qdeclarative_enable_gcov") { + QMAKE_CXXFLAGS = -fprofile-arcs -ftest-coverage -fno-elide-constructors + LIBS += -lgcov +} +include(../qbase.pri) + +#INCLUDEPATH -= $$QMAKE_INCDIR_QT/$$TARGET +#DESTDIR=. + +#modules +include(3rdparty/3rdparty.pri) +include(util/util.pri) +include(graphicsitems/graphicsitems.pri) +include(qml/qml.pri) +include(debugger/debugger.pri) + +symbian:TARGET.UID3=0x2001E623 diff --git a/src/declarative/imports/imports.pro b/src/declarative/imports/imports.pro deleted file mode 100644 index f874644..0000000 --- a/src/declarative/imports/imports.pro +++ /dev/null @@ -1,7 +0,0 @@ -TEMPLATE = subdirs - -SUBDIRS += widgets - -contains(QT_CONFIG, multimedia): SUBDIRS += multimedia -contains(QT_CONFIG, webkit): SUBDIRS += webkit - diff --git a/src/declarative/imports/multimedia/multimedia.cpp b/src/declarative/imports/multimedia/multimedia.cpp deleted file mode 100644 index 8becbf3..0000000 --- a/src/declarative/imports/multimedia/multimedia.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the plugins 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 -#include -#include - -QT_BEGIN_NAMESPACE - -class QMultimediaQmlModule : public QDeclarativeExtensionPlugin -{ - Q_OBJECT -public: - virtual void registerTypes(const char *uri) - { - QtMultimedia::qRegisterDeclarativeElements(uri); - } -}; - -QT_END_NAMESPACE - -#include "multimedia.moc" - -Q_EXPORT_PLUGIN2(qmultimediaqmlmodule, QT_PREPEND_NAMESPACE(QMultimediaQmlModule)); - diff --git a/src/declarative/imports/multimedia/multimedia.pro b/src/declarative/imports/multimedia/multimedia.pro deleted file mode 100644 index d601d2e..0000000 --- a/src/declarative/imports/multimedia/multimedia.pro +++ /dev/null @@ -1,15 +0,0 @@ -TARGET = multimedia -include(../qimportbase.pri) - -QT += multimedia declarative - -SOURCES += multimedia.cpp - -QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/multimedia -target.path = $$[QT_INSTALL_IMPORTS]/Qt/multimedia - -qmldir.files += $$QT_BUILD_TREE/imports/Qt/multimedia/qmldir -qmldir.path += $$[QT_INSTALL_IMPORTS]/Qt/multimedia - -INSTALLS += target qmldir - diff --git a/src/declarative/imports/qimportbase.pri b/src/declarative/imports/qimportbase.pri deleted file mode 100644 index 5b0a4e2..0000000 --- a/src/declarative/imports/qimportbase.pri +++ /dev/null @@ -1,16 +0,0 @@ -TEMPLATE = lib -CONFIG += qt plugin - -win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release -TARGET = $$qtLibraryTarget($$TARGET) -contains(QT_CONFIG, reduce_exports):CONFIG += hide_symbols - -include(../../qt_targets.pri) - -wince*:LIBS += $$QMAKE_LIBS_GUI - -symbian: { - TARGET.EPOCALLOWDLLDATA=1 - TARGET.CAPABILITY = All -Tcb - load(armcc_warnings) -} diff --git a/src/declarative/imports/webkit/plugin.cpp b/src/declarative/imports/webkit/plugin.cpp deleted file mode 100644 index 2f6205d..0000000 --- a/src/declarative/imports/webkit/plugin.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** 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 plugins 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 -#include - -#include "qdeclarativewebview_p.h" -#include "qdeclarativewebview_p_p.h" - -QT_BEGIN_NAMESPACE - -class WebKitQmlPlugin : public QDeclarativeExtensionPlugin -{ - Q_OBJECT -public: - virtual void registerTypes(const char *uri) - { - Q_ASSERT(QLatin1String(uri) == QLatin1String("org.webkit")); - qmlRegisterType(uri,1,0,"WebView"); - } -}; - -QT_END_NAMESPACE - -#include "plugin.moc" - -Q_EXPORT_PLUGIN2(webkitqmlplugin, QT_PREPEND_NAMESPACE(WebKitQmlPlugin)); - diff --git a/src/declarative/imports/webkit/qdeclarativewebview.cpp b/src/declarative/imports/webkit/qdeclarativewebview.cpp deleted file mode 100644 index 733ac86..0000000 --- a/src/declarative/imports/webkit/qdeclarativewebview.cpp +++ /dev/null @@ -1,1340 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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 "qdeclarativewebview_p.h" -#include "qdeclarativewebview_p_p.h" - -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system - -class QDeclarativeWebViewPrivate : public QDeclarativePaintedItemPrivate -{ - Q_DECLARE_PUBLIC(QDeclarativeWebView) - -public: - QDeclarativeWebViewPrivate() - : QDeclarativePaintedItemPrivate(), page(0), preferredwidth(0), preferredheight(0), - progress(1.0), status(QDeclarativeWebView::Null), pending(PendingNone), - newWindowComponent(0), newWindowParent(0), - pressTime(400), - rendering(true) - { - } - - QUrl url; // page url might be different if it has not loaded yet - QWebPage *page; - - int preferredwidth, preferredheight; - qreal progress; - QDeclarativeWebView::Status status; - QString statusText; - enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending; - QUrl pending_url; - QString pending_string; - QByteArray pending_data; - mutable QDeclarativeWebSettings settings; - QDeclarativeComponent *newWindowComponent; - QDeclarativeItem *newWindowParent; - - QBasicTimer pressTimer; - QPoint pressPoint; - int pressTime; // milliseconds before it's a "hold" - - - static void windowObjects_append(QDeclarativeListProperty *prop, QObject *o) { - static_cast(prop->data)->windowObjects.append(o); - static_cast(prop->data)->updateWindowObjects(); - } - - void updateWindowObjects(); - QObjectList windowObjects; - - bool rendering; -}; - -/*! - \qmlclass WebView QDeclarativeWebView - \since 4.7 - \brief The WebView item allows you to add web content to a canvas. - \inherits Item - - A WebView renders web content based on a URL. - - If the width and height of the item is not set, they will - dynamically adjust to a size appropriate for the content. - This width may be large for typical online web pages. - - If the preferredWidth is set, the width will be this amount or larger, - usually laying out the web content to fit the preferredWidth. - - \qml - import org.webkit 1.0 - - WebView { - url: "http://www.nokia.com" - width: 490 - height: 400 - scale: 0.5 - smooth: false - smoothCache: true - } - \endqml - - \image webview.png - - The item includes no scrolling, scaling, - toolbars, etc., those must be implemented around WebView. See the WebBrowser example - for a demonstration of this. -*/ - -/*! - \internal - \class QDeclarativeWebView - \brief The QDeclarativeWebView class allows you to add web content to a QDeclarativeView. - - A WebView renders web content base on a URL. - - \image webview.png - - The item includes no scrolling, scaling, - toolbars, etc., those must be implemented around WebView. See the WebBrowser example - for a demonstration of this. - - A QDeclarativeWebView object can be instantiated in Qml using the tag \l WebView. -*/ - -QDeclarativeWebView::QDeclarativeWebView(QDeclarativeItem *parent) - : QDeclarativePaintedItem(*(new QDeclarativeWebViewPrivate), parent) -{ - init(); -} - -QDeclarativeWebView::~QDeclarativeWebView() -{ - Q_D(QDeclarativeWebView); - delete d->page; -} - -void QDeclarativeWebView::init() -{ - Q_D(QDeclarativeWebView); - - QWebSettings::enablePersistentStorage(); - - setAcceptHoverEvents(true); - setAcceptedMouseButtons(Qt::LeftButton); - setFlag(QGraphicsItem::ItemHasNoContents, false); - - d->page = 0; -} - -void QDeclarativeWebView::componentComplete() -{ - QDeclarativePaintedItem::componentComplete(); - Q_D(QDeclarativeWebView); - switch (d->pending) { - case QDeclarativeWebViewPrivate::PendingUrl: - setUrl(d->pending_url); - break; - case QDeclarativeWebViewPrivate::PendingHtml: - setHtml(d->pending_string, d->pending_url); - break; - case QDeclarativeWebViewPrivate::PendingContent: - setContent(d->pending_data, d->pending_string, d->pending_url); - break; - default: - break; - } - d->pending = QDeclarativeWebViewPrivate::PendingNone; - d->updateWindowObjects(); -} - -QDeclarativeWebView::Status QDeclarativeWebView::status() const -{ - Q_D(const QDeclarativeWebView); - return d->status; -} - - -/*! - \qmlproperty real WebView::progress - This property holds the progress of loading the current URL, from 0 to 1. - - If you just want to know when progress gets to 1, use - WebView::onLoadFinished() or WebView::onLoadFailed() instead. -*/ -qreal QDeclarativeWebView::progress() const -{ - Q_D(const QDeclarativeWebView); - return d->progress; -} - -void QDeclarativeWebView::doLoadStarted() -{ - Q_D(QDeclarativeWebView); - - if (!d->url.isEmpty()) { - d->status = Loading; - emit statusChanged(d->status); - } - emit loadStarted(); -} - -void QDeclarativeWebView::doLoadProgress(int p) -{ - Q_D(QDeclarativeWebView); - if (d->progress == p/100.0) - return; - d->progress = p/100.0; - emit progressChanged(); -} - -void QDeclarativeWebView::pageUrlChanged() -{ - Q_D(QDeclarativeWebView); - - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - expandToWebPage(); - - if ((d->url.isEmpty() && page()->mainFrame()->url() != QUrl(QLatin1String("about:blank"))) - || (d->url != page()->mainFrame()->url() && !page()->mainFrame()->url().isEmpty())) - { - d->url = page()->mainFrame()->url(); - if (d->url == QUrl(QLatin1String("about:blank"))) - d->url = QUrl(); - emit urlChanged(); - } -} - -void QDeclarativeWebView::doLoadFinished(bool ok) -{ - Q_D(QDeclarativeWebView); - - if (title().isEmpty()) - pageUrlChanged(); // XXX bug 232556 - pages with no title never get urlChanged() - - if (ok) { - d->status = d->url.isEmpty() ? Null : Ready; - emit loadFinished(); - } else { - d->status = Error; - emit loadFailed(); - } - emit statusChanged(d->status); -} - -/*! - \qmlproperty url WebView::url - This property holds the URL to the page displayed in this item. It can be set, - but also can change spontaneously (eg. because of network redirection). - - If the url is empty, the page is blank. - - The url is always absolute (QML will resolve relative URL strings in the context - of the containing QML document). -*/ -QUrl QDeclarativeWebView::url() const -{ - Q_D(const QDeclarativeWebView); - return d->url; -} - -void QDeclarativeWebView::setUrl(const QUrl &url) -{ - Q_D(QDeclarativeWebView); - if (url == d->url) - return; - - if (isComponentComplete()) { - d->url = url; - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - QUrl seturl = url; - if (seturl.isEmpty()) - seturl = QUrl(QLatin1String("about:blank")); - - Q_ASSERT(!seturl.isRelative()); - - page()->mainFrame()->load(seturl); - - emit urlChanged(); - } else { - d->pending = d->PendingUrl; - d->pending_url = url; - } -} - -/*! - \qmlproperty int WebView::preferredWidth - This property holds the ideal width for displaying the current URL. -*/ -int QDeclarativeWebView::preferredWidth() const -{ - Q_D(const QDeclarativeWebView); - return d->preferredwidth; -} - -void QDeclarativeWebView::setPreferredWidth(int iw) -{ - Q_D(QDeclarativeWebView); - if (d->preferredwidth == iw) return; - d->preferredwidth = iw; - //expandToWebPage(); - emit preferredWidthChanged(); -} - -/*! - \qmlproperty int WebView::preferredHeight - This property holds the ideal height for displaying the current URL. - This only affects the area zoomed by heuristicZoom(). -*/ -int QDeclarativeWebView::preferredHeight() const -{ - Q_D(const QDeclarativeWebView); - return d->preferredheight; -} -void QDeclarativeWebView::setPreferredHeight(int ih) -{ - Q_D(QDeclarativeWebView); - if (d->preferredheight == ih) return; - d->preferredheight = ih; - emit preferredHeightChanged(); -} - -/*! - \qmlmethod bool WebView::evaluateJavaScript(string) - - Evaluates the \a scriptSource JavaScript inside the context of the - main web frame, and returns the result of the last executed statement. - - Note that this JavaScript does \e not have any access to QML objects - except as made available as windowObjects. -*/ -QVariant QDeclarativeWebView::evaluateJavaScript(const QString &scriptSource) -{ - return this->page()->mainFrame()->evaluateJavaScript(scriptSource); -} - -void QDeclarativeWebView::focusChanged(bool hasFocus) -{ - QFocusEvent e(hasFocus ? QEvent::FocusIn : QEvent::FocusOut); - page()->event(&e); - QDeclarativeItem::focusChanged(hasFocus); -} - -void QDeclarativeWebView::initialLayout() -{ - // nothing useful to do at this point -} - -void QDeclarativeWebView::noteContentsSizeChanged(const QSize&) -{ - expandToWebPage(); -} - -void QDeclarativeWebView::expandToWebPage() -{ - Q_D(QDeclarativeWebView); - QSize cs = page()->mainFrame()->contentsSize(); - if (cs.width() < d->preferredwidth) - cs.setWidth(d->preferredwidth); - if (cs.height() < d->preferredheight) - cs.setHeight(d->preferredheight); - if (widthValid()) - cs.setWidth(width()); - if (heightValid()) - cs.setHeight(height()); - if (cs != page()->viewportSize()) { - page()->setViewportSize(cs); - } - if (cs != contentsSize()) - setContentsSize(cs); -} - -void QDeclarativeWebView::geometryChanged(const QRectF &newGeometry, - const QRectF &oldGeometry) -{ - if (newGeometry.size() != oldGeometry.size()) - expandToWebPage(); - QDeclarativePaintedItem::geometryChanged(newGeometry, oldGeometry); -} - -void QDeclarativeWebView::paintPage(const QRect& r) -{ - dirtyCache(r); - update(); -} - -/*! - \qmlproperty list WebView::javaScriptWindowObjects - - This property is a list of object that are available from within - the webview's JavaScript context. - - The \a object will be inserted as a child of the frame's window - object, under the name given by the attached property \c WebView.windowObjectName. - - \qml - WebView { - javaScriptWindowObjects: Object { - WebView.windowObjectName: "coordinates" - } - } - \endqml - - Properties of the object will be exposed as JavaScript properties and slots as - JavaScript methods. - - If Javascript is not enabled for this page, then this property does nothing. -*/ -QDeclarativeListProperty QDeclarativeWebView::javaScriptWindowObjects() -{ - Q_D(QDeclarativeWebView); - return QDeclarativeListProperty(this, d, &QDeclarativeWebViewPrivate::windowObjects_append); -} - -QDeclarativeWebViewAttached *QDeclarativeWebView::qmlAttachedProperties(QObject *o) -{ - return new QDeclarativeWebViewAttached(o); -} - -void QDeclarativeWebViewPrivate::updateWindowObjects() -{ - Q_Q(QDeclarativeWebView); - if (!q->isComponentComplete() || !page) - return; - - for (int ii = 0; ii < windowObjects.count(); ++ii) { - QObject *object = windowObjects.at(ii); - QDeclarativeWebViewAttached *attached = static_cast(qmlAttachedPropertiesObject(object)); - if (attached && !attached->windowObjectName().isEmpty()) { - page->mainFrame()->addToJavaScriptWindowObject(attached->windowObjectName(), object); - } - } -} - -bool QDeclarativeWebView::renderingEnabled() const -{ - Q_D(const QDeclarativeWebView); - return d->rendering; -} - -void QDeclarativeWebView::setRenderingEnabled(bool enabled) -{ - Q_D(QDeclarativeWebView); - if (d->rendering == enabled) - return; - d->rendering = enabled; - emit renderingEnabledChanged(); - - setCacheFrozen(!enabled); - if (enabled) - clearCache(); -} - - -void QDeclarativeWebView::drawContents(QPainter *p, const QRect &r) -{ - Q_D(QDeclarativeWebView); - if (d->rendering) - page()->mainFrame()->render(p,r); -} - -QMouseEvent *QDeclarativeWebView::sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *e) -{ - QEvent::Type t; - switch(e->type()) { - default: - case QEvent::GraphicsSceneMousePress: - t = QEvent::MouseButtonPress; - break; - case QEvent::GraphicsSceneMouseRelease: - t = QEvent::MouseButtonRelease; - break; - case QEvent::GraphicsSceneMouseMove: - t = QEvent::MouseMove; - break; - case QGraphicsSceneEvent::GraphicsSceneMouseDoubleClick: - t = QEvent::MouseButtonDblClick; - break; - } - - QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), e->button(), e->buttons(), 0); - return me; -} - -QMouseEvent *QDeclarativeWebView::sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *e) -{ - QEvent::Type t = QEvent::MouseMove; - - QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), Qt::NoButton, Qt::NoButton, 0); - - return me; -} - - -/*! - \qmlsignal WebView::onDoubleClick(clickx,clicky) - - The WebView does not pass double-click events to the web engine, but rather - emits this signals. -*/ - -void QDeclarativeWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) -{ - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - emit doubleClick(me->x(),me->y()); - delete me; -} - -/*! - \qmlmethod bool WebView::heuristicZoom(clickX,clickY,maxzoom) - - Finds a zoom that: - \list - \i shows a whole item - \i includes (\a clickX, \a clickY) - \i fits into the preferredWidth and preferredHeight - \i zooms by no more than \a maxzoom - \i is more than 10% above the current zoom - \endlist - - If such a zoom exists, emits zoomTo(zoom,centerX,centerY) and returns true; otherwise, - no signal is emitted and returns false. -*/ -bool QDeclarativeWebView::heuristicZoom(int clickX, int clickY, qreal maxzoom) -{ - Q_D(QDeclarativeWebView); - if (contentsScale() >= maxzoom/zoomFactor()) - return false; - qreal ozf = contentsScale(); - QRect showarea = elementAreaAt(clickX, clickY, d->preferredwidth/maxzoom, d->preferredheight/maxzoom); - qreal z = qMin(qreal(d->preferredwidth)/showarea.width(),qreal(d->preferredheight)/showarea.height()); - if (z > maxzoom/zoomFactor()) - z = maxzoom/zoomFactor(); - if (z/ozf > 1.2) { - QRectF r(showarea.left()*z, showarea.top()*z, showarea.width()*z, showarea.height()*z); - emit zoomTo(z,r.x()+r.width()/2, r.y()+r.height()/2); - return true; - } else { - return false; - } -} - -/*! - \qmlproperty int WebView::pressGrabTime - - The number of milliseconds the user must press before the WebView - starts passing move events through to the web engine (rather than - letting other QML elements such as a Flickable take them). - - Defaults to 400ms. Set to 0 to always grab and pass move events to - the web engine. -*/ -int QDeclarativeWebView::pressGrabTime() const -{ - Q_D(const QDeclarativeWebView); - return d->pressTime; -} - -void QDeclarativeWebView::setPressGrabTime(int ms) -{ - Q_D(QDeclarativeWebView); - if (d->pressTime == ms) - return; - d->pressTime = ms; - emit pressGrabTimeChanged(); -} - -void QDeclarativeWebView::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - setFocus (true); - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - - d->pressPoint = me->pos(); - if (d->pressTime) { - d->pressTimer.start(d->pressTime,this); - setKeepMouseGrab(false); - } else { - grabMouse(); - setKeepMouseGrab(true); - } - - page()->event(me); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit - Might be a bug in WebKit, though - */ -#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) { - QDeclarativePaintedItem::mousePressEvent(event); - } -} - -void QDeclarativeWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - page()->event(me); - d->pressTimer.stop(); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send all the events to WebKit - */ -#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) { - QDeclarativePaintedItem::mouseReleaseEvent(event); - } - setKeepMouseGrab(false); - ungrabMouse(); -} - -void QDeclarativeWebView::timerEvent(QTimerEvent *event) -{ - Q_D(QDeclarativeWebView); - if (event->timerId() == d->pressTimer.timerId()) { - d->pressTimer.stop(); - grabMouse(); - setKeepMouseGrab(true); - } -} - -void QDeclarativeWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - Q_D(QDeclarativeWebView); - - QMouseEvent *me = sceneMouseEventToMouseEvent(event); - if (d->pressTimer.isActive()) { - if ((me->pos() - d->pressPoint).manhattanLength() > QApplication::startDragDistance()) { - d->pressTimer.stop(); - } - } - if (keepMouseGrab()) { - page()->event(me); - event->setAccepted( -/* - It is not correct to send the press event upwards, if it is not accepted by WebKit - e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit - Might be a bug in WebKit, though - */ -#if 1 // QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - } - delete me; - if (!event->isAccepted()) - QDeclarativePaintedItem::mouseMoveEvent(event); - -} -void QDeclarativeWebView::hoverMoveEvent (QGraphicsSceneHoverEvent * event) -{ - QMouseEvent *me = sceneHoverMoveEventToMouseEvent(event); - page()->event(me); - event->setAccepted( -#if QT_VERSION <= 0x040500 // XXX see bug 230835 - true -#else - me->isAccepted() -#endif - ); - delete me; - if (!event->isAccepted()) - QDeclarativePaintedItem::hoverMoveEvent(event); -} - -void QDeclarativeWebView::keyPressEvent(QKeyEvent* event) -{ - page()->event(event); - if (!event->isAccepted()) - QDeclarativePaintedItem::keyPressEvent(event); -} - -void QDeclarativeWebView::keyReleaseEvent(QKeyEvent* event) -{ - page()->event(event); - if (!event->isAccepted()) - QDeclarativePaintedItem::keyReleaseEvent(event); -} - -bool QDeclarativeWebView::sceneEvent(QEvent *event) -{ - if (event->type() == QEvent::KeyPress) { - QKeyEvent *k = static_cast(event); - if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) { - if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? - page()->event(event); - if (event->isAccepted()) - return true; - } - } - } - return QDeclarativePaintedItem::sceneEvent(event); -} - - -/*! - \qmlproperty action WebView::back - This property holds the action for causing the previous URL in the history to be displayed. -*/ -QAction *QDeclarativeWebView::backAction() const -{ - return page()->action(QWebPage::Back); -} - -/*! - \qmlproperty action WebView::forward - This property holds the action for causing the next URL in the history to be displayed. -*/ -QAction *QDeclarativeWebView::forwardAction() const -{ - return page()->action(QWebPage::Forward); -} - -/*! - \qmlproperty action WebView::reload - This property holds the action for reloading with the current URL -*/ -QAction *QDeclarativeWebView::reloadAction() const -{ - return page()->action(QWebPage::Reload); -} - -/*! - \qmlproperty action WebView::stop - This property holds the action for stopping loading with the current URL -*/ -QAction *QDeclarativeWebView::stopAction() const -{ - return page()->action(QWebPage::Stop); -} - -/*! - \qmlproperty real WebView::title - This property holds the title of the web page currently viewed - - By default, this property contains an empty string. -*/ -QString QDeclarativeWebView::title() const -{ - return page()->mainFrame()->title(); -} - - - -/*! - \qmlproperty pixmap WebView::icon - This property holds the icon associated with the web page currently viewed -*/ -QPixmap QDeclarativeWebView::icon() const -{ - return page()->mainFrame()->icon().pixmap(QSize(256,256)); -} - - -/*! - \qmlproperty real WebView::zoomFactor - This property holds the multiplier used to scale the contents of a Web page. -*/ -void QDeclarativeWebView::setZoomFactor(qreal factor) -{ - Q_D(QDeclarativeWebView); - if (factor == page()->mainFrame()->zoomFactor()) - return; - - page()->mainFrame()->setZoomFactor(factor); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth*factor : width()*factor, - d->preferredheight>0 ? d->preferredheight*factor : height()*factor)); - expandToWebPage(); - - emit zoomFactorChanged(); -} - -qreal QDeclarativeWebView::zoomFactor() const -{ - return page()->mainFrame()->zoomFactor(); -} - -/*! - \qmlproperty string WebView::statusText - - This property is the current status suggested by the current web page. In a web browser, - such status is often shown in some kind of status bar. -*/ -void QDeclarativeWebView::setStatusText(const QString& s) -{ - Q_D(QDeclarativeWebView); - d->statusText = s; - emit statusTextChanged(); -} - -void QDeclarativeWebView::windowObjectCleared() -{ - Q_D(QDeclarativeWebView); - d->updateWindowObjects(); -} - -QString QDeclarativeWebView::statusText() const -{ - Q_D(const QDeclarativeWebView); - return d->statusText; -} - -QWebPage *QDeclarativeWebView::page() const -{ - Q_D(const QDeclarativeWebView); - - if (!d->page) { - QDeclarativeWebView *self = const_cast(this); - QWebPage *wp = new QDeclarativeWebPage(self); - - // QML items don't default to having a background, - // even though most we pages will set one anyway. - QPalette pal = QApplication::palette(); - pal.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0)); - wp->setPalette(pal); - - wp->setNetworkAccessManager(qmlEngine(this)->networkAccessManager()); - - self->setPage(wp); - - return wp; - } - - return d->page; -} - - -// The QObject interface to settings(). -/*! - \qmlproperty string WebView::settings.standardFontFamily - \qmlproperty string WebView::settings.fixedFontFamily - \qmlproperty string WebView::settings.serifFontFamily - \qmlproperty string WebView::settings.sansSerifFontFamily - \qmlproperty string WebView::settings.cursiveFontFamily - \qmlproperty string WebView::settings.fantasyFontFamily - - \qmlproperty int WebView::settings.minimumFontSize - \qmlproperty int WebView::settings.minimumLogicalFontSize - \qmlproperty int WebView::settings.defaultFontSize - \qmlproperty int WebView::settings.defaultFixedFontSize - - \qmlproperty bool WebView::settings.autoLoadImages - \qmlproperty bool WebView::settings.javascriptEnabled - \qmlproperty bool WebView::settings.javaEnabled - \qmlproperty bool WebView::settings.pluginsEnabled - \qmlproperty bool WebView::settings.privateBrowsingEnabled - \qmlproperty bool WebView::settings.javascriptCanOpenWindows - \qmlproperty bool WebView::settings.javascriptCanAccessClipboard - \qmlproperty bool WebView::settings.developerExtrasEnabled - \qmlproperty bool WebView::settings.linksIncludedInFocusChain - \qmlproperty bool WebView::settings.zoomTextOnly - \qmlproperty bool WebView::settings.printElementBackgrounds - \qmlproperty bool WebView::settings.offlineStorageDatabaseEnabled - \qmlproperty bool WebView::settings.offlineWebApplicationCacheEnabled - \qmlproperty bool WebView::settings.localStorageDatabaseEnabled - \qmlproperty bool WebView::settings.localContentCanAccessRemoteUrls - - These properties give access to the settings controlling the web view. - - See QWebSettings for details of these properties. - - \qml - WebView { - settings.pluginsEnabled: true - settings.standardFontFamily: "Arial" - ... - } - \endqml -*/ -QObject *QDeclarativeWebView::settingsObject() const -{ - Q_D(const QDeclarativeWebView); - d->settings.s = page()->settings(); - return &d->settings; -} - -void QDeclarativeWebView::setPage(QWebPage *page) -{ - Q_D(QDeclarativeWebView); - if (d->page == page) - return; - if (d->page) { - if (d->page->parent() == this) { - delete d->page; - } else { - d->page->disconnect(this); - } - } - d->page = page; - d->page->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - d->page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff); - d->page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff); - connect(d->page,SIGNAL(repaintRequested(QRect)),this,SLOT(paintPage(QRect))); - connect(d->page->mainFrame(),SIGNAL(urlChanged(QUrl)),this,SLOT(pageUrlChanged())); - connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString))); - connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(iconChanged())); - connect(d->page->mainFrame(), SIGNAL(iconChanged()), this, SIGNAL(iconChanged())); - connect(d->page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), this, SLOT(noteContentsSizeChanged(QSize))); - connect(d->page->mainFrame(), SIGNAL(initialLayoutCompleted()), this, SLOT(initialLayout())); - - connect(d->page,SIGNAL(loadStarted()),this,SLOT(doLoadStarted())); - connect(d->page,SIGNAL(loadProgress(int)),this,SLOT(doLoadProgress(int))); - connect(d->page,SIGNAL(loadFinished(bool)),this,SLOT(doLoadFinished(bool))); - connect(d->page,SIGNAL(statusBarMessage(QString)),this,SLOT(setStatusText(QString))); - - connect(d->page->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(windowObjectCleared())); -} - -/*! - \qmlsignal WebView::onLoadStarted() - - This handler is called when the web engine begins loading - a page. Later, WebView::onLoadFinished() or WebView::onLoadFailed() - will be emitted. -*/ - -/*! - \qmlsignal WebView::onLoadFinished() - - This handler is called when the web engine \e successfully - finishes loading a page, including any component content - (WebView::onLoadFailed() will be emitted otherwise). - - \sa progress -*/ - -/*! - \qmlsignal WebView::onLoadFailed() - - This handler is called when the web engine fails loading - a page or any component content - (WebView::onLoadFinished() will be emitted on success). -*/ - -void QDeclarativeWebView::load(const QNetworkRequest &request, - QNetworkAccessManager::Operation operation, - const QByteArray &body) -{ - page()->mainFrame()->load(request, operation, body); -} - -QString QDeclarativeWebView::html() const -{ - return page()->mainFrame()->toHtml(); -} - -/*! - \qmlproperty string WebView::html - This property holds HTML text set directly - - The html property can be set as a string. - - \qml - WebView { - html: "

This is HTML." - } - \endqml -*/ -void QDeclarativeWebView::setHtml(const QString &html, const QUrl &baseUrl) -{ - Q_D(QDeclarativeWebView); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - if (isComponentComplete()) - page()->mainFrame()->setHtml(html, baseUrl); - else { - d->pending = d->PendingHtml; - d->pending_url = baseUrl; - d->pending_string = html; - } - emit htmlChanged(); -} - -void QDeclarativeWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) -{ - Q_D(QDeclarativeWebView); - page()->setViewportSize(QSize( - d->preferredwidth>0 ? d->preferredwidth : width(), - d->preferredheight>0 ? d->preferredheight : height())); - - if (isComponentComplete()) - page()->mainFrame()->setContent(data,mimeType,qmlContext(this)->resolvedUrl(baseUrl)); - else { - d->pending = d->PendingContent; - d->pending_url = baseUrl; - d->pending_string = mimeType; - d->pending_data = data; - } -} - -QWebHistory *QDeclarativeWebView::history() const -{ - return page()->history(); -} - -QWebSettings *QDeclarativeWebView::settings() const -{ - return page()->settings(); -} - -QDeclarativeWebView *QDeclarativeWebView::createWindow(QWebPage::WebWindowType type) -{ - Q_D(QDeclarativeWebView); - switch (type) { - case QWebPage::WebBrowserWindow: { - if (!d->newWindowComponent && d->newWindowParent) - qWarning("WebView::newWindowComponent not set - WebView::newWindowParent ignored"); - else if (d->newWindowComponent && !d->newWindowParent) - qWarning("WebView::newWindowParent not set - WebView::newWindowComponent ignored"); - else if (d->newWindowComponent && d->newWindowParent) { - QDeclarativeWebView *webview = 0; - QDeclarativeContext *windowContext = new QDeclarativeContext(qmlContext(this)); - - QObject *nobj = d->newWindowComponent->create(windowContext); - if (nobj) { - windowContext->setParent(nobj); - QDeclarativeItem *item = qobject_cast(nobj); - if (!item) { - delete nobj; - } else { - webview = item->findChild(); - if (!webview) { - delete item; - } else { - nobj->setParent(d->newWindowParent); - static_cast(item)->setParentItem(d->newWindowParent); - } - } - } else { - delete windowContext; - } - - return webview; - } - } - break; - case QWebPage::WebModalDialog: { - // Not supported - } - } - return 0; -} - -/*! - \qmlproperty component WebView::newWindowComponent - - This property holds the component to use for new windows. - The component must have a WebView somewhere in its structure. - - When the web engine requests a new window, it will be an instance of - this component. - - The parent of the new window is set by newWindowParent. It must be set. -*/ -QDeclarativeComponent *QDeclarativeWebView::newWindowComponent() const -{ - Q_D(const QDeclarativeWebView); - return d->newWindowComponent; -} - -void QDeclarativeWebView::setNewWindowComponent(QDeclarativeComponent *newWindow) -{ - Q_D(QDeclarativeWebView); - if (newWindow == d->newWindowComponent) - return; - d->newWindowComponent = newWindow; - emit newWindowComponentChanged(); -} - - -/*! - \qmlproperty item WebView::newWindowParent - - The parent item for new windows. - - \sa newWindowComponent -*/ -QDeclarativeItem *QDeclarativeWebView::newWindowParent() const -{ - Q_D(const QDeclarativeWebView); - return d->newWindowParent; -} - -void QDeclarativeWebView::setNewWindowParent(QDeclarativeItem *parent) -{ - Q_D(QDeclarativeWebView); - if (parent == d->newWindowParent) - return; - if (d->newWindowParent && parent) { - QList children = d->newWindowParent->childItems(); - for (int i = 0; i < children.count(); ++i) { - children.at(i)->setParentItem(parent); - } - } - d->newWindowParent = parent; - emit newWindowParentChanged(); -} - -/*! - Returns the area of the largest element at position (\a x,\a y) that is no larger - than \a maxwidth by \a maxheight pixels. - - May return an area larger in the case when no smaller element is at the position. -*/ -QRect QDeclarativeWebView::elementAreaAt(int x, int y, int maxwidth, int maxheight) const -{ - QWebHitTestResult hit = page()->mainFrame()->hitTestContent(QPoint(x,y)); - QRect rv = hit.boundingRect(); - QWebElement element = hit.enclosingBlockElement(); - if (maxwidth<=0) maxwidth = INT_MAX; - if (maxheight<=0) maxheight = INT_MAX; - while (!element.parent().isNull() && element.geometry().width() <= maxwidth && element.geometry().height() <= maxheight) { - rv = element.geometry(); - element = element.parent(); - } - return rv; -} - -/*! - \internal - \class QDeclarativeWebPage - \brief The QDeclarativeWebPage class is a QWebPage that can create QML plugins. - - \sa QDeclarativeWebView -*/ -QDeclarativeWebPage::QDeclarativeWebPage(QDeclarativeWebView *parent) : - QWebPage(parent) -{ -} - -QDeclarativeWebPage::~QDeclarativeWebPage() -{ -} - -void QDeclarativeWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) -{ - qWarning() << sourceID << ':' << lineNumber << ':' << message; -} - -QString QDeclarativeWebPage::chooseFile(QWebFrame *originatingFrame, const QString& oldFile) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(oldFile) - return oldFile; -} - -void QDeclarativeWebPage::javaScriptAlert(QWebFrame *originatingFrame, const QString& msg) -{ - Q_UNUSED(originatingFrame) - emit viewItem()->alert(msg); -} - -bool QDeclarativeWebPage::javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(msg) - return false; -} - -bool QDeclarativeWebPage::javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result) -{ - // Not supported (it's modal) - Q_UNUSED(originatingFrame) - Q_UNUSED(msg) - Q_UNUSED(defaultValue) - Q_UNUSED(result) - return false; -} - - -/* - Qt WebKit does not understand non-QWidget plugins, so dummy widgets - are created, parented to a single dummy tool window. - - The requirements for QML object plugins are input to the Qt WebKit - non-QWidget plugin support, which will obsolete this kludge. -*/ -class QWidget_Dummy_Plugin : public QWidget -{ - Q_OBJECT -public: - static QWidget *dummy_shared_parent() - { - static QWidget *dsp = 0; - if (!dsp) { - dsp = new QWidget(0,Qt::Tool); - dsp->setGeometry(-10000,-10000,0,0); - dsp->show(); - } - return dsp; - } - QWidget_Dummy_Plugin(const QUrl& url, QDeclarativeWebView *view, const QStringList ¶mNames, const QStringList ¶mValues) : - QWidget(dummy_shared_parent()), - propertyNames(paramNames), - propertyValues(paramValues), - webview(view) - { - QDeclarativeEngine *engine = qmlEngine(webview); - component = new QDeclarativeComponent(engine, url, this); - item = 0; - if (component->isLoading()) - connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(qmlLoaded())); - else - qmlLoaded(); - } - -public Q_SLOTS: - void qmlLoaded() - { - if (component->isError()) { - // ### Could instead give these errors to the WebView to handle. - qWarning() << component->errors(); - return; - } - item = qobject_cast(component->create(qmlContext(webview))); - item->setParent(webview); - QString jsObjName; - for (int i=0; isetProperty(propertyNames[i].toUtf8(),propertyValues[i]); - if (propertyNames[i] == QLatin1String("objectname")) - jsObjName = propertyValues[i]; - } - } - if (!jsObjName.isNull()) { - QWebFrame *f = webview->page()->mainFrame(); - f->addToJavaScriptWindowObject(jsObjName, item); - } - resizeEvent(0); - delete component; - component = 0; - } - void resizeEvent(QResizeEvent*) - { - if (item) { - item->setX(x()); - item->setY(y()); - item->setWidth(width()); - item->setHeight(height()); - } - } - -private: - QDeclarativeComponent *component; - QDeclarativeItem *item; - QStringList propertyNames, propertyValues; - QDeclarativeWebView *webview; -}; - -QDeclarativeWebView *QDeclarativeWebPage::viewItem() -{ - return static_cast(parent()); -} - -QObject *QDeclarativeWebPage::createPlugin(const QString &, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) -{ - QUrl comp = qmlContext(viewItem())->resolvedUrl(url); - return new QWidget_Dummy_Plugin(comp,viewItem(),paramNames,paramValues); -} - -QWebPage *QDeclarativeWebPage::createWindow(WebWindowType type) -{ - QDeclarativeWebView *newView = viewItem()->createWindow(type); - if (newView) - return newView->page(); - return 0; -} - -QT_END_NAMESPACE - -#include diff --git a/src/declarative/imports/webkit/qdeclarativewebview_p.h b/src/declarative/imports/webkit/qdeclarativewebview_p.h deleted file mode 100644 index 0bb5d29..0000000 --- a/src/declarative/imports/webkit/qdeclarativewebview_p.h +++ /dev/null @@ -1,285 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef QDECLARATIVEWEBVIEW_H -#define QDECLARATIVEWEBVIEW_H - -#include - -#include -#include -#include -#include - -QT_BEGIN_HEADER - -class QWebHistory; -class QWebSettings; - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) -class QDeclarativeWebViewPrivate; -class QNetworkRequest; -class QDeclarativeWebView; - -class Q_DECLARATIVE_EXPORT QDeclarativeWebPage : public QWebPage -{ - Q_OBJECT -public: - explicit QDeclarativeWebPage(QDeclarativeWebView *parent); - ~QDeclarativeWebPage(); -protected: - QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); - QWebPage *createWindow(WebWindowType type); - void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); - QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); - void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); - bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); - bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); - -private: - QDeclarativeWebView *viewItem(); -}; - - -class QDeclarativeWebViewAttached; - -//### TODO: browser plugins - -class Q_DECLARATIVE_EXPORT QDeclarativeWebView : public QDeclarativePaintedItem -{ - Q_OBJECT - - Q_ENUMS(Status SelectionMode) - - Q_PROPERTY(QString title READ title NOTIFY titleChanged) - Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged) - Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor NOTIFY zoomFactorChanged) - Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged) - - Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged) - - Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime NOTIFY pressGrabTimeChanged) - - Q_PROPERTY(int preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged) - Q_PROPERTY(int preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged) - Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) - Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) - Q_PROPERTY(Status status READ status NOTIFY statusChanged) - - Q_PROPERTY(QAction* reload READ reloadAction CONSTANT) - Q_PROPERTY(QAction* back READ backAction CONSTANT) - Q_PROPERTY(QAction* forward READ forwardAction CONSTANT) - Q_PROPERTY(QAction* stop READ stopAction CONSTANT) - - Q_PROPERTY(QObject* settings READ settingsObject CONSTANT) - - Q_PROPERTY(QDeclarativeListProperty javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT) - - Q_PROPERTY(QDeclarativeComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent NOTIFY newWindowComponentChanged) - Q_PROPERTY(QDeclarativeItem* newWindowParent READ newWindowParent WRITE setNewWindowParent NOTIFY newWindowParentChanged) - - Q_PROPERTY(bool renderingEnabled READ renderingEnabled WRITE setRenderingEnabled NOTIFY renderingEnabledChanged) - -public: - QDeclarativeWebView(QDeclarativeItem *parent=0); - ~QDeclarativeWebView(); - - QUrl url() const; - void setUrl(const QUrl &); - - QString title() const; - - QPixmap icon() const; - - qreal zoomFactor() const; - void setZoomFactor(qreal); - Q_INVOKABLE bool heuristicZoom(int clickX, int clickY, qreal maxzoom); - QRect elementAreaAt(int x, int y, int minwidth, int minheight) const; - - int pressGrabTime() const; - void setPressGrabTime(int); - - int preferredWidth() const; - void setPreferredWidth(int); - int preferredHeight() const; - void setPreferredHeight(int); - - enum Status { Null, Ready, Loading, Error }; - Status status() const; - qreal progress() const; - QString statusText() const; - - QAction *reloadAction() const; - QAction *backAction() const; - QAction *forwardAction() const; - QAction *stopAction() const; - - QWebPage *page() const; - void setPage(QWebPage *page); - - void load(const QNetworkRequest &request, - QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, - const QByteArray &body = QByteArray()); - - QString html() const; - - void setHtml(const QString &html, const QUrl &baseUrl = QUrl()); - void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl()); - - QWebHistory *history() const; - QWebSettings *settings() const; - QObject *settingsObject() const; - - bool renderingEnabled() const; - void setRenderingEnabled(bool); - - QDeclarativeListProperty javaScriptWindowObjects(); - - static QDeclarativeWebViewAttached *qmlAttachedProperties(QObject *); - - QDeclarativeComponent *newWindowComponent() const; - void setNewWindowComponent(QDeclarativeComponent *newWindow); - QDeclarativeItem *newWindowParent() const; - void setNewWindowParent(QDeclarativeItem *newWindow); - -Q_SIGNALS: - void preferredWidthChanged(); - void preferredHeightChanged(); - void urlChanged(); - void progressChanged(); - void statusChanged(Status); - void titleChanged(const QString&); - void iconChanged(); - void statusTextChanged(); - void htmlChanged(); - void pressGrabTimeChanged(); - void zoomFactorChanged(); - void newWindowComponentChanged(); - void newWindowParentChanged(); - void renderingEnabledChanged(); - - void loadStarted(); - void loadFinished(); - void loadFailed(); - - void doubleClick(int clickX, int clickY); - - void zoomTo(qreal zoom, int centerX, int centerY); - - void alert(const QString& message); - -public Q_SLOTS: - QVariant evaluateJavaScript(const QString&); - -private Q_SLOTS: - void expandToWebPage(); - void paintPage(const QRect&); - void doLoadStarted(); - void doLoadProgress(int p); - void doLoadFinished(bool ok); - void setStatusText(const QString&); - void windowObjectCleared(); - void pageUrlChanged(); - void noteContentsSizeChanged(const QSize&); - void initialLayout(); - -protected: - void drawContents(QPainter *, const QRect &); - - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - void timerEvent(QTimerEvent *event); - void hoverMoveEvent (QGraphicsSceneHoverEvent * event); - void keyPressEvent(QKeyEvent* event); - void keyReleaseEvent(QKeyEvent* event); - virtual void geometryChanged(const QRectF &newGeometry, - const QRectF &oldGeometry); - virtual void focusChanged(bool); - virtual bool sceneEvent(QEvent *event); - QDeclarativeWebView *createWindow(QWebPage::WebWindowType type); - -private: - void init(); - virtual void componentComplete(); - Q_DISABLE_COPY(QDeclarativeWebView) - Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeWebView) - QMouseEvent *sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *); - QMouseEvent *sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *); - friend class QDeclarativeWebPage; -}; - -class QDeclarativeWebViewAttached : public QObject -{ - Q_OBJECT - Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName) -public: - QDeclarativeWebViewAttached(QObject *parent) - : QObject(parent) - { - } - - QString windowObjectName() const - { - return m_windowObjectName; - } - - void setWindowObjectName(const QString &n) - { - m_windowObjectName = n; - } - -private: - QString m_windowObjectName; -}; - - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QDeclarativeWebView) -QML_DECLARE_TYPEINFO(QDeclarativeWebView, QML_HAS_ATTACHED_PROPERTIES) - -QT_END_HEADER - -#endif diff --git a/src/declarative/imports/webkit/qdeclarativewebview_p_p.h b/src/declarative/imports/webkit/qdeclarativewebview_p_p.h deleted file mode 100644 index 258b472..0000000 --- a/src/declarative/imports/webkit/qdeclarativewebview_p_p.h +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef QDECLARATIVEWEBVIEW_P_H -#define QDECLARATIVEWEBVIEW_P_H - -#include - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) - -class QDeclarativeWebSettings : public QObject { - Q_OBJECT - - Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily) - Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily) - Q_PROPERTY(QString serifFontFamily READ serifFontFamily WRITE setSerifFontFamily) - Q_PROPERTY(QString sansSerifFontFamily READ sansSerifFontFamily WRITE setSansSerifFontFamily) - Q_PROPERTY(QString cursiveFontFamily READ cursiveFontFamily WRITE setCursiveFontFamily) - Q_PROPERTY(QString fantasyFontFamily READ fantasyFontFamily WRITE setFantasyFontFamily) - - Q_PROPERTY(int minimumFontSize READ minimumFontSize WRITE setMinimumFontSize) - Q_PROPERTY(int minimumLogicalFontSize READ minimumLogicalFontSize WRITE setMinimumLogicalFontSize) - Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize) - Q_PROPERTY(int defaultFixedFontSize READ defaultFixedFontSize WRITE setDefaultFixedFontSize) - - Q_PROPERTY(bool autoLoadImages READ autoLoadImages WRITE setAutoLoadImages) - Q_PROPERTY(bool javascriptEnabled READ javascriptEnabled WRITE setJavascriptEnabled) - Q_PROPERTY(bool javaEnabled READ javaEnabled WRITE setJavaEnabled) - Q_PROPERTY(bool pluginsEnabled READ pluginsEnabled WRITE setPluginsEnabled) - Q_PROPERTY(bool privateBrowsingEnabled READ privateBrowsingEnabled WRITE setPrivateBrowsingEnabled) - Q_PROPERTY(bool javascriptCanOpenWindows READ javascriptCanOpenWindows WRITE setJavascriptCanOpenWindows) - Q_PROPERTY(bool javascriptCanAccessClipboard READ javascriptCanAccessClipboard WRITE setJavascriptCanAccessClipboard) - Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled) - Q_PROPERTY(bool linksIncludedInFocusChain READ linksIncludedInFocusChain WRITE setLinksIncludedInFocusChain) - Q_PROPERTY(bool zoomTextOnly READ zoomTextOnly WRITE setZoomTextOnly) - Q_PROPERTY(bool printElementBackgrounds READ printElementBackgrounds WRITE setPrintElementBackgrounds) - Q_PROPERTY(bool offlineStorageDatabaseEnabled READ offlineStorageDatabaseEnabled WRITE setOfflineStorageDatabaseEnabled) - Q_PROPERTY(bool offlineWebApplicationCacheEnabled READ offlineWebApplicationCacheEnabled WRITE setOfflineWebApplicationCacheEnabled) - Q_PROPERTY(bool localStorageDatabaseEnabled READ localStorageDatabaseEnabled WRITE setLocalStorageDatabaseEnabled) - Q_PROPERTY(bool localContentCanAccessRemoteUrls READ localContentCanAccessRemoteUrls WRITE setLocalContentCanAccessRemoteUrls) - -public: - QDeclarativeWebSettings() {} - - QString standardFontFamily() const { return s->fontFamily(QWebSettings::StandardFont); } - void setStandardFontFamily(const QString& f) { s->setFontFamily(QWebSettings::StandardFont,f); } - QString fixedFontFamily() const { return s->fontFamily(QWebSettings::FixedFont); } - void setFixedFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FixedFont,f); } - QString serifFontFamily() const { return s->fontFamily(QWebSettings::SerifFont); } - void setSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SerifFont,f); } - QString sansSerifFontFamily() const { return s->fontFamily(QWebSettings::SansSerifFont); } - void setSansSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SansSerifFont,f); } - QString cursiveFontFamily() const { return s->fontFamily(QWebSettings::CursiveFont); } - void setCursiveFontFamily(const QString& f) { s->setFontFamily(QWebSettings::CursiveFont,f); } - QString fantasyFontFamily() const { return s->fontFamily(QWebSettings::FantasyFont); } - void setFantasyFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FantasyFont,f); } - - int minimumFontSize() const { return s->fontSize(QWebSettings::MinimumFontSize); } - void setMinimumFontSize(int size) { s->setFontSize(QWebSettings::MinimumFontSize,size); } - int minimumLogicalFontSize() const { return s->fontSize(QWebSettings::MinimumLogicalFontSize); } - void setMinimumLogicalFontSize(int size) { s->setFontSize(QWebSettings::MinimumLogicalFontSize,size); } - int defaultFontSize() const { return s->fontSize(QWebSettings::DefaultFontSize); } - void setDefaultFontSize(int size) { s->setFontSize(QWebSettings::DefaultFontSize,size); } - int defaultFixedFontSize() const { return s->fontSize(QWebSettings::DefaultFixedFontSize); } - void setDefaultFixedFontSize(int size) { s->setFontSize(QWebSettings::DefaultFixedFontSize,size); } - - bool autoLoadImages() const { return s->testAttribute(QWebSettings::AutoLoadImages); } - void setAutoLoadImages(bool on) { s->setAttribute(QWebSettings::AutoLoadImages, on); } - bool javascriptEnabled() const { return s->testAttribute(QWebSettings::JavascriptEnabled); } - void setJavascriptEnabled(bool on) { s->setAttribute(QWebSettings::JavascriptEnabled, on); } - bool javaEnabled() const { return s->testAttribute(QWebSettings::JavaEnabled); } - void setJavaEnabled(bool on) { s->setAttribute(QWebSettings::JavaEnabled, on); } - bool pluginsEnabled() const { return s->testAttribute(QWebSettings::PluginsEnabled); } - void setPluginsEnabled(bool on) { s->setAttribute(QWebSettings::PluginsEnabled, on); } - bool privateBrowsingEnabled() const { return s->testAttribute(QWebSettings::PrivateBrowsingEnabled); } - void setPrivateBrowsingEnabled(bool on) { s->setAttribute(QWebSettings::PrivateBrowsingEnabled, on); } - bool javascriptCanOpenWindows() const { return s->testAttribute(QWebSettings::JavascriptCanOpenWindows); } - void setJavascriptCanOpenWindows(bool on) { s->setAttribute(QWebSettings::JavascriptCanOpenWindows, on); } - bool javascriptCanAccessClipboard() const { return s->testAttribute(QWebSettings::JavascriptCanAccessClipboard); } - void setJavascriptCanAccessClipboard(bool on) { s->setAttribute(QWebSettings::JavascriptCanAccessClipboard, on); } - bool developerExtrasEnabled() const { return s->testAttribute(QWebSettings::DeveloperExtrasEnabled); } - void setDeveloperExtrasEnabled(bool on) { s->setAttribute(QWebSettings::DeveloperExtrasEnabled, on); } - bool linksIncludedInFocusChain() const { return s->testAttribute(QWebSettings::LinksIncludedInFocusChain); } - void setLinksIncludedInFocusChain(bool on) { s->setAttribute(QWebSettings::LinksIncludedInFocusChain, on); } - bool zoomTextOnly() const { return s->testAttribute(QWebSettings::ZoomTextOnly); } - void setZoomTextOnly(bool on) { s->setAttribute(QWebSettings::ZoomTextOnly, on); } - bool printElementBackgrounds() const { return s->testAttribute(QWebSettings::PrintElementBackgrounds); } - void setPrintElementBackgrounds(bool on) { s->setAttribute(QWebSettings::PrintElementBackgrounds, on); } - bool offlineStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled); } - void setOfflineStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, on); } - bool offlineWebApplicationCacheEnabled() const { return s->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled); } - void setOfflineWebApplicationCacheEnabled(bool on) { s->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, on); } - bool localStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::LocalStorageDatabaseEnabled); } - void setLocalStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, on); } - bool localContentCanAccessRemoteUrls() const { return s->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls); } - void setLocalContentCanAccessRemoteUrls(bool on) { s->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, on); } - - QWebSettings *s; -}; - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QDeclarativeWebSettings) - -QT_END_HEADER - -#endif diff --git a/src/declarative/imports/webkit/webkit.pro b/src/declarative/imports/webkit/webkit.pro deleted file mode 100644 index 7ad8564..0000000 --- a/src/declarative/imports/webkit/webkit.pro +++ /dev/null @@ -1,18 +0,0 @@ -TARGET = webkitqmlplugin -include(../qimportbase.pri) - -contains(QT_CONFIG, webkit) { - QT += webkit declarative - - SOURCES += qdeclarativewebview.cpp plugin.cpp - HEADERS += qdeclarativewebview_p.h - HEADERS += qdeclarativewebview_p_p.h - - QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/org/webkit - target.path = $$[QT_INSTALL_IMPORTS]/org/webkit - - qmldir.files += $$QT_BUILD_TREE/imports/org/webkit/qmldir - qmldir.path += $$[QT_INSTALL_IMPORTS]/org/webkit - - INSTALLS += target qmldir -} diff --git a/src/declarative/imports/widgets/graphicslayouts.cpp b/src/declarative/imports/widgets/graphicslayouts.cpp deleted file mode 100644 index fc15ad2..0000000 --- a/src/declarative/imports/widgets/graphicslayouts.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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 "graphicslayouts_p.h" - -#include -#include - -QT_BEGIN_NAMESPACE - -LinearLayoutAttached::LinearLayoutAttached(QObject *parent) -: QObject(parent), _stretch(1), _alignment(Qt::AlignCenter) -{ -} - -void LinearLayoutAttached::setStretchFactor(int f) -{ - if (_stretch == f) - return; - - _stretch = f; - emit stretchChanged(reinterpret_cast(parent()), _stretch); -} - -void LinearLayoutAttached::setAlignment(Qt::Alignment a) -{ - if (_alignment == a) - return; - - _alignment = a; - emit alignmentChanged(reinterpret_cast(parent()), _alignment); -} - -QGraphicsLinearLayoutStretchItemObject::QGraphicsLinearLayoutStretchItemObject(QObject *parent) - : QObject(parent) -{ -} - -QSizeF QGraphicsLinearLayoutStretchItemObject::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const -{ -Q_UNUSED(which); -Q_UNUSED(constraint); -return QSizeF(); -} - - -QGraphicsLinearLayoutObject::QGraphicsLinearLayoutObject(QObject *parent) -: QObject(parent) -{ -} - -QGraphicsLinearLayoutObject::~QGraphicsLinearLayoutObject() -{ -} - -void QGraphicsLinearLayoutObject::insertLayoutItem(int index, QGraphicsLayoutItem *item) -{ -insertItem(index, item); - -//connect attached properties -if (LinearLayoutAttached *obj = attachedProperties.value(item)) { - setStretchFactor(item, obj->stretchFactor()); - setAlignment(item, obj->alignment()); - QObject::connect(obj, SIGNAL(stretchChanged(QGraphicsLayoutItem*,int)), - this, SLOT(updateStretch(QGraphicsLayoutItem*,int))); - QObject::connect(obj, SIGNAL(alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment)), - this, SLOT(updateAlignment(QGraphicsLayoutItem*,Qt::Alignment))); - //### need to disconnect when widget is removed? -} -} - -//### is there a better way to do this? -void QGraphicsLinearLayoutObject::clearChildren() -{ -for (int i = 0; i < count(); ++i) - removeAt(i); -} - -void QGraphicsLinearLayoutObject::updateStretch(QGraphicsLayoutItem *item, int stretch) -{ -QGraphicsLinearLayout::setStretchFactor(item, stretch); -} - -void QGraphicsLinearLayoutObject::updateAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment) -{ -QGraphicsLinearLayout::setAlignment(item, alignment); -} - -QHash QGraphicsLinearLayoutObject::attachedProperties; -LinearLayoutAttached *QGraphicsLinearLayoutObject::qmlAttachedProperties(QObject *obj) -{ -// ### This is not allowed - you must attach to any object -if (!qobject_cast(obj)) - return 0; -LinearLayoutAttached *rv = new LinearLayoutAttached(obj); -attachedProperties.insert(qobject_cast(obj), rv); -return rv; -} - -////////////////////////////////////////////////////////////////////////////////////////////////////// -// QGraphicsGridLayout-related classes -////////////////////////////////////////////////////////////////////////////////////////////////////// -GridLayoutAttached::GridLayoutAttached(QObject *parent) -: QObject(parent), _row(-1), _column(-1), _rowspan(1), _colspan(1), _alignment(-1) -{ -} - -void GridLayoutAttached::setRow(int r) -{ - if (_row == r) - return; - - _row = r; - //emit rowChanged(reinterpret_cast(parent()), _row); -} - -void GridLayoutAttached::setColumn(int c) -{ - if (_column == c) - return; - - _column = c; - //emit columnChanged(reinterpret_cast(parent()), _column); -} - -void GridLayoutAttached::setRowSpan(int rs) -{ - if (_rowspan == rs) - return; - - _rowspan = rs; - //emit rowSpanChanged(reinterpret_cast(parent()), _rowSpan); -} - -void GridLayoutAttached::setColumnSpan(int cs) -{ - if (_colspan == cs) - return; - - _colspan = cs; - //emit columnSpanChanged(reinterpret_cast(parent()), _columnSpan); -} - -void GridLayoutAttached::setAlignment(Qt::Alignment a) -{ - if (_alignment == a) - return; - - _alignment = a; - //emit alignmentChanged(reinterpret_cast(parent()), _alignment); -} - -QGraphicsGridLayoutObject::QGraphicsGridLayoutObject(QObject *parent) -: QObject(parent) -{ -} - -QGraphicsGridLayoutObject::~QGraphicsGridLayoutObject() -{ -} - -void QGraphicsGridLayoutObject::addWidget(QGraphicsWidget *wid) -{ -//use attached properties -if (QObject *obj = attachedProperties.value(qobject_cast(wid))) { - int row = static_cast(obj)->row(); - int column = static_cast(obj)->column(); - int rowSpan = static_cast(obj)->rowSpan(); - int columnSpan = static_cast(obj)->columnSpan(); - if (row == -1 || column == -1) { - qWarning() << "Must set row and column for an item in a grid layout"; - return; - } - addItem(wid, row, column, rowSpan, columnSpan); -} -} - -void QGraphicsGridLayoutObject::addLayoutItem(QGraphicsLayoutItem *item) -{ -//use attached properties -if (GridLayoutAttached *obj = attachedProperties.value(item)) { - int row = obj->row(); - int column = obj->column(); - int rowSpan = obj->rowSpan(); - int columnSpan = obj->columnSpan(); - Qt::Alignment alignment = obj->alignment(); - if (row == -1 || column == -1) { - qWarning() << "Must set row and column for an item in a grid layout"; - return; - } - addItem(item, row, column, rowSpan, columnSpan); - if (alignment != -1) - setAlignment(item,alignment); -} -} - -//### is there a better way to do this? -void QGraphicsGridLayoutObject::clearChildren() -{ -for (int i = 0; i < count(); ++i) - removeAt(i); -} - -qreal QGraphicsGridLayoutObject::spacing() const -{ -if (verticalSpacing() == horizontalSpacing()) - return verticalSpacing(); -return -1; //### -} - -QHash QGraphicsGridLayoutObject::attachedProperties; -GridLayoutAttached *QGraphicsGridLayoutObject::qmlAttachedProperties(QObject *obj) -{ -// ### This is not allowed - you must attach to any object -if (!qobject_cast(obj)) - return 0; -GridLayoutAttached *rv = new GridLayoutAttached(obj); -attachedProperties.insert(qobject_cast(obj), rv); -return rv; -} - -QT_END_NAMESPACE diff --git a/src/declarative/imports/widgets/graphicslayouts_p.h b/src/declarative/imports/widgets/graphicslayouts_p.h deleted file mode 100644 index f9b9ae8..0000000 --- a/src/declarative/imports/widgets/graphicslayouts_p.h +++ /dev/null @@ -1,226 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef GRAPHICSLAYOUTS_H -#define GRAPHICSLAYOUTS_H - -#include "graphicswidgets_p.h" - -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) - -class QGraphicsLinearLayoutStretchItemObject : public QObject, public QGraphicsLayoutItem -{ - Q_OBJECT - Q_INTERFACES(QGraphicsLayoutItem) -public: - QGraphicsLinearLayoutStretchItemObject(QObject *parent = 0); - - virtual QSizeF sizeHint(Qt::SizeHint, const QSizeF &) const; -}; - -class LinearLayoutAttached; -class QGraphicsLinearLayoutObject : public QObject, public QGraphicsLinearLayout -{ - Q_OBJECT - Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation) - Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsLinearLayoutObject(QObject * = 0); - ~QGraphicsLinearLayoutObject(); - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } - - static LinearLayoutAttached *qmlAttachedProperties(QObject *); - -private Q_SLOTS: - void updateStretch(QGraphicsLayoutItem*,int); - void updateAlignment(QGraphicsLayoutItem*,Qt::Alignment); - -private: - friend class LinearLayoutAttached; - void clearChildren(); - void insertLayoutItem(int, QGraphicsLayoutItem *); - static QHash attachedProperties; - - static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { - static_cast(prop->object)->insertLayoutItem(-1, item); - } - - static void children_clear(QDeclarativeListProperty *prop) { - static_cast(prop->object)->clearChildren(); - } - - static int children_count(QDeclarativeListProperty *prop) { - return static_cast(prop->object)->count(); - } - - static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { - return static_cast(prop->object)->itemAt(index); - } -}; - -class GridLayoutAttached; -class QGraphicsGridLayoutObject : public QObject, public QGraphicsGridLayout -{ - Q_OBJECT - Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) - Q_PROPERTY(qreal verticalSpacing READ verticalSpacing WRITE setVerticalSpacing) - Q_PROPERTY(qreal horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsGridLayoutObject(QObject * = 0); - ~QGraphicsGridLayoutObject(); - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } - - qreal spacing() const; - - static GridLayoutAttached *qmlAttachedProperties(QObject *); - -private: - friend class GraphicsLayoutAttached; - void addWidget(QGraphicsWidget *); - void clearChildren(); - void addLayoutItem(QGraphicsLayoutItem *); - static QHash attachedProperties; - - static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { - static_cast(prop->object)->addLayoutItem(item); - } - - static void children_clear(QDeclarativeListProperty *prop) { - static_cast(prop->object)->clearChildren(); - } - - static int children_count(QDeclarativeListProperty *prop) { - return static_cast(prop->object)->count(); - } - - static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { - return static_cast(prop->object)->itemAt(index); - } -}; - -class LinearLayoutAttached : public QObject -{ - Q_OBJECT - - Q_PROPERTY(int stretchFactor READ stretchFactor WRITE setStretchFactor NOTIFY stretchChanged) - Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) -public: - LinearLayoutAttached(QObject *parent); - - int stretchFactor() const { return _stretch; } - void setStretchFactor(int f); - Qt::Alignment alignment() const { return _alignment; } - void setAlignment(Qt::Alignment a); - -Q_SIGNALS: - void stretchChanged(QGraphicsLayoutItem*,int); - void alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment); - -private: - int _stretch; - Qt::Alignment _alignment; -}; - -class GridLayoutAttached : public QObject -{ - Q_OBJECT - - Q_PROPERTY(int row READ row WRITE setRow) - Q_PROPERTY(int column READ column WRITE setColumn) - Q_PROPERTY(int rowSpan READ rowSpan WRITE setRowSpan) - Q_PROPERTY(int columnSpan READ columnSpan WRITE setColumnSpan) - Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment) -public: - GridLayoutAttached(QObject *parent); - - int row() const { return _row; } - void setRow(int r); - - int column() const { return _column; } - void setColumn(int c); - - int rowSpan() const { return _rowspan; } - void setRowSpan(int rs); - - int columnSpan() const { return _colspan; } - void setColumnSpan(int cs); - - Qt::Alignment alignment() const { return _alignment; } - void setAlignment(Qt::Alignment a); - -private: - int _row; - int _column; - int _rowspan; - int _colspan; - Qt::Alignment _alignment; -}; - -QT_END_NAMESPACE - -QML_DECLARE_INTERFACE(QGraphicsLayoutItem) -QML_DECLARE_INTERFACE(QGraphicsLayout) -QML_DECLARE_TYPE(QGraphicsLinearLayoutStretchItemObject) -QML_DECLARE_TYPE(QGraphicsLinearLayoutObject) -QML_DECLARE_TYPEINFO(QGraphicsLinearLayoutObject, QML_HAS_ATTACHED_PROPERTIES) -QML_DECLARE_TYPE(QGraphicsGridLayoutObject) -QML_DECLARE_TYPEINFO(QGraphicsGridLayoutObject, QML_HAS_ATTACHED_PROPERTIES) - -QT_END_HEADER - -#endif // GRAPHICSLAYOUTS_H diff --git a/src/declarative/imports/widgets/graphicswidgets.cpp b/src/declarative/imports/widgets/graphicswidgets.cpp deleted file mode 100644 index 062e516..0000000 --- a/src/declarative/imports/widgets/graphicswidgets.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ diff --git a/src/declarative/imports/widgets/graphicswidgets_p.h b/src/declarative/imports/widgets/graphicswidgets_p.h deleted file mode 100644 index 2c2b707..0000000 --- a/src/declarative/imports/widgets/graphicswidgets_p.h +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** -** -** 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 QtDeclarative module 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$ -** -****************************************************************************/ - -#ifndef GRAPHICSWIDGETS_H -#define GRAPHICSWIDGETS_H - -#include - -#include -#include -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) - -QT_END_NAMESPACE - -QML_DECLARE_TYPE(QGraphicsView) -QML_DECLARE_TYPE_HASMETATYPE(QGraphicsScene) -QML_DECLARE_TYPE(QGraphicsWidget) -QML_DECLARE_TYPE(QGraphicsObject) -QML_DECLARE_INTERFACE_HASMETATYPE(QGraphicsItem) - -QT_END_HEADER - -#endif // GRAPHICSWIDGETS_H diff --git a/src/declarative/imports/widgets/widgets.cpp b/src/declarative/imports/widgets/widgets.cpp deleted file mode 100644 index ec21cc4..0000000 --- a/src/declarative/imports/widgets/widgets.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the plugins 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 -#include - -#include "graphicslayouts_p.h" -#include "graphicswidgets_p.h" - -QT_BEGIN_NAMESPACE - -class QGraphicsViewDeclarativeUI : public QObject -{ - Q_OBJECT - - Q_PROPERTY(QGraphicsScene *scene READ scene WRITE setScene) - Q_CLASSINFO("DefaultProperty", "scene") -public: - QGraphicsViewDeclarativeUI(QObject *other) : QObject(other) {} - - QGraphicsScene *scene() const { return static_cast(parent())->scene(); } - void setScene(QGraphicsScene *scene) - { - static_cast(parent())->setScene(scene); - } -}; - -class QGraphicsSceneDeclarativeUI : public QObject -{ - Q_OBJECT - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsSceneDeclarativeUI(QObject *other) : QObject(other) {} - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this->parent(), 0, children_append); } - -private: - static void children_append(QDeclarativeListProperty *prop, QObject *o) { - if (QGraphicsObject *go = qobject_cast(o)) - static_cast(prop->object)->addItem(go); - } -}; - -class QGraphicsWidgetDeclarativeUI : public QObject -{ - Q_OBJECT - - Q_PROPERTY(QDeclarativeListProperty children READ children) - Q_PROPERTY(QGraphicsLayout *layout READ layout WRITE setLayout) - Q_CLASSINFO("DefaultProperty", "children") -public: - QGraphicsWidgetDeclarativeUI(QObject *other) : QObject(other) {} - - QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append); } - - QGraphicsLayout *layout() const { return static_cast(parent())->layout(); } - void setLayout(QGraphicsLayout *lo) - { - static_cast(parent())->setLayout(lo); - } - -private: - void setItemParent(QGraphicsItem *wid) - { - wid->setParentItem(static_cast(parent())); - } - - static void children_append(QDeclarativeListProperty *prop, QGraphicsItem *i) { - static_cast(prop->object)->setItemParent(i); - } -}; - -class QWidgetsQmlModule : public QDeclarativeExtensionPlugin -{ - Q_OBJECT -public: - virtual void registerTypes(const char *uri) - { - Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.widgets")); - - QML_REGISTER_INTERFACE(QGraphicsLayoutItem); - QML_REGISTER_INTERFACE(QGraphicsLayout); - qmlRegisterType(uri,4,6,"QGraphicsLinearLayoutStretchItem"); - qmlRegisterType(uri,4,6,"QGraphicsLinearLayout"); - qmlRegisterType(uri,4,6,"QGraphicsGridLayout"); - qmlRegisterExtendedType(uri,4,6,"QGraphicsView"); - qmlRegisterExtendedType(uri,4,6,"QGraphicsScene"); - qmlRegisterExtendedType(uri,4,6,"QGraphicsWidget"); - QML_REGISTER_INTERFACE(QGraphicsItem); - } -}; - -QT_END_NAMESPACE - -#include "widgets.moc" - -Q_EXPORT_PLUGIN2(qtwidgetsqmlmodule, QT_PREPEND_NAMESPACE(QWidgetsQmlModule)); - diff --git a/src/declarative/imports/widgets/widgets.pro b/src/declarative/imports/widgets/widgets.pro deleted file mode 100644 index 230d398..0000000 --- a/src/declarative/imports/widgets/widgets.pro +++ /dev/null @@ -1,20 +0,0 @@ -TARGET = widgets -include(../qimportbase.pri) - -QT += declarative - -SOURCES += \ - graphicslayouts.cpp \ - widgets.cpp - -HEADERS += \ - graphicswidgets_p.h \ - graphicslayouts_p.h - -QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/widgets -target.path = $$[QT_INSTALL_IMPORTS]/Qt/widgets - -qmldir.files += $$QT_BUILD_TREE/imports/Qt/widgets/qmldir -qmldir.path += $$[QT_INSTALL_IMPORTS]/Qt/widgets - -INSTALLS += target qmldir diff --git a/src/declarative/libdeclarative.pro b/src/declarative/libdeclarative.pro deleted file mode 100644 index 4287e25..0000000 --- a/src/declarative/libdeclarative.pro +++ /dev/null @@ -1,29 +0,0 @@ -TARGET = QtDeclarative -QPRO_PWD = $$PWD -QT = core gui xml script network -contains(QT_CONFIG, svg): QT += svg -contains(QT_CONFIG, opengl): QT += opengl -DEFINES += QT_BUILD_DECLARATIVE_LIB QT_NO_URL_CAST_FROM_STRING -win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x66000000 -solaris-cc*:QMAKE_CXXFLAGS_RELEASE -= -O2 - -unix:QMAKE_PKGCONFIG_REQUIRES = QtCore QtGui QtXml - -exists("qdeclarative_enable_gcov") { - QMAKE_CXXFLAGS = -fprofile-arcs -ftest-coverage -fno-elide-constructors - LIBS += -lgcov -} - -include(../qbase.pri) - -#INCLUDEPATH -= $$QMAKE_INCDIR_QT/$$TARGET -#DESTDIR=. - -#modules -include(3rdparty/3rdparty.pri) -include(util/util.pri) -include(graphicsitems/graphicsitems.pri) -include(qml/qml.pri) -include(debugger/debugger.pri) - -symbian:TARGET.UID3=0x2001E623 diff --git a/src/imports/imports.pro b/src/imports/imports.pro new file mode 100644 index 0000000..8b47043 --- /dev/null +++ b/src/imports/imports.pro @@ -0,0 +1,7 @@ +TEMPLATE = subdirs + +SUBDIRS += widgets + +contains(QT_CONFIG, webkit): SUBDIRS += webkit +contains(QT_CONFIG, multimedia): SUBDIRS += multimedia + diff --git a/src/imports/multimedia/multimedia.cpp b/src/imports/multimedia/multimedia.cpp new file mode 100644 index 0000000..8becbf3 --- /dev/null +++ b/src/imports/multimedia/multimedia.cpp @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the plugins 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 +#include +#include + +QT_BEGIN_NAMESPACE + +class QMultimediaQmlModule : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + virtual void registerTypes(const char *uri) + { + QtMultimedia::qRegisterDeclarativeElements(uri); + } +}; + +QT_END_NAMESPACE + +#include "multimedia.moc" + +Q_EXPORT_PLUGIN2(qmultimediaqmlmodule, QT_PREPEND_NAMESPACE(QMultimediaQmlModule)); + diff --git a/src/imports/multimedia/multimedia.pro b/src/imports/multimedia/multimedia.pro new file mode 100644 index 0000000..ad2ce1b --- /dev/null +++ b/src/imports/multimedia/multimedia.pro @@ -0,0 +1,15 @@ +TARGET = multimedia +TARGETPATH = $$[QT_INSTALL_IMPORTS]/Qt/multimedia +include(../qimportbase.pri) + +QT += multimedia declarative + +SOURCES += multimedia.cpp + +QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/multimedia +target.path = $$TARGETPATH + +qmldir.files += $$QT_BUILD_TREE/imports/Qt/multimedia/qmldir +qmldir.path += $$TARGETPATH + +INSTALLS += target qmldir diff --git a/src/imports/multimedia/qmldir b/src/imports/multimedia/qmldir new file mode 100644 index 0000000..0e6f656 --- /dev/null +++ b/src/imports/multimedia/qmldir @@ -0,0 +1 @@ +plugin multimedia diff --git a/src/imports/qimportbase.pri b/src/imports/qimportbase.pri new file mode 100644 index 0000000..363dd88 --- /dev/null +++ b/src/imports/qimportbase.pri @@ -0,0 +1,33 @@ +TEMPLATE = lib +CONFIG += qt plugin + +win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release + +isEmpty(TARGETPATH) { + error("qimportbase.pri: You must provide a TARGETPATH!") +} +isEmpty(TARGET) { + error("qimportbase.pri: You must provide a TARGET!") +} + +QMLDIRFILE = $${_PRO_FILE_PWD_}/qmldir +copy2build.input = QMLDIRFILE +copy2build.output = $$TARGETPATH/qmldir +isEmpty(vcproj):copy2build.variable_out = PRE_TARGETDEPS +copy2build.commands = $$QMAKE_COPY ${QMAKE_FILE_IN} ${QMAKE_FILE_OUT} +copy2build.name = COPY ${QMAKE_FILE_IN} +copy2build.CONFIG += no_link +QMAKE_EXTRA_COMPILERS += copy2build + +TARGET = $$qtLibraryTarget($$TARGET) +contains(QT_CONFIG, reduce_exports):CONFIG += hide_symbols + +include(../../qt_targets.pri) + +wince*:LIBS += $$QMAKE_LIBS_GUI + +symbian: { + TARGET.EPOCALLOWDLLDATA=1 + TARGET.CAPABILITY = All -Tcb + load(armcc_warnings) +} diff --git a/src/imports/webkit/plugin.cpp b/src/imports/webkit/plugin.cpp new file mode 100644 index 0000000..2f6205d --- /dev/null +++ b/src/imports/webkit/plugin.cpp @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** 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 plugins 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 +#include + +#include "qdeclarativewebview_p.h" +#include "qdeclarativewebview_p_p.h" + +QT_BEGIN_NAMESPACE + +class WebKitQmlPlugin : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + virtual void registerTypes(const char *uri) + { + Q_ASSERT(QLatin1String(uri) == QLatin1String("org.webkit")); + qmlRegisterType(uri,1,0,"WebView"); + } +}; + +QT_END_NAMESPACE + +#include "plugin.moc" + +Q_EXPORT_PLUGIN2(webkitqmlplugin, QT_PREPEND_NAMESPACE(WebKitQmlPlugin)); + diff --git a/src/imports/webkit/qdeclarativewebview.cpp b/src/imports/webkit/qdeclarativewebview.cpp new file mode 100644 index 0000000..733ac86 --- /dev/null +++ b/src/imports/webkit/qdeclarativewebview.cpp @@ -0,0 +1,1340 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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 "qdeclarativewebview_p.h" +#include "qdeclarativewebview_p_p.h" + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system + +class QDeclarativeWebViewPrivate : public QDeclarativePaintedItemPrivate +{ + Q_DECLARE_PUBLIC(QDeclarativeWebView) + +public: + QDeclarativeWebViewPrivate() + : QDeclarativePaintedItemPrivate(), page(0), preferredwidth(0), preferredheight(0), + progress(1.0), status(QDeclarativeWebView::Null), pending(PendingNone), + newWindowComponent(0), newWindowParent(0), + pressTime(400), + rendering(true) + { + } + + QUrl url; // page url might be different if it has not loaded yet + QWebPage *page; + + int preferredwidth, preferredheight; + qreal progress; + QDeclarativeWebView::Status status; + QString statusText; + enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending; + QUrl pending_url; + QString pending_string; + QByteArray pending_data; + mutable QDeclarativeWebSettings settings; + QDeclarativeComponent *newWindowComponent; + QDeclarativeItem *newWindowParent; + + QBasicTimer pressTimer; + QPoint pressPoint; + int pressTime; // milliseconds before it's a "hold" + + + static void windowObjects_append(QDeclarativeListProperty *prop, QObject *o) { + static_cast(prop->data)->windowObjects.append(o); + static_cast(prop->data)->updateWindowObjects(); + } + + void updateWindowObjects(); + QObjectList windowObjects; + + bool rendering; +}; + +/*! + \qmlclass WebView QDeclarativeWebView + \since 4.7 + \brief The WebView item allows you to add web content to a canvas. + \inherits Item + + A WebView renders web content based on a URL. + + If the width and height of the item is not set, they will + dynamically adjust to a size appropriate for the content. + This width may be large for typical online web pages. + + If the preferredWidth is set, the width will be this amount or larger, + usually laying out the web content to fit the preferredWidth. + + \qml + import org.webkit 1.0 + + WebView { + url: "http://www.nokia.com" + width: 490 + height: 400 + scale: 0.5 + smooth: false + smoothCache: true + } + \endqml + + \image webview.png + + The item includes no scrolling, scaling, + toolbars, etc., those must be implemented around WebView. See the WebBrowser example + for a demonstration of this. +*/ + +/*! + \internal + \class QDeclarativeWebView + \brief The QDeclarativeWebView class allows you to add web content to a QDeclarativeView. + + A WebView renders web content base on a URL. + + \image webview.png + + The item includes no scrolling, scaling, + toolbars, etc., those must be implemented around WebView. See the WebBrowser example + for a demonstration of this. + + A QDeclarativeWebView object can be instantiated in Qml using the tag \l WebView. +*/ + +QDeclarativeWebView::QDeclarativeWebView(QDeclarativeItem *parent) + : QDeclarativePaintedItem(*(new QDeclarativeWebViewPrivate), parent) +{ + init(); +} + +QDeclarativeWebView::~QDeclarativeWebView() +{ + Q_D(QDeclarativeWebView); + delete d->page; +} + +void QDeclarativeWebView::init() +{ + Q_D(QDeclarativeWebView); + + QWebSettings::enablePersistentStorage(); + + setAcceptHoverEvents(true); + setAcceptedMouseButtons(Qt::LeftButton); + setFlag(QGraphicsItem::ItemHasNoContents, false); + + d->page = 0; +} + +void QDeclarativeWebView::componentComplete() +{ + QDeclarativePaintedItem::componentComplete(); + Q_D(QDeclarativeWebView); + switch (d->pending) { + case QDeclarativeWebViewPrivate::PendingUrl: + setUrl(d->pending_url); + break; + case QDeclarativeWebViewPrivate::PendingHtml: + setHtml(d->pending_string, d->pending_url); + break; + case QDeclarativeWebViewPrivate::PendingContent: + setContent(d->pending_data, d->pending_string, d->pending_url); + break; + default: + break; + } + d->pending = QDeclarativeWebViewPrivate::PendingNone; + d->updateWindowObjects(); +} + +QDeclarativeWebView::Status QDeclarativeWebView::status() const +{ + Q_D(const QDeclarativeWebView); + return d->status; +} + + +/*! + \qmlproperty real WebView::progress + This property holds the progress of loading the current URL, from 0 to 1. + + If you just want to know when progress gets to 1, use + WebView::onLoadFinished() or WebView::onLoadFailed() instead. +*/ +qreal QDeclarativeWebView::progress() const +{ + Q_D(const QDeclarativeWebView); + return d->progress; +} + +void QDeclarativeWebView::doLoadStarted() +{ + Q_D(QDeclarativeWebView); + + if (!d->url.isEmpty()) { + d->status = Loading; + emit statusChanged(d->status); + } + emit loadStarted(); +} + +void QDeclarativeWebView::doLoadProgress(int p) +{ + Q_D(QDeclarativeWebView); + if (d->progress == p/100.0) + return; + d->progress = p/100.0; + emit progressChanged(); +} + +void QDeclarativeWebView::pageUrlChanged() +{ + Q_D(QDeclarativeWebView); + + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + expandToWebPage(); + + if ((d->url.isEmpty() && page()->mainFrame()->url() != QUrl(QLatin1String("about:blank"))) + || (d->url != page()->mainFrame()->url() && !page()->mainFrame()->url().isEmpty())) + { + d->url = page()->mainFrame()->url(); + if (d->url == QUrl(QLatin1String("about:blank"))) + d->url = QUrl(); + emit urlChanged(); + } +} + +void QDeclarativeWebView::doLoadFinished(bool ok) +{ + Q_D(QDeclarativeWebView); + + if (title().isEmpty()) + pageUrlChanged(); // XXX bug 232556 - pages with no title never get urlChanged() + + if (ok) { + d->status = d->url.isEmpty() ? Null : Ready; + emit loadFinished(); + } else { + d->status = Error; + emit loadFailed(); + } + emit statusChanged(d->status); +} + +/*! + \qmlproperty url WebView::url + This property holds the URL to the page displayed in this item. It can be set, + but also can change spontaneously (eg. because of network redirection). + + If the url is empty, the page is blank. + + The url is always absolute (QML will resolve relative URL strings in the context + of the containing QML document). +*/ +QUrl QDeclarativeWebView::url() const +{ + Q_D(const QDeclarativeWebView); + return d->url; +} + +void QDeclarativeWebView::setUrl(const QUrl &url) +{ + Q_D(QDeclarativeWebView); + if (url == d->url) + return; + + if (isComponentComplete()) { + d->url = url; + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + QUrl seturl = url; + if (seturl.isEmpty()) + seturl = QUrl(QLatin1String("about:blank")); + + Q_ASSERT(!seturl.isRelative()); + + page()->mainFrame()->load(seturl); + + emit urlChanged(); + } else { + d->pending = d->PendingUrl; + d->pending_url = url; + } +} + +/*! + \qmlproperty int WebView::preferredWidth + This property holds the ideal width for displaying the current URL. +*/ +int QDeclarativeWebView::preferredWidth() const +{ + Q_D(const QDeclarativeWebView); + return d->preferredwidth; +} + +void QDeclarativeWebView::setPreferredWidth(int iw) +{ + Q_D(QDeclarativeWebView); + if (d->preferredwidth == iw) return; + d->preferredwidth = iw; + //expandToWebPage(); + emit preferredWidthChanged(); +} + +/*! + \qmlproperty int WebView::preferredHeight + This property holds the ideal height for displaying the current URL. + This only affects the area zoomed by heuristicZoom(). +*/ +int QDeclarativeWebView::preferredHeight() const +{ + Q_D(const QDeclarativeWebView); + return d->preferredheight; +} +void QDeclarativeWebView::setPreferredHeight(int ih) +{ + Q_D(QDeclarativeWebView); + if (d->preferredheight == ih) return; + d->preferredheight = ih; + emit preferredHeightChanged(); +} + +/*! + \qmlmethod bool WebView::evaluateJavaScript(string) + + Evaluates the \a scriptSource JavaScript inside the context of the + main web frame, and returns the result of the last executed statement. + + Note that this JavaScript does \e not have any access to QML objects + except as made available as windowObjects. +*/ +QVariant QDeclarativeWebView::evaluateJavaScript(const QString &scriptSource) +{ + return this->page()->mainFrame()->evaluateJavaScript(scriptSource); +} + +void QDeclarativeWebView::focusChanged(bool hasFocus) +{ + QFocusEvent e(hasFocus ? QEvent::FocusIn : QEvent::FocusOut); + page()->event(&e); + QDeclarativeItem::focusChanged(hasFocus); +} + +void QDeclarativeWebView::initialLayout() +{ + // nothing useful to do at this point +} + +void QDeclarativeWebView::noteContentsSizeChanged(const QSize&) +{ + expandToWebPage(); +} + +void QDeclarativeWebView::expandToWebPage() +{ + Q_D(QDeclarativeWebView); + QSize cs = page()->mainFrame()->contentsSize(); + if (cs.width() < d->preferredwidth) + cs.setWidth(d->preferredwidth); + if (cs.height() < d->preferredheight) + cs.setHeight(d->preferredheight); + if (widthValid()) + cs.setWidth(width()); + if (heightValid()) + cs.setHeight(height()); + if (cs != page()->viewportSize()) { + page()->setViewportSize(cs); + } + if (cs != contentsSize()) + setContentsSize(cs); +} + +void QDeclarativeWebView::geometryChanged(const QRectF &newGeometry, + const QRectF &oldGeometry) +{ + if (newGeometry.size() != oldGeometry.size()) + expandToWebPage(); + QDeclarativePaintedItem::geometryChanged(newGeometry, oldGeometry); +} + +void QDeclarativeWebView::paintPage(const QRect& r) +{ + dirtyCache(r); + update(); +} + +/*! + \qmlproperty list WebView::javaScriptWindowObjects + + This property is a list of object that are available from within + the webview's JavaScript context. + + The \a object will be inserted as a child of the frame's window + object, under the name given by the attached property \c WebView.windowObjectName. + + \qml + WebView { + javaScriptWindowObjects: Object { + WebView.windowObjectName: "coordinates" + } + } + \endqml + + Properties of the object will be exposed as JavaScript properties and slots as + JavaScript methods. + + If Javascript is not enabled for this page, then this property does nothing. +*/ +QDeclarativeListProperty QDeclarativeWebView::javaScriptWindowObjects() +{ + Q_D(QDeclarativeWebView); + return QDeclarativeListProperty(this, d, &QDeclarativeWebViewPrivate::windowObjects_append); +} + +QDeclarativeWebViewAttached *QDeclarativeWebView::qmlAttachedProperties(QObject *o) +{ + return new QDeclarativeWebViewAttached(o); +} + +void QDeclarativeWebViewPrivate::updateWindowObjects() +{ + Q_Q(QDeclarativeWebView); + if (!q->isComponentComplete() || !page) + return; + + for (int ii = 0; ii < windowObjects.count(); ++ii) { + QObject *object = windowObjects.at(ii); + QDeclarativeWebViewAttached *attached = static_cast(qmlAttachedPropertiesObject(object)); + if (attached && !attached->windowObjectName().isEmpty()) { + page->mainFrame()->addToJavaScriptWindowObject(attached->windowObjectName(), object); + } + } +} + +bool QDeclarativeWebView::renderingEnabled() const +{ + Q_D(const QDeclarativeWebView); + return d->rendering; +} + +void QDeclarativeWebView::setRenderingEnabled(bool enabled) +{ + Q_D(QDeclarativeWebView); + if (d->rendering == enabled) + return; + d->rendering = enabled; + emit renderingEnabledChanged(); + + setCacheFrozen(!enabled); + if (enabled) + clearCache(); +} + + +void QDeclarativeWebView::drawContents(QPainter *p, const QRect &r) +{ + Q_D(QDeclarativeWebView); + if (d->rendering) + page()->mainFrame()->render(p,r); +} + +QMouseEvent *QDeclarativeWebView::sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *e) +{ + QEvent::Type t; + switch(e->type()) { + default: + case QEvent::GraphicsSceneMousePress: + t = QEvent::MouseButtonPress; + break; + case QEvent::GraphicsSceneMouseRelease: + t = QEvent::MouseButtonRelease; + break; + case QEvent::GraphicsSceneMouseMove: + t = QEvent::MouseMove; + break; + case QGraphicsSceneEvent::GraphicsSceneMouseDoubleClick: + t = QEvent::MouseButtonDblClick; + break; + } + + QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), e->button(), e->buttons(), 0); + return me; +} + +QMouseEvent *QDeclarativeWebView::sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *e) +{ + QEvent::Type t = QEvent::MouseMove; + + QMouseEvent *me = new QMouseEvent(t, (e->pos()/contentsScale()).toPoint(), Qt::NoButton, Qt::NoButton, 0); + + return me; +} + + +/*! + \qmlsignal WebView::onDoubleClick(clickx,clicky) + + The WebView does not pass double-click events to the web engine, but rather + emits this signals. +*/ + +void QDeclarativeWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + emit doubleClick(me->x(),me->y()); + delete me; +} + +/*! + \qmlmethod bool WebView::heuristicZoom(clickX,clickY,maxzoom) + + Finds a zoom that: + \list + \i shows a whole item + \i includes (\a clickX, \a clickY) + \i fits into the preferredWidth and preferredHeight + \i zooms by no more than \a maxzoom + \i is more than 10% above the current zoom + \endlist + + If such a zoom exists, emits zoomTo(zoom,centerX,centerY) and returns true; otherwise, + no signal is emitted and returns false. +*/ +bool QDeclarativeWebView::heuristicZoom(int clickX, int clickY, qreal maxzoom) +{ + Q_D(QDeclarativeWebView); + if (contentsScale() >= maxzoom/zoomFactor()) + return false; + qreal ozf = contentsScale(); + QRect showarea = elementAreaAt(clickX, clickY, d->preferredwidth/maxzoom, d->preferredheight/maxzoom); + qreal z = qMin(qreal(d->preferredwidth)/showarea.width(),qreal(d->preferredheight)/showarea.height()); + if (z > maxzoom/zoomFactor()) + z = maxzoom/zoomFactor(); + if (z/ozf > 1.2) { + QRectF r(showarea.left()*z, showarea.top()*z, showarea.width()*z, showarea.height()*z); + emit zoomTo(z,r.x()+r.width()/2, r.y()+r.height()/2); + return true; + } else { + return false; + } +} + +/*! + \qmlproperty int WebView::pressGrabTime + + The number of milliseconds the user must press before the WebView + starts passing move events through to the web engine (rather than + letting other QML elements such as a Flickable take them). + + Defaults to 400ms. Set to 0 to always grab and pass move events to + the web engine. +*/ +int QDeclarativeWebView::pressGrabTime() const +{ + Q_D(const QDeclarativeWebView); + return d->pressTime; +} + +void QDeclarativeWebView::setPressGrabTime(int ms) +{ + Q_D(QDeclarativeWebView); + if (d->pressTime == ms) + return; + d->pressTime = ms; + emit pressGrabTimeChanged(); +} + +void QDeclarativeWebView::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + setFocus (true); + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + + d->pressPoint = me->pos(); + if (d->pressTime) { + d->pressTimer.start(d->pressTime,this); + setKeepMouseGrab(false); + } else { + grabMouse(); + setKeepMouseGrab(true); + } + + page()->event(me); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit + Might be a bug in WebKit, though + */ +#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) { + QDeclarativePaintedItem::mousePressEvent(event); + } +} + +void QDeclarativeWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + page()->event(me); + d->pressTimer.stop(); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send all the events to WebKit + */ +#if 1 //QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) { + QDeclarativePaintedItem::mouseReleaseEvent(event); + } + setKeepMouseGrab(false); + ungrabMouse(); +} + +void QDeclarativeWebView::timerEvent(QTimerEvent *event) +{ + Q_D(QDeclarativeWebView); + if (event->timerId() == d->pressTimer.timerId()) { + d->pressTimer.stop(); + grabMouse(); + setKeepMouseGrab(true); + } +} + +void QDeclarativeWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeWebView); + + QMouseEvent *me = sceneMouseEventToMouseEvent(event); + if (d->pressTimer.isActive()) { + if ((me->pos() - d->pressPoint).manhattanLength() > QApplication::startDragDistance()) { + d->pressTimer.stop(); + } + } + if (keepMouseGrab()) { + page()->event(me); + event->setAccepted( +/* + It is not correct to send the press event upwards, if it is not accepted by WebKit + e.g. push button does not work, if done so as QGraphicsScene will not send the release event at all to WebKit + Might be a bug in WebKit, though + */ +#if 1 // QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + } + delete me; + if (!event->isAccepted()) + QDeclarativePaintedItem::mouseMoveEvent(event); + +} +void QDeclarativeWebView::hoverMoveEvent (QGraphicsSceneHoverEvent * event) +{ + QMouseEvent *me = sceneHoverMoveEventToMouseEvent(event); + page()->event(me); + event->setAccepted( +#if QT_VERSION <= 0x040500 // XXX see bug 230835 + true +#else + me->isAccepted() +#endif + ); + delete me; + if (!event->isAccepted()) + QDeclarativePaintedItem::hoverMoveEvent(event); +} + +void QDeclarativeWebView::keyPressEvent(QKeyEvent* event) +{ + page()->event(event); + if (!event->isAccepted()) + QDeclarativePaintedItem::keyPressEvent(event); +} + +void QDeclarativeWebView::keyReleaseEvent(QKeyEvent* event) +{ + page()->event(event); + if (!event->isAccepted()) + QDeclarativePaintedItem::keyReleaseEvent(event); +} + +bool QDeclarativeWebView::sceneEvent(QEvent *event) +{ + if (event->type() == QEvent::KeyPress) { + QKeyEvent *k = static_cast(event); + if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) { + if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? + page()->event(event); + if (event->isAccepted()) + return true; + } + } + } + return QDeclarativePaintedItem::sceneEvent(event); +} + + +/*! + \qmlproperty action WebView::back + This property holds the action for causing the previous URL in the history to be displayed. +*/ +QAction *QDeclarativeWebView::backAction() const +{ + return page()->action(QWebPage::Back); +} + +/*! + \qmlproperty action WebView::forward + This property holds the action for causing the next URL in the history to be displayed. +*/ +QAction *QDeclarativeWebView::forwardAction() const +{ + return page()->action(QWebPage::Forward); +} + +/*! + \qmlproperty action WebView::reload + This property holds the action for reloading with the current URL +*/ +QAction *QDeclarativeWebView::reloadAction() const +{ + return page()->action(QWebPage::Reload); +} + +/*! + \qmlproperty action WebView::stop + This property holds the action for stopping loading with the current URL +*/ +QAction *QDeclarativeWebView::stopAction() const +{ + return page()->action(QWebPage::Stop); +} + +/*! + \qmlproperty real WebView::title + This property holds the title of the web page currently viewed + + By default, this property contains an empty string. +*/ +QString QDeclarativeWebView::title() const +{ + return page()->mainFrame()->title(); +} + + + +/*! + \qmlproperty pixmap WebView::icon + This property holds the icon associated with the web page currently viewed +*/ +QPixmap QDeclarativeWebView::icon() const +{ + return page()->mainFrame()->icon().pixmap(QSize(256,256)); +} + + +/*! + \qmlproperty real WebView::zoomFactor + This property holds the multiplier used to scale the contents of a Web page. +*/ +void QDeclarativeWebView::setZoomFactor(qreal factor) +{ + Q_D(QDeclarativeWebView); + if (factor == page()->mainFrame()->zoomFactor()) + return; + + page()->mainFrame()->setZoomFactor(factor); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth*factor : width()*factor, + d->preferredheight>0 ? d->preferredheight*factor : height()*factor)); + expandToWebPage(); + + emit zoomFactorChanged(); +} + +qreal QDeclarativeWebView::zoomFactor() const +{ + return page()->mainFrame()->zoomFactor(); +} + +/*! + \qmlproperty string WebView::statusText + + This property is the current status suggested by the current web page. In a web browser, + such status is often shown in some kind of status bar. +*/ +void QDeclarativeWebView::setStatusText(const QString& s) +{ + Q_D(QDeclarativeWebView); + d->statusText = s; + emit statusTextChanged(); +} + +void QDeclarativeWebView::windowObjectCleared() +{ + Q_D(QDeclarativeWebView); + d->updateWindowObjects(); +} + +QString QDeclarativeWebView::statusText() const +{ + Q_D(const QDeclarativeWebView); + return d->statusText; +} + +QWebPage *QDeclarativeWebView::page() const +{ + Q_D(const QDeclarativeWebView); + + if (!d->page) { + QDeclarativeWebView *self = const_cast(this); + QWebPage *wp = new QDeclarativeWebPage(self); + + // QML items don't default to having a background, + // even though most we pages will set one anyway. + QPalette pal = QApplication::palette(); + pal.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0)); + wp->setPalette(pal); + + wp->setNetworkAccessManager(qmlEngine(this)->networkAccessManager()); + + self->setPage(wp); + + return wp; + } + + return d->page; +} + + +// The QObject interface to settings(). +/*! + \qmlproperty string WebView::settings.standardFontFamily + \qmlproperty string WebView::settings.fixedFontFamily + \qmlproperty string WebView::settings.serifFontFamily + \qmlproperty string WebView::settings.sansSerifFontFamily + \qmlproperty string WebView::settings.cursiveFontFamily + \qmlproperty string WebView::settings.fantasyFontFamily + + \qmlproperty int WebView::settings.minimumFontSize + \qmlproperty int WebView::settings.minimumLogicalFontSize + \qmlproperty int WebView::settings.defaultFontSize + \qmlproperty int WebView::settings.defaultFixedFontSize + + \qmlproperty bool WebView::settings.autoLoadImages + \qmlproperty bool WebView::settings.javascriptEnabled + \qmlproperty bool WebView::settings.javaEnabled + \qmlproperty bool WebView::settings.pluginsEnabled + \qmlproperty bool WebView::settings.privateBrowsingEnabled + \qmlproperty bool WebView::settings.javascriptCanOpenWindows + \qmlproperty bool WebView::settings.javascriptCanAccessClipboard + \qmlproperty bool WebView::settings.developerExtrasEnabled + \qmlproperty bool WebView::settings.linksIncludedInFocusChain + \qmlproperty bool WebView::settings.zoomTextOnly + \qmlproperty bool WebView::settings.printElementBackgrounds + \qmlproperty bool WebView::settings.offlineStorageDatabaseEnabled + \qmlproperty bool WebView::settings.offlineWebApplicationCacheEnabled + \qmlproperty bool WebView::settings.localStorageDatabaseEnabled + \qmlproperty bool WebView::settings.localContentCanAccessRemoteUrls + + These properties give access to the settings controlling the web view. + + See QWebSettings for details of these properties. + + \qml + WebView { + settings.pluginsEnabled: true + settings.standardFontFamily: "Arial" + ... + } + \endqml +*/ +QObject *QDeclarativeWebView::settingsObject() const +{ + Q_D(const QDeclarativeWebView); + d->settings.s = page()->settings(); + return &d->settings; +} + +void QDeclarativeWebView::setPage(QWebPage *page) +{ + Q_D(QDeclarativeWebView); + if (d->page == page) + return; + if (d->page) { + if (d->page->parent() == this) { + delete d->page; + } else { + d->page->disconnect(this); + } + } + d->page = page; + d->page->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + d->page->mainFrame()->setScrollBarPolicy(Qt::Horizontal,Qt::ScrollBarAlwaysOff); + d->page->mainFrame()->setScrollBarPolicy(Qt::Vertical,Qt::ScrollBarAlwaysOff); + connect(d->page,SIGNAL(repaintRequested(QRect)),this,SLOT(paintPage(QRect))); + connect(d->page->mainFrame(),SIGNAL(urlChanged(QUrl)),this,SLOT(pageUrlChanged())); + connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString))); + connect(d->page->mainFrame(), SIGNAL(titleChanged(QString)), this, SIGNAL(iconChanged())); + connect(d->page->mainFrame(), SIGNAL(iconChanged()), this, SIGNAL(iconChanged())); + connect(d->page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), this, SLOT(noteContentsSizeChanged(QSize))); + connect(d->page->mainFrame(), SIGNAL(initialLayoutCompleted()), this, SLOT(initialLayout())); + + connect(d->page,SIGNAL(loadStarted()),this,SLOT(doLoadStarted())); + connect(d->page,SIGNAL(loadProgress(int)),this,SLOT(doLoadProgress(int))); + connect(d->page,SIGNAL(loadFinished(bool)),this,SLOT(doLoadFinished(bool))); + connect(d->page,SIGNAL(statusBarMessage(QString)),this,SLOT(setStatusText(QString))); + + connect(d->page->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(windowObjectCleared())); +} + +/*! + \qmlsignal WebView::onLoadStarted() + + This handler is called when the web engine begins loading + a page. Later, WebView::onLoadFinished() or WebView::onLoadFailed() + will be emitted. +*/ + +/*! + \qmlsignal WebView::onLoadFinished() + + This handler is called when the web engine \e successfully + finishes loading a page, including any component content + (WebView::onLoadFailed() will be emitted otherwise). + + \sa progress +*/ + +/*! + \qmlsignal WebView::onLoadFailed() + + This handler is called when the web engine fails loading + a page or any component content + (WebView::onLoadFinished() will be emitted on success). +*/ + +void QDeclarativeWebView::load(const QNetworkRequest &request, + QNetworkAccessManager::Operation operation, + const QByteArray &body) +{ + page()->mainFrame()->load(request, operation, body); +} + +QString QDeclarativeWebView::html() const +{ + return page()->mainFrame()->toHtml(); +} + +/*! + \qmlproperty string WebView::html + This property holds HTML text set directly + + The html property can be set as a string. + + \qml + WebView { + html: "

This is HTML." + } + \endqml +*/ +void QDeclarativeWebView::setHtml(const QString &html, const QUrl &baseUrl) +{ + Q_D(QDeclarativeWebView); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + if (isComponentComplete()) + page()->mainFrame()->setHtml(html, baseUrl); + else { + d->pending = d->PendingHtml; + d->pending_url = baseUrl; + d->pending_string = html; + } + emit htmlChanged(); +} + +void QDeclarativeWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) +{ + Q_D(QDeclarativeWebView); + page()->setViewportSize(QSize( + d->preferredwidth>0 ? d->preferredwidth : width(), + d->preferredheight>0 ? d->preferredheight : height())); + + if (isComponentComplete()) + page()->mainFrame()->setContent(data,mimeType,qmlContext(this)->resolvedUrl(baseUrl)); + else { + d->pending = d->PendingContent; + d->pending_url = baseUrl; + d->pending_string = mimeType; + d->pending_data = data; + } +} + +QWebHistory *QDeclarativeWebView::history() const +{ + return page()->history(); +} + +QWebSettings *QDeclarativeWebView::settings() const +{ + return page()->settings(); +} + +QDeclarativeWebView *QDeclarativeWebView::createWindow(QWebPage::WebWindowType type) +{ + Q_D(QDeclarativeWebView); + switch (type) { + case QWebPage::WebBrowserWindow: { + if (!d->newWindowComponent && d->newWindowParent) + qWarning("WebView::newWindowComponent not set - WebView::newWindowParent ignored"); + else if (d->newWindowComponent && !d->newWindowParent) + qWarning("WebView::newWindowParent not set - WebView::newWindowComponent ignored"); + else if (d->newWindowComponent && d->newWindowParent) { + QDeclarativeWebView *webview = 0; + QDeclarativeContext *windowContext = new QDeclarativeContext(qmlContext(this)); + + QObject *nobj = d->newWindowComponent->create(windowContext); + if (nobj) { + windowContext->setParent(nobj); + QDeclarativeItem *item = qobject_cast(nobj); + if (!item) { + delete nobj; + } else { + webview = item->findChild(); + if (!webview) { + delete item; + } else { + nobj->setParent(d->newWindowParent); + static_cast(item)->setParentItem(d->newWindowParent); + } + } + } else { + delete windowContext; + } + + return webview; + } + } + break; + case QWebPage::WebModalDialog: { + // Not supported + } + } + return 0; +} + +/*! + \qmlproperty component WebView::newWindowComponent + + This property holds the component to use for new windows. + The component must have a WebView somewhere in its structure. + + When the web engine requests a new window, it will be an instance of + this component. + + The parent of the new window is set by newWindowParent. It must be set. +*/ +QDeclarativeComponent *QDeclarativeWebView::newWindowComponent() const +{ + Q_D(const QDeclarativeWebView); + return d->newWindowComponent; +} + +void QDeclarativeWebView::setNewWindowComponent(QDeclarativeComponent *newWindow) +{ + Q_D(QDeclarativeWebView); + if (newWindow == d->newWindowComponent) + return; + d->newWindowComponent = newWindow; + emit newWindowComponentChanged(); +} + + +/*! + \qmlproperty item WebView::newWindowParent + + The parent item for new windows. + + \sa newWindowComponent +*/ +QDeclarativeItem *QDeclarativeWebView::newWindowParent() const +{ + Q_D(const QDeclarativeWebView); + return d->newWindowParent; +} + +void QDeclarativeWebView::setNewWindowParent(QDeclarativeItem *parent) +{ + Q_D(QDeclarativeWebView); + if (parent == d->newWindowParent) + return; + if (d->newWindowParent && parent) { + QList children = d->newWindowParent->childItems(); + for (int i = 0; i < children.count(); ++i) { + children.at(i)->setParentItem(parent); + } + } + d->newWindowParent = parent; + emit newWindowParentChanged(); +} + +/*! + Returns the area of the largest element at position (\a x,\a y) that is no larger + than \a maxwidth by \a maxheight pixels. + + May return an area larger in the case when no smaller element is at the position. +*/ +QRect QDeclarativeWebView::elementAreaAt(int x, int y, int maxwidth, int maxheight) const +{ + QWebHitTestResult hit = page()->mainFrame()->hitTestContent(QPoint(x,y)); + QRect rv = hit.boundingRect(); + QWebElement element = hit.enclosingBlockElement(); + if (maxwidth<=0) maxwidth = INT_MAX; + if (maxheight<=0) maxheight = INT_MAX; + while (!element.parent().isNull() && element.geometry().width() <= maxwidth && element.geometry().height() <= maxheight) { + rv = element.geometry(); + element = element.parent(); + } + return rv; +} + +/*! + \internal + \class QDeclarativeWebPage + \brief The QDeclarativeWebPage class is a QWebPage that can create QML plugins. + + \sa QDeclarativeWebView +*/ +QDeclarativeWebPage::QDeclarativeWebPage(QDeclarativeWebView *parent) : + QWebPage(parent) +{ +} + +QDeclarativeWebPage::~QDeclarativeWebPage() +{ +} + +void QDeclarativeWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) +{ + qWarning() << sourceID << ':' << lineNumber << ':' << message; +} + +QString QDeclarativeWebPage::chooseFile(QWebFrame *originatingFrame, const QString& oldFile) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(oldFile) + return oldFile; +} + +void QDeclarativeWebPage::javaScriptAlert(QWebFrame *originatingFrame, const QString& msg) +{ + Q_UNUSED(originatingFrame) + emit viewItem()->alert(msg); +} + +bool QDeclarativeWebPage::javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(msg) + return false; +} + +bool QDeclarativeWebPage::javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result) +{ + // Not supported (it's modal) + Q_UNUSED(originatingFrame) + Q_UNUSED(msg) + Q_UNUSED(defaultValue) + Q_UNUSED(result) + return false; +} + + +/* + Qt WebKit does not understand non-QWidget plugins, so dummy widgets + are created, parented to a single dummy tool window. + + The requirements for QML object plugins are input to the Qt WebKit + non-QWidget plugin support, which will obsolete this kludge. +*/ +class QWidget_Dummy_Plugin : public QWidget +{ + Q_OBJECT +public: + static QWidget *dummy_shared_parent() + { + static QWidget *dsp = 0; + if (!dsp) { + dsp = new QWidget(0,Qt::Tool); + dsp->setGeometry(-10000,-10000,0,0); + dsp->show(); + } + return dsp; + } + QWidget_Dummy_Plugin(const QUrl& url, QDeclarativeWebView *view, const QStringList ¶mNames, const QStringList ¶mValues) : + QWidget(dummy_shared_parent()), + propertyNames(paramNames), + propertyValues(paramValues), + webview(view) + { + QDeclarativeEngine *engine = qmlEngine(webview); + component = new QDeclarativeComponent(engine, url, this); + item = 0; + if (component->isLoading()) + connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(qmlLoaded())); + else + qmlLoaded(); + } + +public Q_SLOTS: + void qmlLoaded() + { + if (component->isError()) { + // ### Could instead give these errors to the WebView to handle. + qWarning() << component->errors(); + return; + } + item = qobject_cast(component->create(qmlContext(webview))); + item->setParent(webview); + QString jsObjName; + for (int i=0; isetProperty(propertyNames[i].toUtf8(),propertyValues[i]); + if (propertyNames[i] == QLatin1String("objectname")) + jsObjName = propertyValues[i]; + } + } + if (!jsObjName.isNull()) { + QWebFrame *f = webview->page()->mainFrame(); + f->addToJavaScriptWindowObject(jsObjName, item); + } + resizeEvent(0); + delete component; + component = 0; + } + void resizeEvent(QResizeEvent*) + { + if (item) { + item->setX(x()); + item->setY(y()); + item->setWidth(width()); + item->setHeight(height()); + } + } + +private: + QDeclarativeComponent *component; + QDeclarativeItem *item; + QStringList propertyNames, propertyValues; + QDeclarativeWebView *webview; +}; + +QDeclarativeWebView *QDeclarativeWebPage::viewItem() +{ + return static_cast(parent()); +} + +QObject *QDeclarativeWebPage::createPlugin(const QString &, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) +{ + QUrl comp = qmlContext(viewItem())->resolvedUrl(url); + return new QWidget_Dummy_Plugin(comp,viewItem(),paramNames,paramValues); +} + +QWebPage *QDeclarativeWebPage::createWindow(WebWindowType type) +{ + QDeclarativeWebView *newView = viewItem()->createWindow(type); + if (newView) + return newView->page(); + return 0; +} + +QT_END_NAMESPACE + +#include diff --git a/src/imports/webkit/qdeclarativewebview_p.h b/src/imports/webkit/qdeclarativewebview_p.h new file mode 100644 index 0000000..5efc3b5 --- /dev/null +++ b/src/imports/webkit/qdeclarativewebview_p.h @@ -0,0 +1,287 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef QDECLARATIVEWEBVIEW_H +#define QDECLARATIVEWEBVIEW_H + +#include "webkitqmlplugin_export.h" + +#include + +#include +#include +#include +#include + +QT_BEGIN_HEADER + +class QWebHistory; +class QWebSettings; + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) +class QDeclarativeWebViewPrivate; +class QNetworkRequest; +class QDeclarativeWebView; + +class WEBKITQMLPLUGIN_EXPORT QDeclarativeWebPage : public QWebPage +{ + Q_OBJECT +public: + explicit QDeclarativeWebPage(QDeclarativeWebView *parent); + ~QDeclarativeWebPage(); +protected: + QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); + QWebPage *createWindow(WebWindowType type); + void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); + QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); + void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); + bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); + bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); + +private: + QDeclarativeWebView *viewItem(); +}; + + +class QDeclarativeWebViewAttached; + +//### TODO: browser plugins + +class WEBKITQMLPLUGIN_EXPORT QDeclarativeWebView : public QDeclarativePaintedItem +{ + Q_OBJECT + + Q_ENUMS(Status SelectionMode) + + Q_PROPERTY(QString title READ title NOTIFY titleChanged) + Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged) + Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor NOTIFY zoomFactorChanged) + Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged) + + Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged) + + Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime NOTIFY pressGrabTimeChanged) + + Q_PROPERTY(int preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged) + Q_PROPERTY(int preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged) + Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) + Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) + Q_PROPERTY(Status status READ status NOTIFY statusChanged) + + Q_PROPERTY(QAction* reload READ reloadAction CONSTANT) + Q_PROPERTY(QAction* back READ backAction CONSTANT) + Q_PROPERTY(QAction* forward READ forwardAction CONSTANT) + Q_PROPERTY(QAction* stop READ stopAction CONSTANT) + + Q_PROPERTY(QObject* settings READ settingsObject CONSTANT) + + Q_PROPERTY(QDeclarativeListProperty javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT) + + Q_PROPERTY(QDeclarativeComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent NOTIFY newWindowComponentChanged) + Q_PROPERTY(QDeclarativeItem* newWindowParent READ newWindowParent WRITE setNewWindowParent NOTIFY newWindowParentChanged) + + Q_PROPERTY(bool renderingEnabled READ renderingEnabled WRITE setRenderingEnabled NOTIFY renderingEnabledChanged) + +public: + QDeclarativeWebView(QDeclarativeItem *parent=0); + ~QDeclarativeWebView(); + + QUrl url() const; + void setUrl(const QUrl &); + + QString title() const; + + QPixmap icon() const; + + qreal zoomFactor() const; + void setZoomFactor(qreal); + Q_INVOKABLE bool heuristicZoom(int clickX, int clickY, qreal maxzoom); + QRect elementAreaAt(int x, int y, int minwidth, int minheight) const; + + int pressGrabTime() const; + void setPressGrabTime(int); + + int preferredWidth() const; + void setPreferredWidth(int); + int preferredHeight() const; + void setPreferredHeight(int); + + enum Status { Null, Ready, Loading, Error }; + Status status() const; + qreal progress() const; + QString statusText() const; + + QAction *reloadAction() const; + QAction *backAction() const; + QAction *forwardAction() const; + QAction *stopAction() const; + + QWebPage *page() const; + void setPage(QWebPage *page); + + void load(const QNetworkRequest &request, + QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, + const QByteArray &body = QByteArray()); + + QString html() const; + + void setHtml(const QString &html, const QUrl &baseUrl = QUrl()); + void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl()); + + QWebHistory *history() const; + QWebSettings *settings() const; + QObject *settingsObject() const; + + bool renderingEnabled() const; + void setRenderingEnabled(bool); + + QDeclarativeListProperty javaScriptWindowObjects(); + + static QDeclarativeWebViewAttached *qmlAttachedProperties(QObject *); + + QDeclarativeComponent *newWindowComponent() const; + void setNewWindowComponent(QDeclarativeComponent *newWindow); + QDeclarativeItem *newWindowParent() const; + void setNewWindowParent(QDeclarativeItem *newWindow); + +Q_SIGNALS: + void preferredWidthChanged(); + void preferredHeightChanged(); + void urlChanged(); + void progressChanged(); + void statusChanged(Status); + void titleChanged(const QString&); + void iconChanged(); + void statusTextChanged(); + void htmlChanged(); + void pressGrabTimeChanged(); + void zoomFactorChanged(); + void newWindowComponentChanged(); + void newWindowParentChanged(); + void renderingEnabledChanged(); + + void loadStarted(); + void loadFinished(); + void loadFailed(); + + void doubleClick(int clickX, int clickY); + + void zoomTo(qreal zoom, int centerX, int centerY); + + void alert(const QString& message); + +public Q_SLOTS: + QVariant evaluateJavaScript(const QString&); + +private Q_SLOTS: + void expandToWebPage(); + void paintPage(const QRect&); + void doLoadStarted(); + void doLoadProgress(int p); + void doLoadFinished(bool ok); + void setStatusText(const QString&); + void windowObjectCleared(); + void pageUrlChanged(); + void noteContentsSizeChanged(const QSize&); + void initialLayout(); + +protected: + void drawContents(QPainter *, const QRect &); + + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void timerEvent(QTimerEvent *event); + void hoverMoveEvent (QGraphicsSceneHoverEvent * event); + void keyPressEvent(QKeyEvent* event); + void keyReleaseEvent(QKeyEvent* event); + virtual void geometryChanged(const QRectF &newGeometry, + const QRectF &oldGeometry); + virtual void focusChanged(bool); + virtual bool sceneEvent(QEvent *event); + QDeclarativeWebView *createWindow(QWebPage::WebWindowType type); + +private: + void init(); + virtual void componentComplete(); + Q_DISABLE_COPY(QDeclarativeWebView) + Q_DECLARE_PRIVATE_D(QGraphicsItem::d_ptr.data(), QDeclarativeWebView) + QMouseEvent *sceneMouseEventToMouseEvent(QGraphicsSceneMouseEvent *); + QMouseEvent *sceneHoverMoveEventToMouseEvent(QGraphicsSceneHoverEvent *); + friend class QDeclarativeWebPage; +}; + +class QDeclarativeWebViewAttached : public QObject +{ + Q_OBJECT + Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName) +public: + QDeclarativeWebViewAttached(QObject *parent) + : QObject(parent) + { + } + + QString windowObjectName() const + { + return m_windowObjectName; + } + + void setWindowObjectName(const QString &n) + { + m_windowObjectName = n; + } + +private: + QString m_windowObjectName; +}; + + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QDeclarativeWebView) +QML_DECLARE_TYPEINFO(QDeclarativeWebView, QML_HAS_ATTACHED_PROPERTIES) + +QT_END_HEADER + +#endif diff --git a/src/imports/webkit/qdeclarativewebview_p_p.h b/src/imports/webkit/qdeclarativewebview_p_p.h new file mode 100644 index 0000000..258b472 --- /dev/null +++ b/src/imports/webkit/qdeclarativewebview_p_p.h @@ -0,0 +1,151 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef QDECLARATIVEWEBVIEW_P_H +#define QDECLARATIVEWEBVIEW_P_H + +#include + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +class QDeclarativeWebSettings : public QObject { + Q_OBJECT + + Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily) + Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily) + Q_PROPERTY(QString serifFontFamily READ serifFontFamily WRITE setSerifFontFamily) + Q_PROPERTY(QString sansSerifFontFamily READ sansSerifFontFamily WRITE setSansSerifFontFamily) + Q_PROPERTY(QString cursiveFontFamily READ cursiveFontFamily WRITE setCursiveFontFamily) + Q_PROPERTY(QString fantasyFontFamily READ fantasyFontFamily WRITE setFantasyFontFamily) + + Q_PROPERTY(int minimumFontSize READ minimumFontSize WRITE setMinimumFontSize) + Q_PROPERTY(int minimumLogicalFontSize READ minimumLogicalFontSize WRITE setMinimumLogicalFontSize) + Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize) + Q_PROPERTY(int defaultFixedFontSize READ defaultFixedFontSize WRITE setDefaultFixedFontSize) + + Q_PROPERTY(bool autoLoadImages READ autoLoadImages WRITE setAutoLoadImages) + Q_PROPERTY(bool javascriptEnabled READ javascriptEnabled WRITE setJavascriptEnabled) + Q_PROPERTY(bool javaEnabled READ javaEnabled WRITE setJavaEnabled) + Q_PROPERTY(bool pluginsEnabled READ pluginsEnabled WRITE setPluginsEnabled) + Q_PROPERTY(bool privateBrowsingEnabled READ privateBrowsingEnabled WRITE setPrivateBrowsingEnabled) + Q_PROPERTY(bool javascriptCanOpenWindows READ javascriptCanOpenWindows WRITE setJavascriptCanOpenWindows) + Q_PROPERTY(bool javascriptCanAccessClipboard READ javascriptCanAccessClipboard WRITE setJavascriptCanAccessClipboard) + Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled) + Q_PROPERTY(bool linksIncludedInFocusChain READ linksIncludedInFocusChain WRITE setLinksIncludedInFocusChain) + Q_PROPERTY(bool zoomTextOnly READ zoomTextOnly WRITE setZoomTextOnly) + Q_PROPERTY(bool printElementBackgrounds READ printElementBackgrounds WRITE setPrintElementBackgrounds) + Q_PROPERTY(bool offlineStorageDatabaseEnabled READ offlineStorageDatabaseEnabled WRITE setOfflineStorageDatabaseEnabled) + Q_PROPERTY(bool offlineWebApplicationCacheEnabled READ offlineWebApplicationCacheEnabled WRITE setOfflineWebApplicationCacheEnabled) + Q_PROPERTY(bool localStorageDatabaseEnabled READ localStorageDatabaseEnabled WRITE setLocalStorageDatabaseEnabled) + Q_PROPERTY(bool localContentCanAccessRemoteUrls READ localContentCanAccessRemoteUrls WRITE setLocalContentCanAccessRemoteUrls) + +public: + QDeclarativeWebSettings() {} + + QString standardFontFamily() const { return s->fontFamily(QWebSettings::StandardFont); } + void setStandardFontFamily(const QString& f) { s->setFontFamily(QWebSettings::StandardFont,f); } + QString fixedFontFamily() const { return s->fontFamily(QWebSettings::FixedFont); } + void setFixedFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FixedFont,f); } + QString serifFontFamily() const { return s->fontFamily(QWebSettings::SerifFont); } + void setSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SerifFont,f); } + QString sansSerifFontFamily() const { return s->fontFamily(QWebSettings::SansSerifFont); } + void setSansSerifFontFamily(const QString& f) { s->setFontFamily(QWebSettings::SansSerifFont,f); } + QString cursiveFontFamily() const { return s->fontFamily(QWebSettings::CursiveFont); } + void setCursiveFontFamily(const QString& f) { s->setFontFamily(QWebSettings::CursiveFont,f); } + QString fantasyFontFamily() const { return s->fontFamily(QWebSettings::FantasyFont); } + void setFantasyFontFamily(const QString& f) { s->setFontFamily(QWebSettings::FantasyFont,f); } + + int minimumFontSize() const { return s->fontSize(QWebSettings::MinimumFontSize); } + void setMinimumFontSize(int size) { s->setFontSize(QWebSettings::MinimumFontSize,size); } + int minimumLogicalFontSize() const { return s->fontSize(QWebSettings::MinimumLogicalFontSize); } + void setMinimumLogicalFontSize(int size) { s->setFontSize(QWebSettings::MinimumLogicalFontSize,size); } + int defaultFontSize() const { return s->fontSize(QWebSettings::DefaultFontSize); } + void setDefaultFontSize(int size) { s->setFontSize(QWebSettings::DefaultFontSize,size); } + int defaultFixedFontSize() const { return s->fontSize(QWebSettings::DefaultFixedFontSize); } + void setDefaultFixedFontSize(int size) { s->setFontSize(QWebSettings::DefaultFixedFontSize,size); } + + bool autoLoadImages() const { return s->testAttribute(QWebSettings::AutoLoadImages); } + void setAutoLoadImages(bool on) { s->setAttribute(QWebSettings::AutoLoadImages, on); } + bool javascriptEnabled() const { return s->testAttribute(QWebSettings::JavascriptEnabled); } + void setJavascriptEnabled(bool on) { s->setAttribute(QWebSettings::JavascriptEnabled, on); } + bool javaEnabled() const { return s->testAttribute(QWebSettings::JavaEnabled); } + void setJavaEnabled(bool on) { s->setAttribute(QWebSettings::JavaEnabled, on); } + bool pluginsEnabled() const { return s->testAttribute(QWebSettings::PluginsEnabled); } + void setPluginsEnabled(bool on) { s->setAttribute(QWebSettings::PluginsEnabled, on); } + bool privateBrowsingEnabled() const { return s->testAttribute(QWebSettings::PrivateBrowsingEnabled); } + void setPrivateBrowsingEnabled(bool on) { s->setAttribute(QWebSettings::PrivateBrowsingEnabled, on); } + bool javascriptCanOpenWindows() const { return s->testAttribute(QWebSettings::JavascriptCanOpenWindows); } + void setJavascriptCanOpenWindows(bool on) { s->setAttribute(QWebSettings::JavascriptCanOpenWindows, on); } + bool javascriptCanAccessClipboard() const { return s->testAttribute(QWebSettings::JavascriptCanAccessClipboard); } + void setJavascriptCanAccessClipboard(bool on) { s->setAttribute(QWebSettings::JavascriptCanAccessClipboard, on); } + bool developerExtrasEnabled() const { return s->testAttribute(QWebSettings::DeveloperExtrasEnabled); } + void setDeveloperExtrasEnabled(bool on) { s->setAttribute(QWebSettings::DeveloperExtrasEnabled, on); } + bool linksIncludedInFocusChain() const { return s->testAttribute(QWebSettings::LinksIncludedInFocusChain); } + void setLinksIncludedInFocusChain(bool on) { s->setAttribute(QWebSettings::LinksIncludedInFocusChain, on); } + bool zoomTextOnly() const { return s->testAttribute(QWebSettings::ZoomTextOnly); } + void setZoomTextOnly(bool on) { s->setAttribute(QWebSettings::ZoomTextOnly, on); } + bool printElementBackgrounds() const { return s->testAttribute(QWebSettings::PrintElementBackgrounds); } + void setPrintElementBackgrounds(bool on) { s->setAttribute(QWebSettings::PrintElementBackgrounds, on); } + bool offlineStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::OfflineStorageDatabaseEnabled); } + void setOfflineStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, on); } + bool offlineWebApplicationCacheEnabled() const { return s->testAttribute(QWebSettings::OfflineWebApplicationCacheEnabled); } + void setOfflineWebApplicationCacheEnabled(bool on) { s->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, on); } + bool localStorageDatabaseEnabled() const { return s->testAttribute(QWebSettings::LocalStorageDatabaseEnabled); } + void setLocalStorageDatabaseEnabled(bool on) { s->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, on); } + bool localContentCanAccessRemoteUrls() const { return s->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls); } + void setLocalContentCanAccessRemoteUrls(bool on) { s->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, on); } + + QWebSettings *s; +}; + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QDeclarativeWebSettings) + +QT_END_HEADER + +#endif diff --git a/src/imports/webkit/qmldir b/src/imports/webkit/qmldir new file mode 100644 index 0000000..258aa2c --- /dev/null +++ b/src/imports/webkit/qmldir @@ -0,0 +1 @@ +plugin webkitqmlplugin diff --git a/src/imports/webkit/webkit.pro b/src/imports/webkit/webkit.pro new file mode 100644 index 0000000..76b46f1 --- /dev/null +++ b/src/imports/webkit/webkit.pro @@ -0,0 +1,19 @@ +TARGET = webkitqmlplugin +TARGETPATH = $$[QT_INSTALL_IMPORTS]/org/webkit +include(../qimportbase.pri) + +QT += webkit declarative +DEFINES += WEBKITQMLPLUGIN_EXPORTS + +SOURCES += qdeclarativewebview.cpp plugin.cpp +HEADERS += qdeclarativewebview_p.h \ + qdeclarativewebview_p_p.h \ + webkitqmlplugin_export.h + +QTDIR_build:DESTDIR = $$TARGETPATH +target.path = $$TARGETPATH + +qmldir.files += $$QT_BUILD_TREE/imports/org/webkit/qmldir +qmldir.path += $$TARGETPATH + +INSTALLS += target qmldir diff --git a/src/imports/webkit/webkitqmlplugin_export.h b/src/imports/webkit/webkitqmlplugin_export.h new file mode 100644 index 0000000..974fd24 --- /dev/null +++ b/src/imports/webkit/webkitqmlplugin_export.h @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef WEBKITQMLPLUGIN_EXPORT_H +#define WEBKITQMLPLUGIN_EXPORT_H + +#include + +#if defined WEBKITQMLPLUGIN_EXPORTS +# define WEBKITQMLPLUGIN_EXPORT Q_DECL_EXPORT +#else +# define WEBKITQMLPLUGIN_EXPORT Q_DECL_IMPORT +#endif + +#endif // WEBKITQMLPLUGIN_EXPORT_H diff --git a/src/imports/widgets/graphicslayouts.cpp b/src/imports/widgets/graphicslayouts.cpp new file mode 100644 index 0000000..fc15ad2 --- /dev/null +++ b/src/imports/widgets/graphicslayouts.cpp @@ -0,0 +1,260 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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 "graphicslayouts_p.h" + +#include +#include + +QT_BEGIN_NAMESPACE + +LinearLayoutAttached::LinearLayoutAttached(QObject *parent) +: QObject(parent), _stretch(1), _alignment(Qt::AlignCenter) +{ +} + +void LinearLayoutAttached::setStretchFactor(int f) +{ + if (_stretch == f) + return; + + _stretch = f; + emit stretchChanged(reinterpret_cast(parent()), _stretch); +} + +void LinearLayoutAttached::setAlignment(Qt::Alignment a) +{ + if (_alignment == a) + return; + + _alignment = a; + emit alignmentChanged(reinterpret_cast(parent()), _alignment); +} + +QGraphicsLinearLayoutStretchItemObject::QGraphicsLinearLayoutStretchItemObject(QObject *parent) + : QObject(parent) +{ +} + +QSizeF QGraphicsLinearLayoutStretchItemObject::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const +{ +Q_UNUSED(which); +Q_UNUSED(constraint); +return QSizeF(); +} + + +QGraphicsLinearLayoutObject::QGraphicsLinearLayoutObject(QObject *parent) +: QObject(parent) +{ +} + +QGraphicsLinearLayoutObject::~QGraphicsLinearLayoutObject() +{ +} + +void QGraphicsLinearLayoutObject::insertLayoutItem(int index, QGraphicsLayoutItem *item) +{ +insertItem(index, item); + +//connect attached properties +if (LinearLayoutAttached *obj = attachedProperties.value(item)) { + setStretchFactor(item, obj->stretchFactor()); + setAlignment(item, obj->alignment()); + QObject::connect(obj, SIGNAL(stretchChanged(QGraphicsLayoutItem*,int)), + this, SLOT(updateStretch(QGraphicsLayoutItem*,int))); + QObject::connect(obj, SIGNAL(alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment)), + this, SLOT(updateAlignment(QGraphicsLayoutItem*,Qt::Alignment))); + //### need to disconnect when widget is removed? +} +} + +//### is there a better way to do this? +void QGraphicsLinearLayoutObject::clearChildren() +{ +for (int i = 0; i < count(); ++i) + removeAt(i); +} + +void QGraphicsLinearLayoutObject::updateStretch(QGraphicsLayoutItem *item, int stretch) +{ +QGraphicsLinearLayout::setStretchFactor(item, stretch); +} + +void QGraphicsLinearLayoutObject::updateAlignment(QGraphicsLayoutItem *item, Qt::Alignment alignment) +{ +QGraphicsLinearLayout::setAlignment(item, alignment); +} + +QHash QGraphicsLinearLayoutObject::attachedProperties; +LinearLayoutAttached *QGraphicsLinearLayoutObject::qmlAttachedProperties(QObject *obj) +{ +// ### This is not allowed - you must attach to any object +if (!qobject_cast(obj)) + return 0; +LinearLayoutAttached *rv = new LinearLayoutAttached(obj); +attachedProperties.insert(qobject_cast(obj), rv); +return rv; +} + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// QGraphicsGridLayout-related classes +////////////////////////////////////////////////////////////////////////////////////////////////////// +GridLayoutAttached::GridLayoutAttached(QObject *parent) +: QObject(parent), _row(-1), _column(-1), _rowspan(1), _colspan(1), _alignment(-1) +{ +} + +void GridLayoutAttached::setRow(int r) +{ + if (_row == r) + return; + + _row = r; + //emit rowChanged(reinterpret_cast(parent()), _row); +} + +void GridLayoutAttached::setColumn(int c) +{ + if (_column == c) + return; + + _column = c; + //emit columnChanged(reinterpret_cast(parent()), _column); +} + +void GridLayoutAttached::setRowSpan(int rs) +{ + if (_rowspan == rs) + return; + + _rowspan = rs; + //emit rowSpanChanged(reinterpret_cast(parent()), _rowSpan); +} + +void GridLayoutAttached::setColumnSpan(int cs) +{ + if (_colspan == cs) + return; + + _colspan = cs; + //emit columnSpanChanged(reinterpret_cast(parent()), _columnSpan); +} + +void GridLayoutAttached::setAlignment(Qt::Alignment a) +{ + if (_alignment == a) + return; + + _alignment = a; + //emit alignmentChanged(reinterpret_cast(parent()), _alignment); +} + +QGraphicsGridLayoutObject::QGraphicsGridLayoutObject(QObject *parent) +: QObject(parent) +{ +} + +QGraphicsGridLayoutObject::~QGraphicsGridLayoutObject() +{ +} + +void QGraphicsGridLayoutObject::addWidget(QGraphicsWidget *wid) +{ +//use attached properties +if (QObject *obj = attachedProperties.value(qobject_cast(wid))) { + int row = static_cast(obj)->row(); + int column = static_cast(obj)->column(); + int rowSpan = static_cast(obj)->rowSpan(); + int columnSpan = static_cast(obj)->columnSpan(); + if (row == -1 || column == -1) { + qWarning() << "Must set row and column for an item in a grid layout"; + return; + } + addItem(wid, row, column, rowSpan, columnSpan); +} +} + +void QGraphicsGridLayoutObject::addLayoutItem(QGraphicsLayoutItem *item) +{ +//use attached properties +if (GridLayoutAttached *obj = attachedProperties.value(item)) { + int row = obj->row(); + int column = obj->column(); + int rowSpan = obj->rowSpan(); + int columnSpan = obj->columnSpan(); + Qt::Alignment alignment = obj->alignment(); + if (row == -1 || column == -1) { + qWarning() << "Must set row and column for an item in a grid layout"; + return; + } + addItem(item, row, column, rowSpan, columnSpan); + if (alignment != -1) + setAlignment(item,alignment); +} +} + +//### is there a better way to do this? +void QGraphicsGridLayoutObject::clearChildren() +{ +for (int i = 0; i < count(); ++i) + removeAt(i); +} + +qreal QGraphicsGridLayoutObject::spacing() const +{ +if (verticalSpacing() == horizontalSpacing()) + return verticalSpacing(); +return -1; //### +} + +QHash QGraphicsGridLayoutObject::attachedProperties; +GridLayoutAttached *QGraphicsGridLayoutObject::qmlAttachedProperties(QObject *obj) +{ +// ### This is not allowed - you must attach to any object +if (!qobject_cast(obj)) + return 0; +GridLayoutAttached *rv = new GridLayoutAttached(obj); +attachedProperties.insert(qobject_cast(obj), rv); +return rv; +} + +QT_END_NAMESPACE diff --git a/src/imports/widgets/graphicslayouts_p.h b/src/imports/widgets/graphicslayouts_p.h new file mode 100644 index 0000000..f9b9ae8 --- /dev/null +++ b/src/imports/widgets/graphicslayouts_p.h @@ -0,0 +1,226 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef GRAPHICSLAYOUTS_H +#define GRAPHICSLAYOUTS_H + +#include "graphicswidgets_p.h" + +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +class QGraphicsLinearLayoutStretchItemObject : public QObject, public QGraphicsLayoutItem +{ + Q_OBJECT + Q_INTERFACES(QGraphicsLayoutItem) +public: + QGraphicsLinearLayoutStretchItemObject(QObject *parent = 0); + + virtual QSizeF sizeHint(Qt::SizeHint, const QSizeF &) const; +}; + +class LinearLayoutAttached; +class QGraphicsLinearLayoutObject : public QObject, public QGraphicsLinearLayout +{ + Q_OBJECT + Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation) + Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsLinearLayoutObject(QObject * = 0); + ~QGraphicsLinearLayoutObject(); + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } + + static LinearLayoutAttached *qmlAttachedProperties(QObject *); + +private Q_SLOTS: + void updateStretch(QGraphicsLayoutItem*,int); + void updateAlignment(QGraphicsLayoutItem*,Qt::Alignment); + +private: + friend class LinearLayoutAttached; + void clearChildren(); + void insertLayoutItem(int, QGraphicsLayoutItem *); + static QHash attachedProperties; + + static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { + static_cast(prop->object)->insertLayoutItem(-1, item); + } + + static void children_clear(QDeclarativeListProperty *prop) { + static_cast(prop->object)->clearChildren(); + } + + static int children_count(QDeclarativeListProperty *prop) { + return static_cast(prop->object)->count(); + } + + static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { + return static_cast(prop->object)->itemAt(index); + } +}; + +class GridLayoutAttached; +class QGraphicsGridLayoutObject : public QObject, public QGraphicsGridLayout +{ + Q_OBJECT + Q_INTERFACES(QGraphicsLayout QGraphicsLayoutItem) + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing) + Q_PROPERTY(qreal verticalSpacing READ verticalSpacing WRITE setVerticalSpacing) + Q_PROPERTY(qreal horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsGridLayoutObject(QObject * = 0); + ~QGraphicsGridLayoutObject(); + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append, children_count, children_at, children_clear); } + + qreal spacing() const; + + static GridLayoutAttached *qmlAttachedProperties(QObject *); + +private: + friend class GraphicsLayoutAttached; + void addWidget(QGraphicsWidget *); + void clearChildren(); + void addLayoutItem(QGraphicsLayoutItem *); + static QHash attachedProperties; + + static void children_append(QDeclarativeListProperty *prop, QGraphicsLayoutItem *item) { + static_cast(prop->object)->addLayoutItem(item); + } + + static void children_clear(QDeclarativeListProperty *prop) { + static_cast(prop->object)->clearChildren(); + } + + static int children_count(QDeclarativeListProperty *prop) { + return static_cast(prop->object)->count(); + } + + static QGraphicsLayoutItem *children_at(QDeclarativeListProperty *prop, int index) { + return static_cast(prop->object)->itemAt(index); + } +}; + +class LinearLayoutAttached : public QObject +{ + Q_OBJECT + + Q_PROPERTY(int stretchFactor READ stretchFactor WRITE setStretchFactor NOTIFY stretchChanged) + Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged) +public: + LinearLayoutAttached(QObject *parent); + + int stretchFactor() const { return _stretch; } + void setStretchFactor(int f); + Qt::Alignment alignment() const { return _alignment; } + void setAlignment(Qt::Alignment a); + +Q_SIGNALS: + void stretchChanged(QGraphicsLayoutItem*,int); + void alignmentChanged(QGraphicsLayoutItem*,Qt::Alignment); + +private: + int _stretch; + Qt::Alignment _alignment; +}; + +class GridLayoutAttached : public QObject +{ + Q_OBJECT + + Q_PROPERTY(int row READ row WRITE setRow) + Q_PROPERTY(int column READ column WRITE setColumn) + Q_PROPERTY(int rowSpan READ rowSpan WRITE setRowSpan) + Q_PROPERTY(int columnSpan READ columnSpan WRITE setColumnSpan) + Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment) +public: + GridLayoutAttached(QObject *parent); + + int row() const { return _row; } + void setRow(int r); + + int column() const { return _column; } + void setColumn(int c); + + int rowSpan() const { return _rowspan; } + void setRowSpan(int rs); + + int columnSpan() const { return _colspan; } + void setColumnSpan(int cs); + + Qt::Alignment alignment() const { return _alignment; } + void setAlignment(Qt::Alignment a); + +private: + int _row; + int _column; + int _rowspan; + int _colspan; + Qt::Alignment _alignment; +}; + +QT_END_NAMESPACE + +QML_DECLARE_INTERFACE(QGraphicsLayoutItem) +QML_DECLARE_INTERFACE(QGraphicsLayout) +QML_DECLARE_TYPE(QGraphicsLinearLayoutStretchItemObject) +QML_DECLARE_TYPE(QGraphicsLinearLayoutObject) +QML_DECLARE_TYPEINFO(QGraphicsLinearLayoutObject, QML_HAS_ATTACHED_PROPERTIES) +QML_DECLARE_TYPE(QGraphicsGridLayoutObject) +QML_DECLARE_TYPEINFO(QGraphicsGridLayoutObject, QML_HAS_ATTACHED_PROPERTIES) + +QT_END_HEADER + +#endif // GRAPHICSLAYOUTS_H diff --git a/src/imports/widgets/graphicswidgets.cpp b/src/imports/widgets/graphicswidgets.cpp new file mode 100644 index 0000000..062e516 --- /dev/null +++ b/src/imports/widgets/graphicswidgets.cpp @@ -0,0 +1,40 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ diff --git a/src/imports/widgets/graphicswidgets_p.h b/src/imports/widgets/graphicswidgets_p.h new file mode 100644 index 0000000..2c2b707 --- /dev/null +++ b/src/imports/widgets/graphicswidgets_p.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** 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 QtDeclarative module 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$ +** +****************************************************************************/ + +#ifndef GRAPHICSWIDGETS_H +#define GRAPHICSWIDGETS_H + +#include + +#include +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +QT_END_NAMESPACE + +QML_DECLARE_TYPE(QGraphicsView) +QML_DECLARE_TYPE_HASMETATYPE(QGraphicsScene) +QML_DECLARE_TYPE(QGraphicsWidget) +QML_DECLARE_TYPE(QGraphicsObject) +QML_DECLARE_INTERFACE_HASMETATYPE(QGraphicsItem) + +QT_END_HEADER + +#endif // GRAPHICSWIDGETS_H diff --git a/src/imports/widgets/qmldir b/src/imports/widgets/qmldir new file mode 100644 index 0000000..6f19878 --- /dev/null +++ b/src/imports/widgets/qmldir @@ -0,0 +1 @@ +plugin widgets diff --git a/src/imports/widgets/widgets.cpp b/src/imports/widgets/widgets.cpp new file mode 100644 index 0000000..ec21cc4 --- /dev/null +++ b/src/imports/widgets/widgets.cpp @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the plugins 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 +#include + +#include "graphicslayouts_p.h" +#include "graphicswidgets_p.h" + +QT_BEGIN_NAMESPACE + +class QGraphicsViewDeclarativeUI : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QGraphicsScene *scene READ scene WRITE setScene) + Q_CLASSINFO("DefaultProperty", "scene") +public: + QGraphicsViewDeclarativeUI(QObject *other) : QObject(other) {} + + QGraphicsScene *scene() const { return static_cast(parent())->scene(); } + void setScene(QGraphicsScene *scene) + { + static_cast(parent())->setScene(scene); + } +}; + +class QGraphicsSceneDeclarativeUI : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsSceneDeclarativeUI(QObject *other) : QObject(other) {} + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this->parent(), 0, children_append); } + +private: + static void children_append(QDeclarativeListProperty *prop, QObject *o) { + if (QGraphicsObject *go = qobject_cast(o)) + static_cast(prop->object)->addItem(go); + } +}; + +class QGraphicsWidgetDeclarativeUI : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QDeclarativeListProperty children READ children) + Q_PROPERTY(QGraphicsLayout *layout READ layout WRITE setLayout) + Q_CLASSINFO("DefaultProperty", "children") +public: + QGraphicsWidgetDeclarativeUI(QObject *other) : QObject(other) {} + + QDeclarativeListProperty children() { return QDeclarativeListProperty(this, 0, children_append); } + + QGraphicsLayout *layout() const { return static_cast(parent())->layout(); } + void setLayout(QGraphicsLayout *lo) + { + static_cast(parent())->setLayout(lo); + } + +private: + void setItemParent(QGraphicsItem *wid) + { + wid->setParentItem(static_cast(parent())); + } + + static void children_append(QDeclarativeListProperty *prop, QGraphicsItem *i) { + static_cast(prop->object)->setItemParent(i); + } +}; + +class QWidgetsQmlModule : public QDeclarativeExtensionPlugin +{ + Q_OBJECT +public: + virtual void registerTypes(const char *uri) + { + Q_ASSERT(QLatin1String(uri) == QLatin1String("Qt.widgets")); + + QML_REGISTER_INTERFACE(QGraphicsLayoutItem); + QML_REGISTER_INTERFACE(QGraphicsLayout); + qmlRegisterType(uri,4,6,"QGraphicsLinearLayoutStretchItem"); + qmlRegisterType(uri,4,6,"QGraphicsLinearLayout"); + qmlRegisterType(uri,4,6,"QGraphicsGridLayout"); + qmlRegisterExtendedType(uri,4,6,"QGraphicsView"); + qmlRegisterExtendedType(uri,4,6,"QGraphicsScene"); + qmlRegisterExtendedType(uri,4,6,"QGraphicsWidget"); + QML_REGISTER_INTERFACE(QGraphicsItem); + } +}; + +QT_END_NAMESPACE + +#include "widgets.moc" + +Q_EXPORT_PLUGIN2(qtwidgetsqmlmodule, QT_PREPEND_NAMESPACE(QWidgetsQmlModule)); + diff --git a/src/imports/widgets/widgets.pro b/src/imports/widgets/widgets.pro new file mode 100644 index 0000000..b98be59 --- /dev/null +++ b/src/imports/widgets/widgets.pro @@ -0,0 +1,22 @@ +TARGET = widgets +TARGETPATH = $$[QT_INSTALL_IMPORTS]/Qt/widgets +include(../qimportbase.pri) + +QT += declarative + +SOURCES += \ + graphicslayouts.cpp \ + widgets.cpp + +HEADERS += \ + graphicswidgets_p.h \ + graphicslayouts_p.h + +QTDIR_build:DESTDIR = $$QT_BUILD_TREE/imports/Qt/widgets +target.path = $$TARGETPATH + +# install qmldir file +qmldir.files += qmldir +qmldir.path = $$TARGETPATH + +INSTALLS += target qmldir diff --git a/src/src.pro b/src/src.pro index 2b9dc30..7bb731e 100644 --- a/src/src.pro +++ b/src/src.pro @@ -29,6 +29,7 @@ contains(QT_CONFIG, scripttools): SRC_SUBDIRS += src_scripttools contains(QT_CONFIG, declarative): SRC_SUBDIRS += src_declarative contains(QT_CONFIG, multimedia): SRC_SUBDIRS += src_multimedia SRC_SUBDIRS += src_plugins +contains(QT_CONFIG, declarative): SRC_SUBDIRS += src_imports src_s60main.subdir = $$QT_SOURCE_TREE/src/s60main src_s60main.target = sub-s60main @@ -70,6 +71,8 @@ src_activeqt.subdir = $$QT_SOURCE_TREE/src/activeqt src_activeqt.target = sub-activeqt src_plugins.subdir = $$QT_SOURCE_TREE/src/plugins src_plugins.target = sub-plugins +src_imports.subdir = $$QT_SOURCE_TREE/src/imports +src_imports.target = sub-imports src_testlib.subdir = $$QT_SOURCE_TREE/src/testlib src_testlib.target = sub-testlib src_javascriptcore.subdir = $$QT_SOURCE_TREE/src/3rdparty/webkit/JavaScriptCore @@ -103,11 +106,13 @@ src_declarative.target = sub-declarative src_tools_activeqt.depends = src_tools_idc src_gui src_declarative.depends = src_xml src_gui src_script src_network src_svg src_plugins.depends = src_gui src_sql src_svg src_multimedia + src_imports.depends = src_gui src_declarative contains(QT_CONFIG, webkit) { src_webkit.depends = src_gui src_sql src_network src_xml contains(QT_CONFIG, phonon):src_webkit.depends += src_phonon contains(QT_CONFIG, xmlpatterns): src_webkit.depends += src_xmlpatterns contains(QT_CONFIG, declarative):src_declarative.depends += src_webkit + src_imports.depends += webkit #exists($$QT_SOURCE_TREE/src/3rdparty/webkit/JavaScriptCore/JavaScriptCore.pro): src_webkit.depends += src_javascriptcore } contains(QT_CONFIG, qt3support): src_plugins.depends += src_qt3support @@ -117,6 +122,7 @@ src_declarative.target = sub-declarative } contains(QT_CONFIG, opengl)|contains(QT_CONFIG, opengles1)|contains(QT_CONFIG, opengles2): src_plugins.depends += src_opengl contains(QT_CONFIG, declarative): src_multimedia.depends += src_declarative + contains(QT_CONFIG, multimedia): src_imports += src_multimedia } !symbian { -- cgit v0.12 From d88f9fbe1522c48dfef153eef768f9eec123ec9e Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Wed, 3 Mar 2010 09:35:00 +1000 Subject: Make test more reliable. --- .../qdeclarativeanimations/tst_qdeclarativeanimations.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp b/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp index 0c166df..f5e15fb 100644 --- a/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp +++ b/tests/auto/declarative/qdeclarativeanimations/tst_qdeclarativeanimations.cpp @@ -217,11 +217,11 @@ void tst_qdeclarativeanimations::resume() animation.setProperty("x"); animation.setFrom(10); animation.setTo(200); - animation.setDuration(500); + animation.setDuration(1000); QVERIFY(animation.from() == 10); animation.start(); - QTest::qWait(200); + QTest::qWait(400); animation.pause(); qreal x = rect.x(); QVERIFY(x != qreal(200) && x != qreal(10)); @@ -231,7 +231,7 @@ void tst_qdeclarativeanimations::resume() animation.resume(); QVERIFY(animation.isRunning()); QVERIFY(!animation.isPaused()); - QTest::qWait(200); + QTest::qWait(400); animation.stop(); QVERIFY(rect.x() > x); } -- cgit v0.12 From eaf436568b2e6870a72e97baf2837d320f5d8ec8 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Wed, 3 Mar 2010 09:35:50 +1000 Subject: Initialize variable before use. --- src/declarative/util/qdeclarativeanimation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/util/qdeclarativeanimation.cpp b/src/declarative/util/qdeclarativeanimation.cpp index ebf1a20..7f4f1c0 100644 --- a/src/declarative/util/qdeclarativeanimation.cpp +++ b/src/declarative/util/qdeclarativeanimation.cpp @@ -2225,7 +2225,7 @@ struct PropertyUpdater : public QDeclarativeBulkValueUpdater bool fromSourced; bool fromDefined; bool *wasDeleted; - PropertyUpdater() : wasDeleted(0) {} + PropertyUpdater() : prevInterpolatorType(0), wasDeleted(0) {} ~PropertyUpdater() { if (wasDeleted) *wasDeleted = true; } void setValue(qreal v) { -- cgit v0.12 From 398f97c90f52a8927ac1efe3d7e272da900d6be3 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Wed, 3 Mar 2010 10:08:38 +1000 Subject: /src/imports/ now also contains plugins, so treat the same. --- tests/auto/headers/tst_headers.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/auto/headers/tst_headers.cpp b/tests/auto/headers/tst_headers.cpp index 3745767..12c5843 100644 --- a/tests/auto/headers/tst_headers.cpp +++ b/tests/auto/headers/tst_headers.cpp @@ -271,6 +271,7 @@ void tst_Headers::macros() if (header.endsWith("_p.h") || header.endsWith("_pch.h") || header.contains("global/qconfig-") || header.endsWith("/qconfig.h") || header.contains("/src/tools/") || header.contains("/src/plugins/") + || header.contains("/src/imports/") || header.endsWith("/qiconset.h") || header.endsWith("/qfeatures.h") || header.endsWith("qt_windows.h")) return; -- cgit v0.12