diff options
| author | Simon Hausmann <simon.hausmann@digia.com> | 2012-11-30 16:58:06 +0100 |
|---|---|---|
| committer | Simon Hausmann <simon.hausmann@digia.com> | 2012-11-30 17:03:09 +0100 |
| commit | 32ea33253afbbdefd2680aa95ab5f57455272ae7 (patch) | |
| tree | 2389569585b666c310fbb36d3fb8e6ab94462967 /Source/WebKit/qt/Api | |
| parent | 41c25f231cbca1babc445187283524cc6c751c71 (diff) | |
| download | qtwebkit-32ea33253afbbdefd2680aa95ab5f57455272ae7.tar.gz | |
Imported WebKit commit 6a4a1d32e1d779548c726c4826cba9d69eb87601 (http://svn.webkit.org/repository/webkit/trunk@136242)
Final import for the Qt 5.x series that implements the QtWebKit / QtWebKitWidgets split
Extra fixes will be cherry-picked.
Change-Id: I844f1ebb99c6d6b75db31d6538c2acd628e79681
Reviewed-by: Simon Hausmann <simon.hausmann@digia.com>
Diffstat (limited to 'Source/WebKit/qt/Api')
22 files changed, 14 insertions, 10633 deletions
diff --git a/Source/WebKit/qt/Api/qgraphicswebview.cpp b/Source/WebKit/qt/Api/qgraphicswebview.cpp deleted file mode 100644 index 84b4e801b..000000000 --- a/Source/WebKit/qt/Api/qgraphicswebview.cpp +++ /dev/null @@ -1,1197 +0,0 @@ -/* - Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2009 Girish Ramakrishnan <girish@forwardbias.in> - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" -#include "qgraphicswebview.h" - -#if !defined(QT_NO_GRAPHICSVIEW) - -#include "qwebframe.h" -#include "qwebframe_p.h" -#include "qwebpage.h" -#include "qwebpage_p.h" -#include "Page.h" -#include "PageClientQt.h" -#include "Frame.h" -#include "FrameView.h" -#include "GraphicsContext.h" -#include "IntRect.h" -#include "TiledBackingStore.h" -#include <qapplication.h> -#include <qgraphicsscene.h> -#include <qgraphicssceneevent.h> -#include <qgraphicsview.h> -#include <qscrollbar.h> -#include <qstyleoption.h> -#include <QtCore/qmetaobject.h> -#include <QtCore/qsharedpointer.h> -#include <QtCore/qtimer.h> -#include <QtGui/qpixmapcache.h> - -#if defined(Q_WS_X11) -#include <QX11Info> -#endif -#include <Settings.h> - -using namespace WebCore; - -class QGraphicsWebViewPrivate { -public: - QGraphicsWebViewPrivate(QGraphicsWebView* parent) - : q(parent) - , page(0) - , resizesToContents(false) - , renderHints(QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform) {} - - virtual ~QGraphicsWebViewPrivate(); - - void syncLayers(); - - void updateResizesToContentsForPage(); - - void detachCurrentPage(); - - void _q_doLoadFinished(bool success); - void _q_contentsSizeChanged(const QSize&); - void _q_scaleChanged(); - - void _q_pageDestroyed(); - - QGraphicsWebView* q; - QWebPage* page; - bool resizesToContents; - QPainter::RenderHints renderHints; - - QGraphicsItemOverlay* overlay() const - { - if (!page || !page->d->client) - return 0; - return pageClient()->overlay; - } - - PageClientQGraphicsWidget* pageClient() const - { - return static_cast<WebCore::PageClientQGraphicsWidget*> (page->d->client.data()); - } -}; - -QGraphicsWebViewPrivate::~QGraphicsWebViewPrivate() -{ - detachCurrentPage(); -} - -void QGraphicsWebViewPrivate::syncLayers() -{ -#if USE(ACCELERATED_COMPOSITING) - pageClient()->syncLayers(); -#endif -} - -void QGraphicsWebViewPrivate::_q_doLoadFinished(bool success) -{ - // If the page had no title, still make sure it gets the signal - if (q->title().isEmpty()) - emit q->urlChanged(q->url()); - - emit q->loadFinished(success); -} - -void QGraphicsWebViewPrivate::_q_pageDestroyed() -{ - page = 0; - q->setPage(0); -} - -void QGraphicsWebViewPrivate::updateResizesToContentsForPage() -{ - ASSERT(page); - pageClient()->viewResizesToContents = resizesToContents; - if (resizesToContents) { - // resizes to contents mode requires preferred contents size to be set - if (!page->preferredContentsSize().isValid()) - page->setPreferredContentsSize(QSize(960, 800)); - - QObject::connect(page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), - q, SLOT(_q_contentsSizeChanged(const QSize&)), Qt::UniqueConnection); - } else { - QObject::disconnect(page->mainFrame(), SIGNAL(contentsSizeChanged(QSize)), - q, SLOT(_q_contentsSizeChanged(const QSize&))); - } - page->d->page->mainFrame()->view()->setPaintsEntireContents(resizesToContents); - page->d->page->mainFrame()->view()->setDelegatesScrolling(resizesToContents); -} - -void QGraphicsWebViewPrivate::_q_contentsSizeChanged(const QSize& size) -{ - if (!resizesToContents) - return; - q->setGeometry(QRectF(q->geometry().topLeft(), size)); -} - -void QGraphicsWebViewPrivate::_q_scaleChanged() -{ -#if USE(TILED_BACKING_STORE) - if (!page) - return; - pageClient()->updateTiledBackingStoreScale(); -#endif -} - -/*! - \class QGraphicsWebView - \brief The QGraphicsWebView class allows Web content to be added to a GraphicsView. - \since 4.6 - - An instance of this class renders Web content from a URL or supplied as data, using - features of the QtWebKit module. - - If the width and height of the item are not set, they will default to 800 and 600, - respectively. If the Web page contents is larger than that, scrollbars will be shown - if not disabled explicitly. - - \section1 Browser Features - - Many of the functions, signals and properties provided by QWebView are also available - for this item, making it simple to adapt existing code to use QGraphicsWebView instead - of QWebView. - - The item uses a QWebPage object to perform the rendering of Web content, and this can - be obtained with the page() function, enabling the document itself to be accessed and - modified. - - As with QWebView, the item records the browsing history using a QWebHistory object, - accessible using the history() function. The QWebSettings object that defines the - configuration of the browser can be obtained with the settings() function, enabling - features like plugin support to be customized for each item. - - \sa QWebView, QGraphicsTextItem -*/ - -/*! - \fn void QGraphicsWebView::titleChanged(const QString &title) - - This signal is emitted whenever the \a title of the main frame changes. - - \sa title() -*/ - -/*! - \fn void QGraphicsWebView::urlChanged(const QUrl &url) - - This signal is emitted when the \a url of the view changes. - - \sa url(), load() -*/ - -/*! - \fn void QGraphicsWebView::iconChanged() - - This signal is emitted whenever the icon of the page is loaded or changes. - - In order for icons to be loaded, you will need to set an icon database path - using QWebSettings::setIconDatabasePath(). - - \sa icon(), QWebSettings::setIconDatabasePath() -*/ - -/*! - \fn void QGraphicsWebView::loadStarted() - - This signal is emitted when a new load of the page is started. - - \sa loadProgress(), loadFinished() -*/ - -/*! - \fn void QGraphicsWebView::loadFinished(bool ok) - - This signal is emitted when a load of the page is finished. - \a ok will indicate whether the load was successful or any error occurred. - - \sa loadStarted() -*/ - -/*! - Constructs an empty QGraphicsWebView with parent \a parent. - - \sa load() -*/ -QGraphicsWebView::QGraphicsWebView(QGraphicsItem* parent) - : QGraphicsWidget(parent) - , d(new QGraphicsWebViewPrivate(this)) -{ - setFlag(QGraphicsItem::ItemUsesExtendedStyleOption, true); - setAcceptDrops(true); - setAcceptHoverEvents(true); - setAcceptTouchEvents(true); - setFocusPolicy(Qt::StrongFocus); - setFlag(QGraphicsItem::ItemClipsChildrenToShape, true); -#if USE(TILED_BACKING_STORE) - QObject::connect(this, SIGNAL(scaleChanged()), this, SLOT(_q_scaleChanged())); -#endif -} - -/*! - Destroys the item. -*/ -QGraphicsWebView::~QGraphicsWebView() -{ - delete d; -} - -/*! - Returns a pointer to the underlying web page. - - \sa setPage() -*/ -QWebPage* QGraphicsWebView::page() const -{ - if (!d->page) { - QGraphicsWebView* that = const_cast<QGraphicsWebView*>(this); - QWebPage* page = new QWebPage(that); - - // Default to not having a background, in the case - // the page doesn't provide one. - QPalette palette = QApplication::palette(); - palette.setBrush(QPalette::Base, QColor::fromRgbF(0, 0, 0, 0)); - page->setPalette(palette); - - that->setPage(page); - } - - return d->page; -} - -/*! \reimp -*/ -void QGraphicsWebView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget*) -{ - QPainter::RenderHints oldHints = painter->renderHints(); - painter->setRenderHints(oldHints | d->renderHints); -#if USE(TILED_BACKING_STORE) - if (WebCore::TiledBackingStore* backingStore = QWebFramePrivate::core(page()->mainFrame())->tiledBackingStore()) { - // FIXME: We should set the backing store viewport earlier than in paint - backingStore->coverWithTilesIfNeeded(); - // QWebFrame::render is a public API, bypass it for tiled rendering so behavior does not need to change. - WebCore::GraphicsContext context(painter); - page()->mainFrame()->d->renderFromTiledBackingStore(&context, option->exposedRect.toAlignedRect()); - painter->setRenderHints(oldHints); - return; - } -#endif - page()->mainFrame()->render(painter, QWebFrame::AllLayers, option->exposedRect.toRect()); - painter->setRenderHints(oldHints); -} - -/*! \reimp -*/ -bool QGraphicsWebView::sceneEvent(QEvent* event) -{ - // Re-implemented in order to allows fixing event-related bugs in patch releases. - - if (d->page && (event->type() == QEvent::TouchBegin - || event->type() == QEvent::TouchEnd - || event->type() == QEvent::TouchUpdate - || event->type() == QEvent::TouchCancel - )) { - d->page->event(event); - - // Always return true so that we'll receive also TouchUpdate and TouchEnd events - return true; - } - - return QGraphicsWidget::sceneEvent(event); -} - -/*! \reimp -*/ -QVariant QGraphicsWebView::itemChange(GraphicsItemChange change, const QVariant& value) -{ - switch (change) { - // Differently from QWebView, it is interesting to QGraphicsWebView to handle - // post mouse cursor change notifications. Reason: 'ItemCursorChange' is sent - // as the first action in QGraphicsItem::setCursor implementation, and at that - // item widget's cursor has not been effectively changed yet. - // After cursor is properly set (at 'ItemCursorHasChanged' emission time), we - // fire 'CursorChange'. - case ItemCursorChange: - return value; - case ItemCursorHasChanged: { - QEvent event(QEvent::CursorChange); - QApplication::sendEvent(this, &event); - return value; - } - default: - break; - } - - return QGraphicsWidget::itemChange(change, value); -} - -/*! \reimp -*/ -QSizeF QGraphicsWebView::sizeHint(Qt::SizeHint which, const QSizeF& constraint) const -{ - if (which == Qt::PreferredSize) - return QSizeF(800, 600); // ### - return QGraphicsWidget::sizeHint(which, constraint); -} - -/*! \reimp -*/ -QVariant QGraphicsWebView::inputMethodQuery(Qt::InputMethodQuery query) const -{ - if (d->page) - return d->page->inputMethodQuery(query); - return QVariant(); -} - -/*! - \property QGraphicsWebView::renderHints - \since 4.8 - \brief the default render hints for the view - - These hints are used to initialize QPainter before painting the Web page. - - QPainter::TextAntialiasing and QPainter::SmoothPixmapTransform are enabled by default and will be - used to render the item in addition of what has been set on the painter given by QGraphicsScene. - - \sa QPainter::renderHints() -*/ - -/*! - \since 4.8 - Returns the render hints used by the view to render content. - - \sa QPainter::renderHints() -*/ -QPainter::RenderHints QGraphicsWebView::renderHints() const -{ - return d->renderHints; -} - -/*! - \since 4.8 - Sets the render hints used by the view to the specified \a hints. - - \sa QPainter::setRenderHints() -*/ -void QGraphicsWebView::setRenderHints(QPainter::RenderHints hints) -{ - if (hints == d->renderHints) - return; - d->renderHints = hints; - update(); -} - -/*! - \since 4.8 - If \a enabled is true, enables the specified render \a hint; otherwise - disables it. - - \sa renderHints, QPainter::renderHints() -*/ -void QGraphicsWebView::setRenderHint(QPainter::RenderHint hint, bool enabled) -{ - QPainter::RenderHints oldHints = d->renderHints; - if (enabled) - d->renderHints |= hint; - else - d->renderHints &= ~hint; - if (oldHints != d->renderHints) - update(); -} - -/*! \reimp -*/ -bool QGraphicsWebView::event(QEvent* event) -{ - // Re-implemented in order to allows fixing event-related bugs in patch releases. - - if (d->page) { - if (event->type() == QEvent::PaletteChange) - d->page->setPalette(palette()); -#ifndef QT_NO_CONTEXTMENU - if (event->type() == QEvent::GraphicsSceneContextMenu) { - if (!isEnabled()) - return false; - - QGraphicsSceneContextMenuEvent* ev = static_cast<QGraphicsSceneContextMenuEvent*>(event); - QContextMenuEvent fakeEvent(QContextMenuEvent::Reason(ev->reason()), ev->pos().toPoint()); - if (d->page->swallowContextMenuEvent(&fakeEvent)) { - event->accept(); - return true; - } - d->page->updatePositionDependentActions(fakeEvent.pos()); - } else -#endif // QT_NO_CONTEXTMENU - { -#ifndef QT_NO_CURSOR - if (event->type() == QEvent::CursorChange) { - // An unsetCursor will set the cursor to Qt::ArrowCursor. - // Thus this cursor change might be a QWidget::unsetCursor() - // If this is not the case and it came from WebCore, the - // QWebPageClient already has set its cursor internally - // to Qt::ArrowCursor, so updating the cursor is always - // right, as it falls back to the last cursor set by - // WebCore. - // FIXME: Add a QEvent::CursorUnset or similar to Qt. - if (cursor().shape() == Qt::ArrowCursor) - d->page->d->client->resetCursor(); - } -#endif - } - } - return QGraphicsWidget::event(event); -} - -void QGraphicsWebViewPrivate::detachCurrentPage() -{ - if (!page) - return; - - page->d->view = 0; - page->d->client.reset(); - - // if the page was created by us, we own it and need to - // destroy it as well. - - if (page->parent() == q) - delete page; - else - page->disconnect(q); - - page = 0; -} - -/*! - Makes \a page the new web page of the web graphicsitem. - - The parent QObject of the provided page remains the owner - of the object. If the current document is a child of the web - view, it will be deleted. - - \sa page() -*/ -void QGraphicsWebView::setPage(QWebPage* page) -{ - if (d->page == page) - return; - - d->detachCurrentPage(); - d->page = page; - - if (!d->page) - return; - - d->page->d->client.reset(new PageClientQGraphicsWidget(this, page)); - - if (d->overlay()) - d->overlay()->prepareGraphicsItemGeometryChange(); - - QSize size = geometry().size().toSize(); - page->setViewportSize(size); - - if (d->resizesToContents) - d->updateResizesToContentsForPage(); - - QWebFrame* mainFrame = d->page->mainFrame(); - - connect(mainFrame, SIGNAL(titleChanged(QString)), - this, SIGNAL(titleChanged(QString))); - connect(mainFrame, SIGNAL(iconChanged()), - this, SIGNAL(iconChanged())); - connect(mainFrame, SIGNAL(urlChanged(QUrl)), - this, SIGNAL(urlChanged(QUrl))); - connect(d->page, SIGNAL(loadStarted()), - this, SIGNAL(loadStarted())); - connect(d->page, SIGNAL(loadProgress(int)), - this, SIGNAL(loadProgress(int))); - connect(d->page, SIGNAL(loadFinished(bool)), - this, SLOT(_q_doLoadFinished(bool))); - connect(d->page, SIGNAL(statusBarMessage(QString)), - this, SIGNAL(statusBarMessage(QString))); - connect(d->page, SIGNAL(linkClicked(QUrl)), - this, SIGNAL(linkClicked(QUrl))); - connect(d->page, SIGNAL(destroyed()), - this, SLOT(_q_pageDestroyed())); -#if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS)) - connect(d->page, SIGNAL(microFocusChanged()), - this, SLOT(updateMicroFocus())); -#endif -} - -/*! - \property QGraphicsWebView::url - \brief the url of the web page currently viewed - - Setting this property clears the view and loads the URL. - - By default, this property contains an empty, invalid URL. - - \sa load(), urlChanged() -*/ - -void QGraphicsWebView::setUrl(const QUrl &url) -{ - page()->mainFrame()->setUrl(url); -} - -QUrl QGraphicsWebView::url() const -{ - if (d->page) - return d->page->mainFrame()->url(); - - return QUrl(); -} - -/*! - \property QGraphicsWebView::title - \brief the title of the web page currently viewed - - By default, this property contains an empty string. - - \sa titleChanged() -*/ -QString QGraphicsWebView::title() const -{ - if (d->page) - return d->page->mainFrame()->title(); - - return QString(); -} - -/*! - \property QGraphicsWebView::icon - \brief the icon associated with the web page currently viewed - - By default, this property contains a null icon. - - \sa iconChanged(), QWebSettings::iconForUrl() -*/ -QIcon QGraphicsWebView::icon() const -{ - if (d->page) - return d->page->mainFrame()->icon(); - - return QIcon(); -} - -/*! - \property QGraphicsWebView::zoomFactor - \brief the zoom factor for the view -*/ - -void QGraphicsWebView::setZoomFactor(qreal factor) -{ - if (factor == page()->mainFrame()->zoomFactor()) - return; - - page()->mainFrame()->setZoomFactor(factor); -} - -qreal QGraphicsWebView::zoomFactor() const -{ - return page()->mainFrame()->zoomFactor(); -} - -/*! \reimp -*/ -void QGraphicsWebView::updateGeometry() -{ - if (d->overlay()) - d->overlay()->prepareGraphicsItemGeometryChange(); - - QGraphicsWidget::updateGeometry(); - - if (!d->page) - return; - - QSize size = geometry().size().toSize(); - d->page->setViewportSize(size); -} - -/*! \reimp -*/ -void QGraphicsWebView::setGeometry(const QRectF& rect) -{ - QGraphicsWidget::setGeometry(rect); - - if (d->overlay()) - d->overlay()->prepareGraphicsItemGeometryChange(); - - if (!d->page) - return; - - // NOTE: call geometry() as setGeometry ensures that - // the geometry is within legal bounds (minimumSize, maximumSize) - QSize size = geometry().size().toSize(); - d->page->setViewportSize(size); -} - -/*! - Convenience slot that stops loading the document. - - \sa reload(), loadFinished() -*/ -void QGraphicsWebView::stop() -{ - if (d->page) - d->page->triggerAction(QWebPage::Stop); -} - -/*! - Convenience slot that loads the previous document in the list of documents - built by navigating links. Does nothing if there is no previous document. - - \sa forward() -*/ -void QGraphicsWebView::back() -{ - if (d->page) - d->page->triggerAction(QWebPage::Back); -} - -/*! - Convenience slot that loads the next document in the list of documents - built by navigating links. Does nothing if there is no next document. - - \sa back() -*/ -void QGraphicsWebView::forward() -{ - if (d->page) - d->page->triggerAction(QWebPage::Forward); -} - -/*! - Reloads the current document. - - \sa stop(), loadStarted() -*/ -void QGraphicsWebView::reload() -{ - if (d->page) - d->page->triggerAction(QWebPage::Reload); -} - -/*! - Loads the specified \a url and displays it. - - \note The view remains the same until enough data has arrived to display the new \a url. - - \sa setUrl(), url(), urlChanged() -*/ -void QGraphicsWebView::load(const QUrl& url) -{ - page()->mainFrame()->load(url); -} - -/*! - \fn void QGraphicsWebView::load(const QNetworkRequest &request, QNetworkAccessManager::Operation operation, const QByteArray &body) - - Loads a network request, \a request, using the method specified in \a operation. - - \a body is optional and is only used for POST operations. - - \note The view remains the same until enough data has arrived to display the new url. - - \sa url(), urlChanged() -*/ - -void QGraphicsWebView::load(const QNetworkRequest& request, - QNetworkAccessManager::Operation operation, - const QByteArray& body) -{ - page()->mainFrame()->load(request, operation, body); -} - -/*! - Sets the content of the web view to the specified \a html. - - External objects such as stylesheets or images referenced in the HTML - document are located relative to \a baseUrl. - - The \a html is loaded immediately; external objects are loaded asynchronously. - - When using this method, WebKit assumes that external resources such as - JavaScript programs or style sheets are encoded in UTF-8 unless otherwise - specified. For example, the encoding of an external script can be specified - through the charset attribute of the HTML script tag. Alternatively, the - encoding can also be specified by the web server. - - This is a convenience function equivalent to setContent(html, "text/html", baseUrl). - - \warning This function works only for HTML, for other mime types (i.e. XHTML, SVG) - setContent() should be used instead. - - \sa load(), setContent(), QWebFrame::toHtml(), QWebFrame::setContent() -*/ -void QGraphicsWebView::setHtml(const QString& html, const QUrl& baseUrl) -{ - page()->mainFrame()->setHtml(html, baseUrl); -} - -/*! - Sets the content of the web graphicsitem to the specified content \a data. If the \a mimeType argument - is empty it is currently assumed that the content is HTML but in future versions we may introduce - auto-detection. - - External objects referenced in the content are located relative to \a baseUrl. - - The \a data is loaded immediately; external objects are loaded asynchronously. - - \sa load(), setHtml(), QWebFrame::toHtml() -*/ -void QGraphicsWebView::setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl) -{ - page()->mainFrame()->setContent(data, mimeType, baseUrl); -} - -/*! - Returns a pointer to the view's history of navigated web pages. - - It is equivalent to - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 0 -*/ -QWebHistory* QGraphicsWebView::history() const -{ - return page()->history(); -} - -/*! - \property QGraphicsWebView::modified - \brief whether the document was modified by the user - - Parts of HTML documents can be editable for example through the - \c{contenteditable} attribute on HTML elements. - - By default, this property is false. -*/ -bool QGraphicsWebView::isModified() const -{ - if (d->page) - return d->page->isModified(); - return false; -} - -/*! - Returns a pointer to the view/page specific settings object. - - It is equivalent to - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 1 - - \sa QWebSettings::globalSettings() -*/ -QWebSettings* QGraphicsWebView::settings() const -{ - return page()->settings(); -} - -/*! - Returns a pointer to a QAction that encapsulates the specified web action \a action. -*/ -QAction *QGraphicsWebView::pageAction(QWebPage::WebAction action) const -{ -#ifdef QT_NO_ACTION - Q_UNUSED(action) - return 0; -#else - return page()->action(action); -#endif -} - -/*! - Triggers the specified \a action. If it is a checkable action the specified - \a checked state is assumed. - - \sa pageAction() -*/ -void QGraphicsWebView::triggerPageAction(QWebPage::WebAction action, bool checked) -{ - page()->triggerAction(action, checked); -} - -/*! - Finds the specified string, \a subString, in the page, using the given \a options. - - If the HighlightAllOccurrences flag is passed, the function will highlight all occurrences - that exist in the page. All subsequent calls will extend the highlight, rather than - replace it, with occurrences of the new string. - - If the HighlightAllOccurrences flag is not passed, the function will select an occurrence - and all subsequent calls will replace the current occurrence with the next one. - - To clear the selection, just pass an empty string. - - Returns true if \a subString was found; otherwise returns false. - - \sa QWebPage::selectedText(), QWebPage::selectionChanged() -*/ -bool QGraphicsWebView::findText(const QString &subString, QWebPage::FindFlags options) -{ - if (d->page) - return d->page->findText(subString, options); - return false; -} - -/*! - \property QGraphicsWebView::resizesToContents - \brief whether the size of the QGraphicsWebView and its viewport changes to match the contents size - \since 4.7 - - If this property is set, the QGraphicsWebView will automatically change its - size to match the size of the main frame contents. As a result the top level frame - will never have scrollbars. It will also make CSS fixed positioning to behave like absolute positioning - with elements positioned relative to the document instead of the viewport. - - This property should be used in conjunction with the QWebPage::preferredContentsSize property. - If not explicitly set, the preferredContentsSize is automatically set to a reasonable value. - - \sa QWebPage::setPreferredContentsSize() -*/ -void QGraphicsWebView::setResizesToContents(bool enabled) -{ - if (d->resizesToContents == enabled) - return; - d->resizesToContents = enabled; - if (d->page) - d->updateResizesToContentsForPage(); -} - -bool QGraphicsWebView::resizesToContents() const -{ - return d->resizesToContents; -} - -/*! - \property QGraphicsWebView::tiledBackingStoreFrozen - \brief whether the tiled backing store updates its contents - \since 4.7 - - If the tiled backing store is enabled using QWebSettings::TiledBackingStoreEnabled attribute, this property - can be used to disable backing store updates temporarily. This can be useful for example for running - a smooth animation that changes the scale of the QGraphicsWebView. - - When the backing store is unfrozen, its contents will be automatically updated to match the current - state of the document. If the QGraphicsWebView scale was changed, the backing store is also - re-rendered using the new scale. - - If the tiled backing store is not enabled, this property does nothing. - - \sa QWebSettings::TiledBackingStoreEnabled - \sa QGraphicsObject::scale -*/ -bool QGraphicsWebView::isTiledBackingStoreFrozen() const -{ -#if USE(TILED_BACKING_STORE) - WebCore::TiledBackingStore* backingStore = QWebFramePrivate::core(page()->mainFrame())->tiledBackingStore(); - if (!backingStore) - return false; - return backingStore->contentsFrozen(); -#else - return false; -#endif -} - -void QGraphicsWebView::setTiledBackingStoreFrozen(bool frozen) -{ -#if USE(TILED_BACKING_STORE) - WebCore::TiledBackingStore* backingStore = QWebFramePrivate::core(page()->mainFrame())->tiledBackingStore(); - if (!backingStore) - return; - backingStore->setContentsFrozen(frozen); -#else - UNUSED_PARAM(frozen); -#endif -} - -/*! \reimp -*/ -void QGraphicsWebView::hoverMoveEvent(QGraphicsSceneHoverEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - QMouseEvent me = QMouseEvent(QEvent::MouseMove, - ev->pos().toPoint(), Qt::NoButton, - Qt::NoButton, Qt::NoModifier); - d->page->event(&me); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsItem::hoverMoveEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::hoverLeaveEvent(QGraphicsSceneHoverEvent* ev) -{ - Q_UNUSED(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::mouseMoveEvent(QGraphicsSceneMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsItem::mouseMoveEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::mousePressEvent(QGraphicsSceneMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsItem::mousePressEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsItem::mouseReleaseEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsItem::mouseDoubleClickEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::keyPressEvent(QKeyEvent* ev) -{ - if (d->page) - d->page->event(ev); - - if (!ev->isAccepted()) - QGraphicsItem::keyPressEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::keyReleaseEvent(QKeyEvent* ev) -{ - if (d->page) - d->page->event(ev); - - if (!ev->isAccepted()) - QGraphicsItem::keyReleaseEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::focusInEvent(QFocusEvent* ev) -{ - if (d->page) - d->page->event(ev); - else - QGraphicsItem::focusInEvent(ev); -} - -/*! \reimp -*/ -void QGraphicsWebView::focusOutEvent(QFocusEvent* ev) -{ - if (d->page) - d->page->event(ev); - else - QGraphicsItem::focusOutEvent(ev); -} - -/*! \reimp -*/ -bool QGraphicsWebView::focusNextPrevChild(bool next) -{ - if (d->page) - return d->page->focusNextPrevChild(next); - - return QGraphicsWidget::focusNextPrevChild(next); -} - -/*! \reimp -*/ -void QGraphicsWebView::dragEnterEvent(QGraphicsSceneDragDropEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) - d->page->event(ev); -#else - Q_UNUSED(ev); -#endif -} - -/*! \reimp -*/ -void QGraphicsWebView::dragLeaveEvent(QGraphicsSceneDragDropEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsWidget::dragLeaveEvent(ev); -#else - Q_UNUSED(ev); -#endif -} - -/*! \reimp -*/ -void QGraphicsWebView::dragMoveEvent(QGraphicsSceneDragDropEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsWidget::dragMoveEvent(ev); -#else - Q_UNUSED(ev); -#endif -} - -/*! \reimp -*/ -void QGraphicsWebView::dropEvent(QGraphicsSceneDragDropEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsWidget::dropEvent(ev); -#else - Q_UNUSED(ev); -#endif -} - -#ifndef QT_NO_CONTEXTMENU -/*! \reimp -*/ -void QGraphicsWebView::contextMenuEvent(QGraphicsSceneContextMenuEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } -} -#endif // QT_NO_CONTEXTMENU - -#ifndef QT_NO_WHEELEVENT -/*! \reimp -*/ -void QGraphicsWebView::wheelEvent(QGraphicsSceneWheelEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } - - if (!ev->isAccepted()) - QGraphicsItem::wheelEvent(ev); -} -#endif // QT_NO_WHEELEVENT - -/*! \reimp -*/ -void QGraphicsWebView::inputMethodEvent(QInputMethodEvent* ev) -{ - if (d->page) - d->page->event(ev); - - if (!ev->isAccepted()) - QGraphicsItem::inputMethodEvent(ev); -} - -/*! - \fn void QGraphicsWebView::statusBarMessage(const QString& text) - - This signal is emitted when the statusbar \a text is changed by the page. -*/ - -/*! - \fn void QGraphicsWebView::loadProgress(int progress) - - This signal is emitted every time an element in the web page - completes loading and the overall loading progress advances. - - This signal tracks the progress of all child frames. - - The current value is provided by \a progress and scales from 0 to 100, - which is the default range of QProgressBar. - - \sa loadStarted(), loadFinished() -*/ - -/*! - \fn void QGraphicsWebView::linkClicked(const QUrl &url) - - This signal is emitted whenever the user clicks on a link and the page's linkDelegationPolicy - property is set to delegate the link handling for the specified \a url. - - \sa QWebPage::linkDelegationPolicy() -*/ - -#endif // QT_NO_GRAPHICSVIEW - -#include "moc_qgraphicswebview.cpp" diff --git a/Source/WebKit/qt/Api/qgraphicswebview.h b/Source/WebKit/qt/Api/qgraphicswebview.h deleted file mode 100644 index 0f9f17b48..000000000 --- a/Source/WebKit/qt/Api/qgraphicswebview.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QGraphicsWebView_h -#define QGraphicsWebView_h - -#include "qwebkitglobal.h" -#include "qwebpage.h" -#include <QtCore/qurl.h> -#include <QtWidgets/qgraphicswidget.h> -#include <QtGui/qevent.h> -#include <QtGui/qicon.h> -#include <QtGui/qpainter.h> -#include <QtNetwork/qnetworkaccessmanager.h> - -#if !defined(QT_NO_GRAPHICSVIEW) - -class QWebPage; -class QWebHistory; -class QWebSettings; - -class QGraphicsWebViewPrivate; - -class QWEBKIT_EXPORT QGraphicsWebView : public QGraphicsWidget { - Q_OBJECT - - Q_PROPERTY(QString title READ title NOTIFY titleChanged) - Q_PROPERTY(QIcon icon READ icon NOTIFY iconChanged) - Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor) - - Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) - - Q_PROPERTY(bool modified READ isModified) - Q_PROPERTY(bool resizesToContents READ resizesToContents WRITE setResizesToContents) - Q_PROPERTY(bool tiledBackingStoreFrozen READ isTiledBackingStoreFrozen WRITE setTiledBackingStoreFrozen) - - Q_PROPERTY(QPainter::RenderHints renderHints READ renderHints WRITE setRenderHints) - Q_FLAGS(QPainter::RenderHints) - -public: - explicit QGraphicsWebView(QGraphicsItem* parent = 0); - ~QGraphicsWebView(); - - QWebPage* page() const; - void setPage(QWebPage*); - - QUrl url() const; - void setUrl(const QUrl&); - - QString title() const; - QIcon icon() const; - - qreal zoomFactor() const; - void setZoomFactor(qreal); - - bool isModified() const; - - void load(const QUrl& url); - void load(const QNetworkRequest& request, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, const QByteArray& body = QByteArray()); - - void setHtml(const QString& html, const QUrl& baseUrl = QUrl()); - // FIXME: Consider rename to setHtml? - void setContent(const QByteArray& data, const QString& mimeType = QString(), const QUrl& baseUrl = QUrl()); - - QWebHistory* history() const; - QWebSettings* settings() const; - - QAction* pageAction(QWebPage::WebAction action) const; - void triggerPageAction(QWebPage::WebAction action, bool checked = false); - - bool findText(const QString& subString, QWebPage::FindFlags options = 0); - - bool resizesToContents() const; - void setResizesToContents(bool enabled); - - bool isTiledBackingStoreFrozen() const; - void setTiledBackingStoreFrozen(bool frozen); - - virtual void setGeometry(const QRectF& rect); - virtual void updateGeometry(); - virtual void paint(QPainter*, const QStyleOptionGraphicsItem* options, QWidget* widget = 0); - virtual QVariant itemChange(GraphicsItemChange change, const QVariant& value); - virtual bool event(QEvent*); - - virtual QSizeF sizeHint(Qt::SizeHint which, const QSizeF& constraint) const; - - virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const; - - QPainter::RenderHints renderHints() const; - void setRenderHints(QPainter::RenderHints); - void setRenderHint(QPainter::RenderHint, bool enabled = true); - -public Q_SLOTS: - void stop(); - void back(); - void forward(); - void reload(); - -Q_SIGNALS: - void loadStarted(); - void loadFinished(bool); - - void loadProgress(int progress); - void urlChanged(const QUrl&); - void titleChanged(const QString&); - void iconChanged(); - void statusBarMessage(const QString& message); - void linkClicked(const QUrl&); - -protected: - virtual void mousePressEvent(QGraphicsSceneMouseEvent*); - virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent*); - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent*); - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent*); - virtual void hoverMoveEvent(QGraphicsSceneHoverEvent*); - virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent*); -#ifndef QT_NO_WHEELEVENT - virtual void wheelEvent(QGraphicsSceneWheelEvent*); -#endif - virtual void keyPressEvent(QKeyEvent*); - virtual void keyReleaseEvent(QKeyEvent*); -#ifndef QT_NO_CONTEXTMENU - virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent*); -#endif - virtual void dragEnterEvent(QGraphicsSceneDragDropEvent*); - virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent*); - virtual void dragMoveEvent(QGraphicsSceneDragDropEvent*); - virtual void dropEvent(QGraphicsSceneDragDropEvent*); - virtual void focusInEvent(QFocusEvent*); - virtual void focusOutEvent(QFocusEvent*); - virtual void inputMethodEvent(QInputMethodEvent*); - virtual bool focusNextPrevChild(bool next); - - virtual bool sceneEvent(QEvent*); - -private: - Q_PRIVATE_SLOT(d, void _q_doLoadFinished(bool success)) - Q_PRIVATE_SLOT(d, void _q_pageDestroyed()) - // we don't want to change the moc based on USE() macro, so this function is here - // but will be empty if ACCLERATED_COMPOSITING is disabled - Q_PRIVATE_SLOT(d, void syncLayers()) - Q_PRIVATE_SLOT(d, void _q_contentsSizeChanged(const QSize&)) - Q_PRIVATE_SLOT(d, void _q_scaleChanged()) - - QGraphicsWebViewPrivate* const d; - friend class QGraphicsWebViewPrivate; -}; - -#endif // QT_NO_GRAPHICSVIEW - -#endif // QGraphicsWebView_h diff --git a/Source/WebKit/qt/Api/qwebelement.h b/Source/WebKit/qt/Api/qwebelement.h index efec5eb7c..e907a69a1 100644 --- a/Source/WebKit/qt/Api/qwebelement.h +++ b/Source/WebKit/qt/Api/qwebelement.h @@ -150,7 +150,7 @@ private: static QWebElement enclosingElement(WebCore::Node*); friend class DumpRenderTreeSupportQt; - friend class QWebFrame; + friend class QWebFrameAdapter; friend class QWebElementCollection; friend class QWebHitTestResult; friend class QWebHitTestResultPrivate; diff --git a/Source/WebKit/qt/Api/qwebframe.cpp b/Source/WebKit/qt/Api/qwebframe.cpp deleted file mode 100644 index 3fa0e8b71..000000000 --- a/Source/WebKit/qt/Api/qwebframe.cpp +++ /dev/null @@ -1,1816 +0,0 @@ -/* - Copyright (C) 2008,2009 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2007 Staikos Computing Services Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" -#include "qwebframe.h" - -#include "APICast.h" -#include "BridgeJSC.h" -#include "CallFrame.h" -#include "Document.h" -#include "DocumentLoader.h" -#include "DragData.h" -#include "Element.h" -#include "FocusController.h" -#include "Frame.h" -#include "FrameLoadRequest.h" -#include "FrameLoaderClientQt.h" -#include "FrameSelection.h" -#include "FrameTree.h" -#include "FrameView.h" -#include "GCController.h" -#include "GraphicsContext.h" -#include "HTMLFormElement.h" -#include "HTMLMetaElement.h" -#include "HitTestResult.h" -#include "HTTPParsers.h" -#include "IconDatabase.h" -#include "InspectorController.h" -#include "JavaScript.h" -#include "JSDOMBinding.h" -#include "JSDOMWindowBase.h" -#include "JSLock.h" -#include "JSObject.h" -#include "JSRetainPtr.h" -#include "OpaqueJSString.h" -#include "NetworkingContext.h" -#include "NodeList.h" -#include "Page.h" -#include "PlatformMouseEvent.h" -#include "PlatformWheelEvent.h" -#include "PrintContext.h" -#include "PropertyDescriptor.h" -#include "PutPropertySlot.h" -#include "RenderLayer.h" -#include "RenderTreeAsText.h" -#include "RenderView.h" -#include "ResourceRequest.h" -#include "ScriptController.h" -#include "ScriptSourceCode.h" -#include "ScriptValue.h" -#include "Scrollbar.h" -#include "Settings.h" -#include "SubstituteData.h" -#include "SVGSMILElement.h" -#include "TiledBackingStore.h" -#include "htmlediting.h" -#include "markup.h" -#include "qt_instance.h" -#include "qt_runtime.h" -#include "qwebelement.h" -#include "qwebframe_p.h" -#include "qwebpage.h" -#include "qwebpage_p.h" -#include "qwebsecurityorigin.h" -#include "qwebsecurityorigin_p.h" -#include "qwebscriptworld.h" -#include "qwebscriptworld_p.h" -#include "runtime_object.h" -#include "runtime_root.h" -#if USE(TEXTURE_MAPPER) -#include "texmap/TextureMapper.h" -#include "texmap/TextureMapperLayer.h" -#endif -#include "wtf/HashMap.h" -#include <QMultiMap> -#include <qdebug.h> -#include <qevent.h> -#include <qfileinfo.h> -#include <qpainter.h> -#if HAVE(QTPRINTSUPPORT) -#include <qprinter.h> -#endif -#include <qregion.h> -#include <qnetworkrequest.h> - -using namespace WebCore; - -// from text/qfont.cpp -QT_BEGIN_NAMESPACE -extern Q_GUI_EXPORT int qt_defaultDpi(); -QT_END_NAMESPACE - -void QWebFramePrivate::setPage(QWebPage* newPage) -{ - if (page == newPage) - return; - - // The QWebFrame is created as a child of QWebPage or a parent QWebFrame. - // That adds it to QObject's internal children list and ensures it will be - // deleted when parent QWebPage is deleted. Reparent if needed. - if (q->parent() == qobject_cast<QObject*>(page)) - q->setParent(newPage); - - page = newPage; - pageAdapter = newPage->handle(); - emit q->pageChanged(); -} - -WebCore::Scrollbar* QWebFramePrivate::horizontalScrollBar() const -{ - if (!frame->view()) - return 0; - return frame->view()->horizontalScrollbar(); -} - -WebCore::Scrollbar* QWebFramePrivate::verticalScrollBar() const -{ - if (!frame->view()) - return 0; - return frame->view()->verticalScrollbar(); -} - -#if USE(TILED_BACKING_STORE) -void QWebFramePrivate::renderFromTiledBackingStore(GraphicsContext* context, const QRegion& clip) -{ - ASSERT(frame->tiledBackingStore()); - - if (!frame->view() || !frame->contentRenderer()) - return; - - QVector<QRect> vector = clip.rects(); - if (vector.isEmpty()) - return; - - QPainter* painter = context->platformContext(); - - WebCore::FrameView* view = frame->view(); - - int scrollX = view->scrollX(); - int scrollY = view->scrollY(); - context->translate(-scrollX, -scrollY); - - for (int i = 0; i < vector.size(); ++i) { - const QRect& clipRect = vector.at(i); - - painter->save(); - - QRect rect = clipRect.translated(scrollX, scrollY); - painter->setClipRect(rect, Qt::IntersectClip); - - frame->tiledBackingStore()->paint(context, rect); - - painter->restore(); - } - -#if USE(ACCELERATED_COMPOSITING) - renderCompositedLayers(context, IntRect(clip.boundingRect())); - renderFrameExtras(context, QFlags<QWebFrame::RenderLayer>(QWebFrame::ScrollBarLayer) | QWebFrame::PanIconLayer, clip); -#endif -} -#endif - -#if USE(ACCELERATED_COMPOSITING) -void QWebFramePrivate::renderCompositedLayers(GraphicsContext* context, const IntRect& clip) -{ - if (!rootTextureMapperLayer || !textureMapper) - return; - - textureMapper->setGraphicsContext(context); - textureMapper->setImageInterpolationQuality(context->imageInterpolationQuality()); - textureMapper->setTextDrawingMode(context->textDrawingMode()); - QPainter* painter = context->platformContext(); - const QTransform transform = painter->worldTransform(); - const TransformationMatrix matrix( - transform.m11(), transform.m12(), 0, transform.m13(), - transform.m21(), transform.m22(), 0, transform.m23(), - 0, 0, 1, 0, - transform.m31(), transform.m32(), 0, transform.m33() - ); - rootTextureMapperLayer->setTransform(matrix); - rootTextureMapperLayer->setOpacity(painter->opacity()); - textureMapper->beginPainting(); - textureMapper->beginClip(matrix, clip); - rootTextureMapperLayer->paint(); - textureMapper->endClip(); - textureMapper->endPainting(); -} -#endif - -// This code is copied from ChromeClientGtk.cpp. -static void coalesceRectsIfPossible(const QRect& clipRect, QVector<QRect>& rects) -{ - const unsigned int rectThreshold = 10; - const float wastedSpaceThreshold = 0.75f; - bool useUnionedRect = (rects.size() <= 1) || (rects.size() > rectThreshold); - if (!useUnionedRect) { - // Attempt to guess whether or not we should use the unioned rect or the individual rects. - // We do this by computing the percentage of "wasted space" in the union. If that wasted space - // is too large, then we will do individual rect painting instead. - float unionPixels = (clipRect.width() * clipRect.height()); - float singlePixels = 0; - for (size_t i = 0; i < rects.size(); ++i) - singlePixels += rects[i].width() * rects[i].height(); - float wastedSpace = 1 - (singlePixels / unionPixels); - if (wastedSpace <= wastedSpaceThreshold) - useUnionedRect = true; - } - - if (!useUnionedRect) - return; - - rects.clear(); - rects.append(clipRect); -} - -void QWebFramePrivate::renderRelativeCoords(GraphicsContext* context, QFlags<QWebFrame::RenderLayer> layers, const QRegion& clip) -{ - if (!frame->view() || !frame->contentRenderer()) - return; - - QVector<QRect> vector = clip.rects(); - if (vector.isEmpty()) - return; - - QPainter* painter = context->platformContext(); - - WebCore::FrameView* view = frame->view(); - view->updateLayoutAndStyleIfNeededRecursive(); - - if (layers & QWebFrame::ContentsLayer) { - QRect clipBoundingRect = clip.boundingRect(); - coalesceRectsIfPossible(clipBoundingRect, vector); - for (int i = 0; i < vector.size(); ++i) { - const QRect& clipRect = vector.at(i); - - QRect rect = clipRect.intersected(view->frameRect()); - - context->save(); - painter->setClipRect(clipRect, Qt::IntersectClip); - - int x = view->x(); - int y = view->y(); - - int scrollX = view->scrollX(); - int scrollY = view->scrollY(); - - context->translate(x, y); - rect.translate(-x, -y); - context->translate(-scrollX, -scrollY); - rect.translate(scrollX, scrollY); - context->clip(view->visibleContentRect()); - - view->paintContents(context, rect); - - context->restore(); - } -#if USE(ACCELERATED_COMPOSITING) - renderCompositedLayers(context, IntRect(clipBoundingRect)); -#endif - } - renderFrameExtras(context, layers, clip); -#if ENABLE(INSPECTOR) - if (frame->page()->inspectorController()->highlightedNode()) { - context->save(); - frame->page()->inspectorController()->drawHighlight(*context); - context->restore(); - } -#endif -} - -void QWebFramePrivate::renderFrameExtras(GraphicsContext* context, QFlags<QWebFrame::RenderLayer> layers, const QRegion& clip) -{ - if (!(layers & (QWebFrame::PanIconLayer | QWebFrame::ScrollBarLayer))) - return; - QPainter* painter = context->platformContext(); - WebCore::FrameView* view = frame->view(); - QVector<QRect> vector = clip.rects(); - for (int i = 0; i < vector.size(); ++i) { - const QRect& clipRect = vector.at(i); - - QRect intersectedRect = clipRect.intersected(view->frameRect()); - - painter->save(); - painter->setClipRect(clipRect, Qt::IntersectClip); - - int x = view->x(); - int y = view->y(); - - if (layers & QWebFrame::ScrollBarLayer - && !view->scrollbarsSuppressed() - && (view->horizontalScrollbar() || view->verticalScrollbar())) { - - QRect rect = intersectedRect; - context->translate(x, y); - rect.translate(-x, -y); - view->paintScrollbars(context, rect); - context->translate(-x, -y); - } - -#if ENABLE(PAN_SCROLLING) - if (layers & QWebFrame::PanIconLayer) - view->paintPanScrollIcon(context); -#endif - - painter->restore(); - } -} - -void QWebFramePrivate::emitUrlChanged() -{ - url = frame->document()->url(); - emit q->urlChanged(url); -} - -void QWebFramePrivate::didStartProvisionalLoad() -{ - emit q->provisionalLoad(); -} - -void QWebFramePrivate::_q_orientationChanged() -{ -#if ENABLE(ORIENTATION_EVENTS) - int orientation; - WebCore::Frame* frame = core(q); - - switch (m_orientation.reading()->orientation()) { - case QOrientationReading::TopUp: - orientation = 0; - break; - case QOrientationReading::TopDown: - orientation = 180; - break; - case QOrientationReading::LeftUp: - orientation = -90; - break; - case QOrientationReading::RightUp: - orientation = 90; - break; - case QOrientationReading::FaceUp: - case QOrientationReading::FaceDown: - // WebCore unable to handle it - default: - return; - } - frame->sendOrientationChangeEvent(orientation); -#endif -} - -void QWebFramePrivate::didClearWindowObject() -{ - emit q->javaScriptWindowObjectCleared(); -} - -bool QWebFramePrivate::handleProgressFinished(QPoint *localPos) -{ - QWidget *view = q->page()->view(); - if (!view || !localPos) - return false; - *localPos = view->mapFromGlobal(QCursor::pos()); - return view->hasFocus() && view->rect().contains(*localPos); -} - -void QWebFramePrivate::emitInitialLayoutCompleted() -{ - emit q->initialLayoutCompleted(); -} - -void QWebFramePrivate::emitIconChanged() -{ - emit q->iconChanged(); -} - -void QWebFramePrivate::emitLoadStarted(bool originatingLoad) -{ - if (page && originatingLoad) - emit page->loadStarted(); - emit q->loadStarted(); -} - -void QWebFramePrivate::emitLoadFinished(bool originatingLoad, bool ok) -{ - if (page && originatingLoad) - emit page->loadFinished(ok); - emit q->loadFinished(ok); -} - -QWebFrameAdapter* QWebFramePrivate::createChildFrame(QWebFrameData* frameData) -{ - QWebFrame* newFrame = new QWebFrame(/*parent frame*/q, frameData); - return newFrame->d; -} - -QWebFrame *QWebFramePrivate::apiHandle() -{ - return q; -} - -QObject *QWebFramePrivate::handle() -{ - return q; -} - -void QWebFramePrivate::contentsSizeDidChange(const QSize &size) -{ - emit q->contentsSizeChanged(size); -} - -int QWebFramePrivate::scrollBarPolicy(Qt::Orientation orientation) const -{ - return (int) q->scrollBarPolicy(orientation); -} - -/*! - \class QWebFrame - \since 4.4 - \brief The QWebFrame class represents a frame in a web page. - - \inmodule QtWebKit - - QWebFrame represents a frame inside a web page. Each QWebPage - object contains at least one frame, the main frame, obtained using - QWebPage::mainFrame(). Additional frames will be created for HTML - \c{<frame>} or \c{<iframe>} elements. - - A frame can be loaded using load() or setUrl(). Alternatively, if you have - the HTML content readily available, you can use setHtml() instead. - - The page() function returns a pointer to the web page object. See - \l{QWebView}{Elements of QWebView} for an explanation of how web - frames are related to a web page and web view. - - The QWebFrame class also offers methods to retrieve both the URL currently - loaded by the frame (see url()) as well as the URL originally requested - to be loaded (see requestedUrl()). These methods make possible the retrieval - of the URL before and after a DNS resolution or a redirection occurs during - the load process. The requestedUrl() also matches to the URL added to the - frame history (\l{QWebHistory}) if load is successful. - - The title of an HTML frame can be accessed with the title() property. - Additionally, a frame may also specify an icon, which can be accessed - using the icon() property. If the title or the icon changes, the - corresponding titleChanged() and iconChanged() signals will be emitted. - The zoomFactor() property can be used to change the overall size - of the content displayed in the frame. - - QWebFrame objects are created and controlled by the web page. You - can connect to the web page's \l{QWebPage::}{frameCreated()} signal - to be notified when a new frame is created. - - There are multiple ways to programmatically examine the contents of a frame. - The hitTestContent() function can be used to find elements by coordinate. - For access to the underlying DOM tree, there is documentElement(), - findAllElements() and findFirstElement(). - - A QWebFrame can be printed onto a QPrinter using the print() function. - This function is marked as a slot and can be conveniently connected to - \l{QPrintPreviewDialog}'s \l{QPrintPreviewDialog::}{paintRequested()} - signal. - - \sa QWebPage -*/ - -/*! - \enum QWebFrame::RenderLayer - - This enum describes the layers available for rendering using \l{QWebFrame::}{render()}. - The layers can be OR-ed together from the following list: - - \value ContentsLayer The web content of the frame - \value ScrollBarLayer The scrollbars of the frame - \value PanIconLayer The icon used when panning the frame - - \value AllLayers Includes all the above layers -*/ - -QWebFrame::QWebFrame(QWebPage *parentPage) - : QObject(parentPage) - , d(new QWebFramePrivate) -{ - d->page = parentPage; - d->q = this; - d->init(/*page adapter*/ parentPage->handle()); - -#if ENABLE(ORIENTATION_EVENTS) - connect(&d->m_orientation, SIGNAL(readingChanged()), this, SLOT(_q_orientationChanged())); - d->m_orientation.start(); -#endif -} - -QWebFrame::QWebFrame(QWebFrame* parent, QWebFrameData* frameData) - : QObject(parent) - , d(new QWebFramePrivate) -{ - d->page = parent->d->page; - d->q = this; - d->init(parent->d->pageAdapter, frameData); -#if ENABLE(ORIENTATION_EVENTS) - connect(&d->m_orientation, SIGNAL(readingChanged()), this, SLOT(_q_orientationChanged())); - d->m_orientation.start(); -#endif -} - -QWebFrame::~QWebFrame() -{ - delete d; -} - -/*! - \fn void QWebFrame::addToJavaScriptWindowObject(const QString &name, QObject *object, ValueOwnership own) - - Make \a object available under \a name from within the frame's JavaScript - context. The \a object will be inserted as a child of the frame's window - object. - - Qt properties will be exposed as JavaScript properties and slots as - JavaScript methods. - The interaction between C++ and JavaScript is explained in the documentation of the \l{The QtWebKit Bridge}{QtWebKit bridge}. - - If you want to ensure that your QObjects remain accessible after loading a - new URL, you should add them in a slot connected to the - javaScriptWindowObjectCleared() signal. - - If Javascript is not enabled for this page, then this method does nothing. - - The ownership of \a object is specified using \a own. -*/ -void QWebFrame::addToJavaScriptWindowObject(const QString &name, QObject *object, ValueOwnership ownership) -{ - if (!page()->settings()->testAttribute(QWebSettings::JavascriptEnabled)) - return; - JSC::Bindings::QtInstance::ValueOwnership valueOwnership = static_cast<JSC::Bindings::QtInstance::ValueOwnership>(ownership); - JSDOMWindow* window = toJSDOMWindow(d->frame, mainThreadNormalWorld()); - JSC::Bindings::RootObject* root; - if (valueOwnership == JSC::Bindings::QtInstance::QtOwnership) - root = d->frame->script()->cacheableBindingRootObject(); - else - root = d->frame->script()->bindingRootObject(); - - if (!window) { - qDebug() << "Warning: couldn't get window object"; - return; - } - if (!root) { - qDebug() << "Warning: couldn't get root object"; - return; - } - - JSC::ExecState* exec = window->globalExec(); - JSC::JSLockHolder lock(exec); - - JSC::JSObject* runtimeObject = - JSC::Bindings::QtInstance::getQtInstance(object, root, valueOwnership)->createRuntimeObject(exec); - - JSC::PutPropertySlot slot; - window->methodTable()->put(window, exec, JSC::Identifier(&exec->globalData(), reinterpret_cast_ptr<const UChar*>(name.constData()), name.length()), runtimeObject, slot); -} - -/*! - Returns the frame's content as HTML, enclosed in HTML and BODY tags. - - \sa setHtml(), toPlainText() -*/ -QString QWebFrame::toHtml() const -{ - if (!d->frame->document()) - return QString(); - return createMarkup(d->frame->document()); -} - -/*! - Returns the content of this frame converted to plain text, completely - stripped of all HTML formatting. - - \sa toHtml() -*/ -QString QWebFrame::toPlainText() const -{ - if (d->frame->view() && d->frame->view()->layoutPending()) - d->frame->view()->layout(); - - Element *documentElement = d->frame->document()->documentElement(); - if (documentElement) - return documentElement->innerText(); - return QString(); -} - -/*! - Returns a dump of the rendering tree. This is mainly useful for debugging - html. -*/ -QString QWebFrame::renderTreeDump() const -{ - if (d->frame->view() && d->frame->view()->layoutPending()) - d->frame->view()->layout(); - - return externalRepresentation(d->frame); -} - -/*! - \property QWebFrame::title - \brief the title of the frame as defined by the HTML <title> element - - \sa titleChanged() -*/ - -QString QWebFrame::title() const -{ - if (d->frame->document()) - return d->frame->loader()->documentLoader()->title().string(); - return QString(); -} - -/*! - \since 4.5 - \brief Returns the meta data in this frame as a QMultiMap - - The meta data consists of the name and content attributes of the - of the \c{<meta>} tags in the HTML document. - - For example: - - \code - <html> - <head> - <meta name="description" content="This document is a tutorial about Qt development"> - <meta name="keywords" content="Qt, WebKit, Programming"> - </head> - ... - </html> - \endcode - - Given the above HTML code the metaData() function will return a map with two entries: - \table - \header \li Key - \li Value - \row \li "description" - \li "This document is a tutorial about Qt development" - \row \li "keywords" - \li "Qt, WebKit, Programming" - \endtable - - This function returns a multi map to support multiple meta tags with the same attribute name. -*/ -QMultiMap<QString, QString> QWebFrame::metaData() const -{ - if (!d->frame->document()) - return QMap<QString, QString>(); - - QMultiMap<QString, QString> map; - Document* doc = d->frame->document(); - RefPtr<NodeList> list = doc->getElementsByTagName("meta"); - unsigned len = list->length(); - for (unsigned i = 0; i < len; i++) { - HTMLMetaElement* meta = static_cast<HTMLMetaElement*>(list->item(i)); - map.insert(meta->name(), meta->content()); - } - return map; -} - -static inline void clearCoreFrame(WebCore::Frame* frame) -{ - WebCore::DocumentLoader* documentLoader = frame->loader()->activeDocumentLoader(); - Q_ASSERT(documentLoader); - documentLoader->writer()->begin(); - documentLoader->writer()->end(); -} - -static inline bool isCoreFrameClear(WebCore::Frame* frame) -{ - return frame->document()->url().isEmpty(); -} - -/*! - \property QWebFrame::url - \brief the url of the frame currently viewed - - Setting this property clears the view and loads the URL. - - By default, this property contains an empty, invalid URL. - - \sa urlChanged() -*/ - -void QWebFrame::setUrl(const QUrl &url) -{ - clearCoreFrame(d->frame); - const QUrl absolute = QWebFrameAdapter::ensureAbsoluteUrl(url); - d->url = absolute; - load(absolute); -} - -QUrl QWebFrame::url() const -{ - return d->url; -} - -/*! - \since 4.6 - \property QWebFrame::requestedUrl - - The URL requested to loaded by the frame currently viewed. The URL may differ from - the one returned by url() if a DNS resolution or a redirection occurs. - - \sa url(), setUrl() -*/ -QUrl QWebFrame::requestedUrl() const -{ - return d->frameLoaderClient->lastRequestedUrl(); -} -/*! - \since 4.6 - \property QWebFrame::baseUrl - \brief the base URL of the frame, can be used to resolve relative URLs - \since 4.6 -*/ - -QUrl QWebFrame::baseUrl() const -{ - if (isCoreFrameClear(d->frame)) - return QUrl(d->url).resolved(QUrl()); - return d->frame->document()->baseURL(); -} - -/*! - \property QWebFrame::icon - \brief the icon associated with this frame - - \sa iconChanged(), QWebSettings::iconForUrl() -*/ - -QIcon QWebFrame::icon() const -{ - return QWebSettings::iconForUrl(d->frame->document()->url()); -} - -/*! - The name of this frame as defined by the parent frame. -*/ -QString QWebFrame::frameName() const -{ - return d->frame->tree()->uniqueName(); -} - -/*! - The web page that contains this frame. - - \sa pageChanged() -*/ -QWebPage *QWebFrame::page() const -{ - return d->page; -} - -/*! - Loads \a url into this frame. - - \note The view remains the same until enough data has arrived to display the new \a url. - - \sa setUrl(), setHtml(), setContent() -*/ -void QWebFrame::load(const QUrl &url) -{ - // The load() overload ensures that the url is absolute. - load(QNetworkRequest(url)); -} - -/*! - Loads a network request, \a req, into this frame, using the method specified in \a - operation. - - \a body is optional and is only used for POST operations. - - \note The view remains the same until enough data has arrived to display the new content. - - \sa setUrl() -*/ -void QWebFrame::load(const QNetworkRequest &req, - QNetworkAccessManager::Operation operation, - const QByteArray &body) -{ - d->load(req, operation, body); -} - -/*! - Sets the content of this frame to \a html. \a baseUrl is optional and used to resolve relative - URLs in the document, such as referenced images or stylesheets. - - The \a html is loaded immediately; external objects are loaded asynchronously. - - If a script in the \a html runs longer than the default script timeout (currently 10 seconds), - for example due to being blocked by a modal JavaScript alert dialog, this method will return - as soon as possible after the timeout and any subsequent \a html will be loaded asynchronously. - - When using this method WebKit assumes that external resources such as JavaScript programs or style - sheets are encoded in UTF-8 unless otherwise specified. For example, the encoding of an external - script can be specified through the charset attribute of the HTML script tag. It is also possible - for the encoding to be specified by web server. - - This is a convenience function equivalent to setContent(html, "text/html", baseUrl). - - \note This method will not affect session or global history for the frame. - - \warning This function works only for HTML, for other mime types (i.e. XHTML, SVG) - setContent() should be used instead. - - \sa toHtml(), setContent(), load() -*/ -void QWebFrame::setHtml(const QString &html, const QUrl &baseUrl) -{ - KURL kurl(baseUrl); - WebCore::ResourceRequest request(kurl); - const QByteArray utf8 = html.toUtf8(); - WTF::RefPtr<WebCore::SharedBuffer> data = WebCore::SharedBuffer::create(utf8.constData(), utf8.length()); - WebCore::SubstituteData substituteData(data, WTF::String("text/html"), WTF::String("utf-8"), KURL()); - d->frame->loader()->load(WebCore::FrameLoadRequest(d->frame, request, substituteData)); -} - -/*! - Sets the content of this frame to the specified content \a data. If the \a mimeType argument - is empty it is currently assumed that the content is HTML but in future versions we may introduce - auto-detection. - - External objects referenced in the content are located relative to \a baseUrl. - - The \a data is loaded immediately; external objects are loaded asynchronously. - - \note This method will not affect session or global history for the frame. - - \sa toHtml(), setHtml() -*/ -void QWebFrame::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) -{ - KURL kurl(baseUrl); - WebCore::ResourceRequest request(kurl); - WTF::RefPtr<WebCore::SharedBuffer> buffer = WebCore::SharedBuffer::create(data.constData(), data.length()); - QString actualMimeType; - WTF::String encoding; - if (mimeType.isEmpty()) - actualMimeType = QLatin1String("text/html"); - else { - actualMimeType = extractMIMETypeFromMediaType(mimeType); - encoding = extractCharsetFromMediaType(mimeType); - } - WebCore::SubstituteData substituteData(buffer, WTF::String(actualMimeType), encoding, KURL()); - d->frame->loader()->load(WebCore::FrameLoadRequest(d->frame, request, substituteData)); -} - -/*! - Returns the parent frame of this frame, or 0 if the frame is the web pages - main frame. - - This is equivalent to qobject_cast<QWebFrame*>(frame->parent()). - - \sa childFrames() -*/ -QWebFrame *QWebFrame::parentFrame() const -{ - return d->parentFrame(); -} - -/*! - Returns a list of all frames that are direct children of this frame. - - \sa parentFrame() -*/ -QList<QWebFrame*> QWebFrame::childFrames() const -{ - QList<QWebFrame*> rc; - if (d->frame) { - FrameTree *tree = d->frame->tree(); - for (Frame *child = tree->firstChild(); child; child = child->tree()->nextSibling()) { - FrameLoader *loader = child->loader(); - QWebFrame* webFrame = qobject_cast<QWebFrame*>(loader->networkingContext()->originatingObject()); - if (webFrame) - rc.append(webFrame); - } - - } - return rc; -} - -/*! - Returns the scrollbar policy for the scrollbar defined by \a orientation. -*/ -Qt::ScrollBarPolicy QWebFrame::scrollBarPolicy(Qt::Orientation orientation) const -{ - if (orientation == Qt::Horizontal) - return d->horizontalScrollBarPolicy; - return d->verticalScrollBarPolicy; -} - -/*! - Sets the scrollbar policy for the scrollbar defined by \a orientation to \a policy. -*/ -void QWebFrame::setScrollBarPolicy(Qt::Orientation orientation, Qt::ScrollBarPolicy policy) -{ - Q_ASSERT((int)ScrollbarAuto == (int)Qt::ScrollBarAsNeeded); - Q_ASSERT((int)ScrollbarAlwaysOff == (int)Qt::ScrollBarAlwaysOff); - Q_ASSERT((int)ScrollbarAlwaysOn == (int)Qt::ScrollBarAlwaysOn); - - if (orientation == Qt::Horizontal) { - d->horizontalScrollBarPolicy = policy; - if (d->frame->view()) { - d->frame->view()->setHorizontalScrollbarMode((ScrollbarMode)policy, policy != Qt::ScrollBarAsNeeded /* lock */); - d->frame->view()->updateCanHaveScrollbars(); - } - } else { - d->verticalScrollBarPolicy = policy; - if (d->frame->view()) { - d->frame->view()->setVerticalScrollbarMode((ScrollbarMode)policy, policy != Qt::ScrollBarAsNeeded /* lock */); - d->frame->view()->updateCanHaveScrollbars(); - } - } -} - -/*! - Sets the current \a value for the scrollbar with orientation \a orientation. - - The scrollbar forces the \a value to be within the legal range: minimum <= value <= maximum. - - Changing the value also updates the thumb position. - - \sa scrollBarMinimum(), scrollBarMaximum() -*/ -void QWebFrame::setScrollBarValue(Qt::Orientation orientation, int value) -{ - Scrollbar *sb; - sb = (orientation == Qt::Horizontal) ? d->horizontalScrollBar() : d->verticalScrollBar(); - if (sb) { - if (value < 0) - value = 0; - else if (value > scrollBarMaximum(orientation)) - value = scrollBarMaximum(orientation); - sb->scrollableArea()->scrollToOffsetWithoutAnimation(orientation == Qt::Horizontal ? HorizontalScrollbar : VerticalScrollbar, value); - } -} - -/*! - Returns the current value for the scrollbar with orientation \a orientation, or 0 - if no scrollbar is found for \a orientation. - - \sa scrollBarMinimum(), scrollBarMaximum() -*/ -int QWebFrame::scrollBarValue(Qt::Orientation orientation) const -{ - Scrollbar *sb; - sb = (orientation == Qt::Horizontal) ? d->horizontalScrollBar() : d->verticalScrollBar(); - if (sb) - return sb->value(); - return 0; -} - -/*! - Returns the maximum value for the scrollbar with orientation \a orientation, or 0 - if no scrollbar is found for \a orientation. - - \sa scrollBarMinimum() -*/ -int QWebFrame::scrollBarMaximum(Qt::Orientation orientation) const -{ - Scrollbar *sb; - sb = (orientation == Qt::Horizontal) ? d->horizontalScrollBar() : d->verticalScrollBar(); - if (sb) - return sb->maximum(); - return 0; -} - -/*! - Returns the minimum value for the scrollbar with orientation \a orientation. - - The minimum value is always 0. - - \sa scrollBarMaximum() -*/ -int QWebFrame::scrollBarMinimum(Qt::Orientation orientation) const -{ - Q_UNUSED(orientation) - return 0; -} - -/*! - \since 4.6 - Returns the geometry for the scrollbar with orientation \a orientation. - - If the scrollbar does not exist an empty rect is returned. -*/ -QRect QWebFrame::scrollBarGeometry(Qt::Orientation orientation) const -{ - Scrollbar *sb; - sb = (orientation == Qt::Horizontal) ? d->horizontalScrollBar() : d->verticalScrollBar(); - if (sb) - return sb->frameRect(); - return QRect(); -} - -/*! - \since 4.5 - Scrolls the frame \a dx pixels to the right and \a dy pixels downward. Both - \a dx and \a dy may be negative. - - \sa QWebFrame::scrollPosition -*/ - -void QWebFrame::scroll(int dx, int dy) -{ - if (!d->frame->view()) - return; - - d->frame->view()->scrollBy(IntSize(dx, dy)); -} - -/*! - \property QWebFrame::scrollPosition - \since 4.5 - \brief the position the frame is currently scrolled to. -*/ - -QPoint QWebFrame::scrollPosition() const -{ - IntSize ofs = d->scrollPosition(); - return QPoint(ofs.width(), ofs.height()); -} - -void QWebFrame::setScrollPosition(const QPoint &pos) -{ - QPoint current = scrollPosition(); - int dx = pos.x() - current.x(); - int dy = pos.y() - current.y(); - scroll(dx, dy); -} - -/*! - \since 4.7 - Scrolls the frame to the given \a anchor name. -*/ -void QWebFrame::scrollToAnchor(const QString& anchor) -{ - FrameView *view = d->frame->view(); - if (view) - view->scrollToAnchor(anchor); -} - -/*! - \since 4.6 - Render the \a layer of the frame using \a painter clipping to \a clip. - - \sa print() -*/ - -void QWebFrame::render(QPainter* painter, RenderLayer layer, const QRegion& clip) -{ - GraphicsContext context(painter); - if (context.paintingDisabled() && !context.updatingControlTints()) - return; - - if (!clip.isEmpty()) - d->renderRelativeCoords(&context, layer, clip); - else if (d->frame->view()) - d->renderRelativeCoords(&context, layer, QRegion(d->frame->view()->frameRect())); -} - -/*! - Render the frame into \a painter clipping to \a clip. -*/ -void QWebFrame::render(QPainter* painter, const QRegion& clip) -{ - GraphicsContext context(painter); - if (context.paintingDisabled() && !context.updatingControlTints()) - return; - - d->renderRelativeCoords(&context, AllLayers, clip); -} - -/*! - Render the frame into \a painter. -*/ -void QWebFrame::render(QPainter* painter) -{ - if (!d->frame->view()) - return; - - GraphicsContext context(painter); - if (context.paintingDisabled() && !context.updatingControlTints()) - return; - - d->renderRelativeCoords(&context, AllLayers, QRegion(d->frame->view()->frameRect())); -} - -/*! - \property QWebFrame::textSizeMultiplier - \brief the scaling factor for all text in the frame - \obsolete - - Use setZoomFactor instead, in combination with the ZoomTextOnly attribute in - QWebSettings. - - \note Setting this property also enables the ZoomTextOnly attribute in - QWebSettings. -*/ - -/*! - Sets the value of the multiplier used to scale the text in a Web frame to - the \a factor specified. -*/ -void QWebFrame::setTextSizeMultiplier(qreal factor) -{ - page()->settings()->setAttribute(QWebSettings::ZoomTextOnly, true); - - d->frame->setPageAndTextZoomFactors(1, factor); -} - -/*! - Returns the value of the multiplier used to scale the text in a Web frame. -*/ -qreal QWebFrame::textSizeMultiplier() const -{ - return page()->settings()->testAttribute(QWebSettings::ZoomTextOnly) ? d->frame->textZoomFactor() : d->frame->pageZoomFactor(); -} - -/*! - \property QWebFrame::zoomFactor - \since 4.5 - \brief the zoom factor for the frame -*/ - -void QWebFrame::setZoomFactor(qreal factor) -{ - if (page()->settings()->testAttribute(QWebSettings::ZoomTextOnly)) - d->frame->setTextZoomFactor(factor); - else - d->frame->setPageZoomFactor(factor); -} - -qreal QWebFrame::zoomFactor() const -{ - return page()->settings()->testAttribute(QWebSettings::ZoomTextOnly) ? d->frame->textZoomFactor() : d->frame->pageZoomFactor(); -} - -/*! - \property QWebFrame::focus - \since 4.6 - - Returns true if this frame has keyboard input focus; otherwise, returns false. -*/ -bool QWebFrame::hasFocus() const -{ - WebCore::Frame* ff = d->frame->page()->focusController()->focusedFrame(); - return ff && QWebFramePrivate::kit(ff) == this; -} - -/*! - \since 4.6 - - Gives keyboard input focus to this frame. -*/ -void QWebFrame::setFocus() -{ - QWebFramePrivate::core(this)->page()->focusController()->setFocusedFrame(QWebFramePrivate::core(this)); -} - -/*! - Returns the position of the frame relative to it's parent frame. -*/ -QPoint QWebFrame::pos() const -{ - if (!d->frame->view()) - return QPoint(); - - return d->frame->view()->frameRect().location(); -} - -/*! - Return the geometry of the frame relative to it's parent frame. -*/ -QRect QWebFrame::geometry() const -{ - return d->frameRect(); -} - -/*! - \property QWebFrame::contentsSize - \brief the size of the contents in this frame - - \sa contentsSizeChanged() -*/ -QSize QWebFrame::contentsSize() const -{ - FrameView *view = d->frame->view(); - if (!view) - return QSize(); - return QSize(view->contentsWidth(), view->contentsHeight()); -} - -/*! - \since 4.6 - - Returns the document element of this frame. - - The document element provides access to the entire structured - content of the frame. -*/ -QWebElement QWebFrame::documentElement() const -{ - WebCore::Document *doc = d->frame->document(); - if (!doc) - return QWebElement(); - return QWebElement(doc->documentElement()); -} - -/*! - \since 4.6 - Returns a new list of elements matching the given CSS selector \a selectorQuery. - If there are no matching elements, an empty list is returned. - - \l{http://www.w3.org/TR/REC-CSS2/selector.html#q1}{Standard CSS2 selector} syntax is - used for the query. - - \sa QWebElement::findAll() -*/ -QWebElementCollection QWebFrame::findAllElements(const QString &selectorQuery) const -{ - return documentElement().findAll(selectorQuery); -} - -/*! - \since 4.6 - Returns the first element in the frame's document that matches the - given CSS selector \a selectorQuery. If there is no matching element, a - null element is returned. - - \l{http://www.w3.org/TR/REC-CSS2/selector.html#q1}{Standard CSS2 selector} syntax is - used for the query. - - \sa QWebElement::findFirst() -*/ -QWebElement QWebFrame::findFirstElement(const QString &selectorQuery) const -{ - return documentElement().findFirst(selectorQuery); -} - -/*! - Performs a hit test on the frame contents at the given position \a pos and returns the hit test result. -*/ -QWebHitTestResult QWebFrame::hitTestContent(const QPoint &pos) const -{ - if (!d->frame->view() || !d->frame->contentRenderer()) - return QWebHitTestResult(); - - HitTestResult result = d->frame->eventHandler()->hitTestResultAtPoint(d->frame->view()->windowToContents(pos), /*allowShadowContent*/ false, /*ignoreClipping*/ true); - - if (result.scrollbar()) - return QWebHitTestResult(); - - return QWebHitTestResult(new QWebHitTestResultPrivate(result)); -} - -/*! \reimp -*/ -bool QWebFrame::event(QEvent *e) -{ - return QObject::event(e); -} - -#ifndef QT_NO_PRINTER -/*! - Prints the frame to the given \a printer. - - \sa render() -*/ -void QWebFrame::print(QPrinter *printer) const -{ -#if HAVE(QTPRINTSUPPORT) - QPainter painter; - if (!painter.begin(printer)) - return; - - const qreal zoomFactorX = (qreal)printer->logicalDpiX() / qt_defaultDpi(); - const qreal zoomFactorY = (qreal)printer->logicalDpiY() / qt_defaultDpi(); - - PrintContext printContext(d->frame); - float pageHeight = 0; - - QRect qprinterRect = printer->pageRect(); - - IntRect pageRect(0, 0, - int(qprinterRect.width() / zoomFactorX), - int(qprinterRect.height() / zoomFactorY)); - - printContext.begin(pageRect.width(), pageRect.height()); - - printContext.computePageRects(pageRect, /* headerHeight */ 0, /* footerHeight */ 0, /* userScaleFactor */ 1.0, pageHeight); - - int docCopies; - int pageCopies; - if (printer->collateCopies()) { - docCopies = 1; - pageCopies = printer->numCopies(); - } else { - docCopies = printer->numCopies(); - pageCopies = 1; - } - - int fromPage = printer->fromPage(); - int toPage = printer->toPage(); - bool ascending = true; - - if (fromPage == 0 && toPage == 0) { - fromPage = 1; - toPage = printContext.pageCount(); - } - // paranoia check - fromPage = qMax(1, fromPage); - toPage = qMin(static_cast<int>(printContext.pageCount()), toPage); - if (toPage < fromPage) { - // if the user entered a page range outside the actual number - // of printable pages, just return - return; - } - - if (printer->pageOrder() == QPrinter::LastPageFirst) { - int tmp = fromPage; - fromPage = toPage; - toPage = tmp; - ascending = false; - } - - painter.scale(zoomFactorX, zoomFactorY); - GraphicsContext ctx(&painter); - - for (int i = 0; i < docCopies; ++i) { - int page = fromPage; - while (true) { - for (int j = 0; j < pageCopies; ++j) { - if (printer->printerState() == QPrinter::Aborted - || printer->printerState() == QPrinter::Error) { - printContext.end(); - return; - } - printContext.spoolPage(ctx, page - 1, pageRect.width()); - if (j < pageCopies - 1) - printer->newPage(); - } - - if (page == toPage) - break; - - if (ascending) - ++page; - else - --page; - - printer->newPage(); - } - - if ( i < docCopies - 1) - printer->newPage(); - } - - printContext.end(); -#endif // HAVE(PRINTSUPPORT) -} -#endif // QT_NO_PRINTER - -/*! - Evaluates the JavaScript defined by \a scriptSource using this frame as context - and returns the result of the last executed statement. - - \sa addToJavaScriptWindowObject(), javaScriptWindowObjectCleared() -*/ -QVariant QWebFrame::evaluateJavaScript(const QString& scriptSource) -{ - ScriptController *proxy = d->frame->script(); - QVariant rc; - if (proxy) { - int distance = 0; - JSC::JSValue v = d->frame->script()->executeScript(ScriptSourceCode(scriptSource)).jsValue(); - JSC::ExecState* exec = proxy->globalObject(mainThreadNormalWorld())->globalExec(); - JSValueRef* ignoredException = 0; - rc = JSC::Bindings::convertValueToQVariant(toRef(exec), toRef(exec, v), QMetaType::Void, &distance, ignoredException); - } - return rc; -} - -/*! - \since 4.5 - - Returns the frame's security origin. -*/ -QWebSecurityOrigin QWebFrame::securityOrigin() const -{ - QWebFrame* that = const_cast<QWebFrame*>(this); - QWebSecurityOriginPrivate* priv = new QWebSecurityOriginPrivate(QWebFramePrivate::core(that)->document()->securityOrigin()); - return QWebSecurityOrigin(priv); -} - -WebCore::Frame* QWebFramePrivate::core(const QWebFrame* webFrame) -{ - return webFrame->d->frame; -} - -QWebFrame* QWebFramePrivate::kit(const WebCore::Frame* coreFrame) -{ - return qobject_cast<QWebFrame*>(coreFrame->loader()->networkingContext()->originatingObject()); -} - -QWebFrame *QWebFramePrivate::kit(const QWebFrameAdapter* frameAdapter) -{ - return static_cast<const QWebFramePrivate*>(frameAdapter)->q; -} - - -/*! - \fn void QWebFrame::javaScriptWindowObjectCleared() - - This signal is emitted whenever the global window object of the JavaScript - environment is cleared, e.g., before starting a new load. - - If you intend to add QObjects to a QWebFrame using - addToJavaScriptWindowObject(), you should add them in a slot connected - to this signal. This ensures that your objects remain accessible when - loading new URLs. -*/ - -/*! - \fn void QWebFrame::provisionalLoad() - \internal -*/ - -/*! - \fn void QWebFrame::titleChanged(const QString &title) - - This signal is emitted whenever the title of the frame changes. - The \a title string specifies the new title. - - \sa title() -*/ - -/*! - \fn void QWebFrame::urlChanged(const QUrl &url) - - This signal is emitted with the URL of the frame when the frame's title is - received. The new URL is specified by \a url. - - \sa url() -*/ - -/*! - \fn void QWebFrame::initialLayoutCompleted() - - This signal is emitted when the frame is laid out the first time. - This is the first time you will see contents displayed on the frame. - - \note A frame can be laid out multiple times. -*/ - -/*! - \fn void QWebFrame::iconChanged() - - This signal is emitted when the icon ("favicon") associated with the frame - has been loaded. - - \sa icon() -*/ - -/*! - \fn void QWebFrame::contentsSizeChanged(const QSize &size) - \since 4.6 - - This signal is emitted when the frame's contents size changes - to \a size. - - \sa contentsSize() -*/ - -/*! - \fn void QWebFrame::loadStarted() - \since 4.6 - - This signal is emitted when a new load of this frame is started. - - \sa loadFinished() -*/ - -/*! - \fn void QWebFrame::loadFinished(bool ok) - \since 4.6 - - This signal is emitted when a load of this frame is finished. - \a ok will indicate whether the load was successful or any error occurred. - - \sa loadStarted() -*/ - -/*! - \fn void QWebFrame::pageChanged() - \since 4.7 - - This signal is emitted when this frame has been moved to a different QWebPage. - - \sa page() -*/ - -/*! - \class QWebHitTestResult - \since 4.4 - \brief The QWebHitTestResult class provides information about the web - page content after a hit test. - - \inmodule QtWebKit - - QWebHitTestResult is returned by QWebFrame::hitTestContent() to provide - information about the content of the web page at the specified position. -*/ - -/*! - \internal -*/ -QWebHitTestResult::QWebHitTestResult(QWebHitTestResultPrivate *priv) - : d(priv) -{ -} - -QWebHitTestResultPrivate::QWebHitTestResultPrivate(const WebCore::HitTestResult &hitTest) - : isContentEditable(false) - , isContentSelected(false) - , isScrollBar(false) -{ - if (!hitTest.innerNode()) - return; - pos = hitTest.roundedPointInInnerNodeFrame(); - WebCore::TextDirection dir; - title = hitTest.title(dir); - linkText = hitTest.textContent(); - linkUrl = hitTest.absoluteLinkURL(); - linkTitle = hitTest.titleDisplayString(); - alternateText = hitTest.altDisplayString(); - imageUrl = hitTest.absoluteImageURL(); - innerNode = hitTest.innerNode(); - innerNonSharedNode = hitTest.innerNonSharedNode(); - boundingRect = innerNonSharedNode ? innerNonSharedNode->renderer()->absoluteBoundingBoxRect() : IntRect(); - WebCore::Image *img = hitTest.image(); - if (img) { - QPixmap *pix = img->nativeImageForCurrentFrame(); - if (pix) - pixmap = *pix; - } - WebCore::Frame *wframe = hitTest.targetFrame(); - if (wframe) - linkTargetFrame = QWebFramePrivate::kit(wframe); - linkElement = QWebElement(hitTest.URLElement()); - - isContentEditable = hitTest.isContentEditable(); - isContentSelected = hitTest.isSelected(); - isScrollBar = hitTest.scrollbar(); - - WebCore::Frame *innerNodeFrame = hitTest.innerNodeFrame(); - if (innerNodeFrame) - frame = QWebFramePrivate::kit(innerNodeFrame); - - enclosingBlock = QWebElement(WebCore::enclosingBlock(innerNode.get())); -} - -/*! - Constructs a null hit test result. -*/ -QWebHitTestResult::QWebHitTestResult() - : d(0) -{ -} - -/*! - Constructs a hit test result from \a other. -*/ -QWebHitTestResult::QWebHitTestResult(const QWebHitTestResult &other) - : d(0) -{ - if (other.d) - d = new QWebHitTestResultPrivate(*other.d); -} - -/*! - Assigns the \a other hit test result to this. -*/ -QWebHitTestResult &QWebHitTestResult::operator=(const QWebHitTestResult &other) -{ - if (this != &other) { - if (other.d) { - if (!d) - d = new QWebHitTestResultPrivate; - *d = *other.d; - } else { - delete d; - d = 0; - } - } - return *this; -} - -/*! - Destructor. -*/ -QWebHitTestResult::~QWebHitTestResult() -{ - delete d; -} - -/*! - Returns true if the hit test result is null; otherwise returns false. -*/ -bool QWebHitTestResult::isNull() const -{ - return !d; -} - -/*! - Returns the position where the hit test occured in the coordinates of frame containing the element hit. - - \sa frame() -*/ -QPoint QWebHitTestResult::pos() const -{ - if (!d) - return QPoint(); - return d->pos; -} - -/*! - \since 4.5 - Returns the bounding rect of the element. -*/ -QRect QWebHitTestResult::boundingRect() const -{ - if (!d) - return QRect(); - return d->boundingRect; -} - -/*! - \since 4.6 - Returns the block element that encloses the element hit. - - A block element is an element that is rendered using the - CSS "block" style. This includes for example text - paragraphs. -*/ -QWebElement QWebHitTestResult::enclosingBlockElement() const -{ - if (!d) - return QWebElement(); - return d->enclosingBlock; -} - -/*! - Returns the title of the nearest enclosing HTML element. -*/ -QString QWebHitTestResult::title() const -{ - if (!d) - return QString(); - return d->title; -} - -/*! - Returns the text of the link. -*/ -QString QWebHitTestResult::linkText() const -{ - if (!d) - return QString(); - return d->linkText; -} - -/*! - Returns the url to which the link points to. -*/ -QUrl QWebHitTestResult::linkUrl() const -{ - if (!d) - return QUrl(); - return d->linkUrl; -} - -/*! - Returns the title of the link. -*/ -QUrl QWebHitTestResult::linkTitle() const -{ - if (!d) - return QUrl(); - return d->linkTitle; -} - -/*! - \since 4.6 - Returns the element that represents the link. - - \sa linkTargetFrame() -*/ -QWebElement QWebHitTestResult::linkElement() const -{ - if (!d) - return QWebElement(); - return d->linkElement; -} - -/*! - Returns the frame that will load the link if it is activated. - - \sa linkElement() -*/ -QWebFrame *QWebHitTestResult::linkTargetFrame() const -{ - if (!d) - return 0; - return d->linkTargetFrame.data(); -} - -/*! - Returns the alternate text of the element. This corresponds to the HTML alt attribute. -*/ -QString QWebHitTestResult::alternateText() const -{ - if (!d) - return QString(); - return d->alternateText; -} - -/*! - Returns the url of the image. -*/ -QUrl QWebHitTestResult::imageUrl() const -{ - if (!d) - return QUrl(); - return d->imageUrl; -} - -/*! - Returns a QPixmap containing the image. A null pixmap is returned if the - element being tested is not an image. -*/ -QPixmap QWebHitTestResult::pixmap() const -{ - if (!d) - return QPixmap(); - return d->pixmap; -} - -/*! - Returns true if the content is editable by the user; otherwise returns false. -*/ -bool QWebHitTestResult::isContentEditable() const -{ - if (!d) - return false; - return d->isContentEditable; -} - -/*! - Returns true if the content tested is part of the selection; otherwise returns false. -*/ -bool QWebHitTestResult::isContentSelected() const -{ - if (!d) - return false; - return d->isContentSelected; -} - -/*! - \since 4.6 - Returns the underlying DOM element as QWebElement. -*/ -QWebElement QWebHitTestResult::element() const -{ - if (!d || !d->innerNonSharedNode || !d->innerNonSharedNode->isElementNode()) - return QWebElement(); - - return QWebElement(static_cast<WebCore::Element*>(d->innerNonSharedNode.get())); -} - -/*! - Returns the frame of the element hit. -*/ -QWebFrame *QWebHitTestResult::frame() const -{ - if (!d) - return 0; - return d->frame.data(); -} - -/*! - * \internal - */ -QWebFrameAdapter *QWebFrame::handle() const -{ - return d; -} - -#include "moc_qwebframe.cpp" diff --git a/Source/WebKit/qt/Api/qwebframe.h b/Source/WebKit/qt/Api/qwebframe.h deleted file mode 100644 index fe00d81f5..000000000 --- a/Source/WebKit/qt/Api/qwebframe.h +++ /dev/null @@ -1,245 +0,0 @@ -/* - Copyright (C) 2008,2009 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2007 Staikos Computing Services Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QWEBFRAME_H -#define QWEBFRAME_H - -#include <QtCore/qobject.h> -#include <QtCore/qurl.h> -#include <QtCore/qvariant.h> -#include <QtGui/qicon.h> -#include <QtNetwork/qnetworkaccessmanager.h> -#include "qwebkitglobal.h" - -QT_BEGIN_NAMESPACE -class QRect; -class QPoint; -class QPainter; -class QPixmap; -class QMouseEvent; -class QWheelEvent; -class QNetworkRequest; -class QRegion; -class QPrinter; -QT_END_NAMESPACE - -class QWebNetworkRequest; -class QWebFrameAdapter; -class QWebFramePrivate; -class QWebPage; -class QWebPageAdapter; -class QWebHitTestResult; -class QWebHistoryItem; -class QWebSecurityOrigin; -class QWebElement; -class QWebElementCollection; -class QWebScriptWorld; - -class DumpRenderTreeSupportQt; -namespace WebCore { - class WidgetPrivate; - class FrameLoaderClientQt; - class ChromeClientQt; - class TextureMapperLayerClientQt; -} -class QWebFrameData; -class QWebHitTestResultPrivate; -class QWebFrame; - -class QWEBKIT_EXPORT QWebHitTestResult { -public: - QWebHitTestResult(); - QWebHitTestResult(const QWebHitTestResult &other); - QWebHitTestResult &operator=(const QWebHitTestResult &other); - ~QWebHitTestResult(); - - bool isNull() const; - - QPoint pos() const; - QRect boundingRect() const; - QWebElement enclosingBlockElement() const; - QString title() const; - - QString linkText() const; - QUrl linkUrl() const; - QUrl linkTitle() const; - QWebFrame *linkTargetFrame() const; - QWebElement linkElement() const; - - QString alternateText() const; // for img, area, input and applet - - QUrl imageUrl() const; - QPixmap pixmap() const; - - bool isContentEditable() const; - bool isContentSelected() const; - - QWebElement element() const; - - QWebFrame *frame() const; - -private: - QWebHitTestResult(QWebHitTestResultPrivate *priv); - QWebHitTestResultPrivate *d; - - friend class QWebFrame; - friend class QWebPagePrivate; - friend class QWebPage; -}; - -class QWEBKIT_EXPORT QWebFrame : public QObject { - Q_OBJECT - Q_PROPERTY(qreal textSizeMultiplier READ textSizeMultiplier WRITE setTextSizeMultiplier DESIGNABLE false) - Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor) - Q_PROPERTY(QString title READ title) - Q_PROPERTY(QUrl url READ url WRITE setUrl) - Q_PROPERTY(QUrl requestedUrl READ requestedUrl) - Q_PROPERTY(QUrl baseUrl READ baseUrl) - Q_PROPERTY(QIcon icon READ icon) - Q_PROPERTY(QSize contentsSize READ contentsSize) - Q_PROPERTY(QPoint scrollPosition READ scrollPosition WRITE setScrollPosition) - Q_PROPERTY(bool focus READ hasFocus) -private: - QWebFrame(QWebPage *parentPage); - QWebFrame(QWebFrame* parent, QWebFrameData*); - ~QWebFrame(); - -public: - enum ValueOwnership { - QtOwnership, - ScriptOwnership, - AutoOwnership - }; - - QWebPage *page() const; - - void load(const QUrl &url); - void load(const QNetworkRequest &request, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, const QByteArray &body = QByteArray()); - void setHtml(const QString &html, const QUrl &baseUrl = QUrl()); - void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl()); - - void addToJavaScriptWindowObject(const QString &name, QObject *object, ValueOwnership ownership = QtOwnership); - QString toHtml() const; - QString toPlainText() const; - QString renderTreeDump() const; - - QString title() const; - void setUrl(const QUrl &url); - QUrl url() const; - QUrl requestedUrl() const; - QUrl baseUrl() const; - QIcon icon() const; - QMultiMap<QString, QString> metaData() const; - - QString frameName() const; - - QWebFrame *parentFrame() const; - QList<QWebFrame*> childFrames() const; - - Qt::ScrollBarPolicy scrollBarPolicy(Qt::Orientation orientation) const; - void setScrollBarPolicy(Qt::Orientation orientation, Qt::ScrollBarPolicy policy); - - void setScrollBarValue(Qt::Orientation orientation, int value); - int scrollBarValue(Qt::Orientation orientation) const; - int scrollBarMinimum(Qt::Orientation orientation) const; - int scrollBarMaximum(Qt::Orientation orientation) const; - QRect scrollBarGeometry(Qt::Orientation orientation) const; - - void scroll(int, int); - QPoint scrollPosition() const; - void setScrollPosition(const QPoint &pos); - - void scrollToAnchor(const QString& anchor); - - enum RenderLayer { - ContentsLayer = 0x10, - ScrollBarLayer = 0x20, - PanIconLayer = 0x40, - - AllLayers = 0xff - }; - - void render(QPainter*); - void render(QPainter*, const QRegion& clip); - void render(QPainter*, RenderLayer layer, const QRegion& clip = QRegion()); - - void setTextSizeMultiplier(qreal factor); - qreal textSizeMultiplier() const; - - qreal zoomFactor() const; - void setZoomFactor(qreal factor); - - bool hasFocus() const; - void setFocus(); - - QPoint pos() const; - QRect geometry() const; - QSize contentsSize() const; - - QWebElement documentElement() const; - QWebElementCollection findAllElements(const QString &selectorQuery) const; - QWebElement findFirstElement(const QString &selectorQuery) const; - - QWebHitTestResult hitTestContent(const QPoint &pos) const; - - virtual bool event(QEvent *); - - QWebSecurityOrigin securityOrigin() const; - QWebFrameAdapter* handle() const; - -public Q_SLOTS: - QVariant evaluateJavaScript(const QString& scriptSource); -#ifndef QT_NO_PRINTER - void print(QPrinter *printer) const; -#endif - -Q_SIGNALS: - void javaScriptWindowObjectCleared(); - - void provisionalLoad(); - void titleChanged(const QString &title); - void urlChanged(const QUrl &url); - - void initialLayoutCompleted(); - - void iconChanged(); - - void contentsSizeChanged(const QSize &size); - - void loadStarted(); - void loadFinished(bool ok); - - void pageChanged(); - -private: - friend class QGraphicsWebView; - friend class QWebPage; - friend class QWebPagePrivate; - friend class QWebFramePrivate; - friend class DumpRenderTreeSupportQt; - friend class WebCore::WidgetPrivate; - friend class WebCore::FrameLoaderClientQt; - friend class WebCore::ChromeClientQt; - friend class WebCore::TextureMapperLayerClientQt; - QWebFramePrivate *d; - Q_PRIVATE_SLOT(d, void _q_orientationChanged()) -}; - -#endif diff --git a/Source/WebKit/qt/Api/qwebframe_p.h b/Source/WebKit/qt/Api/qwebframe_p.h deleted file mode 100644 index dbdcbc85a..000000000 --- a/Source/WebKit/qt/Api/qwebframe_p.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2007 Staikos Computing Services Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QWEBFRAME_P_H -#define QWEBFRAME_P_H - -#include "QWebFrameAdapter.h" - -#include "qwebframe.h" -#include "qwebpage_p.h" - -#include "EventHandler.h" -#include "Frame.h" -#include "GraphicsContext.h" -#include "KURL.h" -#if ENABLE(ORIENTATION_EVENTS) -#include "qorientationsensor.h" -#endif // ENABLE(ORIENTATION_EVENTS). -#include "qwebelement.h" -#if USE(ACCELERATED_COMPOSITING) -#include "texmap/TextureMapper.h" -#endif -#include "ViewportArguments.h" -#include <wtf/RefPtr.h> -#include <wtf/text/WTFString.h> - - -namespace WebCore { - class FrameLoaderClientQt; - class FrameView; - class HTMLFrameOwnerElement; - class Scrollbar; - class TextureMapperLayer; -} -class QWebPage; - -class QWebFramePrivate : public QWebFrameAdapter { -public: - QWebFramePrivate() - : q(0) - , horizontalScrollBarPolicy(Qt::ScrollBarAsNeeded) - , verticalScrollBarPolicy(Qt::ScrollBarAsNeeded) - , page(0) -#if USE(ACCELERATED_COMPOSITING) - , rootTextureMapperLayer(0) -#endif - {} - void setPage(QWebPage*); - - inline QWebFrame *parentFrame() { return qobject_cast<QWebFrame*>(q->parent()); } - - WebCore::Scrollbar* horizontalScrollBar() const; - WebCore::Scrollbar* verticalScrollBar() const; - - static WebCore::Frame* core(const QWebFrame*); - static QWebFrame* kit(const WebCore::Frame*); - static QWebFrame* kit(const QWebFrameAdapter*); - - void renderRelativeCoords(WebCore::GraphicsContext*, QFlags<QWebFrame::RenderLayer>, const QRegion& clip); -#if USE(TILED_BACKING_STORE) - void renderFromTiledBackingStore(WebCore::GraphicsContext*, const QRegion& clip); -#endif - -#if USE(ACCELERATED_COMPOSITING) - void renderCompositedLayers(WebCore::GraphicsContext*, const WebCore::IntRect& clip); -#endif - void renderFrameExtras(WebCore::GraphicsContext*, QFlags<QWebFrame::RenderLayer>, const QRegion& clip); - void _q_orientationChanged(); - - - // Adapter implementation - virtual QWebFrame* apiHandle() OVERRIDE; - virtual QObject* handle() OVERRIDE; - virtual void contentsSizeDidChange(const QSize &) OVERRIDE; - virtual int scrollBarPolicy(Qt::Orientation) const OVERRIDE; - virtual void emitUrlChanged() OVERRIDE; - virtual void didStartProvisionalLoad() OVERRIDE; - virtual void didClearWindowObject() OVERRIDE; - virtual bool handleProgressFinished(QPoint*) OVERRIDE; - virtual void emitInitialLayoutCompleted() OVERRIDE; - virtual void emitIconChanged() OVERRIDE; - virtual void emitLoadStarted(bool originatingLoad) OVERRIDE; - virtual void emitLoadFinished(bool originatingLoad, bool ok) OVERRIDE; - virtual QWebFrameAdapter* createChildFrame(QWebFrameData*) OVERRIDE; - - QWebFrame *q; - Qt::ScrollBarPolicy horizontalScrollBarPolicy; - Qt::ScrollBarPolicy verticalScrollBarPolicy; - QWebPage *page; - -#if USE(ACCELERATED_COMPOSITING) - WebCore::TextureMapperLayer* rootTextureMapperLayer; - OwnPtr<WebCore::TextureMapper> textureMapper; -#endif - -#if ENABLE(ORIENTATION_EVENTS) - QOrientationSensor m_orientation; -#endif // ENABLE(ORIENTATION_EVENTS). -}; - -class QWebHitTestResultPrivate { -public: - QWebHitTestResultPrivate() : isContentEditable(false), isContentSelected(false), isScrollBar(false) {} - QWebHitTestResultPrivate(const WebCore::HitTestResult &hitTest); - - QPoint pos; - QRect boundingRect; - QWebElement enclosingBlock; - QString title; - QString linkText; - QUrl linkUrl; - QString linkTitle; - QPointer<QWebFrame> linkTargetFrame; - QWebElement linkElement; - QString alternateText; - QUrl imageUrl; - QPixmap pixmap; - bool isContentEditable; - bool isContentSelected; - bool isScrollBar; - QPointer<QWebFrame> frame; - RefPtr<WebCore::Node> innerNode; - RefPtr<WebCore::Node> innerNonSharedNode; -}; - -#endif diff --git a/Source/WebKit/qt/Api/qwebhistory.h b/Source/WebKit/qt/Api/qwebhistory.h index 753eb6376..092f425ee 100644 --- a/Source/WebKit/qt/Api/qwebhistory.h +++ b/Source/WebKit/qt/Api/qwebhistory.h @@ -101,7 +101,7 @@ private: ~QWebHistory(); friend class QWebPage; - friend class QWebPagePrivate; + friend class QWebPageAdapter; friend QWEBKIT_EXPORT QDataStream& operator>>(QDataStream&, QWebHistory&); friend QWEBKIT_EXPORT QDataStream& operator<<(QDataStream&, const QWebHistory&); diff --git a/Source/WebKit/qt/Api/qwebinspector.cpp b/Source/WebKit/qt/Api/qwebinspector.cpp deleted file mode 100644 index 55089e1a1..000000000 --- a/Source/WebKit/qt/Api/qwebinspector.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" -#include "qwebinspector.h" - -#include "Element.h" -#include "InspectorController.h" -#include "qwebelement.h" -#include "qwebinspector_p.h" -#include "qwebpage_p.h" - -#include <QResizeEvent> - -/*! - \class QWebInspector - \since 4.6 - \inmodule QtWebKit - \brief The QWebInspector class allows the placement and control of a - QWebPage's inspector. - The inspector can display a page's hierarchy, its loading statistics and - the current state of its individual elements. It is mostly used by web - developers. - - The QWebPage to be inspected must be specified using the setPage() method. - - A typical use of QWebInspector follows: - - \snippet webkitsnippets/qtwebkit_qwebinspector_snippet.cpp 0 - - A QWebInspector can be made visible either programmatically using - setVisible(), or by the user through the attached QWebPage's context - menu. - - \note A QWebInspector will display a blank widget if either: - \list - \li page() is null - \li QWebSettings::DeveloperExtrasEnabled is false - \endlist - - \section1 Resources - - This class acts mostly as a container and a controller for the inspector. - Most of the resources needed by the inspector are owned by the associated - QWebPage and are allocated the first time that: - \list - \li an element is inspected - \li the QWebInspector is shown. - \endlist - - \section1 Inspector configuration persistence - - The inspector allows the user to configure some options through its - user interface (e.g. the resource tracking "Always enable" option). - These settings will be persisted automatically by QtWebKit only if - your application previously called QCoreApplication::setOrganizationName() - and QCoreApplication::setApplicationName(). - See QSettings's default constructor documentation for an explanation - of why this is necessary. -*/ - -/*! - Constructs an unbound QWebInspector with \a parent as its parent. -*/ -QWebInspector::QWebInspector(QWidget* parent) - : QWidget(parent) - , d(new QWebInspectorPrivate(this)) -{ -} - -/*! - Destroys the inspector. -*/ -QWebInspector::~QWebInspector() -{ - // Remove association principally to prevent deleting a child frontend - setPage(0); - delete d; - d = 0; -} - -/*! - Bind this inspector to the QWebPage to be inspected. - - \b {Notes:} - \list - \li There can only be one QWebInspector associated with a QWebPage - and vice versa. - \li Calling this method with a null \a page will break the current association, if any. - \li If \a page is already associated to another QWebInspector, the association - will be replaced and the previous QWebInspector will become unbound - \endlist - - \sa page() -*/ -void QWebInspector::setPage(QWebPage* page) -{ - if (d->page) { - // Break currentPage-->this - d->page->d->setInspector(0); - } - if (page && page->d->inspector && page->d->inspector != this) { - // Break newPage<->newPageCurrentInspector - page->d->inspector->setPage(0); - } - - d->page = page; - - if (page) { - // Setup the reciprocal association - page->d->setInspector(this); - } -} - -/*! - Returns the inspected QWebPage. - If no web page is currently associated, a null pointer is returned. -*/ -QWebPage* QWebInspector::page() const -{ - return d->page; -} - -/*! \reimp */ -QSize QWebInspector::sizeHint() const -{ - return QSize(450, 300); -} - -/*! \reimp */ -bool QWebInspector::event(QEvent* ev) -{ - return QWidget::event(ev); -} - -/*! \reimp */ -void QWebInspector::resizeEvent(QResizeEvent* event) -{ - d->adjustFrontendSize(event->size()); -} - -/*! \reimp */ -void QWebInspector::showEvent(QShowEvent* event) -{ -#if ENABLE(INSPECTOR) - // Allows QWebInspector::show() to init the inspector. - if (d->page) - d->page->d->inspectorController()->show(); -#endif -} - -/*! \reimp */ -void QWebInspector::hideEvent(QHideEvent* event) -{ -#if ENABLE(INSPECTOR) - if (d->page) - d->page->d->inspectorController()->close(); -#endif -} - -/*! \reimp */ -void QWebInspector::closeEvent(QCloseEvent* event) -{ -#if ENABLE(INSPECTOR) - if (d->page) - d->page->d->inspectorController()->close(); -#endif -} - -/*! \internal */ -void QWebInspectorPrivate::setFrontend(QObject* newFrontend) -{ - if (frontend) - frontend->setParent(0); - - frontend = qobject_cast<QWidget*>(newFrontend); - - if (frontend) { - frontend->setParent(q); - frontend->show(); - adjustFrontendSize(q->size()); - } -} - -void QWebInspectorPrivate::adjustFrontendSize(const QSize& size) -{ - if (frontend) - frontend->resize(size); -} - diff --git a/Source/WebKit/qt/Api/qwebinspector.h b/Source/WebKit/qt/Api/qwebinspector.h deleted file mode 100644 index f192e921b..000000000 --- a/Source/WebKit/qt/Api/qwebinspector.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QWEBINSPECTOR_H -#define QWEBINSPECTOR_H - -#include "qwebkitglobal.h" -#include "qwebpage.h" - -#include "qwebview.h" - -class QWebInspectorPrivate; - -class QWEBKIT_EXPORT QWebInspector : public QWidget { - Q_OBJECT -public: - QWebInspector(QWidget* parent = 0); - ~QWebInspector(); - - void setPage(QWebPage* page); - QWebPage* page() const; - - QSize sizeHint() const; - bool event(QEvent*); - -protected: - void resizeEvent(QResizeEvent* event); - void showEvent(QShowEvent* event); - void hideEvent(QHideEvent* event); - void closeEvent(QCloseEvent* event); - -private: - QWebInspectorPrivate* d; - - friend class QWebInspectorPrivate; - friend class QWebPage; - friend class QWebPagePrivate; - friend class WebCore::InspectorClientQt; - friend class WebCore::InspectorFrontendClientQt; -}; -#endif diff --git a/Source/WebKit/qt/Api/qwebinspector_p.h b/Source/WebKit/qt/Api/qwebinspector_p.h deleted file mode 100644 index 908de84ed..000000000 --- a/Source/WebKit/qt/Api/qwebinspector_p.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright (C) 2008, 2009 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QWEBINSPECTOR_P_H -#define QWEBINSPECTOR_P_H - -QT_BEGIN_NAMESPACE -class QSize; -class QWidget; -QT_END_NAMESPACE -class QWebInspector; -class QWebPage; - -class QWebInspectorPrivate { -public: - QWebInspectorPrivate(QWebInspector* qq) - : q(qq) - , page(0) - , frontend(0) - {} - - void setFrontend(QObject* newFrontend); - void adjustFrontendSize(const QSize& size); - - QWebInspector* q; - QWebPage* page; - QWidget* frontend; -}; - -#endif diff --git a/Source/WebKit/qt/Api/qwebkitversion.cpp b/Source/WebKit/qt/Api/qwebkitglobal.cpp index 1143f99e0..0ae955b8f 100644 --- a/Source/WebKit/qt/Api/qwebkitversion.cpp +++ b/Source/WebKit/qt/Api/qwebkitglobal.cpp @@ -18,7 +18,8 @@ */ #include "config.h" -#include <qwebkitversion.h> +#include "qwebkitglobal.h" + #include <WebKitVersion.h> /*! diff --git a/Source/WebKit/qt/Api/qwebkitglobal.h b/Source/WebKit/qt/Api/qwebkitglobal.h index 947ba0654..1d61182c8 100644 --- a/Source/WebKit/qt/Api/qwebkitglobal.h +++ b/Source/WebKit/qt/Api/qwebkitglobal.h @@ -1,5 +1,6 @@ /* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + Copyright (C) 2009 Robert Hogan <robert@roberthogan.net> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public @@ -21,11 +22,8 @@ #define QWEBKITGLOBAL_H #include <QtCore/qglobal.h> +#include <QtCore/qstring.h> -#define QTWEBKIT_VERSION_STR "2.2.0" -// QTWEBKIT_VERSION is (major << 16) + (minor << 8) + patch. Similar to Qt. -#define QTWEBKIT_VERSION 0x020200 -// Use: #if (QTWEBKIT_VERSION >= QTWEBKIT_VERSION_CHECK(2, 0, 0)). Similar to Qt. #define QTWEBKIT_VERSION_CHECK(major, minor, patch) ((major<<16)|(minor<<8)|(patch)) #ifndef QT_STATIC @@ -38,4 +36,8 @@ # define QWEBKIT_EXPORT #endif +QWEBKIT_EXPORT QString qWebKitVersion(); +QWEBKIT_EXPORT int qWebKitMajorVersion(); +QWEBKIT_EXPORT int qWebKitMinorVersion(); + #endif // QWEBKITGLOBAL_H diff --git a/Source/WebKit/qt/Api/qwebkitversion.h b/Source/WebKit/qt/Api/qwebkitversion.h deleted file mode 100644 index de79dd1a7..000000000 --- a/Source/WebKit/qt/Api/qwebkitversion.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright (C) 2009 Robert Hogan <robert@roberthogan.net> - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include <QtCore/qstring.h> - -#ifndef qwebkitversion_h -#define qwebkitversion_h - -#include <QtCore/qstring.h> -#include "qwebkitglobal.h" - -QWEBKIT_EXPORT QString qWebKitVersion(); -QWEBKIT_EXPORT int qWebKitMajorVersion(); -QWEBKIT_EXPORT int qWebKitMinorVersion(); - -#endif // qwebkitversion_h diff --git a/Source/WebKit/qt/Api/qwebpage.cpp b/Source/WebKit/qt/Api/qwebpage.cpp deleted file mode 100644 index 65624d190..000000000 --- a/Source/WebKit/qt/Api/qwebpage.cpp +++ /dev/null @@ -1,4476 +0,0 @@ -/* - Copyright (C) 2008, 2009, 2012 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2007 Staikos Computing Services Inc. - Copyright (C) 2007 Apple Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" -#include "qwebpage.h" - -#include "CSSComputedStyleDeclaration.h" -#include "CSSParser.h" -#include "ApplicationCacheStorage.h" -#include "BackForwardListImpl.h" -#include "MemoryCache.h" -#include "Chrome.h" -#include "ChromeClientQt.h" -#include "ClientRect.h" -#include "ContextMenu.h" -#include "ContextMenuClientQt.h" -#include "ContextMenuController.h" -#if USE(QT_MULTIMEDIA) -#include "DefaultFullScreenVideoHandler.h" -#endif -#if ENABLE(DEVICE_ORIENTATION) -#include "DeviceMotionClientQt.h" -#include "DeviceOrientationClientMock.h" -#include "DeviceOrientationClientQt.h" -#endif -#include "DocumentLoader.h" -#include "DragClientQt.h" -#include "DragController.h" -#include "DragData.h" -#include "DragSession.h" -#include "Editor.h" -#include "EditorClientQt.h" -#include "FocusController.h" -#include "FormState.h" -#include "Frame.h" -#include "FrameLoadRequest.h" -#include "FrameLoader.h" -#include "FrameLoaderClientQt.h" -#include "FrameTree.h" -#include "FrameView.h" -#if ENABLE(GEOLOCATION) -#include "GeolocationClientMock.h" -#include "GeolocationClientQt.h" -#include "GeolocationController.h" -#endif -#include "GeolocationPermissionClientQt.h" -#include "HTMLFormElement.h" -#include "HTMLFrameOwnerElement.h" -#include "HTMLInputElement.h" -#include "HTMLNames.h" -#include "HitTestResult.h" -#include "Image.h" -#include "InitWebCoreQt.h" -#include "InitWebKitQt.h" -#include "InspectorClientQt.h" -#include "InspectorClientWebPage.h" -#include "InspectorController.h" -#include "InspectorServerQt.h" -#include "KURL.h" -#include "LocalizedStrings.h" -#include "MIMETypeRegistry.h" -#include "NavigationAction.h" -#include "NetworkingContext.h" -#include "NodeList.h" -#include "NotImplemented.h" -#include "NotificationPresenterClientQt.h" -#include "Page.h" -#include "PageClientQt.h" -#include "PageGroup.h" -#include "Pasteboard.h" -#include "PlatformKeyboardEvent.h" -#include "PlatformTouchEvent.h" -#include "PlatformWheelEvent.h" -#include "PluginDatabase.h" -#include "PluginPackage.h" -#include "ProgressTracker.h" -#include "QGraphicsWidgetPluginImpl.h" -#include "QWebUndoCommand.h" -#include "QWidgetPluginImpl.h" -#include "QtFallbackWebPopup.h" -#include "QtPlatformPlugin.h" -#include "RenderTextControl.h" -#include "RenderThemeQt.h" -#include "SchemeRegistry.h" -#include "Scrollbar.h" -#include "ScrollbarTheme.h" -#include "SecurityOrigin.h" -#include "Settings.h" -#if defined Q_OS_WIN32 -#include "SystemInfo.h" -#endif // Q_OS_WIN32 -#include "TextIterator.h" -#include "UndoStepQt.h" -#include "UserAgentQt.h" -#include "WebEventConversion.h" -#include "WebKitVersion.h" -#include "WindowFeatures.h" -#include "WorkerThread.h" - -#include "qwebframe.h" -#include "qwebframe_p.h" -#include "qwebhistory.h" -#include "qwebhistory_p.h" -#include "qwebinspector.h" -#include "qwebinspector_p.h" -#include "qwebkitplatformplugin.h" -#include "qwebkitversion.h" -#include "qwebpage_p.h" -#include "qwebsettings.h" -#include "qwebview.h" - -#include <QAction> -#include <QApplication> -#include <QBasicTimer> -#include <QBitArray> -#include <QClipboard> -#include <QColorDialog> -#include <QDebug> -#include <QDesktopWidget> -#include <QDragEnterEvent> -#include <QDragLeaveEvent> -#include <QDragMoveEvent> -#include <QDropEvent> -#include <QFileDialog> -#include <QGestureEvent> -#include <QInputDialog> -#include <QLabel> -#include <QMenu> -#include <QMessageBox> -#include <QNetworkAccessManager> -#include <QNetworkProxy> -#include <QNetworkRequest> -#include <QPainter> -#include <QSslSocket> -#include <QStyle> -#include <QSysInfo> -#if USE(QT_MOBILITY_SYSTEMINFO) -#include <qsysteminfo.h> -#endif -#include <QSystemTrayIcon> -#include <QTextCharFormat> -#include <QToolTip> -#include <QTouchEvent> -#include <QUndoStack> -#include <QUrl> -#if defined(Q_WS_X11) -#include <QX11Info> -#endif - -using namespace WebCore; - -// from text/qfont.cpp -QT_BEGIN_NAMESPACE -extern Q_GUI_EXPORT int qt_defaultDpi(); -QT_END_NAMESPACE - -// Lookup table mapping QWebPage::WebActions to the associated Editor commands -static const char* editorCommandWebActions[] = -{ - 0, // OpenLink, - - 0, // OpenLinkInNewWindow, - 0, // OpenFrameInNewWindow, - - 0, // DownloadLinkToDisk, - 0, // CopyLinkToClipboard, - - 0, // OpenImageInNewWindow, - 0, // DownloadImageToDisk, - 0, // CopyImageToClipboard, - - 0, // Back, - 0, // Forward, - 0, // Stop, - 0, // Reload, - - "Cut", // Cut, - "Copy", // Copy, - "Paste", // Paste, - - "Undo", // Undo, - "Redo", // Redo, - "MoveForward", // MoveToNextChar, - "MoveBackward", // MoveToPreviousChar, - "MoveWordForward", // MoveToNextWord, - "MoveWordBackward", // MoveToPreviousWord, - "MoveDown", // MoveToNextLine, - "MoveUp", // MoveToPreviousLine, - "MoveToBeginningOfLine", // MoveToStartOfLine, - "MoveToEndOfLine", // MoveToEndOfLine, - "MoveToBeginningOfParagraph", // MoveToStartOfBlock, - "MoveToEndOfParagraph", // MoveToEndOfBlock, - "MoveToBeginningOfDocument", // MoveToStartOfDocument, - "MoveToEndOfDocument", // MoveToEndOfDocument, - "MoveForwardAndModifySelection", // SelectNextChar, - "MoveBackwardAndModifySelection", // SelectPreviousChar, - "MoveWordForwardAndModifySelection", // SelectNextWord, - "MoveWordBackwardAndModifySelection", // SelectPreviousWord, - "MoveDownAndModifySelection", // SelectNextLine, - "MoveUpAndModifySelection", // SelectPreviousLine, - "MoveToBeginningOfLineAndModifySelection", // SelectStartOfLine, - "MoveToEndOfLineAndModifySelection", // SelectEndOfLine, - "MoveToBeginningOfParagraphAndModifySelection", // SelectStartOfBlock, - "MoveToEndOfParagraphAndModifySelection", // SelectEndOfBlock, - "MoveToBeginningOfDocumentAndModifySelection", //SelectStartOfDocument, - "MoveToEndOfDocumentAndModifySelection", // SelectEndOfDocument, - "DeleteWordBackward", // DeleteStartOfWord, - "DeleteWordForward", // DeleteEndOfWord, - - 0, // SetTextDirectionDefault, - 0, // SetTextDirectionLeftToRight, - 0, // SetTextDirectionRightToLeft, - - "ToggleBold", // ToggleBold, - "ToggleItalic", // ToggleItalic, - "ToggleUnderline", // ToggleUnderline, - - 0, // InspectElement, - - "InsertNewline", // InsertParagraphSeparator - "InsertLineBreak", // InsertLineSeparator - - "SelectAll", // SelectAll - 0, // ReloadAndBypassCache, - - "PasteAndMatchStyle", // PasteAndMatchStyle - "RemoveFormat", // RemoveFormat - "Strikethrough", // ToggleStrikethrough, - "Subscript", // ToggleSubscript - "Superscript", // ToggleSuperscript - "InsertUnorderedList", // InsertUnorderedList - "InsertOrderedList", // InsertOrderedList - "Indent", // Indent - "Outdent", // Outdent, - - "AlignCenter", // AlignCenter, - "AlignJustified", // AlignJustified, - "AlignLeft", // AlignLeft, - "AlignRight", // AlignRight, - - 0, // StopScheduledPageRefresh, - - 0, // CopyImageUrlToClipboard, - - 0, // OpenLinkInThisWindow, - - 0 // WebActionCount -}; - -// Lookup the appropriate editor command to use for WebAction \a action -const char* QWebPagePrivate::editorCommandForWebActions(QWebPage::WebAction action) -{ - if ((action > QWebPage::NoWebAction) && (action < int(sizeof(editorCommandWebActions) / sizeof(const char*)))) - return editorCommandWebActions[action]; - return 0; -} - -static inline DragOperation dropActionToDragOp(Qt::DropActions actions) -{ - unsigned result = 0; - if (actions & Qt::CopyAction) - result |= DragOperationCopy; - // DragOperationgeneric represents InternetExplorer's equivalent of Move operation, - // hence it should be considered as "move" - if (actions & Qt::MoveAction) - result |= (DragOperationMove | DragOperationGeneric); - if (actions & Qt::LinkAction) - result |= DragOperationLink; - if (result == (DragOperationCopy | DragOperationMove | DragOperationGeneric | DragOperationLink)) - result = DragOperationEvery; - return (DragOperation)result; -} - -static inline Qt::DropAction dragOpToDropAction(unsigned actions) -{ - Qt::DropAction result = Qt::IgnoreAction; - if (actions & DragOperationCopy) - result = Qt::CopyAction; - else if (actions & DragOperationMove) - result = Qt::MoveAction; - // DragOperationgeneric represents InternetExplorer's equivalent of Move operation, - // hence it should be considered as "move" - else if (actions & DragOperationGeneric) - result = Qt::MoveAction; - else if (actions & DragOperationLink) - result = Qt::LinkAction; - return result; -} - -QWebPagePrivate::QWebPagePrivate(QWebPage *qq) - : q(qq) -#ifndef QT_NO_UNDOSTACK - , undoStack(0) -#endif - , m_totalBytes(0) - , m_bytesReceived() - , clickCausedFocus(false) - , linkPolicy(QWebPage::DontDelegateLinks) - , m_viewportSize(QSize(0, 0)) - , useFixedLayout(false) - , inspectorFrontend(0) - , inspector(0) - , inspectorIsInternalOnly(false) - , m_lastDropAction(Qt::IgnoreAction) -{ -#if ENABLE(GEOLOCATION) || ENABLE(DEVICE_ORIENTATION) - bool useMock = QWebPageAdapter::drtRun; -#endif - - WebKit::initializeWebKitWidgets(); - WebCore::initializeWebCoreQt(); - - Page::PageClients pageClients; - pageClients.chromeClient = new ChromeClientQt(this); - pageClients.contextMenuClient = new ContextMenuClientQt(); - pageClients.editorClient = new EditorClientQt(this); - pageClients.dragClient = new DragClientQt(pageClients.chromeClient); - pageClients.inspectorClient = new InspectorClientQt(this); - page = new Page(pageClients); -#if ENABLE(GEOLOCATION) - if (useMock) { - // In case running in DumpRenderTree mode set the controller to mock provider. - GeolocationClientMock* mock = new GeolocationClientMock; - WebCore::provideGeolocationTo(page, mock); - mock->setController(WebCore::GeolocationController::from(page)); - } else - WebCore::provideGeolocationTo(page, new GeolocationClientQt(this)); -#endif -#if ENABLE(DEVICE_ORIENTATION) - if (useMock) - WebCore::provideDeviceOrientationTo(page, new DeviceOrientationClientMock); - else - WebCore::provideDeviceOrientationTo(page, new DeviceOrientationClientQt); - WebCore::provideDeviceMotionTo(page, new DeviceMotionClientQt); -#endif - - // By default each page is put into their own unique page group, which affects popup windows - // and visited links. Page groups (per process only) is a feature making it possible to use - // separate settings for each group, so that for instance an integrated browser/email reader - // can use different settings for displaying HTML pages and HTML email. To make QtWebKit work - // as expected out of the box, we use a default group similar to what other ports are doing. - page->setGroupName("Default Group"); - - page->addLayoutMilestones(DidFirstVisuallyNonEmptyLayout); - - QWebPageAdapter::init(page); - - history.d = new QWebHistoryPrivate(static_cast<WebCore::BackForwardListImpl*>(page->backForwardList())); - memset(actions, 0, sizeof(actions)); - - PageGroup::setShouldTrackVisitedLinks(true); - -#if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) - NotificationPresenterClientQt* presenter = NotificationPresenterClientQt::notificationPresenter(); - presenter->addClient(); -#ifndef QT_NO_SYSTEMTRAYICON - if (!presenter->hasSystemTrayIcon()) - presenter->setSystemTrayIcon(new QSystemTrayIcon); -#endif // QT_NO_SYSTEMTRAYICON -#endif // ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) -} - -QWebPagePrivate::~QWebPagePrivate() -{ -#ifndef QT_NO_CONTEXTMENU - delete currentContextMenu.data(); -#endif -#ifndef QT_NO_UNDOSTACK - delete undoStack; -#endif - - if (inspector) { - // If the inspector is ours, delete it, otherwise just detach from it. - if (inspectorIsInternalOnly) - delete inspector; - else - inspector->setPage(0); - } - // Explicitly destruct the WebCore page at this point when the - // QWebPagePrivate / QWebPageAdapater vtables are still intact, - // in order for various destruction callbacks out of WebCore to - // work. - deletePage(); -} - -WebCore::Page* QWebPagePrivate::core(const QWebPage* page) -{ - return page->d->page; -} - -void QWebPagePrivate::show() -{ - if (!view) - return; - view->window()->show(); -} - -void QWebPagePrivate::setFocus() -{ - if (!view) - return; - view->setFocus(); -} - -void QWebPagePrivate::unfocus() -{ - if (!view) - return; - view->clearFocus(); -} - -void QWebPagePrivate::setWindowRect(const QRect &rect) -{ - emit q->geometryChangeRequested(rect); -} - -QSize QWebPagePrivate::viewportSize() const -{ - return q->viewportSize(); -} - -QWebPageAdapter *QWebPagePrivate::createWindow(bool dialog) -{ - QWebPage *newPage = q->createWindow(dialog ? QWebPage::WebModalDialog : QWebPage::WebBrowserWindow); - if (!newPage) - return 0; - // Make sure the main frame exists, as WebCore expects it when returning from this ChromeClient::createWindow() - newPage->d->createMainFrame(); - return newPage->d; -} - -void QWebPagePrivate::javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID) -{ - q->javaScriptConsoleMessage(message, lineNumber, sourceID); -} - -void QWebPagePrivate::javaScriptAlert(QWebFrameAdapter* frame, const QString& msg) -{ - q->javaScriptAlert(QWebFramePrivate::kit(frame), msg); -} - -bool QWebPagePrivate::javaScriptConfirm(QWebFrameAdapter* frame, const QString& msg) -{ - return q->javaScriptConfirm(QWebFramePrivate::kit(frame), msg); -} - -bool QWebPagePrivate::javaScriptPrompt(QWebFrameAdapter *frame, const QString &msg, const QString &defaultValue, QString *result) -{ - return q->javaScriptPrompt(QWebFramePrivate::kit(frame), msg, defaultValue, result); -} - -bool QWebPagePrivate::shouldInterruptJavaScript() -{ - return q->shouldInterruptJavaScript(); -} - -void QWebPagePrivate::printRequested(QWebFrameAdapter *frame) -{ - emit q->printRequested(QWebFramePrivate::kit(frame)); -} - -void QWebPagePrivate::databaseQuotaExceeded(QWebFrameAdapter* frame, const QString& databaseName) -{ - emit q->databaseQuotaExceeded(QWebFramePrivate::kit(frame), databaseName); -} - -void QWebPagePrivate::applicationCacheQuotaExceeded(QWebSecurityOrigin *origin, quint64 defaultOriginQuota, quint64 c) -{ - emit q->applicationCacheQuotaExceeded(origin, defaultOriginQuota, c); -} - -void QWebPagePrivate::setToolTip(const QString &tip) -{ -#ifndef QT_NO_TOOLTIP - if (!view) - return; - - if (tip.isEmpty()) { - view->setToolTip(QString()); - QToolTip::hideText(); - } else { - QString dtip = QLatin1String("<p>") + QString(tip).toHtmlEscaped() + QLatin1String("</p>"); - view->setToolTip(dtip); - } -#else - Q_UNUSED(tip); -#endif -} - -#if USE(QT_MULTIMEDIA) -QWebFullScreenVideoHandler *QWebPagePrivate::createFullScreenVideoHandler() -{ - return new WebKit::DefaultFullScreenVideoHandler; -} -#endif - -QWebFrameAdapter *QWebPagePrivate::mainFrameAdapter() -{ - return q->mainFrame()->d; -} - -QStringList QWebPagePrivate::chooseFiles(QWebFrameAdapter *frame, bool allowMultiple, const QStringList &suggestedFileNames) -{ - if (allowMultiple && q->supportsExtension(QWebPage::ChooseMultipleFilesExtension)) { - QWebPage::ChooseMultipleFilesExtensionOption option; - option.parentFrame = QWebFramePrivate::kit(frame); - option.suggestedFileNames = suggestedFileNames; - - QWebPage::ChooseMultipleFilesExtensionReturn output; - q->extension(QWebPage::ChooseMultipleFilesExtension, &option, &output); - - return output.fileNames; - } - // Single file - QStringList result; - QString suggestedFile; - if (!suggestedFileNames.isEmpty()) - suggestedFile = suggestedFileNames.first(); - QString file = q->chooseFile(QWebFramePrivate::kit(frame), suggestedFile); - if (!file.isEmpty()) - result << file; - return result; -} - -bool QWebPagePrivate::acceptNavigationRequest(QWebFrameAdapter *frameAdapter, const QNetworkRequest &request, int type) -{ - QWebFrame *frame = frameAdapter ? QWebFramePrivate::kit(frameAdapter): 0; - if (insideOpenCall - && frame == mainFrame.data()) - return true; - return q->acceptNavigationRequest(frame, request, QWebPage::NavigationType(type)); -} - -void QWebPagePrivate::emitRestoreFrameStateRequested(QWebFrameAdapter *frame) -{ - emit q->restoreFrameStateRequested(QWebFramePrivate::kit(frame)); -} - -void QWebPagePrivate::emitSaveFrameStateRequested(QWebFrameAdapter *frame, QWebHistoryItem *item) -{ - emit q->saveFrameStateRequested(QWebFramePrivate::kit(frame), item); -} - -void QWebPagePrivate::emitDownloadRequested(const QNetworkRequest &request) -{ - emit q->downloadRequested(request); -} - -void QWebPagePrivate::emitFrameCreated(QWebFrameAdapter *frame) -{ - emit q->frameCreated(QWebFramePrivate::kit(frame)); -} - -bool QWebPagePrivate::errorPageExtension(QWebPageAdapter::ErrorPageOption *opt, QWebPageAdapter::ErrorPageReturn *out) -{ - QWebPage::ErrorPageExtensionOption option; - if (opt->domain == QLatin1String("QtNetwork")) - option.domain = QWebPage::QtNetwork; - else if (opt->domain == QLatin1String("HTTP")) - option.domain = QWebPage::Http; - else if (opt->domain == QLatin1String("WebKit")) - option.domain = QWebPage::WebKit; - else - return false; - option.url = opt->url; - option.frame = QWebFramePrivate::kit(opt->frame); - option.error = opt->error; - option.errorString = opt->errorString; - QWebPage::ErrorPageExtensionReturn output; - if (!q->extension(QWebPage::ErrorPageExtension, &option, &output)) - return false; - out->baseUrl = output.baseUrl; - out->content = output.content; - out->contentType = output.contentType; - out->encoding = output.encoding; - return true; -} - -QtPluginWidgetAdapter *QWebPagePrivate::createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) -{ - QObject *widget = q->createPlugin(classid, url, paramNames, paramValues); - return adapterForWidget(widget); -} - -QtPluginWidgetAdapter *QWebPagePrivate::adapterForWidget(QObject *object) const -{ - if (QWidget *widget = qobject_cast<QWidget*>(object)) - return new QWidgetPluginImpl(widget); - if (QGraphicsWidget *widget = qobject_cast<QGraphicsWidget*>(object)) - return new QGraphicsWidgetPluginImpl(widget); - return 0; -} - -void QWebPagePrivate::createMainFrame() -{ - if (!mainFrame) { - mainFrame = new QWebFrame(q); - emit q->frameCreated(mainFrame.data()); - } -} - -static QWebPage::WebAction webActionForContextMenuAction(WebCore::ContextMenuAction action) -{ - switch (action) { - case WebCore::ContextMenuItemTagOpenLink: return QWebPage::OpenLink; - case WebCore::ContextMenuItemTagOpenLinkInNewWindow: return QWebPage::OpenLinkInNewWindow; - case WebCore::ContextMenuItemTagOpenLinkInThisWindow: return QWebPage::OpenLinkInThisWindow; - case WebCore::ContextMenuItemTagDownloadLinkToDisk: return QWebPage::DownloadLinkToDisk; - case WebCore::ContextMenuItemTagCopyLinkToClipboard: return QWebPage::CopyLinkToClipboard; - case WebCore::ContextMenuItemTagOpenImageInNewWindow: return QWebPage::OpenImageInNewWindow; - case WebCore::ContextMenuItemTagDownloadImageToDisk: return QWebPage::DownloadImageToDisk; - case WebCore::ContextMenuItemTagCopyImageToClipboard: return QWebPage::CopyImageToClipboard; - case WebCore::ContextMenuItemTagCopyImageUrlToClipboard: return QWebPage::CopyImageUrlToClipboard; - case WebCore::ContextMenuItemTagOpenFrameInNewWindow: return QWebPage::OpenFrameInNewWindow; - case WebCore::ContextMenuItemTagCopy: return QWebPage::Copy; - case WebCore::ContextMenuItemTagGoBack: return QWebPage::Back; - case WebCore::ContextMenuItemTagGoForward: return QWebPage::Forward; - case WebCore::ContextMenuItemTagStop: return QWebPage::Stop; - case WebCore::ContextMenuItemTagReload: return QWebPage::Reload; - case WebCore::ContextMenuItemTagCut: return QWebPage::Cut; - case WebCore::ContextMenuItemTagPaste: return QWebPage::Paste; - case WebCore::ContextMenuItemTagDefaultDirection: return QWebPage::SetTextDirectionDefault; - case WebCore::ContextMenuItemTagLeftToRight: return QWebPage::SetTextDirectionLeftToRight; - case WebCore::ContextMenuItemTagRightToLeft: return QWebPage::SetTextDirectionRightToLeft; - case WebCore::ContextMenuItemTagBold: return QWebPage::ToggleBold; - case WebCore::ContextMenuItemTagItalic: return QWebPage::ToggleItalic; - case WebCore::ContextMenuItemTagUnderline: return QWebPage::ToggleUnderline; - case WebCore::ContextMenuItemTagSelectAll: return QWebPage::SelectAll; -#if ENABLE(INSPECTOR) - case WebCore::ContextMenuItemTagInspectElement: return QWebPage::InspectElement; -#endif - default: break; - } - return QWebPage::NoWebAction; -} - -#ifndef QT_NO_CONTEXTMENU -QMenu *QWebPagePrivate::createContextMenu(const WebCore::ContextMenu *webcoreMenu, - const QList<WebCore::ContextMenuItem> *items, QBitArray *visitedWebActions) -{ - if (!client || !webcoreMenu) - return 0; - - QMenu* menu = new QMenu(q->view()); - for (int i = 0; i < items->count(); ++i) { - const ContextMenuItem &item = items->at(i); - switch (item.type()) { - case WebCore::CheckableActionType: /* fall through */ - case WebCore::ActionType: { - QWebPage::WebAction action = webActionForContextMenuAction(item.action()); - QAction *a = q->action(action); - if (a) { - ContextMenuItem it(item); - page->contextMenuController()->checkOrEnableIfNeeded(it); - PlatformMenuItemDescription desc = it.releasePlatformDescription(); - a->setEnabled(desc.enabled); - a->setChecked(desc.checked); - a->setCheckable(item.type() == WebCore::CheckableActionType); - - menu->addAction(a); - visitedWebActions->setBit(action); - } - break; - } - case WebCore::SeparatorType: - menu->addSeparator(); - break; - case WebCore::SubmenuType: { - QMenu *subMenu = createContextMenu(webcoreMenu, item.platformSubMenu(), visitedWebActions); - - bool anyEnabledAction = false; - - QList<QAction *> actions = subMenu->actions(); - for (int i = 0; i < actions.count(); ++i) { - if (actions.at(i)->isVisible()) - anyEnabledAction |= actions.at(i)->isEnabled(); - } - - // don't show sub-menus with just disabled actions - if (anyEnabledAction) { - subMenu->setTitle(item.title()); - menu->addAction(subMenu->menuAction()); - } else - delete subMenu; - break; - } - } - } - return menu; -} -#endif // QT_NO_CONTEXTMENU - -#ifndef QT_NO_ACTION -void QWebPagePrivate::_q_webActionTriggered(bool checked) -{ - QAction *a = qobject_cast<QAction *>(q->sender()); - if (!a) - return; - QWebPage::WebAction action = static_cast<QWebPage::WebAction>(a->data().toInt()); - q->triggerAction(action, checked); -} -#endif // QT_NO_ACTION - -void QWebPagePrivate::_q_cleanupLeakMessages() -{ -#ifndef NDEBUG - // Need this to make leak messages accurate. - memoryCache()->setCapacities(0, 0, 0); -#endif -} - -void QWebPagePrivate::updateAction(QWebPage::WebAction action) -{ -#ifdef QT_NO_ACTION - Q_UNUSED(action) -#else - QAction *a = actions[action]; - if (!a || !mainFrame) - return; - - WebCore::FrameLoader *loader = mainFrame.data()->d->frame->loader(); - WebCore::Editor *editor = page->focusController()->focusedOrMainFrame()->editor(); - - bool enabled = a->isEnabled(); - bool checked = a->isChecked(); - - switch (action) { - case QWebPage::Back: - enabled = page->canGoBackOrForward(-1); - break; - case QWebPage::Forward: - enabled = page->canGoBackOrForward(1); - break; - case QWebPage::Stop: - enabled = loader->isLoading(); - break; - case QWebPage::Reload: - case QWebPage::ReloadAndBypassCache: - enabled = !loader->isLoading(); - break; -#ifndef QT_NO_UNDOSTACK - case QWebPage::Undo: - case QWebPage::Redo: - // those two are handled by QUndoStack - break; -#endif // QT_NO_UNDOSTACK - case QWebPage::SelectAll: // editor command is always enabled - break; - case QWebPage::SetTextDirectionDefault: - case QWebPage::SetTextDirectionLeftToRight: - case QWebPage::SetTextDirectionRightToLeft: - enabled = editor->canEdit(); - checked = false; - break; - default: { - // see if it's an editor command - const char* commandName = editorCommandForWebActions(action); - - // if it's an editor command, let it's logic determine state - if (commandName) { - Editor::Command command = editor->command(commandName); - enabled = command.isEnabled(); - if (enabled) - checked = command.state() != FalseTriState; - else - checked = false; - } - break; - } - } - - a->setEnabled(enabled); - - if (a->isCheckable()) - a->setChecked(checked); -#endif // QT_NO_ACTION -} - -void QWebPagePrivate::updateNavigationActions() -{ - updateAction(QWebPage::Back); - updateAction(QWebPage::Forward); - updateAction(QWebPage::Stop); - updateAction(QWebPage::Reload); - updateAction(QWebPage::ReloadAndBypassCache); -} - -QObject *QWebPagePrivate::inspectorHandle() -{ - return getOrCreateInspector(); -} - -void QWebPagePrivate::setInspectorFrontend(QObject* frontend) -{ - inspectorFrontend = qobject_cast<QWidget*>(frontend); - if (inspector) - inspector->d->setFrontend(frontend); -} - -void QWebPagePrivate::setInspectorWindowTitle(const QString& title) -{ - if (inspector) - inspector->setWindowTitle(title); -} - -void QWebPagePrivate::createWebInspector(QObject** inspectorView, QWebPageAdapter** inspectorPage) -{ - QWebPage* page = new WebKit::InspectorClientWebPage; - *inspectorView = page->view(); - *inspectorPage = page->d; -} - -#ifndef QT_NO_MENU -static QStringList iterateContextMenu(QMenu* menu) -{ - if (!menu) - return QStringList(); - - QStringList items; - QList<QAction *> actions = menu->actions(); - for (int i = 0; i < actions.count(); ++i) { - if (actions.at(i)->isSeparator()) - items << QLatin1String("<separator>"); - else - items << actions.at(i)->text(); - if (actions.at(i)->menu()) - items << iterateContextMenu(actions.at(i)->menu()); - } - return items; -} -#endif - -QStringList QWebPagePrivate::menuActionsAsText() -{ -#ifndef QT_NO_MENU - return iterateContextMenu(currentContextMenu.data()); -#else - return QStringList(); -#endif -} - -void QWebPagePrivate::emitViewportChangeRequested() -{ - emit q->viewportChangeRequested(); -} - -void QWebPagePrivate::updateEditorActions() -{ - updateAction(QWebPage::Cut); - updateAction(QWebPage::Copy); - updateAction(QWebPage::Paste); - updateAction(QWebPage::MoveToNextChar); - updateAction(QWebPage::MoveToPreviousChar); - updateAction(QWebPage::MoveToNextWord); - updateAction(QWebPage::MoveToPreviousWord); - updateAction(QWebPage::MoveToNextLine); - updateAction(QWebPage::MoveToPreviousLine); - updateAction(QWebPage::MoveToStartOfLine); - updateAction(QWebPage::MoveToEndOfLine); - updateAction(QWebPage::MoveToStartOfBlock); - updateAction(QWebPage::MoveToEndOfBlock); - updateAction(QWebPage::MoveToStartOfDocument); - updateAction(QWebPage::MoveToEndOfDocument); - updateAction(QWebPage::SelectNextChar); - updateAction(QWebPage::SelectPreviousChar); - updateAction(QWebPage::SelectNextWord); - updateAction(QWebPage::SelectPreviousWord); - updateAction(QWebPage::SelectNextLine); - updateAction(QWebPage::SelectPreviousLine); - updateAction(QWebPage::SelectStartOfLine); - updateAction(QWebPage::SelectEndOfLine); - updateAction(QWebPage::SelectStartOfBlock); - updateAction(QWebPage::SelectEndOfBlock); - updateAction(QWebPage::SelectStartOfDocument); - updateAction(QWebPage::SelectEndOfDocument); - updateAction(QWebPage::DeleteStartOfWord); - updateAction(QWebPage::DeleteEndOfWord); - updateAction(QWebPage::SetTextDirectionDefault); - updateAction(QWebPage::SetTextDirectionLeftToRight); - updateAction(QWebPage::SetTextDirectionRightToLeft); - updateAction(QWebPage::ToggleBold); - updateAction(QWebPage::ToggleItalic); - updateAction(QWebPage::ToggleUnderline); - updateAction(QWebPage::InsertParagraphSeparator); - updateAction(QWebPage::InsertLineSeparator); - updateAction(QWebPage::PasteAndMatchStyle); - updateAction(QWebPage::RemoveFormat); - updateAction(QWebPage::ToggleStrikethrough); - updateAction(QWebPage::ToggleSubscript); - updateAction(QWebPage::ToggleSuperscript); - updateAction(QWebPage::InsertUnorderedList); - updateAction(QWebPage::InsertOrderedList); - updateAction(QWebPage::Indent); - updateAction(QWebPage::Outdent); - updateAction(QWebPage::AlignCenter); - updateAction(QWebPage::AlignJustified); - updateAction(QWebPage::AlignLeft); - updateAction(QWebPage::AlignRight); -} - -void QWebPagePrivate::timerEvent(QTimerEvent *ev) -{ - int timerId = ev->timerId(); - if (timerId == tripleClickTimer.timerId()) - tripleClickTimer.stop(); - else - q->timerEvent(ev); -} - -void QWebPagePrivate::mouseMoveEvent(QMouseEvent* ev) -{ - WebCore::Frame* frame = QWebFramePrivate::core(mainFrame.data()); - if (!frame->view()) - return; - - bool accepted = frame->eventHandler()->mouseMoved(convertMouseEvent(ev, 0)); - ev->setAccepted(accepted); -} - -void QWebPagePrivate::mousePressEvent(QMouseEvent* ev) -{ - WebCore::Frame* frame = QWebFramePrivate::core(mainFrame.data()); - if (!frame->view()) - return; - - RefPtr<WebCore::Node> oldNode; - Frame* focusedFrame = page->focusController()->focusedFrame(); - if (Document* focusedDocument = focusedFrame ? focusedFrame->document() : 0) - oldNode = focusedDocument->focusedNode(); - - if (tripleClickTimer.isActive() - && (ev->pos() - tripleClick).manhattanLength() - < QApplication::startDragDistance()) { - mouseTripleClickEvent(ev); - return; - } - - bool accepted = false; - adjustPointForClicking(ev); - PlatformMouseEvent mev = convertMouseEvent(ev, 1); - // ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton - if (mev.button() != NoButton) - accepted = frame->eventHandler()->handleMousePressEvent(mev); - ev->setAccepted(accepted); - - RefPtr<WebCore::Node> newNode; - focusedFrame = page->focusController()->focusedFrame(); - if (Document* focusedDocument = focusedFrame ? focusedFrame->document() : 0) - newNode = focusedDocument->focusedNode(); - - if (newNode && oldNode != newNode) - clickCausedFocus = true; -} - -void QWebPagePrivate::mouseDoubleClickEvent(QMouseEvent *ev) -{ - WebCore::Frame* frame = QWebFramePrivate::core(mainFrame.data()); - if (!frame->view()) - return; - - bool accepted = false; - PlatformMouseEvent mev = convertMouseEvent(ev, 2); - // ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton - if (mev.button() != NoButton) - accepted = frame->eventHandler()->handleMousePressEvent(mev); - ev->setAccepted(accepted); - - tripleClickTimer.start(QApplication::doubleClickInterval(), q); - tripleClick = QPointF(ev->pos()).toPoint(); -} - -void QWebPagePrivate::mouseTripleClickEvent(QMouseEvent *ev) -{ - WebCore::Frame* frame = QWebFramePrivate::core(mainFrame.data()); - if (!frame->view()) - return; - - bool accepted = false; - PlatformMouseEvent mev = convertMouseEvent(ev, 3); - // ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton - if (mev.button() != NoButton) - accepted = frame->eventHandler()->handleMousePressEvent(mev); - ev->setAccepted(accepted); -} - -void QWebPagePrivate::mouseReleaseEvent(QMouseEvent *ev) -{ - WebCore::Frame* frame = QWebFramePrivate::core(mainFrame.data()); - if (!frame->view()) - return; - - bool accepted = false; - adjustPointForClicking(ev); - PlatformMouseEvent mev = convertMouseEvent(ev, 0); - // ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton - if (mev.button() != NoButton) - accepted = frame->eventHandler()->handleMouseReleaseEvent(mev); - ev->setAccepted(accepted); - - handleSoftwareInputPanel(ev->button(), QPointF(ev->pos()).toPoint()); -} - -void QWebPagePrivate::handleSoftwareInputPanel(Qt::MouseButton button, const QPoint& pos) -{ - Frame* frame = page->focusController()->focusedFrame(); - if (!frame) - return; - - if (client && client->inputMethodEnabled() - && frame->document()->focusedNode() - && button == Qt::LeftButton && qApp->autoSipEnabled()) { - QStyle::RequestSoftwareInputPanel behavior = QStyle::RequestSoftwareInputPanel( - client->style()->styleHint(QStyle::SH_RequestSoftwareInputPanel)); - if (!clickCausedFocus || behavior == QStyle::RSIP_OnMouseClick) { - HitTestResult result = frame->eventHandler()->hitTestResultAtPoint(frame->view()->windowToContents(pos), false); - if (result.isContentEditable()) { - QEvent event(QEvent::RequestSoftwareInputPanel); - QApplication::sendEvent(client->ownerWidget(), &event); - } - } - } - - clickCausedFocus = false; -} - -#ifndef QT_NO_CONTEXTMENU -void QWebPagePrivate::contextMenuEvent(const QPoint& globalPos) -{ - QMenu *menu = q->createStandardContextMenu(); - if (menu) { - menu->exec(globalPos); - delete menu; - } -} -#endif // QT_NO_CONTEXTMENU - -/*! - \since 4.5 - This function creates the standard context menu which is shown when - the user clicks on the web page with the right mouse button. It is - called from the default contextMenuEvent() handler. The popup menu's - ownership is transferred to the caller. - */ -QMenu *QWebPage::createStandardContextMenu() -{ -#ifndef QT_NO_CONTEXTMENU - QMenu* menu = d->currentContextMenu.data(); - d->currentContextMenu = 0; - return menu; -#else - return 0; -#endif -} - -#ifndef QT_NO_WHEELEVENT -void QWebPagePrivate::wheelEvent(QWheelEvent *ev) -{ - WebCore::Frame* frame = QWebFramePrivate::core(mainFrame.data()); - if (!frame->view()) - return; - - PlatformWheelEvent pev = convertWheelEvent(ev, QApplication::wheelScrollLines()); - bool accepted = frame->eventHandler()->handleWheelEvent(pev); - ev->setAccepted(accepted); -} -#endif // QT_NO_WHEELEVENT - -#ifndef QT_NO_SHORTCUT -QWebPage::WebAction QWebPagePrivate::editorActionForKeyEvent(QKeyEvent* event) -{ - static struct { - QKeySequence::StandardKey standardKey; - QWebPage::WebAction action; - } editorActions[] = { - { QKeySequence::Cut, QWebPage::Cut }, - { QKeySequence::Copy, QWebPage::Copy }, - { QKeySequence::Paste, QWebPage::Paste }, - { QKeySequence::Undo, QWebPage::Undo }, - { QKeySequence::Redo, QWebPage::Redo }, - { QKeySequence::MoveToNextChar, QWebPage::MoveToNextChar }, - { QKeySequence::MoveToPreviousChar, QWebPage::MoveToPreviousChar }, - { QKeySequence::MoveToNextWord, QWebPage::MoveToNextWord }, - { QKeySequence::MoveToPreviousWord, QWebPage::MoveToPreviousWord }, - { QKeySequence::MoveToNextLine, QWebPage::MoveToNextLine }, - { QKeySequence::MoveToPreviousLine, QWebPage::MoveToPreviousLine }, - { QKeySequence::MoveToStartOfLine, QWebPage::MoveToStartOfLine }, - { QKeySequence::MoveToEndOfLine, QWebPage::MoveToEndOfLine }, - { QKeySequence::MoveToStartOfBlock, QWebPage::MoveToStartOfBlock }, - { QKeySequence::MoveToEndOfBlock, QWebPage::MoveToEndOfBlock }, - { QKeySequence::MoveToStartOfDocument, QWebPage::MoveToStartOfDocument }, - { QKeySequence::MoveToEndOfDocument, QWebPage::MoveToEndOfDocument }, - { QKeySequence::SelectNextChar, QWebPage::SelectNextChar }, - { QKeySequence::SelectPreviousChar, QWebPage::SelectPreviousChar }, - { QKeySequence::SelectNextWord, QWebPage::SelectNextWord }, - { QKeySequence::SelectPreviousWord, QWebPage::SelectPreviousWord }, - { QKeySequence::SelectNextLine, QWebPage::SelectNextLine }, - { QKeySequence::SelectPreviousLine, QWebPage::SelectPreviousLine }, - { QKeySequence::SelectStartOfLine, QWebPage::SelectStartOfLine }, - { QKeySequence::SelectEndOfLine, QWebPage::SelectEndOfLine }, - { QKeySequence::SelectStartOfBlock, QWebPage::SelectStartOfBlock }, - { QKeySequence::SelectEndOfBlock, QWebPage::SelectEndOfBlock }, - { QKeySequence::SelectStartOfDocument, QWebPage::SelectStartOfDocument }, - { QKeySequence::SelectEndOfDocument, QWebPage::SelectEndOfDocument }, - { QKeySequence::DeleteStartOfWord, QWebPage::DeleteStartOfWord }, - { QKeySequence::DeleteEndOfWord, QWebPage::DeleteEndOfWord }, - { QKeySequence::InsertParagraphSeparator, QWebPage::InsertParagraphSeparator }, - { QKeySequence::InsertLineSeparator, QWebPage::InsertLineSeparator }, - { QKeySequence::SelectAll, QWebPage::SelectAll }, - { QKeySequence::UnknownKey, QWebPage::NoWebAction } - }; - - for (int i = 0; editorActions[i].standardKey != QKeySequence::UnknownKey; ++i) - if (event == editorActions[i].standardKey) - return editorActions[i].action; - - return QWebPage::NoWebAction; -} -#endif // QT_NO_SHORTCUT - -void QWebPagePrivate::keyPressEvent(QKeyEvent *ev) -{ - bool handled = false; - WebCore::Frame* frame = page->focusController()->focusedOrMainFrame(); - // we forward the key event to WebCore first to handle potential DOM - // defined event handlers and later on end up in EditorClientQt::handleKeyboardEvent - // to trigger editor commands via triggerAction(). - if (!handled) - handled = frame->eventHandler()->keyEvent(ev); - if (!handled) { - handled = true; - if (!handleScrolling(ev, frame)) { - switch (ev->key()) { - case Qt::Key_Back: - q->triggerAction(QWebPage::Back); - break; - case Qt::Key_Forward: - q->triggerAction(QWebPage::Forward); - break; - case Qt::Key_Stop: - q->triggerAction(QWebPage::Stop); - break; - case Qt::Key_Refresh: - q->triggerAction(QWebPage::Reload); - break; - case Qt::Key_Backspace: - if (ev->modifiers() == Qt::ShiftModifier) - q->triggerAction(QWebPage::Forward); - else - q->triggerAction(QWebPage::Back); - break; - default: - handled = false; - break; - } - } - } - - ev->setAccepted(handled); -} - -void QWebPagePrivate::keyReleaseEvent(QKeyEvent *ev) -{ - if (ev->isAutoRepeat()) { - ev->setAccepted(true); - return; - } - - WebCore::Frame* frame = page->focusController()->focusedOrMainFrame(); - bool handled = frame->eventHandler()->keyEvent(ev); - ev->setAccepted(handled); -} - -void QWebPagePrivate::focusInEvent(QFocusEvent*) -{ - FocusController *focusController = page->focusController(); - focusController->setActive(true); - focusController->setFocused(true); - if (!focusController->focusedFrame()) - focusController->setFocusedFrame(QWebFramePrivate::core(mainFrame.data())); -} - -void QWebPagePrivate::focusOutEvent(QFocusEvent*) -{ - // only set the focused frame inactive so that we stop painting the caret - // and the focus frame. But don't tell the focus controller so that upon - // focusInEvent() we can re-activate the frame. - FocusController *focusController = page->focusController(); - // Call setFocused first so that window.onblur doesn't get called twice - focusController->setFocused(false); - focusController->setActive(false); -} - -template<class T> -void QWebPagePrivate::dragEnterEvent(T* ev) -{ -#ifndef QT_NO_DRAGANDDROP - DragData dragData(ev->mimeData(), QPointF(ev->pos()).toPoint(), - QCursor::pos(), dropActionToDragOp(ev->possibleActions())); - Qt::DropAction action = dragOpToDropAction(page->dragController()->dragEntered(&dragData).operation); - ev->setDropAction(action); - ev->acceptProposedAction(); -#endif -} - -template<class T> -void QWebPagePrivate::dragLeaveEvent(T *ev) -{ -#ifndef QT_NO_DRAGANDDROP - DragData dragData(0, IntPoint(), QCursor::pos(), DragOperationNone); - page->dragController()->dragExited(&dragData); - ev->accept(); -#endif -} - -template<class T> -void QWebPagePrivate::dragMoveEvent(T *ev) -{ -#ifndef QT_NO_DRAGANDDROP - DragData dragData(ev->mimeData(), QPointF(ev->pos()).toPoint(), - QCursor::pos(), dropActionToDragOp(ev->possibleActions())); - m_lastDropAction = dragOpToDropAction(page->dragController()->dragUpdated(&dragData).operation); - ev->setDropAction(m_lastDropAction); - if (m_lastDropAction != Qt::IgnoreAction) - ev->accept(); -#endif -} - -template<class T> -void QWebPagePrivate::dropEvent(T *ev) -{ -#ifndef QT_NO_DRAGANDDROP - DragData dragData(ev->mimeData(), QPointF(ev->pos()).toPoint(), - QCursor::pos(), dropActionToDragOp(ev->possibleActions())); - if (page->dragController()->performDrag(&dragData)) { - ev->setDropAction(m_lastDropAction); - ev->accept(); - } -#endif -} - -void QWebPagePrivate::leaveEvent(QEvent*) -{ - // Fake a mouse move event just outside of the widget, since all - // the interesting mouse-out behavior like invalidating scrollbars - // is handled by the WebKit event handler's mouseMoved function. - QMouseEvent fakeEvent(QEvent::MouseMove, QCursor::pos(), Qt::NoButton, Qt::NoButton, Qt::NoModifier); - mouseMoveEvent(&fakeEvent); -} - -/*! - \property QWebPage::palette - \brief the page's palette - - The base brush of the palette is used to draw the background of the main frame. - - By default, this property contains the application's default palette. -*/ -void QWebPage::setPalette(const QPalette &pal) -{ - d->palette = pal; - if (!d->mainFrame || !d->mainFrame.data()->d->frame->view()) - return; - - QBrush brush = pal.brush(QPalette::Base); - QColor backgroundColor = brush.style() == Qt::SolidPattern ? brush.color() : QColor(); - QWebFramePrivate::core(d->mainFrame.data())->view()->updateBackgroundRecursively(backgroundColor, !backgroundColor.alpha()); -} - -QPalette QWebPage::palette() const -{ - return d->palette; -} - -void QWebPagePrivate::inputMethodEvent(QInputMethodEvent *ev) -{ - WebCore::Frame *frame = page->focusController()->focusedOrMainFrame(); - WebCore::Editor *editor = frame->editor(); - - if (!editor->canEdit()) { - ev->ignore(); - return; - } - - Node* node = 0; - if (frame->selection()->rootEditableElement()) - node = frame->selection()->rootEditableElement()->shadowAncestorNode(); - - Vector<CompositionUnderline> underlines; - bool hasSelection = false; - - for (int i = 0; i < ev->attributes().size(); ++i) { - const QInputMethodEvent::Attribute& a = ev->attributes().at(i); - switch (a.type) { - case QInputMethodEvent::TextFormat: { - QTextCharFormat textCharFormat = a.value.value<QTextFormat>().toCharFormat(); - QColor qcolor = textCharFormat.underlineColor(); - underlines.append(CompositionUnderline(qMin(a.start, (a.start + a.length)), qMax(a.start, (a.start + a.length)), Color(makeRGBA(qcolor.red(), qcolor.green(), qcolor.blue(), qcolor.alpha())), false)); - break; - } - case QInputMethodEvent::Cursor: { - frame->selection()->setCaretVisible(a.length); //if length is 0 cursor is invisible - if (a.length > 0) { - RenderObject* caretRenderer = frame->selection()->caretRenderer(); - if (caretRenderer) { - QColor qcolor = a.value.value<QColor>(); - caretRenderer->style()->setColor(Color(makeRGBA(qcolor.red(), qcolor.green(), qcolor.blue(), qcolor.alpha()))); - } - } - break; - } - case QInputMethodEvent::Selection: { - hasSelection = true; - // A selection in the inputMethodEvent is always reflected in the visible text - if (node) { - if (HTMLTextFormControlElement* textControl = toTextFormControl(node)) - textControl->setSelectionRange(qMin(a.start, (a.start + a.length)), qMax(a.start, (a.start + a.length))); - } - - if (!ev->preeditString().isEmpty()) - editor->setComposition(ev->preeditString(), underlines, qMin(a.start, (a.start + a.length)), qMax(a.start, (a.start + a.length))); - else { - // If we are in the middle of a composition, an empty pre-edit string and a selection of zero - // cancels the current composition - if (editor->hasComposition() && (a.start + a.length == 0)) - editor->setComposition(QString(), underlines, 0, 0); - } - break; - } - default: - break; - } - } - - if (node && ev->replacementLength() > 0) { - int cursorPos = frame->selection()->extent().offsetInContainerNode(); - int start = cursorPos + ev->replacementStart(); - if (HTMLTextFormControlElement* textControl = toTextFormControl(node)) - textControl->setSelectionRange(start, start + ev->replacementLength()); - // Commit regardless of whether commitString is empty, to get rid of selection. - editor->confirmComposition(ev->commitString()); - } else if (!ev->commitString().isEmpty()) { - if (editor->hasComposition()) - editor->confirmComposition(ev->commitString()); - else - editor->insertText(ev->commitString(), 0); - } else if (!hasSelection && !ev->preeditString().isEmpty()) - editor->setComposition(ev->preeditString(), underlines, 0, 0); - else if (ev->preeditString().isEmpty() && editor->hasComposition()) - editor->confirmComposition(String()); - - ev->accept(); -} - -#ifndef QT_NO_PROPERTIES -typedef struct { - const char* name; - double deferredRepaintDelay; - double initialDeferredRepaintDelayDuringLoading; - double maxDeferredRepaintDelayDuringLoading; - double deferredRepaintDelayIncrementDuringLoading; -} QRepaintThrottlingPreset; - -void QWebPagePrivate::dynamicPropertyChangeEvent(QDynamicPropertyChangeEvent* event) -{ - if (event->propertyName() == "_q_viewMode") { - page->setViewMode(Page::stringToViewMode(q->property("_q_viewMode").toString())); - } else if (event->propertyName() == "_q_HTMLTokenizerChunkSize") { - int chunkSize = q->property("_q_HTMLTokenizerChunkSize").toInt(); - q->handle()->page->setCustomHTMLTokenizerChunkSize(chunkSize); - } else if (event->propertyName() == "_q_HTMLTokenizerTimeDelay") { - double timeDelay = q->property("_q_HTMLTokenizerTimeDelay").toDouble(); - q->handle()->page->setCustomHTMLTokenizerTimeDelay(timeDelay); - } else if (event->propertyName() == "_q_RepaintThrottlingDeferredRepaintDelay") { - double p = q->property("_q_RepaintThrottlingDeferredRepaintDelay").toDouble(); - FrameView::setRepaintThrottlingDeferredRepaintDelay(p); - } else if (event->propertyName() == "_q_RepaintThrottlingnInitialDeferredRepaintDelayDuringLoading") { - double p = q->property("_q_RepaintThrottlingnInitialDeferredRepaintDelayDuringLoading").toDouble(); - FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(p); - } else if (event->propertyName() == "_q_RepaintThrottlingMaxDeferredRepaintDelayDuringLoading") { - double p = q->property("_q_RepaintThrottlingMaxDeferredRepaintDelayDuringLoading").toDouble(); - FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(p); - } else if (event->propertyName() == "_q_RepaintThrottlingDeferredRepaintDelayIncrementDuringLoading") { - double p = q->property("_q_RepaintThrottlingDeferredRepaintDelayIncrementDuringLoading").toDouble(); - FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(p); - } else if (event->propertyName() == "_q_RepaintThrottlingPreset") { - static const QRepaintThrottlingPreset presets[] = { - { "NoThrottling", 0, 0, 0, 0 }, - { "Legacy", 0.025, 0, 2.5, 0.5 }, - { "Minimal", 0.01, 0, 1, 0.2 }, - { "Medium", 0.025, 1, 5, 0.5 }, - { "Heavy", 0.1, 2, 10, 1 } - }; - - QString p = q->property("_q_RepaintThrottlingPreset").toString(); - for (size_t i = 0; i < sizeof(presets) / sizeof(presets[0]); i++) { - if (p == QLatin1String(presets[i].name)) { - FrameView::setRepaintThrottlingDeferredRepaintDelay( - presets[i].deferredRepaintDelay); - FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading( - presets[i].initialDeferredRepaintDelayDuringLoading); - FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading( - presets[i].maxDeferredRepaintDelayDuringLoading); - FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading( - presets[i].deferredRepaintDelayIncrementDuringLoading); - break; - } - } - } - else if (event->propertyName() == "_q_webInspectorServerPort") { - InspectorServerQt* inspectorServer = InspectorServerQt::server(); - inspectorServer->listen(inspectorServerPort()); - } else if (event->propertyName() == "_q_deadDecodedDataDeletionInterval") { - double interval = q->property("_q_deadDecodedDataDeletionInterval").toDouble(); - memoryCache()->setDeadDecodedDataDeletionInterval(interval); - } -} -#endif - -void QWebPagePrivate::shortcutOverrideEvent(QKeyEvent* event) -{ - WebCore::Frame* frame = page->focusController()->focusedOrMainFrame(); - WebCore::Editor* editor = frame->editor(); - if (editor->canEdit()) { - if (event->modifiers() == Qt::NoModifier - || event->modifiers() == Qt::ShiftModifier - || event->modifiers() == Qt::KeypadModifier) { - if (event->key() < Qt::Key_Escape) { - event->accept(); - } else { - switch (event->key()) { - case Qt::Key_Return: - case Qt::Key_Enter: - case Qt::Key_Delete: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Backspace: - case Qt::Key_Left: - case Qt::Key_Right: - case Qt::Key_Up: - case Qt::Key_Down: - case Qt::Key_Tab: - event->accept(); - default: - break; - } - } - } -#ifndef QT_NO_SHORTCUT - else if (editorActionForKeyEvent(event) != QWebPage::NoWebAction) - event->accept(); -#endif - } -} - -bool QWebPagePrivate::handleScrolling(QKeyEvent *ev, Frame *frame) -{ - ScrollDirection direction; - ScrollGranularity granularity; - -#ifndef QT_NO_SHORTCUT - if (ev == QKeySequence::MoveToNextPage - || (ev->key() == Qt::Key_Space && !(ev->modifiers() & Qt::ShiftModifier))) { - granularity = ScrollByPage; - direction = ScrollDown; - } else if (ev == QKeySequence::MoveToPreviousPage - || ((ev->key() == Qt::Key_Space) && (ev->modifiers() & Qt::ShiftModifier))) { - granularity = ScrollByPage; - direction = ScrollUp; - } else -#endif // QT_NO_SHORTCUT - if ((ev->key() == Qt::Key_Up && ev->modifiers() & Qt::ControlModifier) - || ev->key() == Qt::Key_Home) { - granularity = ScrollByDocument; - direction = ScrollUp; - } else if ((ev->key() == Qt::Key_Down && ev->modifiers() & Qt::ControlModifier) - || ev->key() == Qt::Key_End) { - granularity = ScrollByDocument; - direction = ScrollDown; - } else { - switch (ev->key()) { - case Qt::Key_Up: - granularity = ScrollByLine; - direction = ScrollUp; - break; - case Qt::Key_Down: - granularity = ScrollByLine; - direction = ScrollDown; - break; - case Qt::Key_Left: - granularity = ScrollByLine; - direction = ScrollLeft; - break; - case Qt::Key_Right: - granularity = ScrollByLine; - direction = ScrollRight; - break; - default: - return false; - } - } - - return frame->eventHandler()->scrollRecursively(direction, granularity); -} - -void QWebPagePrivate::adjustPointForClicking(QMouseEvent*) -{ - notImplemented(); -} - -#if !defined(QT_NO_GRAPHICSVIEW) -void QWebPagePrivate::adjustPointForClicking(QGraphicsSceneMouseEvent* ev) -{ - QtPlatformPlugin platformPlugin; - OwnPtr<QWebTouchModifier> touchModifier = platformPlugin.createTouchModifier(); - if (!touchModifier) - return; - - unsigned topPadding = touchModifier->hitTestPaddingForTouch(QWebTouchModifier::Up); - unsigned rightPadding = touchModifier->hitTestPaddingForTouch(QWebTouchModifier::Right); - unsigned bottomPadding = touchModifier->hitTestPaddingForTouch(QWebTouchModifier::Down); - unsigned leftPadding = touchModifier->hitTestPaddingForTouch(QWebTouchModifier::Left); - - touchModifier = nullptr; - - if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) - return; - - Document* startingDocument = page->mainFrame()->document(); - if (!startingDocument) - return; - - IntPoint originalPoint(QPointF(ev->pos()).toPoint()); - TouchAdjuster touchAdjuster(topPadding, rightPadding, bottomPadding, leftPadding); - IntPoint adjustedPoint = touchAdjuster.findCandidatePointForTouch(originalPoint, startingDocument); - if (adjustedPoint == IntPoint::zero()) - return; - - ev->setPos(QPointF(adjustedPoint)); -} -#endif - -bool QWebPagePrivate::touchEvent(QTouchEvent* event) -{ -#if ENABLE(TOUCH_EVENTS) - WebCore::Frame* frame = QWebFramePrivate::core(mainFrame.data()); - if (!frame->view()) - return false; - - // Always accept the QTouchEvent so that we'll receive also TouchUpdate and TouchEnd events - event->setAccepted(true); - - // Return whether the default action was cancelled in the JS event handler - return frame->eventHandler()->handleTouchEvent(convertTouchEvent(event)); -#else - event->ignore(); - return false; -#endif -} - -bool QWebPagePrivate::gestureEvent(QGestureEvent* event) -{ - QWebFrameAdapter* frame = mainFrame.data()->d; - if (!frame->hasView()) - return false; - // QGestureEvents can contain updates for multiple gestures. - bool handled = false; -#if ENABLE(GESTURE_EVENTS) - // QGestureEvent lives in Widgets, we'll need a dummy struct to mule the info it contains to the "other side" - QGestureEventFacade gestureFacade; - - QGesture* gesture = event->gesture(Qt::TapGesture); - // Beware that gestures send by DumpRenderTree will have state Qt::NoGesture, - // due to not originating from a GestureRecognizer. - if (gesture && (gesture->state() == Qt::GestureStarted || gesture->state() == Qt::NoGesture)) { - gestureFacade.type = Qt::TapGesture; - QPointF globalPos = static_cast<const QTapGesture*>(gesture)->position(); - gestureFacade.globalPos = globalPos.toPoint(); - gestureFacade.pos = event->widget()->mapFromGlobal(globalPos.toPoint()); - frame->handleGestureEvent(&gestureFacade); - handled = true; - } - gesture = event->gesture(Qt::TapAndHoldGesture); - if (gesture && (gesture->state() == Qt::GestureStarted || gesture->state() == Qt::NoGesture)) { - gestureFacade.type = Qt::TapAndHoldGesture; - QPointF globalPos = static_cast<const QTapAndHoldGesture*>(gesture)->position(); - gestureFacade.globalPos = globalPos.toPoint(); - gestureFacade.pos = event->widget()->mapFromGlobal(globalPos.toPoint()); - frame->handleGestureEvent(&gestureFacade); - handled = true; - } -#endif // ENABLE(GESTURE_EVENTS) - - event->setAccepted(handled); - return handled; -} - -/*! - This method is used by the input method to query a set of properties of the page - to be able to support complex input method operations as support for surrounding - text and reconversions. - - \a property specifies which property is queried. - - \sa QWidget::inputMethodEvent(), QInputMethodEvent, QInputContext -*/ -QVariant QWebPage::inputMethodQuery(Qt::InputMethodQuery property) const -{ - Frame* frame = d->page->focusController()->focusedFrame(); - if (!frame) - return QVariant(); - - WebCore::Editor* editor = frame->editor(); - - RenderObject* renderer = 0; - RenderTextControl* renderTextControl = 0; - - if (frame->selection()->rootEditableElement()) - renderer = frame->selection()->rootEditableElement()->shadowAncestorNode()->renderer(); - - if (renderer && renderer->isTextControl()) - renderTextControl = toRenderTextControl(renderer); - - switch (property) { - case Qt::ImMicroFocus: { - WebCore::FrameView* view = frame->view(); - if (view && view->needsLayout()) { - // We can't access absoluteCaretBounds() while the view needs to layout. - return QVariant(); - } - return QVariant(view->contentsToWindow(frame->selection()->absoluteCaretBounds())); - } - case Qt::ImFont: { - if (renderTextControl) { - RenderStyle* renderStyle = renderTextControl->style(); - return QVariant(QFont(renderStyle->font().syntheticFont())); - } - return QVariant(QFont()); - } - case Qt::ImCursorPosition: { - if (editor->hasComposition()) - return QVariant(frame->selection()->end().offsetInContainerNode()); - return QVariant(frame->selection()->extent().offsetInContainerNode()); - } - case Qt::ImSurroundingText: { - if (renderTextControl && renderTextControl->textFormControlElement()) { - QString text = renderTextControl->textFormControlElement()->value(); - RefPtr<Range> range = editor->compositionRange(); - if (range) - text.remove(range->startPosition().offsetInContainerNode(), TextIterator::rangeLength(range.get())); - return QVariant(text); - } - return QVariant(); - } - case Qt::ImCurrentSelection: { - if (!editor->hasComposition() && renderTextControl && renderTextControl->textFormControlElement()) { - int start = frame->selection()->start().offsetInContainerNode(); - int end = frame->selection()->end().offsetInContainerNode(); - if (end > start) - return QVariant(QString(renderTextControl->textFormControlElement()->value()).mid(start, end - start)); - } - return QVariant(); - - } - case Qt::ImAnchorPosition: { - if (editor->hasComposition()) - return QVariant(frame->selection()->start().offsetInContainerNode()); - return QVariant(frame->selection()->base().offsetInContainerNode()); - } - case Qt::ImMaximumTextLength: { - if (frame->selection()->isContentEditable()) { - if (frame->document() && frame->document()->focusedNode()) { - if (frame->document()->focusedNode()->hasTagName(HTMLNames::inputTag)) { - HTMLInputElement* inputElement = static_cast<HTMLInputElement*>(frame->document()->focusedNode()); - return QVariant(inputElement->maxLength()); - } - } - return QVariant(HTMLInputElement::maximumLength); - } - return QVariant(0); - } - default: - return QVariant(); - } -} - -/*! - \internal -*/ -void QWebPagePrivate::setInspector(QWebInspector* insp) -{ - if (inspector) - inspector->d->setFrontend(0); - - inspector = insp; - - // Give inspector frontend web view if previously created - if (inspector && inspectorFrontend) - inspector->d->setFrontend(inspectorFrontend); -} - -/*! - \internal - Returns the inspector and creates it if it wasn't created yet. - The instance created here will not be available through QWebPage's API. -*/ -QWebInspector* QWebPagePrivate::getOrCreateInspector() -{ -#if ENABLE(INSPECTOR) - if (!inspector) { - QWebInspector* insp = new QWebInspector; - insp->setPage(q); - inspectorIsInternalOnly = true; - - Q_ASSERT(inspector); // Associated through QWebInspector::setPage(q) - } -#endif - return inspector; -} - -/*! \internal */ -InspectorController* QWebPagePrivate::inspectorController() -{ -#if ENABLE(INSPECTOR) - return page->inspectorController(); -#else - return 0; -#endif -} - -quint16 QWebPagePrivate::inspectorServerPort() -{ -#if ENABLE(INSPECTOR) && !defined(QT_NO_PROPERTIES) - if (q && q->property("_q_webInspectorServerPort").isValid()) - return q->property("_q_webInspectorServerPort").toInt(); -#endif - return 0; -} - -static bool hasMouseListener(Element* element) -{ - ASSERT(element); - return element->hasEventListeners(eventNames().clickEvent) - || element->hasEventListeners(eventNames().mousedownEvent) - || element->hasEventListeners(eventNames().mouseupEvent); -} - -static bool isClickableElement(Element* element, RefPtr<NodeList> list) -{ - ASSERT(element); - bool isClickable = hasMouseListener(element); - if (!isClickable && list) { - Element* parent = element->parentElement(); - unsigned count = list->length(); - for (unsigned i = 0; i < count && parent; i++) { - if (list->item(i) != parent) - continue; - - isClickable = hasMouseListener(parent); - if (isClickable) - break; - - parent = parent->parentElement(); - } - } - - ExceptionCode ec = 0; - return isClickable - || element->webkitMatchesSelector("a,*:link,*:visited,*[role=button],button,input,select,label", ec) - || CSSComputedStyleDeclaration::create(element)->getPropertyValue(cssPropertyID("cursor")) == "pointer"; -} - -static bool isValidFrameOwner(Element* element) -{ - ASSERT(element); - return element->isFrameOwnerElement() && static_cast<HTMLFrameOwnerElement*>(element)->contentFrame(); -} - -static Element* nodeToElement(Node* node) -{ - if (node && node->isElementNode()) - return static_cast<Element*>(node); - return 0; -} - -QWebPagePrivate::TouchAdjuster::TouchAdjuster(unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding) - : m_topPadding(topPadding) - , m_rightPadding(rightPadding) - , m_bottomPadding(bottomPadding) - , m_leftPadding(leftPadding) -{ -} - -IntPoint QWebPagePrivate::TouchAdjuster::findCandidatePointForTouch(const IntPoint& touchPoint, Document* document) const -{ - if (!document) - return IntPoint(); - - int x = touchPoint.x(); - int y = touchPoint.y(); - - RefPtr<NodeList> intersectedNodes = document->nodesFromRect(x, y, m_topPadding, m_rightPadding, m_bottomPadding, m_leftPadding, false /*ignoreClipping*/, false /*allowShadowContent*/); - if (!intersectedNodes) - return IntPoint(); - - Element* closestClickableElement = 0; - IntRect largestIntersectionRect; - FrameView* view = document->frame()->view(); - - // Touch rect in contents coordinates. - IntRect touchRect(HitTestLocation::rectForPoint(view->windowToContents(IntPoint(x, y)), m_topPadding, m_rightPadding, m_bottomPadding, m_leftPadding)); - - // Iterate over the list of nodes hit looking for the one whose bounding area - // has largest intersection with the touch area (point + padding). - for (unsigned i = 0; i < intersectedNodes->length(); i++) { - Node* currentNode = intersectedNodes->item(i); - - Element* currentElement = nodeToElement(currentNode); - if (!currentElement || (!isClickableElement(currentElement, 0) && !isValidFrameOwner(currentElement))) - continue; - - IntRect currentElementBoundingRect = currentElement->pixelSnappedBoundingBox(); - currentElementBoundingRect.intersect(touchRect); - - if (currentElementBoundingRect.isEmpty()) - continue; - - int currentIntersectionRectArea = currentElementBoundingRect.width() * currentElementBoundingRect.height(); - int largestIntersectionRectArea = largestIntersectionRect.width() * largestIntersectionRect.height(); - if (currentIntersectionRectArea > largestIntersectionRectArea) { - closestClickableElement = currentElement; - largestIntersectionRect = currentElementBoundingRect; - } - } - - if (largestIntersectionRect.isEmpty()) - return IntPoint(); - - // Handle the case when user taps a inner frame. It is done in three steps: - // 1) Transform the original touch point to the inner document coordinates; - // 1) Call nodesFromRect for the inner document in case; - // 3) Re-add the inner frame offset (location) before passing the new clicking - // position to WebCore. - if (closestClickableElement->isFrameOwnerElement()) { - // Adjust client coordinates' origin to be top left of inner frame viewport. - PassRefPtr<ClientRect> rect = closestClickableElement->getBoundingClientRect(); - IntPoint newTouchPoint = touchPoint; - IntSize offset = IntSize(rect->left(), rect->top()); - newTouchPoint -= offset; - - HTMLFrameOwnerElement* owner = static_cast<HTMLFrameOwnerElement*>(closestClickableElement); - Document* childDocument = owner->contentFrame()->document(); - return findCandidatePointForTouch(newTouchPoint, childDocument); - } - return view->contentsToWindow(largestIntersectionRect).center(); -} - -/*! - \enum QWebPage::FindFlag - - This enum describes the options available to the findText() function. The options - can be OR-ed together from the following list: - - \value FindBackward Searches backwards instead of forwards. - \value FindCaseSensitively By default findText() works case insensitive. Specifying this option - changes the behaviour to a case sensitive find operation. - \value FindWrapsAroundDocument Makes findText() restart from the beginning of the document if the end - was reached and the text was not found. - \value HighlightAllOccurrences Highlights all existing occurrences of a specific string. - (This value was introduced in 4.6.) -*/ - -/*! - \enum QWebPage::LinkDelegationPolicy - - This enum defines the delegation policies a webpage can have when activating links and emitting - the linkClicked() signal. - - \value DontDelegateLinks No links are delegated. Instead, QWebPage tries to handle them all. - \value DelegateExternalLinks When activating links that point to documents not stored on the - local filesystem or an equivalent - such as the Qt resource system - then linkClicked() is emitted. - \value DelegateAllLinks Whenever a link is activated the linkClicked() signal is emitted. - - \sa QWebPage::linkDelegationPolicy -*/ - -/*! - \enum QWebPage::NavigationType - - This enum describes the types of navigation available when browsing through hyperlinked - documents. - - \value NavigationTypeLinkClicked The user clicked on a link or pressed return on a focused link. - \value NavigationTypeFormSubmitted The user activated a submit button for an HTML form. - \value NavigationTypeBackOrForward Navigation to a previously shown document in the back or forward history is requested. - \value NavigationTypeReload The user activated the reload action. - \value NavigationTypeFormResubmitted An HTML form was submitted a second time. - \value NavigationTypeOther A navigation to another document using a method not listed above. - - \sa acceptNavigationRequest() -*/ - -/*! - \enum QWebPage::WebAction - - This enum describes the types of action which can be performed on the web page. - - Actions only have an effect when they are applicable. The availability of - actions can be be determined by checking \l{QAction::}{isEnabled()} on the - action returned by action(). - - One method of enabling the text editing, cursor movement, and text selection actions - is by setting \l contentEditable to true. - - \value NoWebAction No action is triggered. - \value OpenLink Open the current link. - \value OpenLinkInNewWindow Open the current link in a new window. - \value OpenLinkInThisWindow Open the current link without opening a new window. Used on links that would default to opening in another frame or a new window. (Added in Qt 5.0) - \value OpenFrameInNewWindow Replicate the current frame in a new window. - \value DownloadLinkToDisk Download the current link to the disk. - \value CopyLinkToClipboard Copy the current link to the clipboard. - \value OpenImageInNewWindow Open the highlighted image in a new window. - \value DownloadImageToDisk Download the highlighted image to the disk. - \value CopyImageToClipboard Copy the highlighted image to the clipboard. (Added in Qt 4.8) - \value CopyImageUrlToClipboard Copy the highlighted image's URL to the clipboard. - \value Back Navigate back in the history of navigated links. - \value Forward Navigate forward in the history of navigated links. - \value Stop Stop loading the current page. - \value StopScheduledPageRefresh Stop all pending page refresh/redirect requests. (Added in Qt 4.7) - \value Reload Reload the current page. - \value ReloadAndBypassCache Reload the current page, but do not use any local cache. (Added in Qt 4.6) - \value Cut Cut the content currently selected into the clipboard. - \value Copy Copy the content currently selected into the clipboard. - \value Paste Paste content from the clipboard. - \value Undo Undo the last editing action. - \value Redo Redo the last editing action. - \value MoveToNextChar Move the cursor to the next character. - \value MoveToPreviousChar Move the cursor to the previous character. - \value MoveToNextWord Move the cursor to the next word. - \value MoveToPreviousWord Move the cursor to the previous word. - \value MoveToNextLine Move the cursor to the next line. - \value MoveToPreviousLine Move the cursor to the previous line. - \value MoveToStartOfLine Move the cursor to the start of the line. - \value MoveToEndOfLine Move the cursor to the end of the line. - \value MoveToStartOfBlock Move the cursor to the start of the block. - \value MoveToEndOfBlock Move the cursor to the end of the block. - \value MoveToStartOfDocument Move the cursor to the start of the document. - \value MoveToEndOfDocument Move the cursor to the end of the document. - \value SelectNextChar Select to the next character. - \value SelectPreviousChar Select to the previous character. - \value SelectNextWord Select to the next word. - \value SelectPreviousWord Select to the previous word. - \value SelectNextLine Select to the next line. - \value SelectPreviousLine Select to the previous line. - \value SelectStartOfLine Select to the start of the line. - \value SelectEndOfLine Select to the end of the line. - \value SelectStartOfBlock Select to the start of the block. - \value SelectEndOfBlock Select to the end of the block. - \value SelectStartOfDocument Select to the start of the document. - \value SelectEndOfDocument Select to the end of the document. - \value DeleteStartOfWord Delete to the start of the word. - \value DeleteEndOfWord Delete to the end of the word. - \value SetTextDirectionDefault Set the text direction to the default direction. - \value SetTextDirectionLeftToRight Set the text direction to left-to-right. - \value SetTextDirectionRightToLeft Set the text direction to right-to-left. - \value ToggleBold Toggle the formatting between bold and normal weight. - \value ToggleItalic Toggle the formatting between italic and normal style. - \value ToggleUnderline Toggle underlining. - \value InspectElement Show the Web Inspector with the currently highlighted HTML element. - \value InsertParagraphSeparator Insert a new paragraph. - \value InsertLineSeparator Insert a new line. - \value SelectAll Selects all content. - \value PasteAndMatchStyle Paste content from the clipboard with current style. (Added in Qt 4.6) - \value RemoveFormat Removes formatting and style. (Added in Qt 4.6) - \value ToggleStrikethrough Toggle the formatting between strikethrough and normal style. (Added in Qt 4.6) - \value ToggleSubscript Toggle the formatting between subscript and baseline. (Added in Qt 4.6) - \value ToggleSuperscript Toggle the formatting between supercript and baseline. (Added in Qt 4.6) - \value InsertUnorderedList Toggles the selection between an ordered list and a normal block. (Added in Qt 4.6) - \value InsertOrderedList Toggles the selection between an ordered list and a normal block. (Added in Qt 4.6) - \value Indent Increases the indentation of the currently selected format block by one increment. (Added in Qt 4.6) - \value Outdent Decreases the indentation of the currently selected format block by one increment. (Added in Qt 4.6) - \value AlignCenter Applies center alignment to content. (Added in Qt 4.6) - \value AlignJustified Applies full justification to content. (Added in Qt 4.6) - \value AlignLeft Applies left justification to content. (Added in Qt 4.6) - \value AlignRight Applies right justification to content. (Added in Qt 4.6) - - - \omitvalue WebActionCount - -*/ - -/*! - \enum QWebPage::WebWindowType - - This enum describes the types of window that can be created by the createWindow() function. - - \value WebBrowserWindow The window is a regular web browser window. - \value WebModalDialog The window acts as modal dialog. -*/ - - -/*! - \class QWebPage::ViewportAttributes - \since 4.7 - \brief The QWebPage::ViewportAttributes class describes hints that can be applied to a viewport. - - QWebPage::ViewportAttributes provides a description of a viewport, such as viewport geometry, - initial scale factor with limits, plus information about whether a user should be able - to scale the contents in the viewport or not, ie. by zooming. - - ViewportAttributes can be set by a web author using the viewport meta tag extension, documented - at \l{http://developer.apple.com/safari/library/documentation/appleapplications/reference/safariwebcontent/usingtheviewport/usingtheviewport.html}{Safari Reference Library: Using the Viewport Meta Tag}. - - All values might not be set, as such when dealing with the hints, the developer needs to - check whether the values are valid. Negative values denote an invalid qreal value. - - \inmodule QtWebKit -*/ - -/*! - Constructs an empty QWebPage::ViewportAttributes. -*/ -QWebPage::ViewportAttributes::ViewportAttributes() - : d(0) - , m_initialScaleFactor(-1.0) - , m_minimumScaleFactor(-1.0) - , m_maximumScaleFactor(-1.0) - , m_devicePixelRatio(-1.0) - , m_isUserScalable(true) - , m_isValid(false) -{ - -} - -/*! - Constructs a QWebPage::ViewportAttributes which is a copy from \a other . -*/ -QWebPage::ViewportAttributes::ViewportAttributes(const QWebPage::ViewportAttributes& other) - : d(other.d) - , m_initialScaleFactor(other.m_initialScaleFactor) - , m_minimumScaleFactor(other.m_minimumScaleFactor) - , m_maximumScaleFactor(other.m_maximumScaleFactor) - , m_devicePixelRatio(other.m_devicePixelRatio) - , m_isUserScalable(other.m_isUserScalable) - , m_isValid(other.m_isValid) - , m_size(other.m_size) -{ - -} - -/*! - Destroys the QWebPage::ViewportAttributes. -*/ -QWebPage::ViewportAttributes::~ViewportAttributes() -{ - -} - -/*! - Assigns the given QWebPage::ViewportAttributes to this viewport hints and returns a - reference to this. -*/ -QWebPage::ViewportAttributes& QWebPage::ViewportAttributes::operator=(const QWebPage::ViewportAttributes& other) -{ - if (this != &other) { - d = other.d; - m_initialScaleFactor = other.m_initialScaleFactor; - m_minimumScaleFactor = other.m_minimumScaleFactor; - m_maximumScaleFactor = other.m_maximumScaleFactor; - m_isUserScalable = other.m_isUserScalable; - m_isValid = other.m_isValid; - m_size = other.m_size; - } - - return *this; -} - -/*! \fn inline bool QWebPage::ViewportAttributes::isValid() const - Returns whether this is a valid ViewportAttributes or not. - - An invalid ViewportAttributes will have an empty QSize, negative values for scale factors and - true for the boolean isUserScalable. -*/ - -/*! \fn inline QSize QWebPage::ViewportAttributes::size() const - Returns the size of the viewport. -*/ - -/*! \fn inline qreal QWebPage::ViewportAttributes::initialScaleFactor() const - Returns the initial scale of the viewport as a multiplier. -*/ - -/*! \fn inline qreal QWebPage::ViewportAttributes::minimumScaleFactor() const - Returns the minimum scale value of the viewport as a multiplier. -*/ - -/*! \fn inline qreal QWebPage::ViewportAttributes::maximumScaleFactor() const - Returns the maximum scale value of the viewport as a multiplier. -*/ - -/*! \fn inline bool QWebPage::ViewportAttributes::isUserScalable() const - Determines whether or not the scale can be modified by the user. -*/ - - -/*! - \class QWebPage - \since 4.4 - \brief The QWebPage class provides an object to view and edit web documents. - - \inmodule QtWebKit - - QWebPage holds a main frame responsible for web content, settings, the history - of navigated links and actions. This class can be used, together with QWebFrame, - to provide functionality like QWebView in a widget-less environment. - - QWebPage's API is very similar to QWebView, as you are still provided with - common functions like action() (known as - \l{QWebView::pageAction()}{pageAction}() in QWebView), triggerAction(), - findText() and settings(). More QWebView-like functions can be found in the - main frame of QWebPage, obtained via the mainFrame() function. For example, - the \l{QWebFrame::load()}{load}(), \l{QWebFrame::setUrl()}{setUrl}() and - \l{QWebFrame::setHtml()}{setHtml}() functions for QWebPage can be accessed - using QWebFrame. - - The loadStarted() signal is emitted when the page begins to load.The - loadProgress() signal, on the other hand, is emitted whenever an element - of the web page completes loading, such as an embedded image, a script, - etc. Finally, the loadFinished() signal is emitted when the page contents - are loaded completely, independent of script execution or page rendering. - Its argument, either true or false, indicates whether or not the load - operation succeeded. - - \section1 Using QWebPage in a Widget-less Environment - - Before you begin painting a QWebPage object, you need to set the size of - the viewport by calling setViewportSize(). Then, you invoke the main - frame's render function (QWebFrame::render()). An example of this - is shown in the code snippet below. - - Suppose we have a \c Thumbnail class as follows: - - \snippet webkitsnippets/webpage/main.cpp 0 - - The \c Thumbnail's constructor takes in a \a url. We connect our QWebPage - object's \l{QWebPage::}{loadFinished()} signal to our private slot, - \c render(). - - \snippet webkitsnippets/webpage/main.cpp 1 - - The \c render() function shows how we can paint a thumbnail using a - QWebPage object. - - \snippet webkitsnippets/webpage/main.cpp 2 - - We begin by setting the \l{QWebPage::viewportSize()}{viewportSize} and - then we instantiate a QImage object, \c image, with the same size as our - \l{QWebPage::viewportSize()}{viewportSize}. This image is then sent - as a parameter to \c painter. Next, we render the contents of the main - frame and its subframes into \c painter. Finally, we save the scaled image. - - \sa QWebFrame -*/ - -/*! - Constructs an empty QWebPage with parent \a parent. -*/ -QWebPage::QWebPage(QObject *parent) - : QObject(parent) - , d(new QWebPagePrivate(this)) -{ - setView(qobject_cast<QWidget*>(parent)); - - connect(this, SIGNAL(loadProgress(int)), this, SLOT(_q_onLoadProgressChanged(int))); -#ifndef NDEBUG - connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(_q_cleanupLeakMessages())); -#endif -} - -/*! - Destroys the web page. -*/ -QWebPage::~QWebPage() -{ - d->createMainFrame(); - FrameLoader* loader = d->mainFrame.data()->d->frame->loader(); - if (loader) - loader->detachFromParent(); - delete d; -} - -/*! - Returns the main frame of the page. - - The main frame provides access to the hierarchy of sub-frames and is also needed if you - want to explicitly render a web page into a given painter. - - \sa currentFrame() -*/ -QWebFrame *QWebPage::mainFrame() const -{ - d->createMainFrame(); - return d->mainFrame.data(); -} - -/*! - Returns the frame currently active. - - \sa mainFrame(), frameCreated() -*/ -QWebFrame *QWebPage::currentFrame() const -{ - d->createMainFrame(); - WebCore::Frame *frame = d->page->focusController()->focusedOrMainFrame(); - return qobject_cast<QWebFrame*>(frame->loader()->networkingContext()->originatingObject()); -} - - -/*! - \since 4.6 - - Returns the frame at the given point \a pos, or 0 if there is no frame at - that position. - - \sa mainFrame(), currentFrame() -*/ -QWebFrame* QWebPage::frameAt(const QPoint& pos) const -{ - QWebFrame* webFrame = mainFrame(); - if (!webFrame->geometry().contains(pos)) - return 0; - QWebHitTestResult hitTestResult = webFrame->hitTestContent(pos); - return hitTestResult.frame(); -} - -/*! - Returns a pointer to the view's history of navigated web pages. -*/ -QWebHistory *QWebPage::history() const -{ - d->createMainFrame(); - return &d->history; -} - -/*! - Sets the \a view that is associated with the web page. - - \sa view() -*/ -void QWebPage::setView(QWidget* view) -{ - if (this->view() == view) - return; - - d->view = view; - setViewportSize(view ? view->size() : QSize(0, 0)); - - // If we have no client, we install a special client delegating - // the responsibility to the QWidget. This is the code path - // handling a.o. the "legacy" QWebView. - // - // If such a special delegate already exist, we substitute the view. - - if (d->client) { - if (d->client->isQWidgetClient()) - static_cast<PageClientQWidget*>(d->client.data())->view = view; - return; - } - - if (view) - d->client.reset(new PageClientQWidget(view, this)); -} - -/*! - Returns the view widget that is associated with the web page. - - \sa setView() -*/ -QWidget *QWebPage::view() const -{ - return d->view.data(); -} - -/*! - This function is called whenever a JavaScript program tries to print a \a message to the web browser's console. - - For example in case of evaluation errors the source URL may be provided in \a sourceID as well as the \a lineNumber. - - The default implementation prints nothing. -*/ -void QWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) -{ - Q_UNUSED(sourceID) - - // Catch plugin logDestroy message for LayoutTests/plugins/open-and-close-window-with-plugin.html - // At this point DRT's WebPage has already been destroyed - if (QWebPageAdapter::drtRun) { - if (message == QLatin1String("PLUGIN: NPP_Destroy")) { - fprintf(stdout, "CONSOLE MESSAGE: "); - if (lineNumber) - fprintf(stdout, "line %d: ", lineNumber); - fprintf(stdout, "%s\n", message.toUtf8().constData()); - } - } -} - -/*! - This function is called whenever a JavaScript program running inside \a frame calls the alert() function with - the message \a msg. - - The default implementation shows the message, \a msg, with QMessageBox::information. -*/ -void QWebPage::javaScriptAlert(QWebFrame *frame, const QString& msg) -{ - Q_UNUSED(frame) -#ifndef QT_NO_MESSAGEBOX - QMessageBox box(view()); - box.setWindowTitle(tr("JavaScript Alert - %1").arg(mainFrame()->url().host())); - box.setTextFormat(Qt::PlainText); - box.setText(msg); - box.setStandardButtons(QMessageBox::Ok); - box.exec(); -#endif -} - -/*! - This function is called whenever a JavaScript program running inside \a frame calls the confirm() function - with the message, \a msg. Returns true if the user confirms the message; otherwise returns false. - - The default implementation executes the query using QMessageBox::information with QMessageBox::Ok and QMessageBox::Cancel buttons. -*/ -bool QWebPage::javaScriptConfirm(QWebFrame *frame, const QString& msg) -{ - Q_UNUSED(frame) -#ifdef QT_NO_MESSAGEBOX - return true; -#else - QMessageBox box(view()); - box.setWindowTitle(tr("JavaScript Confirm - %1").arg(mainFrame()->url().host())); - box.setTextFormat(Qt::PlainText); - box.setText(msg); - box.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); - return QMessageBox::Ok == box.exec(); -#endif -} - -/*! - This function is called whenever a JavaScript program running inside \a frame tries to prompt the user for input. - The program may provide an optional message, \a msg, as well as a default value for the input in \a defaultValue. - - If the prompt was cancelled by the user the implementation should return false; otherwise the - result should be written to \a result and true should be returned. If the prompt was not cancelled by the - user, the implementation should return true and the result string must not be null. - - The default implementation uses QInputDialog::getText(). -*/ -bool QWebPage::javaScriptPrompt(QWebFrame *frame, const QString& msg, const QString& defaultValue, QString* result) -{ - Q_UNUSED(frame) - bool ok = false; -#ifndef QT_NO_INPUTDIALOG - - QInputDialog dlg(view()); - dlg.setWindowTitle(tr("JavaScript Prompt - %1").arg(mainFrame()->url().host())); - - // Hack to force the dialog's QLabel into plain text mode - // prevents https://bugs.webkit.org/show_bug.cgi?id=34429 - QLabel* label = dlg.findChild<QLabel*>(); - if (label) - label->setTextFormat(Qt::PlainText); - - // double the &'s because single & will underline the following character - // (Accelerator mnemonics) - QString escMsg(msg); - escMsg.replace(QChar::fromLatin1('&'), QLatin1String("&&")); - dlg.setLabelText(escMsg); - - dlg.setTextEchoMode(QLineEdit::Normal); - dlg.setTextValue(defaultValue); - - ok = !!dlg.exec(); - - if (ok && result) - *result = dlg.textValue(); -#endif - return ok; -} - -/*! - \fn bool QWebPage::shouldInterruptJavaScript() - \since 4.6 - This function is called when a JavaScript program is running for a long period of time. - - If the user wanted to stop the JavaScript the implementation should return true; otherwise false. - - The default implementation executes the query using QMessageBox::information with QMessageBox::Yes and QMessageBox::No buttons. -*/ -bool QWebPage::shouldInterruptJavaScript() -{ -#ifdef QT_NO_MESSAGEBOX - return false; -#else - return QMessageBox::Yes == QMessageBox::information(view(), tr("JavaScript Problem - %1").arg(mainFrame()->url().host()), tr("The script on this page appears to have a problem. Do you want to stop the script?"), QMessageBox::Yes, QMessageBox::No); -#endif -} - -void QWebPage::setFeaturePermission(QWebFrame* frame, Feature feature, PermissionPolicy policy) -{ - switch (feature) { - case Notifications: -#if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) - if (policy == PermissionGrantedByUser) - NotificationPresenterClientQt::notificationPresenter()->allowNotificationForFrame(frame->d->frame); -#endif - break; - case Geolocation: -#if ENABLE(GEOLOCATION) - if (policy != PermissionUnknown) - GeolocationPermissionClientQt::geolocationPermissionClient()->setPermission(frame->d, (policy == PermissionGrantedByUser)); -#endif - break; - - default: - break; - } -} - -/*! - This function is called whenever WebKit wants to create a new window of the given \a type, for - example when a JavaScript program requests to open a document in a new window. - - If the new window can be created, the new window's QWebPage is returned; otherwise a null pointer is returned. - - If the view associated with the web page is a QWebView object, then the default implementation forwards - the request to QWebView's createWindow() function; otherwise it returns a null pointer. - - If \a type is WebModalDialog, the application must call setWindowModality(Qt::ApplicationModal) on the new window. - - \note In the cases when the window creation is being triggered by JavaScript, apart from - reimplementing this method application must also set the JavaScriptCanOpenWindows attribute - of QWebSettings to true in order for it to get called. - - \sa acceptNavigationRequest(), QWebView::createWindow() -*/ -QWebPage *QWebPage::createWindow(WebWindowType type) -{ - QWebView *webView = qobject_cast<QWebView*>(view()); - if (webView) { - QWebView *newView = webView->createWindow(type); - if (newView) - return newView->page(); - } - return 0; -} - -/*! - This function is called whenever WebKit encounters a HTML object element with type "application/x-qt-plugin". It is - called regardless of the value of QWebSettings::PluginsEnabled. The \a classid, \a url, \a paramNames and \a paramValues - correspond to the HTML object element attributes and child elements to configure the embeddable object. -*/ -QObject *QWebPage::createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) -{ - Q_UNUSED(classid) - Q_UNUSED(url) - Q_UNUSED(paramNames) - Q_UNUSED(paramValues) - return 0; -} - -static void extractContentTypeFromHash(const HashSet<String>& types, QStringList* list) -{ - if (!list) - return; - - HashSet<String>::const_iterator endIt = types.end(); - for (HashSet<String>::const_iterator it = types.begin(); it != endIt; ++it) - *list << *it; -} - -static void extractContentTypeFromPluginVector(const Vector<PluginPackage*>& plugins, QStringList* list) -{ - if (!list) - return; - - for (unsigned int i = 0; i < plugins.size(); ++i) { - MIMEToDescriptionsMap::const_iterator map_it = plugins[i]->mimeToDescriptions().begin(); - MIMEToDescriptionsMap::const_iterator map_end = plugins[i]->mimeToDescriptions().end(); - for (; map_it != map_end; ++map_it) - *list << map_it->key; - } -} - -/*! - * Returns the list of all content types supported by QWebPage. - */ -QStringList QWebPage::supportedContentTypes() const -{ - QStringList mimeTypes; - - extractContentTypeFromHash(MIMETypeRegistry::getSupportedImageMIMETypes(), &mimeTypes); - extractContentTypeFromHash(MIMETypeRegistry::getSupportedNonImageMIMETypes(), &mimeTypes); - if (d->page->settings() && d->page->settings()->arePluginsEnabled()) - extractContentTypeFromPluginVector(PluginDatabase::installedPlugins()->plugins(), &mimeTypes); - - return mimeTypes; -} - -/*! - * Returns true if QWebPage can handle the given \a mimeType; otherwise, returns false. - */ -bool QWebPage::supportsContentType(const QString& mimeType) const -{ - const String type = mimeType.toLower(); - if (MIMETypeRegistry::isSupportedImageMIMEType(type)) - return true; - - if (MIMETypeRegistry::isSupportedNonImageMIMEType(type)) - return true; - - if (d->page->settings() && d->page->settings()->arePluginsEnabled() - && PluginDatabase::installedPlugins()->isMIMETypeRegistered(type)) - return true; - - return false; -} - -static WebCore::FrameLoadRequest frameLoadRequest(const QUrl &url, WebCore::Frame *frame) -{ - return WebCore::FrameLoadRequest(frame->document()->securityOrigin(), - WebCore::ResourceRequest(url, frame->loader()->outgoingReferrer())); -} - -static void openNewWindow(const QUrl& url, WebCore::Frame* frame) -{ - if (Page* oldPage = frame->page()) { - WindowFeatures features; - NavigationAction action; - FrameLoadRequest request = frameLoadRequest(url, frame); - if (Page* newPage = oldPage->chrome()->createWindow(frame, request, features, action)) { - newPage->mainFrame()->loader()->loadFrameRequest(request, false, false, 0, 0, MaybeSendReferrer); - newPage->chrome()->show(); - } - } -} - -static void collectChildFrames(QWebFrame* frame, QList<QWebFrame*>& list) -{ - list << frame->childFrames(); - QListIterator<QWebFrame*> it(frame->childFrames()); - while (it.hasNext()) { - collectChildFrames(it.next(), list); - } -} - -/*! - This function can be called to trigger the specified \a action. - It is also called by QtWebKit if the user triggers the action, for example - through a context menu item. - - If \a action is a checkable action then \a checked specified whether the action - is toggled or not. - - \sa action() -*/ -void QWebPage::triggerAction(WebAction action, bool) -{ - WebCore::Frame *frame = d->page->focusController()->focusedOrMainFrame(); - if (!frame) - return; - WebCore::Editor *editor = frame->editor(); - const char *command = 0; - - switch (action) { - case OpenLink: - if (QWebFrame *targetFrame = d->hitTestResult.linkTargetFrame()) { - WTF::RefPtr<WebCore::Frame> wcFrame = targetFrame->d->frame; - targetFrame->d->frame->loader()->loadFrameRequest(frameLoadRequest(d->hitTestResult.linkUrl(), wcFrame.get()), - /*lockHistory*/ false, /*lockBackForwardList*/ false, /*event*/ 0, - /*FormState*/ 0, MaybeSendReferrer); - break; - } - // fall through - case OpenLinkInNewWindow: - openNewWindow(d->hitTestResult.linkUrl(), frame); - break; - case OpenLinkInThisWindow: - frame->loader()->loadFrameRequest(frameLoadRequest(d->hitTestResult.linkUrl(), frame), - /*lockHistory*/ false, /*lockBackForwardList*/ false, /*event*/ 0, /*FormState*/ 0, MaybeSendReferrer); - break; - case OpenFrameInNewWindow: { - KURL url = frame->loader()->documentLoader()->unreachableURL(); - if (url.isEmpty()) - url = frame->loader()->documentLoader()->url(); - openNewWindow(url, frame); - break; - } - case CopyLinkToClipboard: { -#if defined(Q_WS_X11) - bool oldSelectionMode = Pasteboard::generalPasteboard()->isSelectionMode(); - Pasteboard::generalPasteboard()->setSelectionMode(true); - editor->copyURL(d->hitTestResult.linkUrl(), d->hitTestResult.linkText()); - Pasteboard::generalPasteboard()->setSelectionMode(oldSelectionMode); -#endif - editor->copyURL(d->hitTestResult.linkUrl(), d->hitTestResult.linkText()); - break; - } - case OpenImageInNewWindow: - openNewWindow(d->hitTestResult.imageUrl(), frame); - break; - case DownloadImageToDisk: - frame->loader()->client()->startDownload(WebCore::ResourceRequest(d->hitTestResult.imageUrl(), frame->loader()->outgoingReferrer())); - break; - case DownloadLinkToDisk: - frame->loader()->client()->startDownload(WebCore::ResourceRequest(d->hitTestResult.linkUrl(), frame->loader()->outgoingReferrer())); - break; -#ifndef QT_NO_CLIPBOARD - case CopyImageToClipboard: - QApplication::clipboard()->setPixmap(d->hitTestResult.pixmap()); - break; - case CopyImageUrlToClipboard: - QApplication::clipboard()->setText(d->hitTestResult.imageUrl().toString()); - break; -#endif - case Back: - d->page->goBack(); - break; - case Forward: - d->page->goForward(); - break; - case Stop: - mainFrame()->d->frame->loader()->stopForUserCancel(); - d->updateNavigationActions(); - break; - case Reload: - mainFrame()->d->frame->loader()->reload(/*endtoendreload*/false); - break; - case ReloadAndBypassCache: - mainFrame()->d->frame->loader()->reload(/*endtoendreload*/true); - break; - case SetTextDirectionDefault: - editor->setBaseWritingDirection(NaturalWritingDirection); - break; - case SetTextDirectionLeftToRight: - editor->setBaseWritingDirection(LeftToRightWritingDirection); - break; - case SetTextDirectionRightToLeft: - editor->setBaseWritingDirection(RightToLeftWritingDirection); - break; - case InspectElement: { -#if ENABLE(INSPECTOR) - if (!d->hitTestResult.isNull()) { - d->getOrCreateInspector(); // Make sure the inspector is created - d->inspector->show(); // The inspector is expected to be shown on inspection - d->page->inspectorController()->inspect(d->hitTestResult.d->innerNonSharedNode.get()); - } -#endif - break; - } - case StopScheduledPageRefresh: { - QWebFrame* topFrame = mainFrame(); - topFrame->d->frame->navigationScheduler()->cancel(); - QList<QWebFrame*> childFrames; - collectChildFrames(topFrame, childFrames); - QListIterator<QWebFrame*> it(childFrames); - while (it.hasNext()) - it.next()->d->frame->navigationScheduler()->cancel(); - break; - } - default: - command = QWebPagePrivate::editorCommandForWebActions(action); - break; - } - - if (command) - editor->command(command).execute(); -} - - -QColor QWebPagePrivate::colorSelectionRequested(const QColor &selectedColor) -{ - QColor ret = selectedColor; -#ifndef QT_NO_COLORDIALOG - ret = QColorDialog::getColor(selectedColor, q->view()); - if (!ret.isValid()) - ret = selectedColor; -#endif - return ret; -} - -QWebSelectMethod *QWebPagePrivate::createSelectPopup() -{ - return new QtFallbackWebPopup(this); -} - -QRect QWebPagePrivate::viewRectRelativeToWindow() -{ - - QWidget* ownerWidget= client.isNull() ? 0 : qobject_cast<QWidget*>(client->ownerWidget()); - if (!ownerWidget) - return QRect(); - QWidget* topLevelWidget = ownerWidget->window(); - - QPoint topLeftCorner = ownerWidget->mapFrom(topLevelWidget, QPoint(0, 0)); - return QRect(topLeftCorner, ownerWidget->size()); -} - -void QWebPagePrivate::geolocationPermissionRequested(QWebFrameAdapter* frame) -{ - emit q->featurePermissionRequested(QWebFramePrivate::kit(frame), QWebPage::Geolocation); -} - -void QWebPagePrivate::geolocationPermissionRequestCancelled(QWebFrameAdapter* frame) -{ - emit q->featurePermissionRequestCanceled(QWebFramePrivate::kit(frame), QWebPage::Geolocation); -} - -void QWebPagePrivate::notificationsPermissionRequested(QWebFrameAdapter* frame) -{ - emit q->featurePermissionRequested(QWebFramePrivate::kit(frame), QWebPage::Notifications); -} - -void QWebPagePrivate::notificationsPermissionRequestCancelled(QWebFrameAdapter* frame) -{ - emit q->featurePermissionRequestCanceled(QWebFramePrivate::kit(frame), QWebPage::Notifications); -} - -void QWebPagePrivate::respondToChangedContents() -{ - updateEditorActions(); - - emit q->contentsChanged(); -} - -void QWebPagePrivate::respondToChangedSelection() -{ - updateEditorActions(); - emit q->selectionChanged(); -} - -void QWebPagePrivate::microFocusChanged() -{ - emit q->microFocusChanged(); -} - -void QWebPagePrivate::triggerCopyAction() -{ - q->triggerAction(QWebPage::Copy); -} - -void QWebPagePrivate::triggerActionForKeyEvent(QKeyEvent* event) -{ - QWebPage::WebAction action = editorActionForKeyEvent(event); - q->triggerAction(action); -} - -void QWebPagePrivate::clearUndoStack() -{ -#ifndef QT_NO_UNDOSTACK - if (undoStack) - undoStack->clear(); -#endif -} - -bool QWebPagePrivate::canUndo() const -{ -#ifndef QT_NO_UNDOSTACK - if (!undoStack) - return false; - return undoStack->canUndo(); -#else - return false; -#endif -} - -bool QWebPagePrivate::canRedo() const -{ -#ifndef QT_NO_UNDOSTACK - if (!undoStack) - return false; - return undoStack->canRedo(); -#else - return false; -#endif -} - -void QWebPagePrivate::undo() -{ -#ifndef QT_NO_UNDOSTACK - if (undoStack) - undoStack->undo(); -#endif -} - -void QWebPagePrivate::redo() -{ -#ifndef QT_NO_UNDOSTACK - if (undoStack) - undoStack->redo(); -#endif -} - -void QWebPagePrivate::createUndoStep(QSharedPointer<UndoStepQt> step) -{ -#ifndef QT_NO_UNDOSTACK - // Call undoStack() getter first to ensure stack is created - // if it doesn't exist yet. - q->undoStack()->push(new QWebUndoCommand(step)); -#endif -} - -const char *QWebPagePrivate::editorCommandForKeyEvent(QKeyEvent* event) -{ - QWebPage::WebAction action = editorActionForKeyEvent(event); - return editorCommandForWebActions(action); -} - -QSize QWebPage::viewportSize() const -{ - if (d->mainFrame && d->mainFrame.data()->d->frame->view()) - return d->mainFrame.data()->d->frame->view()->frameRect().size(); - - return d->m_viewportSize; -} - -/*! - \property QWebPage::viewportSize - \brief the size of the viewport - - The size affects for example the visibility of scrollbars - if the document is larger than the viewport. - - By default, for a newly-created Web page, this property contains a size with - zero width and height. - - \sa QWebFrame::render(), preferredContentsSize -*/ -void QWebPage::setViewportSize(const QSize &size) const -{ - d->m_viewportSize = size; - - QWebFrame *frame = mainFrame(); - if (frame->d->frame && frame->d->frame->view()) { - WebCore::FrameView* view = frame->d->frame->view(); - view->resize(size); - view->adjustViewSize(); - } -} - -static int getintenv(const char* variable) -{ - bool ok; - int value = qgetenv(variable).toInt(&ok); - return (ok) ? value : -1; -} - -static QSize queryDeviceSizeForScreenContainingWidget(const QWidget* widget) -{ - QDesktopWidget* desktop = QApplication::desktop(); - if (!desktop) - return QSize(); - - QSize size; - - if (widget) { - // Returns the available geometry of the screen which contains widget. - // NOTE: this must be the the full screen size including any fixed status areas etc. - size = desktop->availableGeometry(widget).size(); - } else - size = desktop->availableGeometry().size(); - - // This must be in portrait mode, adjust if not. - if (size.width() > size.height()) { - int width = size.width(); - size.setWidth(size.height()); - size.setHeight(width); - } - - return size; -} - -/*! - Computes the optimal viewport configuration given the \a availableSize, when - user interface components are disregarded. - - The configuration is also dependent on the device screen size which is obtained - automatically. For testing purposes the size can be overridden by setting two - environment variables QTWEBKIT_DEVICE_WIDTH and QTWEBKIT_DEVICE_HEIGHT, which - both needs to be set. - - The ViewportAttributes includes a pixel density ratio, which will also be exposed to - the web author though the -webkit-pixel-ratio media feature. This is the ratio - between 1 density-independent pixel (DPI) and physical pixels. - - A density-independent pixel is equivalent to one physical pixel on a 160 DPI screen, - so on our platform assumes that as the baseline density. - - The conversion of DIP units to screen pixels is quite simple: - - pixels = DIPs * (density / 160). - - Thus, on a 240 DPI screen, 1 DIPs would equal 1.5 physical pixels. - - An invalid instance will be returned in the case an empty size is passed to the - method. - - \note The density is automatically obtained from the DPI of the screen where the page - is being shown, but as many X11 servers are reporting wrong DPI, it is possible to - override it using QX11Info::setAppDpiY(). -*/ - -QWebPage::ViewportAttributes QWebPage::viewportAttributesForSize(const QSize& availableSize) const -{ - static int desktopWidth = 980; - - ViewportAttributes result; - - if (availableSize.isEmpty()) - return result; // Returns an invalid instance. - - int deviceWidth = getintenv("QTWEBKIT_DEVICE_WIDTH"); - int deviceHeight = getintenv("QTWEBKIT_DEVICE_HEIGHT"); - - // Both environment variables need to be set - or they will be ignored. - if (deviceWidth < 0 && deviceHeight < 0) { - QSize size = queryDeviceSizeForScreenContainingWidget(view()); - deviceWidth = size.width(); - deviceHeight = size.height(); - } - - float devicePixelRatio = qt_defaultDpi() / WebCore::ViewportArguments::deprecatedTargetDPI; - - WebCore::ViewportAttributes conf = WebCore::computeViewportAttributes(d->viewportArguments(), desktopWidth, deviceWidth, deviceHeight, devicePixelRatio, availableSize); - WebCore::restrictMinimumScaleFactorToViewportSize(conf, availableSize, devicePixelRatio); - WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(conf); - - result.m_isValid = true; - result.m_size = QSizeF(conf.layoutSize.width(), conf.layoutSize.height()); - result.m_initialScaleFactor = conf.initialScale; - result.m_minimumScaleFactor = conf.minimumScale; - result.m_maximumScaleFactor = conf.maximumScale; - result.m_devicePixelRatio = devicePixelRatio; - result.m_isUserScalable = static_cast<bool>(conf.userScalable); - - d->page->setDeviceScaleFactor(devicePixelRatio); - - return result; -} - -QSize QWebPage::preferredContentsSize() const -{ - QWebFrame* frame = d->mainFrame.data(); - if (frame) { - WebCore::FrameView* view = frame->d->frame->view(); - if (view && view->useFixedLayout()) - return d->mainFrame.data()->d->frame->view()->fixedLayoutSize(); - } - - return d->fixedLayoutSize; -} - -/*! - \property QWebPage::preferredContentsSize - \since 4.6 - \brief a custom size used for laying out the page contents. - - By default all pages are laid out using the viewport of the page as the base. - - As pages mostly are designed for desktop usage, they often do not layout properly - on small devices as the contents require a certain view width. For this reason - it is common to use a different layout size and then scale the contents to fit - within the actual view. - - If this property is set to a valid size, this size is used for all layout needs - instead of the size of the viewport. - - Setting an invalid size, makes the page fall back to using the viewport size for layout. - - \sa viewportSize -*/ -void QWebPage::setPreferredContentsSize(const QSize& size) const -{ - // FIXME: Rename this method to setCustomLayoutSize - - d->fixedLayoutSize = size; - - QWebFrame* frame = mainFrame(); - if (!frame->d->frame || !frame->d->frame->view()) - return; - - WebCore::FrameView* view = frame->d->frame->view(); - - if (size.isValid()) { - view->setUseFixedLayout(true); - view->setFixedLayoutSize(size); - } else if (view->useFixedLayout()) - view->setUseFixedLayout(false); - - view->layout(); -} - -/* - This function is to be called after any (animated) scroll/pan has ended, in the case the application handles the - scrolling/panning of the web contents. This is commonly used in combination with tiling where is it common for - the application to pan the actual view, which then resizes itself to the size of the contents. - - \note Calling this function makes WebKit stop trying to calculate the visibleContentRect. To turn that on - again, call this method with an empty rect. - - \sa QGraphicsWebView::resizesToContents, QWebSettings::TiledBackingStoreEnabled -*/ -void QWebPage::setActualVisibleContentRect(const QRect& rect) const -{ - QWebFrame* frame = mainFrame(); - if (!frame->d->frame || !frame->d->frame->view()) - return; - - WebCore::FrameView* view = frame->d->frame->view(); - view->setFixedVisibleContentRect(rect); -} - -/*! - \fn bool QWebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, QWebPage::NavigationType type) - - This function is called whenever WebKit requests to navigate \a frame to the resource specified by \a request by means of - the specified navigation type \a type. - - If \a frame is a null pointer then navigation to a new window is requested. If the request is - accepted createWindow() will be called. - - The default implementation interprets the page's linkDelegationPolicy and emits linkClicked accordingly or returns true - to let QWebPage handle the navigation itself. - - \sa createWindow() -*/ -bool QWebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, QWebPage::NavigationType type) -{ - Q_UNUSED(frame) - if (type == NavigationTypeLinkClicked) { - switch (d->linkPolicy) { - case DontDelegateLinks: - return true; - - case DelegateExternalLinks: - if (WebCore::SchemeRegistry::shouldTreatURLSchemeAsLocal(request.url().scheme())) - return true; - emit linkClicked(request.url()); - return false; - - case DelegateAllLinks: - emit linkClicked(request.url()); - return false; - } - } - return true; -} - -/*! - \property QWebPage::hasSelection - \brief whether this page contains selected content or not. - - \sa selectionChanged() -*/ -bool QWebPage::hasSelection() const -{ - d->createMainFrame(); - WebCore::Frame* frame = d->page->focusController()->focusedOrMainFrame(); - if (frame) - return (frame->selection()->selection().selectionType() != VisibleSelection::NoSelection); - return false; -} - -/*! - \property QWebPage::selectedText - \brief the text currently selected - - By default, this property contains an empty string. - - \sa selectionChanged(), selectedHtml() -*/ -QString QWebPage::selectedText() const -{ - d->createMainFrame(); - WebCore::Frame* frame = d->page->focusController()->focusedOrMainFrame(); - if (frame->selection()->selection().selectionType() == VisibleSelection::NoSelection) - return QString(); - return frame->editor()->selectedText(); -} - -/*! - \since 4.8 - \property QWebPage::selectedHtml - \brief the HTML currently selected - - By default, this property contains an empty string. - - \sa selectionChanged(), selectedText() -*/ -QString QWebPage::selectedHtml() const -{ - d->createMainFrame(); - return d->page->focusController()->focusedOrMainFrame()->editor()->selectedRange()->toHTML(); -} - -#ifndef QT_NO_ACTION -/*! - Returns a QAction for the specified WebAction \a action. - - The action is owned by the QWebPage but you can customize the look by - changing its properties. - - QWebPage also takes care of implementing the action, so that upon - triggering the corresponding action is performed on the page. - - \sa triggerAction() -*/ -QAction *QWebPage::action(WebAction action) const -{ - if (action == QWebPage::NoWebAction) return 0; - if (d->actions[action]) - return d->actions[action]; - - QString text; - QIcon icon; - QStyle *style = d->client ? d->client->style() : qApp->style(); - bool checkable = false; - - switch (action) { - case OpenLink: - text = contextMenuItemTagOpenLink(); - break; - case OpenLinkInNewWindow: - text = contextMenuItemTagOpenLinkInNewWindow(); - break; - case OpenFrameInNewWindow: - text = contextMenuItemTagOpenFrameInNewWindow(); - break; - case OpenLinkInThisWindow: - text = contextMenuItemTagOpenLinkInThisWindow(); - break; - - case DownloadLinkToDisk: - text = contextMenuItemTagDownloadLinkToDisk(); - break; - case CopyLinkToClipboard: - text = contextMenuItemTagCopyLinkToClipboard(); - break; - - case OpenImageInNewWindow: - text = contextMenuItemTagOpenImageInNewWindow(); - break; - case DownloadImageToDisk: - text = contextMenuItemTagDownloadImageToDisk(); - break; - case CopyImageToClipboard: - text = contextMenuItemTagCopyImageToClipboard(); - break; - case CopyImageUrlToClipboard: - text = contextMenuItemTagCopyImageUrlToClipboard(); - break; - - case Back: - text = contextMenuItemTagGoBack(); - icon = style->standardIcon(QStyle::SP_ArrowBack); - break; - case Forward: - text = contextMenuItemTagGoForward(); - icon = style->standardIcon(QStyle::SP_ArrowForward); - break; - case Stop: - text = contextMenuItemTagStop(); - icon = style->standardIcon(QStyle::SP_BrowserStop); - break; - case Reload: - text = contextMenuItemTagReload(); - icon = style->standardIcon(QStyle::SP_BrowserReload); - break; - - case Cut: - text = contextMenuItemTagCut(); - break; - case Copy: - text = contextMenuItemTagCopy(); - break; - case Paste: - text = contextMenuItemTagPaste(); - break; - case SelectAll: - text = contextMenuItemTagSelectAll(); - break; -#ifndef QT_NO_UNDOSTACK - case Undo: { - QAction *a = undoStack()->createUndoAction(d->q); - d->actions[action] = a; - return a; - } - case Redo: { - QAction *a = undoStack()->createRedoAction(d->q); - d->actions[action] = a; - return a; - } -#endif // QT_NO_UNDOSTACK - case MoveToNextChar: - text = tr("Move the cursor to the next character"); - break; - case MoveToPreviousChar: - text = tr("Move the cursor to the previous character"); - break; - case MoveToNextWord: - text = tr("Move the cursor to the next word"); - break; - case MoveToPreviousWord: - text = tr("Move the cursor to the previous word"); - break; - case MoveToNextLine: - text = tr("Move the cursor to the next line"); - break; - case MoveToPreviousLine: - text = tr("Move the cursor to the previous line"); - break; - case MoveToStartOfLine: - text = tr("Move the cursor to the start of the line"); - break; - case MoveToEndOfLine: - text = tr("Move the cursor to the end of the line"); - break; - case MoveToStartOfBlock: - text = tr("Move the cursor to the start of the block"); - break; - case MoveToEndOfBlock: - text = tr("Move the cursor to the end of the block"); - break; - case MoveToStartOfDocument: - text = tr("Move the cursor to the start of the document"); - break; - case MoveToEndOfDocument: - text = tr("Move the cursor to the end of the document"); - break; - case SelectNextChar: - text = tr("Select to the next character"); - break; - case SelectPreviousChar: - text = tr("Select to the previous character"); - break; - case SelectNextWord: - text = tr("Select to the next word"); - break; - case SelectPreviousWord: - text = tr("Select to the previous word"); - break; - case SelectNextLine: - text = tr("Select to the next line"); - break; - case SelectPreviousLine: - text = tr("Select to the previous line"); - break; - case SelectStartOfLine: - text = tr("Select to the start of the line"); - break; - case SelectEndOfLine: - text = tr("Select to the end of the line"); - break; - case SelectStartOfBlock: - text = tr("Select to the start of the block"); - break; - case SelectEndOfBlock: - text = tr("Select to the end of the block"); - break; - case SelectStartOfDocument: - text = tr("Select to the start of the document"); - break; - case SelectEndOfDocument: - text = tr("Select to the end of the document"); - break; - case DeleteStartOfWord: - text = tr("Delete to the start of the word"); - break; - case DeleteEndOfWord: - text = tr("Delete to the end of the word"); - break; - - case SetTextDirectionDefault: - text = contextMenuItemTagDefaultDirection(); - break; - case SetTextDirectionLeftToRight: - text = contextMenuItemTagLeftToRight(); - checkable = true; - break; - case SetTextDirectionRightToLeft: - text = contextMenuItemTagRightToLeft(); - checkable = true; - break; - - case ToggleBold: - text = contextMenuItemTagBold(); - checkable = true; - break; - case ToggleItalic: - text = contextMenuItemTagItalic(); - checkable = true; - break; - case ToggleUnderline: - text = contextMenuItemTagUnderline(); - checkable = true; - break; - - case InspectElement: - text = contextMenuItemTagInspectElement(); - break; - - case InsertParagraphSeparator: - text = tr("Insert a new paragraph"); - break; - case InsertLineSeparator: - text = tr("Insert a new line"); - break; - - case PasteAndMatchStyle: - text = tr("Paste and Match Style"); - break; - case RemoveFormat: - text = tr("Remove formatting"); - break; - - case ToggleStrikethrough: - text = tr("Strikethrough"); - checkable = true; - break; - case ToggleSubscript: - text = tr("Subscript"); - checkable = true; - break; - case ToggleSuperscript: - text = tr("Superscript"); - checkable = true; - break; - case InsertUnorderedList: - text = tr("Insert Bulleted List"); - checkable = true; - break; - case InsertOrderedList: - text = tr("Insert Numbered List"); - checkable = true; - break; - case Indent: - text = tr("Indent"); - break; - case Outdent: - text = tr("Outdent"); - break; - case AlignCenter: - text = tr("Center"); - break; - case AlignJustified: - text = tr("Justify"); - break; - case AlignLeft: - text = tr("Align Left"); - break; - case AlignRight: - text = tr("Align Right"); - break; - case NoWebAction: - return 0; - default: - break; - } - - if (text.isEmpty()) - return 0; - - QAction *a = new QAction(d->q); - a->setText(text); - a->setData(action); - a->setCheckable(checkable); - a->setIcon(icon); - - connect(a, SIGNAL(triggered(bool)), - this, SLOT(_q_webActionTriggered(bool))); - - d->actions[action] = a; - d->updateAction(action); - return a; -} -#endif // QT_NO_ACTION - -/*! - \property QWebPage::modified - \brief whether the page contains unsubmitted form data, or the contents have been changed. - - By default, this property is false. - - \sa contentsChanged(), contentEditable, undoStack() -*/ -bool QWebPage::isModified() const -{ -#ifdef QT_NO_UNDOSTACK - return false; -#else - if (!d->undoStack) - return false; - return d->undoStack->canUndo(); -#endif // QT_NO_UNDOSTACK -} - -#ifndef QT_NO_UNDOSTACK -/*! - Returns a pointer to the undo stack used for editable content. - - \sa modified -*/ -QUndoStack *QWebPage::undoStack() const -{ - if (!d->undoStack) - d->undoStack = new QUndoStack(const_cast<QWebPage *>(this)); - - return d->undoStack; -} -#endif // QT_NO_UNDOSTACK - -/*! \reimp -*/ -bool QWebPage::event(QEvent *ev) -{ - switch (ev->type()) { - case QEvent::Timer: - d->timerEvent(static_cast<QTimerEvent*>(ev)); - break; - case QEvent::MouseMove: - d->mouseMoveEvent(static_cast<QMouseEvent*>(ev)); - break; - case QEvent::MouseButtonPress: - d->mousePressEvent(static_cast<QMouseEvent*>(ev)); - break; - case QEvent::MouseButtonDblClick: - d->mouseDoubleClickEvent(static_cast<QMouseEvent*>(ev)); - break; - case QEvent::MouseButtonRelease: - d->mouseReleaseEvent(static_cast<QMouseEvent*>(ev)); - break; -#if !defined(QT_NO_GRAPHICSVIEW) - case QEvent::GraphicsSceneMouseMove: { - QGraphicsSceneMouseEvent *gsEv = static_cast<QGraphicsSceneMouseEvent*>(ev); - QMouseEvent dummyEvent(QEvent::MouseMove, gsEv->pos(), gsEv->screenPos(), gsEv->button(), gsEv->buttons(), gsEv->modifiers()); - d->mouseMoveEvent(&dummyEvent); - ev->setAccepted(dummyEvent.isAccepted()); - break; - } - case QEvent::GraphicsSceneMouseRelease: { - QGraphicsSceneMouseEvent *gsEv = static_cast<QGraphicsSceneMouseEvent*>(ev); - QMouseEvent dummyEvent(QEvent::MouseButtonRelease, gsEv->pos(), gsEv->screenPos(), gsEv->button(), gsEv->buttons(), gsEv->modifiers()); - d->mouseReleaseEvent(&dummyEvent); - ev->setAccepted(dummyEvent.isAccepted()); - break; - } - case QEvent::GraphicsSceneMousePress: { - QGraphicsSceneMouseEvent *gsEv = static_cast<QGraphicsSceneMouseEvent*>(ev); - QMouseEvent dummyEvent(QEvent::MouseButtonPress, gsEv->pos(), gsEv->screenPos(), gsEv->button(), gsEv->buttons(), gsEv->modifiers()); - d->mousePressEvent(&dummyEvent); - ev->setAccepted(dummyEvent.isAccepted()); - break; - } - case QEvent::GraphicsSceneMouseDoubleClick: { - QGraphicsSceneMouseEvent *gsEv = static_cast<QGraphicsSceneMouseEvent*>(ev); - QMouseEvent dummyEvent(QEvent::MouseButtonDblClick, gsEv->pos(), gsEv->screenPos(), gsEv->button(), gsEv->buttons(), gsEv->modifiers()); - d->mouseDoubleClickEvent(&dummyEvent); - ev->setAccepted(dummyEvent.isAccepted()); - break; - } -#endif -#ifndef QT_NO_CONTEXTMENU - case QEvent::ContextMenu: - d->contextMenuEvent(static_cast<QContextMenuEvent*>(ev)->globalPos()); - break; -#if !defined(QT_NO_GRAPHICSVIEW) - case QEvent::GraphicsSceneContextMenu: - d->contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent*>(ev)->screenPos()); - break; -#endif -#endif -#ifndef QT_NO_WHEELEVENT - case QEvent::Wheel: - d->wheelEvent(static_cast<QWheelEvent*>(ev)); - break; -#if !defined(QT_NO_GRAPHICSVIEW) - case QEvent::GraphicsSceneWheel: { - QGraphicsSceneWheelEvent *gsEv = static_cast<QGraphicsSceneWheelEvent*>(ev); - QWheelEvent dummyEvent(gsEv->pos(), gsEv->screenPos(), gsEv->delta(), gsEv->buttons(), gsEv->modifiers(), gsEv->orientation()); - d->wheelEvent(&dummyEvent); - ev->setAccepted(dummyEvent.isAccepted()); - break; - } -#endif -#endif - case QEvent::KeyPress: - d->keyPressEvent(static_cast<QKeyEvent*>(ev)); - break; - case QEvent::KeyRelease: - d->keyReleaseEvent(static_cast<QKeyEvent*>(ev)); - break; - case QEvent::FocusIn: - d->focusInEvent(static_cast<QFocusEvent*>(ev)); - break; - case QEvent::FocusOut: - d->focusOutEvent(static_cast<QFocusEvent*>(ev)); - break; -#ifndef QT_NO_DRAGANDDROP - case QEvent::DragEnter: - d->dragEnterEvent(static_cast<QDragEnterEvent*>(ev)); - break; - case QEvent::DragLeave: - d->dragLeaveEvent(static_cast<QDragLeaveEvent*>(ev)); - break; - case QEvent::DragMove: - d->dragMoveEvent(static_cast<QDragMoveEvent*>(ev)); - break; - case QEvent::Drop: - d->dropEvent(static_cast<QDropEvent*>(ev)); - break; -#if !defined(QT_NO_GRAPHICSVIEW) - case QEvent::GraphicsSceneDragEnter: - d->dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev)); - break; - case QEvent::GraphicsSceneDragMove: - d->dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev)); - break; - case QEvent::GraphicsSceneDragLeave: - d->dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev)); - break; - case QEvent::GraphicsSceneDrop: - d->dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev)); - break; -#endif - -#endif - case QEvent::InputMethod: - d->inputMethodEvent(static_cast<QInputMethodEvent*>(ev)); - break; - case QEvent::ShortcutOverride: - d->shortcutOverrideEvent(static_cast<QKeyEvent*>(ev)); - break; - case QEvent::Leave: - d->leaveEvent(ev); - break; - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - case QEvent::TouchCancel: - // Return whether the default action was cancelled in the JS event handler - return d->touchEvent(static_cast<QTouchEvent*>(ev)); -#ifndef QT_NO_GESTURES - case QEvent::Gesture: - d->gestureEvent(static_cast<QGestureEvent*>(ev)); - break; -#endif -#ifndef QT_NO_PROPERTIES - case QEvent::DynamicPropertyChange: - d->dynamicPropertyChangeEvent(static_cast<QDynamicPropertyChangeEvent*>(ev)); - break; -#endif - default: - return QObject::event(ev); - } - - return true; -} - -/*! - Similar to QWidget::focusNextPrevChild() it focuses the next focusable web element - if \a next is true; otherwise the previous element is focused. - - Returns true if it can find a new focusable element, or false if it can't. -*/ -bool QWebPage::focusNextPrevChild(bool next) -{ - QKeyEvent ev(QEvent::KeyPress, Qt::Key_Tab, Qt::KeyboardModifiers(next ? Qt::NoModifier : Qt::ShiftModifier)); - d->keyPressEvent(&ev); - bool hasFocusedNode = false; - Frame *frame = d->page->focusController()->focusedFrame(); - if (frame) { - Document *document = frame->document(); - hasFocusedNode = document && document->focusedNode(); - } - //qDebug() << "focusNextPrevChild(" << next << ") =" << ev.isAccepted() << "focusedNode?" << hasFocusedNode; - return hasFocusedNode; -} - -/*! - \property QWebPage::contentEditable - \brief whether the content in this QWebPage is editable or not - \since 4.5 - - If this property is enabled the contents of the page can be edited by the user through a visible - cursor. If disabled (the default) only HTML elements in the web page with their - \c{contenteditable} attribute set are editable. - - \sa modified, contentsChanged(), WebAction -*/ -void QWebPage::setContentEditable(bool editable) -{ - if (isContentEditable() != editable) { - d->page->setEditable(editable); - d->page->setTabKeyCyclesThroughElements(!editable); - if (d->mainFrame) { - WebCore::Frame* frame = d->mainFrame.data()->d->frame; - if (editable) { - frame->editor()->applyEditingStyleToBodyElement(); - // FIXME: mac port calls this if there is no selectedDOMRange - //frame->setSelectionFromNone(); - } - } - - d->updateEditorActions(); - } -} - -bool QWebPage::isContentEditable() const -{ - return d->page->isEditable(); -} - -/*! - \property QWebPage::forwardUnsupportedContent - \brief whether QWebPage should forward unsupported content - - If enabled, the unsupportedContent() signal is emitted with a network reply that - can be used to read the content. - - If disabled, the download of such content is aborted immediately. - - By default unsupported content is not forwarded. -*/ - -void QWebPage::setForwardUnsupportedContent(bool forward) -{ - d->forwardUnsupportedContent = forward; -} - -bool QWebPage::forwardUnsupportedContent() const -{ - return d->forwardUnsupportedContent; -} - -/*! - \property QWebPage::linkDelegationPolicy - \brief how QWebPage should delegate the handling of links through the - linkClicked() signal - - The default is to delegate no links. -*/ - -void QWebPage::setLinkDelegationPolicy(LinkDelegationPolicy policy) -{ - d->linkPolicy = policy; -} - -QWebPage::LinkDelegationPolicy QWebPage::linkDelegationPolicy() const -{ - return d->linkPolicy; -} - -#ifndef QT_NO_CONTEXTMENU - -static bool handleScrollbarContextMenuEvent(Scrollbar* scrollBar, QContextMenuEvent* event) -{ - if (!QApplication::style()->styleHint(QStyle::SH_ScrollBar_ContextMenu)) - return true; - - bool horizontal = (scrollBar->orientation() == HorizontalScrollbar); - - QMenu menu; - QAction* actScrollHere = menu.addAction(QCoreApplication::translate("QWebPage", "Scroll here")); - menu.addSeparator(); - - QAction* actScrollTop = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Left edge") : QCoreApplication::translate("QWebPage", "Top")); - QAction* actScrollBottom = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Right edge") : QCoreApplication::translate("QWebPage", "Bottom")); - menu.addSeparator(); - - QAction* actPageUp = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Page left") : QCoreApplication::translate("QWebPage", "Page up")); - QAction* actPageDown = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Page right") : QCoreApplication::translate("QWebPage", "Page down")); - menu.addSeparator(); - - QAction* actScrollUp = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Scroll left") : QCoreApplication::translate("QWebPage", "Scroll up")); - QAction* actScrollDown = menu.addAction(horizontal ? QCoreApplication::translate("QWebPage", "Scroll right") : QCoreApplication::translate("QWebPage", "Scroll down")); - - QAction* actionSelected = menu.exec(event->globalPos()); - - if (actionSelected == actScrollHere) { - ScrollbarTheme* theme = scrollBar->theme(); - // Set the pressed position to the middle of the thumb so that when we - // do move, the delta will be from the current pixel position of the - // thumb to the new position - int position = theme->trackPosition(scrollBar) + theme->thumbPosition(scrollBar) + theme->thumbLength(scrollBar) / 2; - scrollBar->setPressedPos(position); - const QPoint pos = scrollBar->convertFromContainingWindow(event->pos()); - scrollBar->moveThumb(horizontal ? pos.x() : pos.y()); - } else if (actionSelected == actScrollTop) - scrollBar->scrollableArea()->scroll(horizontal ? ScrollLeft : ScrollUp, ScrollByDocument); - else if (actionSelected == actScrollBottom) - scrollBar->scrollableArea()->scroll(horizontal ? ScrollRight : ScrollDown, ScrollByDocument); - else if (actionSelected == actPageUp) - scrollBar->scrollableArea()->scroll(horizontal ? ScrollLeft : ScrollUp, ScrollByPage); - else if (actionSelected == actPageDown) - scrollBar->scrollableArea()->scroll(horizontal ? ScrollRight : ScrollDown, ScrollByPage); - else if (actionSelected == actScrollUp) - scrollBar->scrollableArea()->scroll(horizontal ? ScrollLeft : ScrollUp, ScrollByLine); - else if (actionSelected == actScrollDown) - scrollBar->scrollableArea()->scroll(horizontal ? ScrollRight : ScrollDown, ScrollByLine); - return true; -} - -/*! - Filters the context menu event, \a event, through handlers for scrollbars and - custom event handlers in the web page. Returns true if the event was handled; - otherwise false. - - A web page may swallow a context menu event through a custom event handler, allowing for context - menus to be implemented in HTML/JavaScript. This is used by \l{http://maps.google.com/}{Google - Maps}, for example. -*/ -bool QWebPage::swallowContextMenuEvent(QContextMenuEvent *event) -{ - d->page->contextMenuController()->clearContextMenu(); - - if (QWebFrame* webFrame = frameAt(event->pos())) { - Frame* frame = QWebFramePrivate::core(webFrame); - if (Scrollbar* scrollbar = frame->view()->scrollbarAtPoint(convertMouseEvent(event, 1).position())) - return handleScrollbarContextMenuEvent(scrollbar, event); - } - - WebCore::Frame* focusedFrame = d->page->focusController()->focusedOrMainFrame(); - focusedFrame->eventHandler()->sendContextMenuEvent(convertMouseEvent(event, 1)); - ContextMenu *menu = d->page->contextMenuController()->contextMenu(); - // If the website defines its own handler then sendContextMenuEvent takes care of - // calling/showing it and the context menu pointer will be zero. This is the case - // on maps.google.com for example. - - return !menu; -} -#endif // QT_NO_CONTEXTMENU - -/*! - Updates the page's actions depending on the position \a pos. For example if \a pos is over an image - element the CopyImageToClipboard action is enabled. -*/ -void QWebPage::updatePositionDependentActions(const QPoint &pos) -{ -#ifndef QT_NO_ACTION - // First we disable all actions, but keep track of which ones were originally enabled. - QBitArray originallyEnabledWebActions(QWebPage::WebActionCount); - for (int i = ContextMenuItemTagNoAction; i < ContextMenuItemBaseApplicationTag; ++i) { - QWebPage::WebAction action = webActionForContextMenuAction(WebCore::ContextMenuAction(i)); - if (QAction *a = this->action(action)) { - originallyEnabledWebActions.setBit(action, a->isEnabled()); - a->setEnabled(false); - } - } -#endif // QT_NO_ACTION - - d->createMainFrame(); - WebCore::Frame* focusedFrame = d->page->focusController()->focusedOrMainFrame(); - - HitTestResult result = focusedFrame->eventHandler()->hitTestResultAtPoint(focusedFrame->view()->windowToContents(pos), /*allowShadowContent*/ false); - if (result.scrollbar()) - d->hitTestResult = QWebHitTestResult(); - else - d->hitTestResult = QWebHitTestResult(new QWebHitTestResultPrivate(result)); - d->page->contextMenuController()->setHitTestResult(result); - -#if ENABLE(INSPECTOR) - if (d->page->inspectorController()->enabled()) - d->page->contextMenuController()->addInspectElementItem(); -#endif - - QBitArray visitedWebActions(QWebPage::WebActionCount); - -#ifndef QT_NO_CONTEXTMENU - delete d->currentContextMenu.data(); - - // Then we let createContextMenu() enable the actions that are put into the menu - d->currentContextMenu = d->createContextMenu(d->page->contextMenuController()->contextMenu(), d->page->contextMenuController()->contextMenu()->platformDescription(), &visitedWebActions); -#endif // QT_NO_CONTEXTMENU - -#ifndef QT_NO_ACTION - // Finally, we restore the original enablement for the actions that were not put into the menu. - originallyEnabledWebActions &= ~visitedWebActions; // Mask out visited actions (they're part of the menu) - for (int i = 0; i < QWebPage::WebActionCount; ++i) { - if (originallyEnabledWebActions.at(i)) { - if (QAction *a = this->action(QWebPage::WebAction(i))) - a->setEnabled(true); - } - } -#endif // QT_NO_ACTION - - // This whole process ensures that any actions put into to the context menu has the right - // enablement, while also keeping the correct enablement for actions that were left out of - // the menu. - -} - - - -/*! - \enum QWebPage::Extension - - This enum describes the types of extensions that the page can support. Before using these extensions, you - should verify that the extension is supported by calling supportsExtension(). - - \value ChooseMultipleFilesExtension Whether the web page supports multiple file selection. - This extension is invoked when the web content requests one or more file names, for example - as a result of the user clicking on a "file upload" button in a HTML form where multiple - file selection is allowed. - - \value ErrorPageExtension Whether the web page can provide an error page when loading fails. - (introduced in Qt 4.6) - - \sa ChooseMultipleFilesExtensionOption, ChooseMultipleFilesExtensionReturn, ErrorPageExtensionOption, ErrorPageExtensionReturn -*/ - -/*! - \enum QWebPage::ErrorDomain - \since 4.6 - - This enum describes the domain of an ErrorPageExtensionOption object (i.e. the layer in which the error occurred). - - \value QtNetwork The error occurred in the QtNetwork layer; the error code is of type QNetworkReply::NetworkError. - \value Http The error occurred in the HTTP layer; the error code is a HTTP status code (see QNetworkRequest::HttpStatusCodeAttribute). - \value WebKit The error is an internal WebKit error. -*/ - -/*! - \class QWebPage::ExtensionOption - \since 4.4 - \brief The ExtensionOption class provides an extended input argument to QWebPage's extension support. - - \inmodule QtWebKit - - \sa QWebPage::extension(), QWebPage::ExtensionReturn -*/ - - -/*! - \class QWebPage::ExtensionReturn - \since 4.4 - \brief The ExtensionReturn class provides an output result from a QWebPage's extension. - - \inmodule QtWebKit - - \sa QWebPage::extension(), QWebPage::ExtensionOption -*/ - -/*! - \class QWebPage::ErrorPageExtensionOption - \since 4.6 - \brief The ErrorPageExtensionOption class describes the option - for the error page extension. - - \inmodule QtWebKit - - The ErrorPageExtensionOption class holds the \a url for which an error occurred as well as - the associated \a frame. - - The error itself is reported by an error \a domain, the \a error code as well as \a errorString. - - \sa QWebPage::extension(), QWebPage::ErrorPageExtensionReturn -*/ - -/*! - \variable QWebPage::ErrorPageExtensionOption::url - \brief the url for which an error occurred -*/ - -/*! - \variable QWebPage::ErrorPageExtensionOption::frame - \brief the frame associated with the error -*/ - -/*! - \variable QWebPage::ErrorPageExtensionOption::domain - \brief the domain that reported the error -*/ - -/*! - \variable QWebPage::ErrorPageExtensionOption::error - \brief the error code. Interpretation of the value depends on the \a domain - \sa QWebPage::ErrorDomain -*/ - -/*! - \variable QWebPage::ErrorPageExtensionOption::errorString - \brief a string that describes the error -*/ - -/*! - \class QWebPage::ErrorPageExtensionReturn - \since 4.6 - \brief The ErrorPageExtensionReturn describes the error page, which will be shown for the - frame for which the error occured. - - \inmodule QtWebKit - - The ErrorPageExtensionReturn class holds the data needed for creating an error page. Some are - optional such as \a contentType, which defaults to "text/html", as well as the \a encoding, which - is assumed to be UTF-8 if not indicated otherwise. - - The error page is stored in the \a content byte array, as HTML content. In order to convert a - QString to a byte array, the QString::toUtf8() method can be used. - - External objects such as stylesheets or images referenced in the HTML are located relative to - \a baseUrl. - - \sa QWebPage::extension(), QWebPage::ErrorPageExtensionOption, QString::toUtf8() -*/ - -/*! - \fn QWebPage::ErrorPageExtensionReturn::ErrorPageExtensionReturn() - - Constructs a new error page object. -*/ - - -/*! - \variable QWebPage::ErrorPageExtensionReturn::contentType - \brief the error page's content type -*/ - -/*! - \variable QWebPage::ErrorPageExtensionReturn::encoding - \brief the error page encoding -*/ - -/*! - \variable QWebPage::ErrorPageExtensionReturn::baseUrl - \brief the base url - - External objects such as stylesheets or images referenced in the HTML are located relative to this url. -*/ - -/*! - \variable QWebPage::ErrorPageExtensionReturn::content - \brief the HTML content of the error page -*/ - -/*! - \class QWebPage::ChooseMultipleFilesExtensionOption - \since 4.5 - \brief The ChooseMultipleFilesExtensionOption class describes the option - for the multiple files selection extension. - - \inmodule QtWebKit - - The ChooseMultipleFilesExtensionOption class holds the frame originating the request - and the suggested filenames which might be provided. - - \sa QWebPage::extension(), QWebPage::chooseFile(), QWebPage::ChooseMultipleFilesExtensionReturn -*/ - -/*! - \variable QWebPage::ChooseMultipleFilesExtensionOption::parentFrame - \brief The frame in which the request originated -*/ - -/*! - \variable QWebPage::ChooseMultipleFilesExtensionOption::suggestedFileNames - \brief The suggested filenames -*/ - -/*! - \variable QWebPage::ChooseMultipleFilesExtensionReturn::fileNames - \brief The selected filenames -*/ - -/*! - \class QWebPage::ChooseMultipleFilesExtensionReturn - \since 4.5 - \brief The ChooseMultipleFilesExtensionReturn describes the return value - for the multiple files selection extension. - - \inmodule QtWebKit - - The ChooseMultipleFilesExtensionReturn class holds the filenames selected by the user - when the extension is invoked. - - \sa QWebPage::extension(), QWebPage::ChooseMultipleFilesExtensionOption -*/ - -/*! - This virtual function can be reimplemented in a QWebPage subclass to provide support for extensions. The \a option - argument is provided as input to the extension; the output results can be stored in \a output. - - The behavior of this function is determined by \a extension. The \a option - and \a output values are typically casted to the corresponding types (for - example, ChooseMultipleFilesExtensionOption and - ChooseMultipleFilesExtensionReturn for ChooseMultipleFilesExtension). - - You can call supportsExtension() to check if an extension is supported by the page. - - Returns true if the extension was called successfully; otherwise returns false. - - \sa supportsExtension(), Extension -*/ -bool QWebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output) -{ -#ifndef QT_NO_FILEDIALOG - if (extension == ChooseMultipleFilesExtension) { - // FIXME: do not ignore suggestedFiles - QStringList suggestedFiles = static_cast<const ChooseMultipleFilesExtensionOption*>(option)->suggestedFileNames; - QStringList names = QFileDialog::getOpenFileNames(view(), QString::null); - static_cast<ChooseMultipleFilesExtensionReturn*>(output)->fileNames = names; - return true; - } -#endif - - return false; -} - -/*! - This virtual function returns true if the web page supports \a extension; otherwise false is returned. - - \sa extension() -*/ -bool QWebPage::supportsExtension(Extension extension) const -{ -#ifndef QT_NO_FILEDIALOG - return extension == ChooseMultipleFilesExtension; -#else - Q_UNUSED(extension); - return false; -#endif -} - -/*! - * \internal - */ -QWebPageAdapter *QWebPage::handle() const -{ - return d; -} - -/*! - Finds the specified string, \a subString, in the page, using the given \a options. - - If the HighlightAllOccurrences flag is passed, the function will highlight all occurrences - that exist in the page. All subsequent calls will extend the highlight, rather than - replace it, with occurrences of the new string. - - If the HighlightAllOccurrences flag is not passed, the function will select an occurrence - and all subsequent calls will replace the current occurrence with the next one. - - To clear the selection, just pass an empty string. - - Returns true if \a subString was found; otherwise returns false. -*/ -bool QWebPage::findText(const QString &subString, FindFlags options) -{ - ::TextCaseSensitivity caseSensitivity = ::TextCaseInsensitive; - if (options & FindCaseSensitively) - caseSensitivity = ::TextCaseSensitive; - - if (options & HighlightAllOccurrences) { - if (subString.isEmpty()) { - d->page->unmarkAllTextMatches(); - return true; - } else - return d->page->markAllMatchesForText(subString, caseSensitivity, true, 0); - } else { - if (subString.isEmpty()) { - d->page->mainFrame()->selection()->clear(); - Frame* frame = d->page->mainFrame()->tree()->firstChild(); - while (frame) { - frame->selection()->clear(); - frame = frame->tree()->traverseNextWithWrap(false); - } - } - ::FindDirection direction = ::FindDirectionForward; - if (options & FindBackward) - direction = ::FindDirectionBackward; - - const bool shouldWrap = options & FindWrapsAroundDocument; - - return d->page->findString(subString, caseSensitivity, direction, shouldWrap); - } -} - -/*! - Returns a pointer to the page's settings object. - - \sa QWebSettings::globalSettings() -*/ -QWebSettings *QWebPage::settings() const -{ - return d->settings; -} - -/*! - This function is called when the web content requests a file name, for example - as a result of the user clicking on a "file upload" button in a HTML form. - - A suggested filename may be provided in \a suggestedFile. The frame originating the - request is provided as \a parentFrame. - - \sa ChooseMultipleFilesExtension -*/ -QString QWebPage::chooseFile(QWebFrame *parentFrame, const QString& suggestedFile) -{ - Q_UNUSED(parentFrame) -#ifndef QT_NO_FILEDIALOG - return QFileDialog::getOpenFileName(view(), QString::null, suggestedFile); -#else - return QString::null; -#endif -} - -/*! - Sets the QNetworkAccessManager \a manager responsible for serving network requests for this - QWebPage. - - \note It is currently not supported to change the network access manager after the - QWebPage has used it. The results of doing this are undefined. - - \sa networkAccessManager() -*/ -void QWebPage::setNetworkAccessManager(QNetworkAccessManager *manager) -{ - d->setNetworkAccessManager(manager); -} - -/*! - Returns the QNetworkAccessManager that is responsible for serving network - requests for this QWebPage. - - \sa setNetworkAccessManager() -*/ -QNetworkAccessManager *QWebPage::networkAccessManager() const -{ - return d->networkAccessManager(); -} - -/*! - Sets the QWebPluginFactory \a factory responsible for creating plugins embedded into this - QWebPage. - - Note: The plugin factory is only used if the QWebSettings::PluginsEnabled attribute is enabled. - - \sa pluginFactory() -*/ -void QWebPage::setPluginFactory(QWebPluginFactory *factory) -{ - d->pluginFactory = factory; -} - -/*! - Returns the QWebPluginFactory that is responsible for creating plugins embedded into - this QWebPage. If no plugin factory is installed a null pointer is returned. - - \sa setPluginFactory() -*/ -QWebPluginFactory *QWebPage::pluginFactory() const -{ - return d->pluginFactory; -} - -/*! - This function is called when a user agent for HTTP requests is needed. You can reimplement this - function to dynamically return different user agents for different URLs, based on the \a url parameter. - - The default implementation returns the following value: - - "Mozilla/5.0 (%Platform%%Security%%Subplatform%) AppleWebKit/%WebKitVersion% (KHTML, like Gecko) %AppVersion Safari/%WebKitVersion%" - - In this string the following values are replaced at run-time: - \list - \li %Platform% expands to the windowing system followed by "; " if it is not Windows (e.g. "X11; "). - \li %Security% expands to "N; " if SSL is disabled. - \li %Subplatform% expands to the operating system version (e.g. "Windows NT 6.1" or "Intel Mac OS X 10.5"). - \li %WebKitVersion% is the version of WebKit the application was compiled against. - \li %AppVersion% expands to QCoreApplication::applicationName()/QCoreApplication::applicationVersion() if they're set; otherwise defaulting to Qt and the current Qt version. - \endlist -*/ -QString QWebPage::userAgentForUrl(const QUrl&) const -{ - return UserAgentQt::standardUserAgent("", WEBKIT_MAJOR_VERSION, WEBKIT_MINOR_VERSION); -} - - -void QWebPagePrivate::_q_onLoadProgressChanged(int) -{ - m_totalBytes = page->progress()->totalPageAndResourceBytesToLoad(); - m_bytesReceived = page->progress()->totalBytesReceived(); -} - - -/*! - Returns the total number of bytes that were received from the network to render the current page, - including extra content such as embedded images. - - \sa bytesReceived() -*/ -quint64 QWebPage::totalBytes() const -{ - return d->m_totalBytes; -} - - -/*! - Returns the number of bytes that were received from the network to render the current page. - - \sa totalBytes(), loadProgress() -*/ -quint64 QWebPage::bytesReceived() const -{ - return d->m_bytesReceived; -} - -/*! - \since 4.8 - \fn void QWebPage::viewportChangeRequested() - - Page authors can provide the supplied values by using the viewport meta tag. More information - about this can be found at \l{http://developer.apple.com/safari/library/documentation/appleapplications/reference/safariwebcontent/usingtheviewport/usingtheviewport.html}{Safari Reference Library: Using the Viewport Meta Tag}. - - \sa QWebPage::ViewportAttributes, setPreferredContentsSize(), QGraphicsWebView::setScale() -*/ - -/*! - \fn void QWebPage::loadStarted() - - This signal is emitted when a page starts loading content. - - \sa loadFinished() -*/ - -/*! - \fn void QWebPage::loadProgress(int progress) - - This signal is emitted when the global progress status changes. - The current value is provided by \a progress and scales from 0 to 100, - which is the default range of QProgressBar. - It accumulates changes from all the child frames. - - \sa bytesReceived() -*/ - -/*! - \fn void QWebPage::loadFinished(bool ok) - - This signal is emitted when the page finishes loading content. This signal - is independant of script execution or page rendering. - \a ok will indicate whether the load was successful or any error occurred. - - \sa loadStarted(), ErrorPageExtension -*/ - -/*! - \fn void QWebPage::linkHovered(const QString &link, const QString &title, const QString &textContent) - - This signal is emitted when the mouse hovers over a link. - - \a link contains the link url. - \a title is the link element's title, if it is specified in the markup. - \a textContent provides text within the link element, e.g., text inside an HTML anchor tag. - - When the mouse leaves the link element the signal is emitted with empty parameters. - - \sa linkClicked() -*/ - -/*! - \fn void QWebPage::statusBarMessage(const QString& text) - - This signal is emitted when the statusbar \a text is changed by the page. -*/ - -/*! - \fn void QWebPage::frameCreated(QWebFrame *frame) - - This signal is emitted whenever the page creates a new \a frame. - - \sa currentFrame() -*/ - -/*! - \fn void QWebPage::selectionChanged() - - This signal is emitted whenever the selection changes, either interactively - or programmatically (e.g. by calling triggerAction() with a selection action). - - \sa selectedText() -*/ - -/*! - \fn void QWebPage::contentsChanged() - \since 4.5 - - This signal is emitted whenever the text in form elements changes - as well as other editable content. - - \sa contentEditable, modified, QWebFrame::toHtml(), QWebFrame::toPlainText() -*/ - -/*! - \fn void QWebPage::geometryChangeRequested(const QRect& geom) - - This signal is emitted whenever the document wants to change the position and size of the - page to \a geom. This can happen for example through JavaScript. -*/ - -/*! - \fn void QWebPage::repaintRequested(const QRect& dirtyRect) - - This signal is emitted whenever this QWebPage should be updated. It's useful - when rendering a QWebPage without a QWebView or QGraphicsWebView. - \a dirtyRect contains the area that needs to be updated. To paint the QWebPage get - the mainFrame() and call the render(QPainter*, const QRegion&) method with the - \a dirtyRect as the second parameter. - - \sa mainFrame() - \sa view() -*/ - -/*! - \fn void QWebPage::scrollRequested(int dx, int dy, const QRect& rectToScroll) - - This signal is emitted whenever the content given by \a rectToScroll needs - to be scrolled \a dx and \a dy downwards and no view was set. - - \sa view() -*/ - -/*! - \fn void QWebPage::windowCloseRequested() - - This signal is emitted whenever the page requests the web browser window to be closed, - for example through the JavaScript \c{window.close()} call. -*/ - -/*! - \fn void QWebPage::printRequested(QWebFrame *frame) - - This signal is emitted whenever the page requests the web browser to print \a frame, - for example through the JavaScript \c{window.print()} call. - - \sa QWebFrame::print(), QPrintPreviewDialog -*/ - -/*! - \fn void QWebPage::unsupportedContent(QNetworkReply *reply) - - This signal is emitted when WebKit cannot handle a link the user navigated to or a - web server's response includes a "Content-Disposition" header with the 'attachment' - directive. If "Content-Disposition" is present in \a reply, the web server is indicating - that the client should prompt the user to save the content regardless of content-type. - See RFC 2616 sections 19.5.1 for details about Content-Disposition. - - At signal emission time the meta-data of the QNetworkReply \a reply is available. - - \note The receiving slot is responsible for deleting the QNetworkReply \a reply. - - \note This signal is only emitted if the forwardUnsupportedContent property is set to true. - - \sa downloadRequested() -*/ - -/*! - \fn void QWebPage::downloadRequested(const QNetworkRequest &request) - - This signal is emitted when the user decides to download a link. The url of - the link as well as additional meta-information is contained in \a request. - - \sa unsupportedContent() -*/ - -/*! - \fn void QWebPage::microFocusChanged() - - This signal is emitted when for example the position of the cursor in an editable form - element changes. It is used to inform input methods about the new on-screen position where - the user is able to enter text. This signal is usually connected to the - QWidget::updateMicroFocus() slot. -*/ - -/*! - \fn void QWebPage::linkClicked(const QUrl &url) - - This signal is emitted whenever the user clicks on a link and the page's linkDelegationPolicy - property is set to delegate the link handling for the specified \a url. - - By default no links are delegated and are handled by QWebPage instead. - - \note This signal possibly won't be emitted for clicked links which use - JavaScript to trigger navigation. - - \sa linkHovered() -*/ - -/*! - \fn void QWebPage::toolBarVisibilityChangeRequested(bool visible) - - This signal is emitted whenever the visibility of the toolbar in a web browser - window that hosts QWebPage should be changed to \a visible. -*/ - -/*! - \fn void QWebPage::statusBarVisibilityChangeRequested(bool visible) - - This signal is emitted whenever the visibility of the statusbar in a web browser - window that hosts QWebPage should be changed to \a visible. -*/ - -/*! - \fn void QWebPage::menuBarVisibilityChangeRequested(bool visible) - - This signal is emitted whenever the visibility of the menubar in a web browser - window that hosts QWebPage should be changed to \a visible. -*/ - -/*! - \fn void QWebPage::databaseQuotaExceeded(QWebFrame* frame, QString databaseName); - \since 4.5 - - This signal is emitted whenever the web site shown in \a frame is asking to store data - to the database \a databaseName and the quota allocated to that web site is exceeded. - - \sa QWebDatabase -*/ -/*! - \fn void QWebPage::applicationCacheQuotaExceeded(QWebSecurityOrigin* origin, quint64 defaultOriginQuota, quint64 totalSpaceNeeded); - - This signal is emitted whenever the web site is asking to store data to the application cache - database databaseName and the quota allocated to that web site is exceeded. - -*/ - -/*! - \since 4.5 - \fn void QWebPage::saveFrameStateRequested(QWebFrame* frame, QWebHistoryItem* item); - - This signal is emitted shortly before the history of navigated pages - in \a frame is changed, for example when navigating back in the history. - - The provided QWebHistoryItem, \a item, holds the history entry of the frame before - the change. - - A potential use-case for this signal is to store custom data in - the QWebHistoryItem associated to the frame, using QWebHistoryItem::setUserData(). -*/ - -/*! - \since 4.5 - \fn void QWebPage::restoreFrameStateRequested(QWebFrame* frame); - - This signal is emitted when the load of \a frame is finished and the application may now update its state accordingly. -*/ - -/*! - \fn QWebPagePrivate* QWebPage::handle() const - \internal -*/ - -#include "moc_qwebpage.cpp" diff --git a/Source/WebKit/qt/Api/qwebpage.h b/Source/WebKit/qt/Api/qwebpage.h deleted file mode 100644 index bb5421fcc..000000000 --- a/Source/WebKit/qt/Api/qwebpage.h +++ /dev/null @@ -1,453 +0,0 @@ -/* - Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2007 Staikos Computing Services Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QWEBPAGE_H -#define QWEBPAGE_H - -#include "qwebsettings.h" -#include "qwebkitglobal.h" - -#include <QtCore/qobject.h> -#include <QtCore/qurl.h> -#include <QtWidgets/qwidget.h> - -QT_BEGIN_NAMESPACE -class QNetworkProxy; -class QUndoStack; -class QMenu; -class QNetworkRequest; -class QNetworkReply; -class QNetworkAccessManager; -QT_END_NAMESPACE - -class QWebElement; -class QWebFrame; -class QWebNetworkRequest; -class QWebHistory; - -class QWebFrameData; -class QWebHistoryItem; -class QWebHitTestResult; -class QWebNetworkInterface; -class QWebPageAdapter; -class QWebPagePrivate; -class QWebPluginFactory; -class QWebSecurityOrigin; -class QtViewportAttributesPrivate; - -namespace WebCore { - class ChromeClientQt; - class EditorClientQt; - class FrameLoaderClientQt; - class InspectorClientQt; - class InspectorServerRequestHandlerQt; - class InspectorFrontendClientQt; - class NotificationPresenterClientQt; - class GeolocationPermissionClientQt; - class ResourceHandle; - class HitTestResult; - class QNetworkReplyHandler; - - struct FrameLoadRequest; -} - -class QWEBKIT_EXPORT QWebPage : public QObject { - Q_OBJECT - - Q_PROPERTY(bool modified READ isModified) - Q_PROPERTY(QString selectedText READ selectedText) - Q_PROPERTY(QString selectedHtml READ selectedHtml) - Q_PROPERTY(bool hasSelection READ hasSelection) - Q_PROPERTY(QSize viewportSize READ viewportSize WRITE setViewportSize) - Q_PROPERTY(QSize preferredContentsSize READ preferredContentsSize WRITE setPreferredContentsSize) - Q_PROPERTY(bool forwardUnsupportedContent READ forwardUnsupportedContent WRITE setForwardUnsupportedContent) - Q_PROPERTY(LinkDelegationPolicy linkDelegationPolicy READ linkDelegationPolicy WRITE setLinkDelegationPolicy) - Q_PROPERTY(QPalette palette READ palette WRITE setPalette) - Q_PROPERTY(bool contentEditable READ isContentEditable WRITE setContentEditable) - Q_ENUMS(LinkDelegationPolicy NavigationType WebAction) -public: - enum NavigationType { - NavigationTypeLinkClicked, - NavigationTypeFormSubmitted, - NavigationTypeBackOrForward, - NavigationTypeReload, - NavigationTypeFormResubmitted, - NavigationTypeOther - }; - - enum WebAction { - NoWebAction = - 1, - - OpenLink, - - OpenLinkInNewWindow, - OpenFrameInNewWindow, - - DownloadLinkToDisk, - CopyLinkToClipboard, - - OpenImageInNewWindow, - DownloadImageToDisk, - CopyImageToClipboard, - - Back, - Forward, - Stop, - Reload, - - Cut, - Copy, - Paste, - - Undo, - Redo, - MoveToNextChar, - MoveToPreviousChar, - MoveToNextWord, - MoveToPreviousWord, - MoveToNextLine, - MoveToPreviousLine, - MoveToStartOfLine, - MoveToEndOfLine, - MoveToStartOfBlock, - MoveToEndOfBlock, - MoveToStartOfDocument, - MoveToEndOfDocument, - SelectNextChar, - SelectPreviousChar, - SelectNextWord, - SelectPreviousWord, - SelectNextLine, - SelectPreviousLine, - SelectStartOfLine, - SelectEndOfLine, - SelectStartOfBlock, - SelectEndOfBlock, - SelectStartOfDocument, - SelectEndOfDocument, - DeleteStartOfWord, - DeleteEndOfWord, - - SetTextDirectionDefault, - SetTextDirectionLeftToRight, - SetTextDirectionRightToLeft, - - ToggleBold, - ToggleItalic, - ToggleUnderline, - - InspectElement, - - InsertParagraphSeparator, - InsertLineSeparator, - - SelectAll, - ReloadAndBypassCache, - - PasteAndMatchStyle, - RemoveFormat, - - ToggleStrikethrough, - ToggleSubscript, - ToggleSuperscript, - InsertUnorderedList, - InsertOrderedList, - Indent, - Outdent, - - AlignCenter, - AlignJustified, - AlignLeft, - AlignRight, - - StopScheduledPageRefresh, - - CopyImageUrlToClipboard, - - OpenLinkInThisWindow, - - WebActionCount - }; - - enum FindFlag { - FindBackward = 1, - FindCaseSensitively = 2, - FindWrapsAroundDocument = 4, - HighlightAllOccurrences = 8 - }; - Q_DECLARE_FLAGS(FindFlags, FindFlag) - - enum LinkDelegationPolicy { - DontDelegateLinks, - DelegateExternalLinks, - DelegateAllLinks - }; - - enum WebWindowType { - WebBrowserWindow, - WebModalDialog - }; - - enum PermissionPolicy { - PermissionUnknown, - PermissionGrantedByUser, - PermissionDeniedByUser - }; - - enum Feature { - Notifications, - Geolocation - }; - - class QWEBKIT_EXPORT ViewportAttributes { - public: - ViewportAttributes(); - ViewportAttributes(const QWebPage::ViewportAttributes& other); - - ~ViewportAttributes(); - - QWebPage::ViewportAttributes& operator=(const QWebPage::ViewportAttributes& other); - - inline qreal initialScaleFactor() const { return m_initialScaleFactor; } - inline qreal minimumScaleFactor() const { return m_minimumScaleFactor; } - inline qreal maximumScaleFactor() const { return m_maximumScaleFactor; } - inline qreal devicePixelRatio() const { return m_devicePixelRatio; } - inline bool isUserScalable() const { return m_isUserScalable; } - inline bool isValid() const { return m_isValid; } - inline QSizeF size() const { return m_size; } - - private: - QSharedDataPointer<QtViewportAttributesPrivate> d; - qreal m_initialScaleFactor; - qreal m_minimumScaleFactor; - qreal m_maximumScaleFactor; - qreal m_devicePixelRatio; - bool m_isUserScalable; - bool m_isValid; - QSizeF m_size; - - friend class WebCore::ChromeClientQt; - friend class QWebPage; - }; - - - explicit QWebPage(QObject *parent = 0); - ~QWebPage(); - - QWebFrame *mainFrame() const; - QWebFrame *currentFrame() const; - QWebFrame* frameAt(const QPoint& pos) const; - - QWebHistory *history() const; - QWebSettings *settings() const; - - void setView(QWidget *view); - QWidget *view() const; - - bool isModified() const; -#ifndef QT_NO_UNDOSTACK - QUndoStack *undoStack() const; -#endif - - void setNetworkAccessManager(QNetworkAccessManager *manager); - QNetworkAccessManager *networkAccessManager() const; - - void setPluginFactory(QWebPluginFactory *factory); - QWebPluginFactory *pluginFactory() const; - - quint64 totalBytes() const; - quint64 bytesReceived() const; - - bool hasSelection() const; - QString selectedText() const; - QString selectedHtml() const; - -#ifndef QT_NO_ACTION - QAction *action(WebAction action) const; -#endif - virtual void triggerAction(WebAction action, bool checked = false); - - QSize viewportSize() const; - void setViewportSize(const QSize &size) const; - ViewportAttributes viewportAttributesForSize(const QSize& availableSize) const; - - QSize preferredContentsSize() const; - void setPreferredContentsSize(const QSize &size) const; - void setActualVisibleContentRect(const QRect& rect) const; - - virtual bool event(QEvent*); - bool focusNextPrevChild(bool next); - - QVariant inputMethodQuery(Qt::InputMethodQuery property) const; - - bool findText(const QString &subString, FindFlags options = 0); - - void setForwardUnsupportedContent(bool forward); - bool forwardUnsupportedContent() const; - - void setLinkDelegationPolicy(LinkDelegationPolicy policy); - LinkDelegationPolicy linkDelegationPolicy() const; - - void setPalette(const QPalette &palette); - QPalette palette() const; - - void setContentEditable(bool editable); - bool isContentEditable() const; - -#ifndef QT_NO_CONTEXTMENU - bool swallowContextMenuEvent(QContextMenuEvent *event); -#endif - void updatePositionDependentActions(const QPoint &pos); - - QMenu *createStandardContextMenu(); - - void setFeaturePermission(QWebFrame* frame, Feature feature, PermissionPolicy policy); - - QStringList supportedContentTypes() const; - bool supportsContentType(const QString& mimeType) const; - - enum Extension { - ChooseMultipleFilesExtension, - ErrorPageExtension - }; - class ExtensionOption - {}; - class ExtensionReturn - {}; - - class ChooseMultipleFilesExtensionOption : public ExtensionOption { - public: - QWebFrame *parentFrame; - QStringList suggestedFileNames; - }; - - class ChooseMultipleFilesExtensionReturn : public ExtensionReturn { - public: - QStringList fileNames; - }; - - enum ErrorDomain { QtNetwork, Http, WebKit }; - class ErrorPageExtensionOption : public ExtensionOption { - public: - QUrl url; - QWebFrame* frame; - ErrorDomain domain; - int error; - QString errorString; - }; - - class ErrorPageExtensionReturn : public ExtensionReturn { - public: - ErrorPageExtensionReturn() : contentType(QLatin1String("text/html")), encoding(QLatin1String("utf-8")) {}; - QString contentType; - QString encoding; - QUrl baseUrl; - QByteArray content; - }; - - - virtual bool extension(Extension extension, const ExtensionOption *option = 0, ExtensionReturn *output = 0); - virtual bool supportsExtension(Extension extension) const; - - QWebPageAdapter* handle() const; - - virtual bool shouldInterruptJavaScript(); - -Q_SIGNALS: - void loadStarted(); - void loadProgress(int progress); - void loadFinished(bool ok); - - void linkHovered(const QString &link, const QString &title, const QString &textContent); - void statusBarMessage(const QString& text); - void selectionChanged(); - void frameCreated(QWebFrame *frame); - void geometryChangeRequested(const QRect& geom); - void repaintRequested(const QRect& dirtyRect); - void scrollRequested(int dx, int dy, const QRect& scrollViewRect); - void windowCloseRequested(); - void printRequested(QWebFrame *frame); - void linkClicked(const QUrl &url); - - void toolBarVisibilityChangeRequested(bool visible); - void statusBarVisibilityChangeRequested(bool visible); - void menuBarVisibilityChangeRequested(bool visible); - - void unsupportedContent(QNetworkReply *reply); - void downloadRequested(const QNetworkRequest &request); - - void microFocusChanged(); - void contentsChanged(); - void databaseQuotaExceeded(QWebFrame* frame, QString databaseName); - void applicationCacheQuotaExceeded(QWebSecurityOrigin* origin, quint64 defaultOriginQuota, quint64 totalSpaceNeeded); - - void saveFrameStateRequested(QWebFrame* frame, QWebHistoryItem* item); - void restoreFrameStateRequested(QWebFrame* frame); - - void viewportChangeRequested(); - - void featurePermissionRequested(QWebFrame* frame, QWebPage::Feature feature); - void featurePermissionRequestCanceled(QWebFrame* frame, QWebPage::Feature feature); - -protected: - virtual QWebPage *createWindow(WebWindowType type); - virtual QObject *createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues); - - virtual bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type); - virtual QString chooseFile(QWebFrame *originatingFrame, const QString& oldFile); - virtual void javaScriptAlert(QWebFrame *originatingFrame, const QString& msg); - virtual bool javaScriptConfirm(QWebFrame *originatingFrame, const QString& msg); - virtual bool javaScriptPrompt(QWebFrame *originatingFrame, const QString& msg, const QString& defaultValue, QString* result); - virtual void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID); - - virtual QString userAgentForUrl(const QUrl& url) const; - -private: - Q_PRIVATE_SLOT(d, void _q_onLoadProgressChanged(int)) -#ifndef QT_NO_ACTION - Q_PRIVATE_SLOT(d, void _q_webActionTriggered(bool checked)) -#endif - Q_PRIVATE_SLOT(d, void _q_cleanupLeakMessages()) - - QWebPagePrivate *d; - - friend class QWebFrame; - friend class QWebPagePrivate; - friend class QWebView; - friend class QWebViewPrivate; - friend class QGraphicsWebView; - friend class QGraphicsWebViewPrivate; - friend class QWebInspector; - friend class WebCore::ChromeClientQt; - friend class WebCore::EditorClientQt; - friend class WebCore::FrameLoaderClientQt; - friend class WebCore::InspectorClientQt; - friend class WebCore::InspectorServerRequestHandlerQt; - friend class WebCore::InspectorFrontendClientQt; - friend class WebCore::NotificationPresenterClientQt; - friend class WebCore::GeolocationPermissionClientQt; - friend class WebCore::ResourceHandle; - friend class WebCore::QNetworkReplyHandler; - friend class DumpRenderTreeSupportQt; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(QWebPage::FindFlags) - -#endif diff --git a/Source/WebKit/qt/Api/qwebpage_p.h b/Source/WebKit/qt/Api/qwebpage_p.h deleted file mode 100644 index 2434dd653..000000000 --- a/Source/WebKit/qt/Api/qwebpage_p.h +++ /dev/null @@ -1,257 +0,0 @@ -/* - Copyright (C) 2008, 2009 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2008 Holger Hans Peter Freyther - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QWEBPAGE_P_H -#define QWEBPAGE_P_H - -#include "QWebPageAdapter.h" - -#include "qwebframe.h" -#include "qwebhistory.h" -#include "qwebpage.h" - -#include <QPointer> -#include <qbasictimer.h> -#include <qevent.h> -#include <qgesture.h> -#include <qgraphicssceneevent.h> -#include <qgraphicswidget.h> -#include <qnetworkproxy.h> - - -namespace WebCore { - class ContextMenuClientQt; - class ContextMenuItem; - class ContextMenu; - class Document; - class EditorClientQt; - class Element; - class InspectorController; - class IntRect; - class Node; - class NodeList; - class Frame; -} - -QT_BEGIN_NAMESPACE -class QUndoStack; -class QMenu; -class QBitArray; -QT_END_NAMESPACE - -class QtPluginWidgetAdapter; -class QWebInspector; -class QWebFrameAdapter; -class UndoStepQt; - -class QtViewportAttributesPrivate : public QSharedData { -public: - QtViewportAttributesPrivate(QWebPage::ViewportAttributes* qq) - : q(qq) - { } - - QWebPage::ViewportAttributes* q; -}; - -class QWebPagePrivate : public QWebPageAdapter { -public: - QWebPagePrivate(QWebPage*); - ~QWebPagePrivate(); - - static WebCore::Page* core(const QWebPage*); - - // Adapter implementation - virtual void show() OVERRIDE; - virtual void setFocus() OVERRIDE; - virtual void unfocus() OVERRIDE; - virtual void setWindowRect(const QRect &) OVERRIDE; - virtual QSize viewportSize() const OVERRIDE; - virtual QWebPageAdapter* createWindow(bool /*dialog*/) OVERRIDE; - virtual QObject* handle() OVERRIDE { return q; } - virtual void javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID) OVERRIDE; - virtual void javaScriptAlert(QWebFrameAdapter*, const QString& msg) OVERRIDE; - virtual bool javaScriptConfirm(QWebFrameAdapter*, const QString& msg) OVERRIDE; - virtual bool javaScriptPrompt(QWebFrameAdapter*, const QString& msg, const QString& defaultValue, QString* result) OVERRIDE; - virtual bool shouldInterruptJavaScript() OVERRIDE; - virtual void printRequested(QWebFrameAdapter*) OVERRIDE; - virtual void databaseQuotaExceeded(QWebFrameAdapter*, const QString& databaseName) OVERRIDE; - virtual void applicationCacheQuotaExceeded(QWebSecurityOrigin*, quint64 defaultOriginQuota, quint64 totalSpaceNeeded) OVERRIDE; - virtual void setToolTip(const QString&) OVERRIDE; -#if USE(QT_MULTIMEDIA) - virtual QWebFullScreenVideoHandler* createFullScreenVideoHandler() OVERRIDE; -#endif - virtual QWebFrameAdapter* mainFrameAdapter() OVERRIDE; - virtual QStringList chooseFiles(QWebFrameAdapter*, bool allowMultiple, const QStringList& suggestedFileNames) OVERRIDE; - virtual QColor colorSelectionRequested(const QColor& selectedColor) OVERRIDE; - virtual QWebSelectMethod* createSelectPopup() OVERRIDE; - virtual QRect viewRectRelativeToWindow() OVERRIDE; - virtual void geolocationPermissionRequested(QWebFrameAdapter*) OVERRIDE; - virtual void geolocationPermissionRequestCancelled(QWebFrameAdapter*) OVERRIDE; - virtual void notificationsPermissionRequested(QWebFrameAdapter*) OVERRIDE; - virtual void notificationsPermissionRequestCancelled(QWebFrameAdapter*) OVERRIDE; - - virtual void respondToChangedContents() OVERRIDE; - virtual void respondToChangedSelection() OVERRIDE; - virtual void microFocusChanged() OVERRIDE; - virtual void triggerCopyAction() OVERRIDE; - virtual void triggerActionForKeyEvent(QKeyEvent*) OVERRIDE; - virtual void clearUndoStack() OVERRIDE; - virtual bool canUndo() const OVERRIDE; - virtual bool canRedo() const OVERRIDE; - virtual void undo() OVERRIDE; - virtual void redo() OVERRIDE; - virtual void createUndoStep(QSharedPointer<UndoStepQt>) OVERRIDE; - virtual const char* editorCommandForKeyEvent(QKeyEvent*) OVERRIDE; - - void updateNavigationActions() OVERRIDE; - - virtual QObject* inspectorHandle() OVERRIDE; - virtual void setInspectorFrontend(QObject*) OVERRIDE; - virtual void setInspectorWindowTitle(const QString&) OVERRIDE; - virtual void createWebInspector(QObject** inspectorView, QWebPageAdapter** inspectorPage) OVERRIDE; - virtual QStringList menuActionsAsText() OVERRIDE; - virtual void emitViewportChangeRequested() OVERRIDE; - virtual bool acceptNavigationRequest(QWebFrameAdapter*, const QNetworkRequest&, int type) OVERRIDE; - virtual void emitRestoreFrameStateRequested(QWebFrameAdapter*) OVERRIDE; - virtual void emitSaveFrameStateRequested(QWebFrameAdapter*, QWebHistoryItem*) OVERRIDE; - virtual void emitDownloadRequested(const QNetworkRequest&) OVERRIDE; - virtual void emitFrameCreated(QWebFrameAdapter*) OVERRIDE; - virtual QString userAgentForUrl(const QUrl &url) const OVERRIDE { return q->userAgentForUrl(url); } - virtual bool supportsErrorPageExtension() const OVERRIDE { return q->supportsExtension(QWebPage::ErrorPageExtension); } - virtual bool errorPageExtension(ErrorPageOption *, ErrorPageReturn *) OVERRIDE; - virtual QtPluginWidgetAdapter* createPlugin(const QString &, const QUrl &, const QStringList &, const QStringList &) OVERRIDE; - virtual QtPluginWidgetAdapter* adapterForWidget(QObject *) const OVERRIDE; - - void createMainFrame(); -#ifndef QT_NO_CONTEXTMENU - QMenu* createContextMenu(const WebCore::ContextMenu* webcoreMenu, const QList<WebCore::ContextMenuItem>* items, QBitArray* visitedWebActions); -#endif - void _q_onLoadProgressChanged(int); - void _q_webActionTriggered(bool checked); - void _q_cleanupLeakMessages(); - void updateAction(QWebPage::WebAction action); - void updateEditorActions(); - - void timerEvent(QTimerEvent*); - - void mouseMoveEvent(QMouseEvent*); - void mousePressEvent(QMouseEvent*); - void mouseDoubleClickEvent(QMouseEvent*); - void mouseTripleClickEvent(QMouseEvent*); - void mouseReleaseEvent(QMouseEvent*); -#ifndef QT_NO_CONTEXTMENU - void contextMenuEvent(const QPoint& globalPos); -#endif -#ifndef QT_NO_WHEELEVENT - void wheelEvent(QWheelEvent*); -#endif - void keyPressEvent(QKeyEvent*); - void keyReleaseEvent(QKeyEvent*); - void focusInEvent(QFocusEvent*); - void focusOutEvent(QFocusEvent*); - - template<class T> void dragEnterEvent(T*); - template<class T> void dragLeaveEvent(T*); - template<class T> void dragMoveEvent(T*); - template<class T> void dropEvent(T*); - - void inputMethodEvent(QInputMethodEvent*); - -#ifndef QT_NO_PROPERTIES - void dynamicPropertyChangeEvent(QDynamicPropertyChangeEvent*); -#endif - - void shortcutOverrideEvent(QKeyEvent*); - void leaveEvent(QEvent*); - void handleSoftwareInputPanel(Qt::MouseButton, const QPoint&); - bool handleScrolling(QKeyEvent*, WebCore::Frame*); - - // Returns whether the default action was cancelled in the JS event handler - bool touchEvent(QTouchEvent*); - - bool gestureEvent(QGestureEvent*); - - class TouchAdjuster { - public: - TouchAdjuster(unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding); - - WebCore::IntPoint findCandidatePointForTouch(const WebCore::IntPoint&, WebCore::Document*) const; - - private: - unsigned m_topPadding; - unsigned m_rightPadding; - unsigned m_bottomPadding; - unsigned m_leftPadding; - }; - - void adjustPointForClicking(QMouseEvent*); -#if !defined(QT_NO_GRAPHICSVIEW) - void adjustPointForClicking(QGraphicsSceneMouseEvent*); -#endif - - void setInspector(QWebInspector*); - QWebInspector* getOrCreateInspector(); - WebCore::InspectorController* inspectorController(); - quint16 inspectorServerPort(); - -#ifndef QT_NO_SHORTCUT - static QWebPage::WebAction editorActionForKeyEvent(QKeyEvent* event); -#endif - static const char* editorCommandForWebActions(QWebPage::WebAction action); - - QWebPage *q; - QPointer<QWebFrame> mainFrame; - -#ifndef QT_NO_UNDOSTACK - QUndoStack *undoStack; -#endif - - QPointer<QWidget> view; - - quint64 m_totalBytes; - quint64 m_bytesReceived; - - QPoint tripleClick; - QBasicTimer tripleClickTimer; - - bool clickCausedFocus; - - QWebPage::LinkDelegationPolicy linkPolicy; - - QSize m_viewportSize; - QSize fixedLayoutSize; - - QWebHistory history; - QWebHitTestResult hitTestResult; -#ifndef QT_NO_CONTEXTMENU - QPointer<QMenu> currentContextMenu; -#endif - QPalette palette; - bool useFixedLayout; - - QAction *actions[QWebPage::WebActionCount]; - - QWidget* inspectorFrontend; - QWebInspector* inspector; - bool inspectorIsInternalOnly; // True if created through the Inspect context menu action - Qt::DropAction m_lastDropAction; -}; - -#endif diff --git a/Source/WebKit/qt/Api/qwebsecurityorigin.h b/Source/WebKit/qt/Api/qwebsecurityorigin.h index 7328680f3..61c45f1d6 100644 --- a/Source/WebKit/qt/Api/qwebsecurityorigin.h +++ b/Source/WebKit/qt/Api/qwebsecurityorigin.h @@ -59,7 +59,7 @@ public: QWebSecurityOrigin &operator=(const QWebSecurityOrigin& other); private: friend class QWebDatabase; - friend class QWebFrame; + friend class QWebFrameAdapter; friend class WebCore::ChromeClientQt; QWebSecurityOrigin(QWebSecurityOriginPrivate* priv); diff --git a/Source/WebKit/qt/Api/qwebsettings.cpp b/Source/WebKit/qt/Api/qwebsettings.cpp index 74d8524d8..01818aff4 100644 --- a/Source/WebKit/qt/Api/qwebsettings.cpp +++ b/Source/WebKit/qt/Api/qwebsettings.cpp @@ -41,6 +41,7 @@ #include "Page.h" #include "PageCache.h" #include "PluginDatabase.h" +#include "RuntimeEnabledFeatures.h" #include "Settings.h" #include <QDir> #include <QFileInfo> @@ -167,7 +168,7 @@ void QWebSettingsPrivate::apply() value = attributes.value(QWebSettings::CSSRegionsEnabled, global->attributes.value(QWebSettings::CSSRegionsEnabled)); - settings->setCSSRegionsEnabled(value); + WebCore::RuntimeEnabledFeatures::setCSSRegionsEnabled(value); value = attributes.value(QWebSettings::CSSGridLayoutEnabled, global->attributes.value(QWebSettings::CSSGridLayoutEnabled)); settings->setCSSGridLayoutEnabled(value); @@ -533,7 +534,7 @@ QWebSettings::QWebSettings() d->attributes.insert(QWebSettings::LocalContentCanAccessRemoteUrls, false); d->attributes.insert(QWebSettings::LocalContentCanAccessFileUrls, true); d->attributes.insert(QWebSettings::AcceleratedCompositingEnabled, true); - d->attributes.insert(QWebSettings::WebGLEnabled, false); + d->attributes.insert(QWebSettings::WebGLEnabled, true); d->attributes.insert(QWebSettings::CSSRegionsEnabled, true); d->attributes.insert(QWebSettings::CSSGridLayoutEnabled, false); d->attributes.insert(QWebSettings::HyperlinkAuditingEnabled, false); diff --git a/Source/WebKit/qt/Api/qwebview.cpp b/Source/WebKit/qt/Api/qwebview.cpp deleted file mode 100644 index 2eda6a18e..000000000 --- a/Source/WebKit/qt/Api/qwebview.cpp +++ /dev/null @@ -1,1129 +0,0 @@ -/* - Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2008 Holger Hans Peter Freyther - Copyright (C) 2009 Girish Ramakrishnan <girish@forwardbias.in> - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" -#include "qwebview.h" - -#include "Page.h" -#include "QWebPageClient.h" -#include "Settings.h" -#include "qwebframe.h" -#include "qwebpage_p.h" -#include "qbitmap.h" -#include "qevent.h" -#include "qpainter.h" -#if HAVE(QTPRINTSUPPORT) -#include "qprinter.h" -#endif -#include "qdir.h" -#include "qfile.h" -#ifndef QT_NO_ACCESSIBILITY -#include "qwebviewaccessible_p.h" -#endif - -class QWebViewPrivate { -public: - QWebViewPrivate(QWebView *view) - : view(view) - , page(0) - , renderHints(QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform) - { - Q_ASSERT(view); - } - - virtual ~QWebViewPrivate(); - - void _q_pageDestroyed(); - void detachCurrentPage(); - - QWebView *view; - QWebPage *page; - - QPainter::RenderHints renderHints; -}; - -QWebViewPrivate::~QWebViewPrivate() -{ - detachCurrentPage(); -} - -void QWebViewPrivate::_q_pageDestroyed() -{ - page = 0; - view->setPage(0); -} - -/*! - \class QWebView - \since 4.4 - \brief The QWebView class provides a widget that is used to view and edit - web documents. - \ingroup advanced - - \inmodule QtWebKit - - QWebView is the main widget component of the QtWebKit web browsing module. - It can be used in various applications to display web content live from the - Internet. - - The image below shows QWebView previewed in \QD with a Nokia website. - - \image qwebview-url.png - - A web site can be loaded onto QWebView with the load() function. Like all - Qt widgets, the show() function must be invoked in order to display - QWebView. The snippet below illustrates this: - - \snippet webkitsnippets/simple/main.cpp Using QWebView - - Alternatively, setUrl() can also be used to load a web site. If you have - the HTML content readily available, you can use setHtml() instead. - - The loadStarted() signal is emitted when the view begins loading. The - loadProgress() signal, on the other hand, is emitted whenever an element of - the web view completes loading, such as an embedded image, a script, etc. - Finally, the loadFinished() signal is emitted when the view has loaded - completely. It's argument - either \c true or \c false - indicates - load success or failure. - - The page() function returns a pointer to the web page object. See - \l{Elements of QWebView} for an explanation of how the web page - is related to the view. To modify your web view's settings, you can access - the QWebSettings object with the settings() function. With QWebSettings, - you can change the default fonts, enable or disable features such as - JavaScript and plugins. - - The title of an HTML document can be accessed with the title() property. - Additionally, a web site may also specify an icon, which can be accessed - using the icon() property. If the title or the icon changes, the corresponding - titleChanged() and iconChanged() signals will be emitted. The - textSizeMultiplier() property can be used to change the overall size of - the text displayed in the web view. - - If you require a custom context menu, you can implement it by reimplementing - \l{QWidget::}{contextMenuEvent()} and populating your QMenu with the actions - obtained from pageAction(). More functionality such as reloading the view, - copying selected text to the clipboard, or pasting into the view, is also - encapsulated within the QAction objects returned by pageAction(). These - actions can be programmatically triggered using triggerPageAction(). - Alternatively, the actions can be added to a toolbar or a menu directly. - QWebView maintains the state of the returned actions but allows - modification of action properties such as \l{QAction::}{text} or - \l{QAction::}{icon}. - - A QWebView can be printed onto a QPrinter using the print() function. - This function is marked as a slot and can be conveniently connected to - \l{QPrintPreviewDialog}'s \l{QPrintPreviewDialog::}{paintRequested()} - signal. - - If you want to provide support for web sites that allow the user to open - new windows, such as pop-up windows, you can subclass QWebView and - reimplement the createWindow() function. - - \section1 Elements of QWebView - - QWebView consists of other objects such as QWebFrame and QWebPage. The - flowchart below shows these elements are related. - - \image qwebview-diagram.png - - \note It is possible to use QWebPage and QWebFrame, without using QWebView, - if you do not require QWidget attributes. Nevertheless, QtWebKit depends - on QtGui, so you should use a QApplication instead of QCoreApplication. - - \sa {Previewer Example}, {Web Browser}, {Form Extractor Example}, - {Google Chat Example}, {Fancy Browser Example} -*/ - -#ifndef QT_NO_ACCESSIBILITY -static QAccessibleInterface* accessibleInterfaceFactory(const QString& key, QObject* object) -{ - Q_UNUSED(key) - - if (QWebPage* page = qobject_cast<QWebPage*>(object)) - return new QWebPageAccessible(page); - if (QWebView* view = qobject_cast<QWebView*>(object)) - return new QWebViewAccessible(view); - if (QWebFrame* frame = qobject_cast<QWebFrame*>(object)) - return new QWebFrameAccessible(frame); - return 0; -} -#endif - -/*! - Constructs an empty QWebView with parent \a parent. - - \sa load() -*/ -QWebView::QWebView(QWidget *parent) - : QWidget(parent) -{ - d = new QWebViewPrivate(this); - -#if !defined(Q_WS_QWS) - setAttribute(Qt::WA_InputMethodEnabled); -#endif - - setAttribute(Qt::WA_AcceptTouchEvents); - setAcceptDrops(true); - - setMouseTracking(true); - setFocusPolicy(Qt::WheelFocus); - -#ifndef QT_NO_ACCESSIBILITY - QAccessible::installFactory(accessibleInterfaceFactory); -#endif -} - -/*! - Destroys the web view. -*/ -QWebView::~QWebView() -{ - delete d; -} - -/*! - Returns a pointer to the underlying web page. - - \sa setPage() -*/ -QWebPage *QWebView::page() const -{ - if (!d->page) { - QWebView *that = const_cast<QWebView *>(this); - that->setPage(new QWebPage(that)); - } - return d->page; -} - -void QWebViewPrivate::detachCurrentPage() -{ - if (!page) - return; - - page->d->view = 0; - - // if the page client is the special client constructed for - // delegating the responsibilities to a QWidget, we need - // to destroy it. - - if (page->d->client && page->d->client->isQWidgetClient()) - page->d->client.reset(); - - page->d->client.take(); - - // if the page was created by us, we own it and need to - // destroy it as well. - - if (page->parent() == view) - delete page; - else - page->disconnect(view); - - page = 0; -} - -/*! - Makes \a page the new web page of the web view. - - The parent QObject of the provided page remains the owner - of the object. If the current page is a child of the web - view, it will be deleted. - - \sa page() -*/ -void QWebView::setPage(QWebPage* page) -{ - if (d->page == page) - return; - - d->detachCurrentPage(); - d->page = page; - - if (d->page) { - d->page->setView(this); - d->page->setPalette(palette()); - // #### connect signals - QWebFrame *mainFrame = d->page->mainFrame(); - connect(mainFrame, SIGNAL(titleChanged(QString)), - this, SIGNAL(titleChanged(QString))); - connect(mainFrame, SIGNAL(iconChanged()), - this, SIGNAL(iconChanged())); - connect(mainFrame, SIGNAL(urlChanged(QUrl)), - this, SIGNAL(urlChanged(QUrl))); - - connect(d->page, SIGNAL(loadStarted()), - this, SIGNAL(loadStarted())); - connect(d->page, SIGNAL(loadProgress(int)), - this, SIGNAL(loadProgress(int))); - connect(d->page, SIGNAL(loadFinished(bool)), - this, SIGNAL(loadFinished(bool))); - connect(d->page, SIGNAL(statusBarMessage(QString)), - this, SIGNAL(statusBarMessage(QString))); - connect(d->page, SIGNAL(linkClicked(QUrl)), - this, SIGNAL(linkClicked(QUrl))); - connect(d->page, SIGNAL(selectionChanged()), - this, SIGNAL(selectionChanged())); - - connect(d->page, SIGNAL(microFocusChanged()), - this, SLOT(updateMicroFocus())); - connect(d->page, SIGNAL(destroyed()), - this, SLOT(_q_pageDestroyed())); - } - setAttribute(Qt::WA_OpaquePaintEvent, d->page); - update(); -} - -/*! - Loads the specified \a url and displays it. - - \note The view remains the same until enough data has arrived to display the new \a url. - - \sa setUrl(), url(), urlChanged(), QUrl::fromUserInput() -*/ -void QWebView::load(const QUrl &url) -{ - page()->mainFrame()->load(url); -} - -/*! - \fn void QWebView::load(const QNetworkRequest &request, QNetworkAccessManager::Operation operation, const QByteArray &body) - - Loads a network request, \a request, using the method specified in \a operation. - - \a body is optional and is only used for POST operations. - - \note The view remains the same until enough data has arrived to display the new url. - - \sa url(), urlChanged() -*/ - -void QWebView::load(const QNetworkRequest &request, - QNetworkAccessManager::Operation operation, - const QByteArray &body) -{ - page()->mainFrame()->load(request, operation, body); -} - -/*! - Sets the content of the web view to the specified \a html. - - External objects such as stylesheets or images referenced in the HTML - document are located relative to \a baseUrl. - - The \a html is loaded immediately; external objects are loaded asynchronously. - - When using this method, WebKit assumes that external resources such as - JavaScript programs or style sheets are encoded in UTF-8 unless otherwise - specified. For example, the encoding of an external script can be specified - through the charset attribute of the HTML script tag. Alternatively, the - encoding can also be specified by the web server. - - This is a convenience function equivalent to setContent(html, "text/html", baseUrl). - - \warning This function works only for HTML, for other mime types (i.e. XHTML, SVG) - setContent() should be used instead. - - \sa load(), setContent(), QWebFrame::toHtml(), QWebFrame::setContent() -*/ -void QWebView::setHtml(const QString &html, const QUrl &baseUrl) -{ - page()->mainFrame()->setHtml(html, baseUrl); -} - -/*! - Sets the content of the web view to the specified content \a data. If the \a mimeType argument - is empty it is currently assumed that the content is HTML but in future versions we may introduce - auto-detection. - - External objects referenced in the content are located relative to \a baseUrl. - - The \a data is loaded immediately; external objects are loaded asynchronously. - - \sa load(), setHtml(), QWebFrame::toHtml() -*/ -void QWebView::setContent(const QByteArray &data, const QString &mimeType, const QUrl &baseUrl) -{ - page()->mainFrame()->setContent(data, mimeType, baseUrl); -} - -/*! - Returns a pointer to the view's history of navigated web pages. - - It is equivalent to - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 0 -*/ -QWebHistory *QWebView::history() const -{ - return page()->history(); -} - -/*! - Returns a pointer to the view/page specific settings object. - - It is equivalent to - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 1 - - \sa QWebSettings::globalSettings() -*/ -QWebSettings *QWebView::settings() const -{ - return page()->settings(); -} - -/*! - \property QWebView::title - \brief the title of the web page currently viewed - - By default, this property contains an empty string. - - \sa titleChanged() -*/ -QString QWebView::title() const -{ - if (d->page) - return d->page->mainFrame()->title(); - return QString(); -} - -/*! - \property QWebView::url - \brief the url of the web page currently viewed - - Setting this property clears the view and loads the URL. - - By default, this property contains an empty, invalid URL. - - \sa load(), urlChanged() -*/ - -void QWebView::setUrl(const QUrl &url) -{ - page()->mainFrame()->setUrl(url); -} - -QUrl QWebView::url() const -{ - if (d->page) - return d->page->mainFrame()->url(); - return QUrl(); -} - -/*! - \property QWebView::icon - \brief the icon associated with the web page currently viewed - - By default, this property contains a null icon. - - \sa iconChanged(), QWebSettings::iconForUrl() -*/ -QIcon QWebView::icon() const -{ - if (d->page) - return d->page->mainFrame()->icon(); - return QIcon(); -} - -/*! - \property QWebView::hasSelection - \brief whether this page contains selected content or not. - - By default, this property is false. - - \sa selectionChanged() -*/ -bool QWebView::hasSelection() const -{ - if (d->page) - return d->page->hasSelection(); - return false; -} - -/*! - \property QWebView::selectedText - \brief the text currently selected - - By default, this property contains an empty string. - - \sa findText(), selectionChanged(), selectedHtml() -*/ -QString QWebView::selectedText() const -{ - if (d->page) - return d->page->selectedText(); - return QString(); -} - -/*! - \since 4.8 - \property QWebView::selectedHtml - \brief the HTML currently selected - - By default, this property contains an empty string. - - \sa findText(), selectionChanged(), selectedText() -*/ -QString QWebView::selectedHtml() const -{ - if (d->page) - return d->page->selectedHtml(); - return QString(); -} - -#ifndef QT_NO_ACTION -/*! - Returns a pointer to a QAction that encapsulates the specified web action \a action. -*/ -QAction *QWebView::pageAction(QWebPage::WebAction action) const -{ - return page()->action(action); -} -#endif - -/*! - Triggers the specified \a action. If it is a checkable action the specified - \a checked state is assumed. - - The following example triggers the copy action and therefore copies any - selected text to the clipboard. - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 2 - - \sa pageAction() -*/ -void QWebView::triggerPageAction(QWebPage::WebAction action, bool checked) -{ - page()->triggerAction(action, checked); -} - -/*! - \property QWebView::modified - \brief whether the document was modified by the user - - Parts of HTML documents can be editable for example through the - \c{contenteditable} attribute on HTML elements. - - By default, this property is false. -*/ -bool QWebView::isModified() const -{ - if (d->page) - return d->page->isModified(); - return false; -} - -/* -Qt::TextInteractionFlags QWebView::textInteractionFlags() const -{ - // ### FIXME (add to page) - return Qt::TextInteractionFlags(); -} -*/ - -/* - \property QWebView::textInteractionFlags - \brief how the view should handle user input - - Specifies how the user can interact with the text on the page. -*/ - -/* -void QWebView::setTextInteractionFlags(Qt::TextInteractionFlags flags) -{ - Q_UNUSED(flags) - // ### FIXME (add to page) -} -*/ - -/*! - \reimp -*/ -QSize QWebView::sizeHint() const -{ - return QSize(800, 600); // ####... -} - -/*! - \property QWebView::zoomFactor - \since 4.5 - \brief the zoom factor for the view -*/ - -void QWebView::setZoomFactor(qreal factor) -{ - page()->mainFrame()->setZoomFactor(factor); -} - -qreal QWebView::zoomFactor() const -{ - return page()->mainFrame()->zoomFactor(); -} - -/*! - \property QWebView::textSizeMultiplier - \brief the scaling factor for all text in the frame - \obsolete - - Use setZoomFactor instead, in combination with the - ZoomTextOnly attribute in QWebSettings. - - \note Setting this property also enables the - ZoomTextOnly attribute in QWebSettings. - - By default, this property contains a value of 1.0. -*/ - -/*! - Sets the value of the multiplier used to scale the text in a Web page to - the \a factor specified. -*/ -void QWebView::setTextSizeMultiplier(qreal factor) -{ - page()->mainFrame()->setTextSizeMultiplier(factor); -} - -/*! - Returns the value of the multiplier used to scale the text in a Web page. -*/ -qreal QWebView::textSizeMultiplier() const -{ - return page()->mainFrame()->textSizeMultiplier(); -} - -/*! - \property QWebView::renderHints - \since 4.6 - \brief the default render hints for the view - - These hints are used to initialize QPainter before painting the Web page. - - QPainter::TextAntialiasing and QPainter::SmoothPixmapTransform are enabled by default. - - \sa QPainter::renderHints() -*/ - -/*! - \since 4.6 - Returns the render hints used by the view to render content. - - \sa QPainter::renderHints() -*/ -QPainter::RenderHints QWebView::renderHints() const -{ - return d->renderHints; -} - -/*! - \since 4.6 - Sets the render hints used by the view to the specified \a hints. - - \sa QPainter::setRenderHints() -*/ -void QWebView::setRenderHints(QPainter::RenderHints hints) -{ - if (hints == d->renderHints) - return; - d->renderHints = hints; - update(); -} - -/*! - \since 4.6 - If \a enabled is true, enables the specified render \a hint; otherwise - disables it. - - \sa renderHints, QPainter::renderHints() -*/ -void QWebView::setRenderHint(QPainter::RenderHint hint, bool enabled) -{ - QPainter::RenderHints oldHints = d->renderHints; - if (enabled) - d->renderHints |= hint; - else - d->renderHints &= ~hint; - if (oldHints != d->renderHints) - update(); -} - - -/*! - Finds the specified string, \a subString, in the page, using the given \a options. - - If the HighlightAllOccurrences flag is passed, the function will highlight all occurrences - that exist in the page. All subsequent calls will extend the highlight, rather than - replace it, with occurrences of the new string. - - If the HighlightAllOccurrences flag is not passed, the function will select an occurrence - and all subsequent calls will replace the current occurrence with the next one. - - To clear the selection, just pass an empty string. - - Returns true if \a subString was found; otherwise returns false. - - \sa selectedText(), selectionChanged() -*/ -bool QWebView::findText(const QString &subString, QWebPage::FindFlags options) -{ - if (d->page) - return d->page->findText(subString, options); - return false; -} - -/*! \reimp -*/ -bool QWebView::event(QEvent *e) -{ - if (d->page) { -#ifndef QT_NO_CONTEXTMENU - if (e->type() == QEvent::ContextMenu) { - if (!isEnabled()) - return false; - QContextMenuEvent *event = static_cast<QContextMenuEvent *>(e); - if (d->page->swallowContextMenuEvent(event)) { - e->accept(); - return true; - } - d->page->updatePositionDependentActions(event->pos()); - } else -#endif // QT_NO_CONTEXTMENU - if (e->type() == QEvent::ShortcutOverride) { - d->page->event(e); -#ifndef QT_NO_CURSOR - } else if (e->type() == QEvent::CursorChange) { - // An unsetCursor will set the cursor to Qt::ArrowCursor. - // Thus this cursor change might be a QWidget::unsetCursor() - // If this is not the case and it came from WebCore, the - // QWebPageClient already has set its cursor internally - // to Qt::ArrowCursor, so updating the cursor is always - // right, as it falls back to the last cursor set by - // WebCore. - // FIXME: Add a QEvent::CursorUnset or similar to Qt. - if (cursor().shape() == Qt::ArrowCursor) - d->page->d->client->resetCursor(); -#endif - } else if (e->type() == QEvent::TouchBegin - || e->type() == QEvent::TouchEnd - || e->type() == QEvent::TouchUpdate - || e->type() == QEvent::TouchCancel - ) { - d->page->event(e); - - // Always return true so that we'll receive also TouchUpdate and TouchEnd events - return true; - } else if (e->type() == QEvent::Leave) - d->page->event(e); - } - - return QWidget::event(e); -} - -/*! - Prints the main frame to the given \a printer. - - \sa QWebFrame::print(), QPrintPreviewDialog -*/ -void QWebView::print(QPrinter *printer) const -{ -#if !defined(QT_NO_PRINTER) && HAVE(QTPRINTSUPPORT) - page()->mainFrame()->print(printer); -#endif -} - -/*! - Convenience slot that stops loading the document. - - It is equivalent to - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 3 - - \sa reload(), pageAction(), loadFinished() -*/ -void QWebView::stop() -{ - if (d->page) - d->page->triggerAction(QWebPage::Stop); -} - -/*! - Convenience slot that loads the previous document in the list of documents - built by navigating links. Does nothing if there is no previous document. - - It is equivalent to - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 4 - - \sa forward(), pageAction() -*/ -void QWebView::back() -{ - if (d->page) - d->page->triggerAction(QWebPage::Back); -} - -/*! - Convenience slot that loads the next document in the list of documents - built by navigating links. Does nothing if there is no next document. - - It is equivalent to - - \snippet webkitsnippets/qtwebkit_qwebview_snippet.cpp 5 - - \sa back(), pageAction() -*/ -void QWebView::forward() -{ - if (d->page) - d->page->triggerAction(QWebPage::Forward); -} - -/*! - Reloads the current document. - - \sa stop(), pageAction(), loadStarted() -*/ -void QWebView::reload() -{ - if (d->page) - d->page->triggerAction(QWebPage::Reload); -} - -/*! \reimp -*/ -void QWebView::resizeEvent(QResizeEvent *e) -{ - if (d->page) - d->page->setViewportSize(e->size()); -} - -/*! \reimp -*/ -void QWebView::paintEvent(QPaintEvent *ev) -{ - if (!d->page) - return; -#ifdef QWEBKIT_TIME_RENDERING - QTime time; - time.start(); -#endif - - QWebFrame *frame = d->page->mainFrame(); - QPainter p(this); - p.setRenderHints(d->renderHints); - - frame->render(&p, ev->region()); - -#ifdef QWEBKIT_TIME_RENDERING - int elapsed = time.elapsed(); - qDebug() << "paint event on " << ev->region() << ", took to render = " << elapsed; -#endif -} - -/*! - This function is called from the createWindow() method of the associated QWebPage, - each time the page wants to create a new window of the given \a type. This might - be the result, for example, of a JavaScript request to open a document in a new window. - - \note If the createWindow() method of the associated page is reimplemented, this - method is not called, unless explicitly done so in the reimplementation. - - \note In the cases when the window creation is being triggered by JavaScript, apart from - reimplementing this method application must also set the JavaScriptCanOpenWindows attribute - of QWebSettings to true in order for it to get called. - - \sa QWebPage::createWindow(), QWebPage::acceptNavigationRequest() -*/ -QWebView *QWebView::createWindow(QWebPage::WebWindowType type) -{ - Q_UNUSED(type) - return 0; -} - -/*! \reimp -*/ -void QWebView::mouseMoveEvent(QMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } -} - -/*! \reimp -*/ -void QWebView::mousePressEvent(QMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } -} - -/*! \reimp -*/ -void QWebView::mouseDoubleClickEvent(QMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } -} - -/*! \reimp -*/ -void QWebView::mouseReleaseEvent(QMouseEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } -} - -#ifndef QT_NO_CONTEXTMENU -/*! \reimp -*/ -void QWebView::contextMenuEvent(QContextMenuEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } -} -#endif // QT_NO_CONTEXTMENU - -#ifndef QT_NO_WHEELEVENT -/*! \reimp -*/ -void QWebView::wheelEvent(QWheelEvent* ev) -{ - if (d->page) { - const bool accepted = ev->isAccepted(); - d->page->event(ev); - ev->setAccepted(accepted); - } -} -#endif // QT_NO_WHEELEVENT - -/*! \reimp -*/ -void QWebView::keyPressEvent(QKeyEvent* ev) -{ - if (d->page) - d->page->event(ev); - if (!ev->isAccepted()) - QWidget::keyPressEvent(ev); -} - -/*! \reimp -*/ -void QWebView::keyReleaseEvent(QKeyEvent* ev) -{ - if (d->page) - d->page->event(ev); - if (!ev->isAccepted()) - QWidget::keyReleaseEvent(ev); -} - -/*! \reimp -*/ -void QWebView::focusInEvent(QFocusEvent* ev) -{ - if (d->page) - d->page->event(ev); - else - QWidget::focusInEvent(ev); -} - -/*! \reimp -*/ -void QWebView::focusOutEvent(QFocusEvent* ev) -{ - if (d->page) - d->page->event(ev); - else - QWidget::focusOutEvent(ev); -} - -/*! \reimp -*/ -void QWebView::dragEnterEvent(QDragEnterEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) - d->page->event(ev); -#endif -} - -/*! \reimp -*/ -void QWebView::dragLeaveEvent(QDragLeaveEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) - d->page->event(ev); -#endif -} - -/*! \reimp -*/ -void QWebView::dragMoveEvent(QDragMoveEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) - d->page->event(ev); -#endif -} - -/*! \reimp -*/ -void QWebView::dropEvent(QDropEvent* ev) -{ -#ifndef QT_NO_DRAGANDDROP - if (d->page) - d->page->event(ev); -#endif -} - -/*! \reimp -*/ -bool QWebView::focusNextPrevChild(bool next) -{ - if (d->page && d->page->focusNextPrevChild(next)) - return true; - return QWidget::focusNextPrevChild(next); -} - -/*!\reimp -*/ -QVariant QWebView::inputMethodQuery(Qt::InputMethodQuery property) const -{ - if (d->page) - return d->page->inputMethodQuery(property); - return QVariant(); -} - -/*!\reimp -*/ -void QWebView::inputMethodEvent(QInputMethodEvent *e) -{ - if (d->page) - d->page->event(e); -} - -/*!\reimp -*/ -void QWebView::changeEvent(QEvent *e) -{ - if (d->page && e->type() == QEvent::PaletteChange) - d->page->setPalette(palette()); - QWidget::changeEvent(e); -} - -/*! - \fn void QWebView::titleChanged(const QString &title) - - This signal is emitted whenever the \a title of the main frame changes. - - \sa title() -*/ - -/*! - \fn void QWebView::urlChanged(const QUrl &url) - - This signal is emitted when the \a url of the view changes. - - \sa url(), load() -*/ - -/*! - \fn void QWebView::statusBarMessage(const QString& text) - - This signal is emitted when the status bar \a text is changed by the page. -*/ - -/*! - \fn void QWebView::iconChanged() - - This signal is emitted whenever the icon of the page is loaded or changes. - - In order for icons to be loaded, you will need to set an icon database path - using QWebSettings::setIconDatabasePath(). - - \sa icon(), QWebSettings::setIconDatabasePath() -*/ - -/*! - \fn void QWebView::loadStarted() - - This signal is emitted when a new load of the page is started. - - \sa loadProgress(), loadFinished() -*/ - -/*! - \fn void QWebView::loadFinished(bool ok) - - This signal is emitted when a load of the page is finished. - \a ok will indicate whether the load was successful or any error occurred. - - \sa loadStarted() -*/ - -/*! - \fn void QWebView::selectionChanged() - - This signal is emitted whenever the selection changes. - - \sa selectedText() -*/ - -/*! - \fn void QWebView::loadProgress(int progress) - - This signal is emitted every time an element in the web page - completes loading and the overall loading progress advances. - - This signal tracks the progress of all child frames. - - The current value is provided by \a progress and scales from 0 to 100, - which is the default range of QProgressBar. - - \sa loadStarted(), loadFinished() -*/ - -/*! - \fn void QWebView::linkClicked(const QUrl &url) - - This signal is emitted whenever the user clicks on a link and the page's linkDelegationPolicy - property is set to delegate the link handling for the specified \a url. - - \sa QWebPage::linkDelegationPolicy() -*/ - -#include "moc_qwebview.cpp" - diff --git a/Source/WebKit/qt/Api/qwebview.h b/Source/WebKit/qt/Api/qwebview.h deleted file mode 100644 index d4b4dd917..000000000 --- a/Source/WebKit/qt/Api/qwebview.h +++ /dev/null @@ -1,165 +0,0 @@ -/* - Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2007 Staikos Computing Services Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef QWEBVIEW_H -#define QWEBVIEW_H - -#include "qwebkitglobal.h" -#include "qwebpage.h" -#include <QtWidgets/qwidget.h> -#include <QtGui/qicon.h> -#include <QtGui/qpainter.h> -#include <QtCore/qurl.h> -#include <QtNetwork/qnetworkaccessmanager.h> - -QT_BEGIN_NAMESPACE -class QNetworkRequest; -class QPrinter; -QT_END_NAMESPACE - -class QWebPage; -class QWebViewPrivate; -class QWebNetworkRequest; - -class QWEBKIT_EXPORT QWebView : public QWidget { - Q_OBJECT - Q_PROPERTY(QString title READ title) - Q_PROPERTY(QUrl url READ url WRITE setUrl) - Q_PROPERTY(QIcon icon READ icon) - Q_PROPERTY(QString selectedText READ selectedText) - Q_PROPERTY(QString selectedHtml READ selectedHtml) - Q_PROPERTY(bool hasSelection READ hasSelection) - Q_PROPERTY(bool modified READ isModified) - //Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags) - Q_PROPERTY(qreal textSizeMultiplier READ textSizeMultiplier WRITE setTextSizeMultiplier DESIGNABLE false) - Q_PROPERTY(qreal zoomFactor READ zoomFactor WRITE setZoomFactor) - - Q_PROPERTY(QPainter::RenderHints renderHints READ renderHints WRITE setRenderHints) - Q_FLAGS(QPainter::RenderHints) -public: - explicit QWebView(QWidget* parent = 0); - virtual ~QWebView(); - - QWebPage* page() const; - void setPage(QWebPage* page); - - void load(const QUrl& url); - void load(const QNetworkRequest& request, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, const QByteArray &body = QByteArray()); - 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; - - QString title() const; - void setUrl(const QUrl &url); - QUrl url() const; - QIcon icon() const; - - bool hasSelection() const; - QString selectedText() const; - QString selectedHtml() const; - -#ifndef QT_NO_ACTION - QAction* pageAction(QWebPage::WebAction action) const; -#endif - void triggerPageAction(QWebPage::WebAction action, bool checked = false); - - bool isModified() const; - - /* - Qt::TextInteractionFlags textInteractionFlags() const; - void setTextInteractionFlags(Qt::TextInteractionFlags flags); - void setTextInteractionFlag(Qt::TextInteractionFlag flag); - */ - - QVariant inputMethodQuery(Qt::InputMethodQuery property) const; - - QSize sizeHint() const; - - qreal zoomFactor() const; - void setZoomFactor(qreal factor); - - void setTextSizeMultiplier(qreal factor); - qreal textSizeMultiplier() const; - - QPainter::RenderHints renderHints() const; - void setRenderHints(QPainter::RenderHints hints); - void setRenderHint(QPainter::RenderHint hint, bool enabled = true); - - bool findText(const QString& subString, QWebPage::FindFlags options = 0); - - virtual bool event(QEvent*); - -public Q_SLOTS: - void stop(); - void back(); - void forward(); - void reload(); - - void print(QPrinter*) const; - -Q_SIGNALS: - void loadStarted(); - void loadProgress(int progress); - void loadFinished(bool); - void titleChanged(const QString& title); - void statusBarMessage(const QString& text); - void linkClicked(const QUrl&); - void selectionChanged(); - void iconChanged(); - void urlChanged(const QUrl&); - -protected: - void resizeEvent(QResizeEvent*); - void paintEvent(QPaintEvent*); - - virtual QWebView *createWindow(QWebPage::WebWindowType type); - - virtual void changeEvent(QEvent*); - virtual void mouseMoveEvent(QMouseEvent*); - virtual void mousePressEvent(QMouseEvent*); - virtual void mouseDoubleClickEvent(QMouseEvent*); - virtual void mouseReleaseEvent(QMouseEvent*); -#ifndef QT_NO_CONTEXTMENU - virtual void contextMenuEvent(QContextMenuEvent*); -#endif -#ifndef QT_NO_WHEELEVENT - virtual void wheelEvent(QWheelEvent*); -#endif - virtual void keyPressEvent(QKeyEvent*); - virtual void keyReleaseEvent(QKeyEvent*); - virtual void dragEnterEvent(QDragEnterEvent*); - virtual void dragLeaveEvent(QDragLeaveEvent*); - virtual void dragMoveEvent(QDragMoveEvent*); - virtual void dropEvent(QDropEvent*); - virtual void focusInEvent(QFocusEvent*); - virtual void focusOutEvent(QFocusEvent*); - virtual void inputMethodEvent(QInputMethodEvent*); - - virtual bool focusNextPrevChild(bool next); - -private: - friend class QWebPage; - QWebViewPrivate* d; - Q_PRIVATE_SLOT(d, void _q_pageDestroyed()) -}; - -#endif // QWEBVIEW_H diff --git a/Source/WebKit/qt/Api/qwebviewaccessible.cpp b/Source/WebKit/qt/Api/qwebviewaccessible.cpp deleted file mode 100644 index 7cae19a1a..000000000 --- a/Source/WebKit/qt/Api/qwebviewaccessible.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) - - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" -#include "qwebviewaccessible_p.h" - -#include "qwebframe.h" -#include "qwebframe_p.h" -#include "qwebpage.h" -#include "qwebview.h" - -QWebFrameAccessible::QWebFrameAccessible(QWebFrame* frame) - : QAccessibleObject(frame) -{ -} - -QWebFrame* QWebFrameAccessible::frame() const -{ - return qobject_cast<QWebFrame*>(object()); -} - -QAccessibleInterface* QWebFrameAccessible::parent() const -{ - return QAccessible::queryAccessibleInterface(object()->parent()); -} - -QString QWebFrameAccessible::text(QAccessible::Text) const -{ - return QString(); -} - -int QWebFrameAccessible::childCount() const -{ - return 0; -} - -QAccessibleInterface* QWebFrameAccessible::child(int index) const -{ - return 0; -} - -int QWebFrameAccessible::indexOfChild(const QAccessibleInterface*) const -{ - return 0; -} - -QAccessible::State QWebFrameAccessible::state() const -{ - return QAccessible::State(); -} - -QAccessible::Role QWebFrameAccessible::role() const -{ - return QAccessible::Client; -} - -int QWebFrameAccessible::navigate(QAccessible::RelationFlag, int, QAccessibleInterface** target) const -{ - *target = 0; - return -1; -} - -QWebPageAccessible::QWebPageAccessible(QWebPage* page) - : QAccessibleObject(page) -{ -} - -QWebPage* QWebPageAccessible::page() const -{ - return qobject_cast<QWebPage*>(object()); -} - -QString QWebPageAccessible::text(QAccessible::Text t) const -{ - return QString(); -} - -QAccessibleInterface* QWebPageAccessible::parent() const -{ - return QAccessible::queryAccessibleInterface(object()->parent()); -} - -QAccessibleInterface* QWebPageAccessible::child(int index) const -{ - if (!index && page()->mainFrame()) - return new QWebFrameAccessible(page()->mainFrame()); - return 0; -} - -int QWebPageAccessible::childCount() const -{ - return page()->mainFrame() ? 1 : 0; -} - -int QWebPageAccessible::indexOfChild(const QAccessibleInterface*) const -{ - return 0; -} - -int QWebPageAccessible::navigate(QAccessible::RelationFlag, int, QAccessibleInterface** target) const -{ - *target = 0; - return -1; -} - -QAccessible::Role QWebPageAccessible::role() const -{ - return QAccessible::Client; -} - -QAccessible::State QWebPageAccessible::state() const -{ - return QAccessible::State(); -} - -QWebViewAccessible::QWebViewAccessible(QWebView* view) - : QAccessibleWidget(view, QAccessible::Document) -{ -} - -QWebView* QWebViewAccessible::view() const -{ - return qobject_cast<QWebView*>(object()); -} - -int QWebViewAccessible::childCount() const -{ - return view()->page() ? 1 : 0; -} - -QAccessibleInterface* QWebViewAccessible::child(int index) const -{ - if (!index && view()->page()) - return new QWebPageAccessible(view()->page()); - return 0; -} diff --git a/Source/WebKit/qt/Api/qwebviewaccessible_p.h b/Source/WebKit/qt/Api/qwebviewaccessible_p.h deleted file mode 100644 index 7cbf44870..000000000 --- a/Source/WebKit/qt/Api/qwebviewaccessible_p.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) - - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef qwebviewaccessible_p_h -#define qwebviewaccessible_p_h - -#include <qaccessible.h> -#include <qaccessibleobject.h> -#include <qaccessiblewidget.h> - -class QWebFrame; -class QWebPage; -class QWebView; - -/* - * Classes representing accessible objects for View, Frame and Page. - * - * Each of these just returns one child which lets the accessibility - * framwork navigate towards the actual contents in the frame. - */ - -class QWebFrameAccessible : public QAccessibleObject { -public: - QWebFrameAccessible(QWebFrame*); - - QWebFrame* frame() const; - - QAccessibleInterface* parent() const; - int childCount() const; - QAccessibleInterface* child(int index) const; - int indexOfChild(const QAccessibleInterface*) const; - int navigate(QAccessible::RelationFlag, int, QAccessibleInterface** target) const; - - QString text(QAccessible::Text) const; - QAccessible::Role role() const; - QAccessible::State state() const; -}; - -class QWebPageAccessible : public QAccessibleObject { -public: - QWebPageAccessible(QWebPage*); - - QWebPage* page() const; - - QAccessibleInterface* parent() const; - int childCount() const; - QAccessibleInterface* child(int index) const; - int indexOfChild(const QAccessibleInterface*) const; - int navigate(QAccessible::RelationFlag, int, QAccessibleInterface** target) const; - - QString text(QAccessible::Text) const; - QAccessible::Role role() const; - QAccessible::State state() const; -}; - -class QWebViewAccessible : public QAccessibleWidget { -public: - QWebViewAccessible(QWebView*); - - QWebView* view() const; - - int childCount() const; - QAccessibleInterface* child(int index) const; -}; - -#endif |
