/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2012 David Rosca * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * ============================================================ */ #include "webpage.h" #include "tabbedwebview.h" #include "tabwidget.h" #include "qupzilla.h" #include "downloadmanager.h" #include "webpluginfactory.h" #include "mainapplication.h" #include "checkboxdialog.h" #include "widget.h" #include "globalfunctions.h" #include "pluginproxy.h" #include "speeddial.h" #include "popupwebpage.h" #include "popupwebview.h" #include "networkmanagerproxy.h" #include "adblockicon.h" #include "adblockmanager.h" #include "iconprovider.h" #include "qzsettings.h" #include "useragentmanager.h" #include "recoverywidget.h" #include "html5permissions/html5permissionsmanager.h" #include "schemehandlers/fileschemehandler.h" #ifdef NONBLOCK_JS_DIALOGS #include "ui_jsconfirm.h" #include "ui_jsalert.h" #include "ui_jsprompt.h" #include #endif #include #include #include #include #include #include #include #include #include #include #include QString WebPage::s_lastUploadLocation = QDir::homePath(); QUrl WebPage::s_lastUnsupportedUrl; QTime WebPage::s_lastUnsupportedUrlTime; QList WebPage::s_livingPages; WebPage::WebPage(QupZilla* mainClass) : QWebPage() , p_QupZilla(mainClass) , m_view(0) , m_speedDial(mApp->plugins()->speedDial()) , m_fileWatcher(0) , m_runningLoop(0) , m_loadProgress(-1) , m_blockAlerts(false) , m_secureStatus(false) , m_adjustingScheduled(false) { m_networkProxy = new NetworkManagerProxy(this); m_networkProxy->setPrimaryNetworkAccessManager(mApp->networkManager()); m_networkProxy->setPage(this); setNetworkAccessManager(m_networkProxy); setForwardUnsupportedContent(true); setPluginFactory(new WebPluginFactory(this)); history()->setMaximumItemCount(20); connect(this, SIGNAL(unsupportedContent(QNetworkReply*)), this, SLOT(handleUnsupportedContent(QNetworkReply*))); connect(this, SIGNAL(loadProgress(int)), this, SLOT(progress(int))); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(finished())); connect(this, SIGNAL(printRequested(QWebFrame*)), this, SLOT(printFrame(QWebFrame*))); connect(this, SIGNAL(downloadRequested(QNetworkRequest)), this, SLOT(downloadRequested(QNetworkRequest))); connect(this, SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested())); connect(mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJavaScriptObject())); #if (QTWEBKIT_VERSION >= QTWEBKIT_VERSION_CHECK(2, 2, 0)) connect(this, SIGNAL(featurePermissionRequested(QWebFrame*, QWebPage::Feature)), this, SLOT(featurePermissionRequested(QWebFrame*, QWebPage::Feature))); #endif s_livingPages.append(this); } QUrl WebPage::url() const { return mainFrame()->url(); } void WebPage::setWebView(TabbedWebView* view) { if (m_view == view) { return; } if (m_view) { delete m_view; m_view = 0; } m_view = view; m_view->setWebPage(this); connect(m_view, SIGNAL(urlChanged(QUrl)), this, SLOT(urlChanged(QUrl))); } void WebPage::scheduleAdjustPage() { WebView* webView = qobject_cast(view()); if (!webView) { return; } if (webView->isLoading()) { m_adjustingScheduled = true; } else { const QSize &originalSize = webView->size(); QSize newSize(originalSize.width() - 1, originalSize.height() - 1); webView->resize(newSize); webView->resize(originalSize); } } bool WebPage::loadingError() const { return !mainFrame()->findFirstElement("span[id=\"qupzilla-error-page\"]").isNull(); } void WebPage::addRejectedCerts(const QList &certs) { foreach(const QSslCertificate & cert, certs) { if (!m_rejectedSslCerts.contains(cert)) { m_rejectedSslCerts.append(cert); } } } bool WebPage::containsRejectedCerts(const QList &certs) { int matches = 0; foreach(const QSslCertificate & cert, certs) { if (m_rejectedSslCerts.contains(cert)) { ++matches; } if (m_sslCert == cert) { m_sslCert.clear(); } } return matches == certs.count(); } bool WebPage::isRunningLoop() { return m_runningLoop; } bool WebPage::isLoading() const { return m_loadProgress < 100; } void WebPage::urlChanged(const QUrl &url) { Q_UNUSED(url) if (isLoading()) { m_adBlockedEntries.clear(); m_blockAlerts = false; } } void WebPage::progress(int prog) { m_loadProgress = prog; bool secStatus = qz_isCertificateValid(sslCertificate()); if (secStatus != m_secureStatus) { m_secureStatus = secStatus; emit privacyChanged(qz_isCertificateValid(sslCertificate())); } } void WebPage::finished() { progress(100); if (m_adjustingScheduled) { m_adjustingScheduled = false; mainFrame()->setZoomFactor(mainFrame()->zoomFactor() + 1); mainFrame()->setZoomFactor(mainFrame()->zoomFactor() - 1); } if (url().scheme() == QLatin1String("file")) { QFileInfo info(url().toLocalFile()); if (info.isFile()) { if (!m_fileWatcher) { m_fileWatcher = new QFileSystemWatcher(this); connect(m_fileWatcher, SIGNAL(fileChanged(QString)), this, SLOT(watchedFileChanged(QString))); } const QString &filePath = url().toLocalFile(); if (QFile::exists(filePath) && !m_fileWatcher->files().contains(filePath)) { m_fileWatcher->addPath(filePath); } } } else if (m_fileWatcher && !m_fileWatcher->files().isEmpty()) { m_fileWatcher->removePaths(m_fileWatcher->files()); } cleanBlockedObjects(); } void WebPage::watchedFileChanged(const QString &file) { if (url().toLocalFile() == file) { triggerAction(QWebPage::Reload); } } void WebPage::printFrame(QWebFrame* frame) { WebView* webView = qobject_cast(view()); if (!webView) { return; } webView->printPage(frame); } void WebPage::addJavaScriptObject() { if (url().toString() != QLatin1String("qupzilla:speeddial")) { return; } mainFrame()->addToJavaScriptWindowObject("speeddial", m_speedDial); m_speedDial->addWebFrame(mainFrame()); } void WebPage::handleUnsupportedContent(QNetworkReply* reply) { if (!reply) { return; } const QUrl &url = reply->url(); switch (reply->error()) { case QNetworkReply::NoError: if (reply->header(QNetworkRequest::ContentTypeHeader).isValid()) { QString requestUrl = reply->request().url().toString(QUrl::RemoveFragment | QUrl::RemoveQuery); if (requestUrl.endsWith(QLatin1String(".swf"))) { const QWebElement &docElement = mainFrame()->documentElement(); const QWebElement &object = docElement.findFirst(QString("object[src=\"%1\"]").arg(requestUrl)); const QWebElement &embed = docElement.findFirst(QString("embed[src=\"%1\"]").arg(requestUrl)); if (!object.isNull() || !embed.isNull()) { qDebug() << "WebPage::UnsupportedContent" << url << "Attempt to download flash object on site!"; reply->deleteLater(); return; } } DownloadManager* dManager = mApp->downManager(); dManager->handleUnsupportedContent(reply, this); return; } case QNetworkReply::ProtocolUnknownError: { if (url.scheme() == QLatin1String("file")) { FileSchemeHandler::handleUrl(url); return; } qDebug() << "WebPage::UnsupportedContent" << url << "ProtocolUnknowError"; desktopServicesOpen(url); reply->deleteLater(); return; } default: break; } qDebug() << "WebPage::UnsupportedContent error" << url << reply->errorString(); reply->deleteLater(); } void WebPage::handleUnknownProtocol(const QUrl &url) { const QString &protocol = url.scheme(); if (qzSettings->blockedProtocols.contains(protocol)) { qDebug() << "WebPage::handleUnknownProtocol Protocol" << protocol << "is blocked!"; return; } if (qzSettings->autoOpenProtocols.contains(protocol)) { desktopServicesOpen(url); return; } CheckBoxDialog dialog(QDialogButtonBox::Yes | QDialogButtonBox::No, view()); const QString &wrappedUrl = qz_alignTextToWidth(url.toString(), "
", dialog.fontMetrics(), 450); const QString &text = tr("QupZilla cannot handle %1: links. The requested link " "is
  • %2
Do you want QupZilla to try " "open this link in system application?").arg(protocol, wrappedUrl); dialog.setText(text); dialog.setCheckBoxText(tr("Remember my choice for this protocol")); dialog.setWindowTitle(tr("External Protocol Request")); dialog.setIcon(qIconProvider->standardIcon(QStyle::SP_MessageBoxQuestion)); switch (dialog.exec()) { case QDialog::Accepted: if (dialog.isChecked()) { qzSettings->autoOpenProtocols.append(protocol); qzSettings->saveSettings(); } QDesktopServices::openUrl(url); break; case QDialog::Rejected: if (dialog.isChecked()) { qzSettings->blockedProtocols.append(protocol); qzSettings->saveSettings(); } break; default: break; } } void WebPage::desktopServicesOpen(const QUrl &url) { // Open same url only once in 2 secs if (s_lastUnsupportedUrl != url || QTime::currentTime() > s_lastUnsupportedUrlTime.addSecs(2)) { s_lastUnsupportedUrl = url; s_lastUnsupportedUrlTime = QTime::currentTime(); QDesktopServices::openUrl(url); } else { qWarning() << "WebPage::desktopServicesOpen Url" << url << "has already been opened!\n" "Ignoring it to prevent infinite loop!"; } } void WebPage::downloadRequested(const QNetworkRequest &request) { DownloadManager* dManager = mApp->downManager(); dManager->download(request, this); } void WebPage::windowCloseRequested() { WebView* webView = qobject_cast(view()); if (!webView) { return; } webView->closeView(); } #if (QTWEBKIT_VERSION >= QTWEBKIT_VERSION_CHECK(2, 2, 0)) void WebPage::featurePermissionRequested(QWebFrame* frame, const QWebPage::Feature &feature) { mApp->html5permissions()->requestPermissions(this, frame, feature); } #endif bool WebPage::event(QEvent* event) { if (event->type() == QEvent::Leave) { // QWebPagePrivate::leaveEvent(): // 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. // However, its implementation fake mouse move event on QCursor::pos() // position that is in global screen coordinates. So instead of // really faking it, it just creates mouse move event somewhere in // page. It can for example focus a link, and then link url gets // stuck in status bar message. // So we are faking mouse move event with proper coordinates for // so called "just outside of the widget" position const QPoint cursorPos = view()->mapFromGlobal(QCursor::pos()); QPoint mousePos; if (cursorPos.y() < 0) { // Left on top mousePos = QPoint(cursorPos.x(), -1); } else if (cursorPos.x() < 0) { // Left on left mousePos = QPoint(-1, cursorPos.y()); } else if (cursorPos.y() > view()->height()) { // Left on bottom mousePos = QPoint(cursorPos.x(), view()->height() + 1); } else { // Left on right mousePos = QPoint(view()->width() + 1, cursorPos.y()); } QMouseEvent fakeEvent(QEvent::MouseMove, mousePos, Qt::NoButton, Qt::NoButton, Qt::NoModifier); return QWebPage::event(&fakeEvent); } return QWebPage::event(event); } void WebPage::setSSLCertificate(const QSslCertificate &cert) { // if (cert != m_SslCert) m_sslCert = cert; } QSslCertificate WebPage::sslCertificate() { if (url().scheme() == QLatin1String("https") && qz_isCertificateValid(m_sslCert)) { return m_sslCert; } return QSslCertificate(); } bool WebPage::acceptNavigationRequest(QWebFrame* frame, const QNetworkRequest &request, NavigationType type) { m_lastRequestType = type; m_lastRequestUrl = request.url(); const QString &scheme = request.url().scheme(); if (scheme == QLatin1String("mailto") || scheme == QLatin1String("ftp")) { desktopServicesOpen(request.url()); return false; } if (type == QWebPage::NavigationTypeFormResubmitted) { QString message = tr("To show this page, QupZilla must resend request which do it again \n" "(like searching on making an shopping, which has been already done.)"); bool result = (QMessageBox::question(view(), tr("Confirm form resubmission"), message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes); if (!result) { return false; } } bool accept = QWebPage::acceptNavigationRequest(frame, request, type); return accept; } void WebPage::populateNetworkRequest(QNetworkRequest &request) { WebPage* pagePointer = this; QVariant variant = qVariantFromValue((void*) pagePointer); request.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100), variant); if (m_lastRequestUrl == request.url()) { request.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 101), m_lastRequestType); if (m_lastRequestType == NavigationTypeLinkClicked) { request.setRawHeader("X-QupZilla-UserLoadAction", QByteArray("1")); } } } QWebPage* WebPage::createWindow(QWebPage::WebWindowType type) { return new PopupWebPage(type, p_QupZilla); } QObject* WebPage::createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) { Q_UNUSED(url) Q_UNUSED(paramNames) Q_UNUSED(paramValues) if (classid == QLatin1String("RecoveryWidget") && mApp->restoreManager()) { return new RecoveryWidget(qobject_cast(view()), p_QupZilla); } else { mainFrame()->load(QUrl("qupzilla:start")); } return 0; } void WebPage::addAdBlockRule(const AdBlockRule* rule, const QUrl &url) { AdBlockedEntry entry; entry.rule = rule; entry.url = url; if (!m_adBlockedEntries.contains(entry)) { m_adBlockedEntries.append(entry); } } void WebPage::cleanBlockedObjects() { AdBlockManager* manager = AdBlockManager::instance(); if (!manager->isEnabled()) { return; } const QWebElement &docElement = mainFrame()->documentElement(); foreach(const AdBlockedEntry & entry, m_adBlockedEntries) { const QString &urlString = entry.url.toString(); if (urlString.endsWith(QLatin1String(".js")) || urlString.endsWith(QLatin1String(".css"))) { continue; } QString urlEnd; int pos = urlString.lastIndexOf(QLatin1Char('/')); if (pos > 8) { urlEnd = urlString.mid(pos + 1); } if (urlString.endsWith(QLatin1Char('/'))) { urlEnd = urlString.left(urlString.size() - 1); } QString selector("img[src$=\"%1\"], iframe[src$=\"%1\"],embed[src$=\"%1\"]"); QWebElementCollection elements = docElement.findAll(selector.arg(urlEnd)); foreach(QWebElement element, elements) { QString src = element.attribute("src"); src.remove(QLatin1String("../")); if (urlString.contains(src)) { element.setStyleProperty("display", "none"); } } } // Apply domain-specific element hiding rules QString elementHiding = AdBlockManager::instance()->elementHidingRulesForDomain(url()); if (elementHiding.isEmpty()) { return; } elementHiding.append(QLatin1String("{display: none !important;}\n")); QWebElement bodyElement = docElement.findFirst("body"); bodyElement.appendInside("