Refactoring.

This commit is contained in:
Martin Rotter 2016-01-15 09:18:14 +01:00
parent a77a0a20cb
commit b91d7b926d
19 changed files with 103 additions and 115 deletions

View File

@ -127,7 +127,7 @@ void AdBlockMatcher::update() {
QHash<QString, const AdBlockRule*> css_rules_hash; QHash<QString, const AdBlockRule*> css_rules_hash;
QVector<const AdBlockRule*> exception_css_rules; QVector<const AdBlockRule*> exception_css_rules;
foreach (AdBlockSubscription *subscription, m_manager->subscriptions()) { foreach (const AdBlockSubscription *subscription, m_manager->subscriptions()) {
foreach (const AdBlockRule *rule, subscription->allRules()) { foreach (const AdBlockRule *rule, subscription->allRules()) {
// Don't add internally disabled rules to cache // Don't add internally disabled rules to cache
if (rule->isInternalDisabled()) { if (rule->isInternalDisabled()) {

View File

@ -53,7 +53,7 @@ class AdBlockMatcher : public QObject {
void enabledChanged(bool enabled); void enabledChanged(bool enabled);
private: private:
AdBlockManager* m_manager; AdBlockManager *m_manager;
QVector<AdBlockRule*> m_createdRules; QVector<AdBlockRule*> m_createdRules;
QVector<const AdBlockRule*> m_networkExceptionRules; QVector<const AdBlockRule*> m_networkExceptionRules;

View File

@ -72,6 +72,7 @@ AdBlockRule::~AdBlockRule() {
AdBlockRule *AdBlockRule::copy() const { AdBlockRule *AdBlockRule::copy() const {
AdBlockRule* rule = new AdBlockRule(); AdBlockRule* rule = new AdBlockRule();
rule->m_subscription = m_subscription; rule->m_subscription = m_subscription;
rule->m_type = m_type; rule->m_type = m_type;
rule->m_options = m_options; rule->m_options = m_options;

View File

@ -38,7 +38,7 @@ bool AdBlockSearchTree::add(const AdBlockRule *rule) {
} }
const QString filter = rule->m_matchString; const QString filter = rule->m_matchString;
int len = filter.size(); const int len = filter.size();
if (len <= 0) { if (len <= 0) {
qWarning("Inserting rule with filter len <= 0!"); qWarning("Inserting rule with filter len <= 0!");
@ -67,7 +67,7 @@ bool AdBlockSearchTree::add(const AdBlockRule *rule) {
const AdBlockRule *AdBlockSearchTree::find(const QNetworkRequest &request, const QString &domain, const AdBlockRule *AdBlockSearchTree::find(const QNetworkRequest &request, const QString &domain,
const QString &url_string) const { const QString &url_string) const {
int len = url_string.size(); const int len = url_string.size();
if (len <= 0) { if (len <= 0) {
return NULL; return NULL;

View File

@ -36,8 +36,8 @@ BaseNetworkAccessManager::~BaseNetworkAccessManager() {
void BaseNetworkAccessManager::loadSettings() { void BaseNetworkAccessManager::loadSettings() {
QNetworkProxy new_proxy; QNetworkProxy new_proxy;
QNetworkProxy::ProxyType selected_proxy_type = static_cast<QNetworkProxy::ProxyType>(qApp->settings()->value(GROUP(Proxy), const QNetworkProxy::ProxyType selected_proxy_type = static_cast<QNetworkProxy::ProxyType>(qApp->settings()->value(GROUP(Proxy),
SETTING(Proxy::Type)).toInt()); SETTING(Proxy::Type)).toInt());
if (selected_proxy_type == QNetworkProxy::NoProxy) { if (selected_proxy_type == QNetworkProxy::NoProxy) {
// No extra setting is needed, set new proxy and exit this method. // No extra setting is needed, set new proxy and exit this method.
@ -47,8 +47,7 @@ void BaseNetworkAccessManager::loadSettings() {
setProxy(QNetworkProxy::applicationProxy()); setProxy(QNetworkProxy::applicationProxy());
} }
else { else {
const Settings *settings = qApp->settings();
Settings *settings = qApp->settings();
// Custom proxy is selected, set it up. // Custom proxy is selected, set it up.
new_proxy.setType(selected_proxy_type); new_proxy.setType(selected_proxy_type);

View File

@ -35,7 +35,6 @@ Downloader::Downloader(QObject *parent)
} }
Downloader::~Downloader() { Downloader::~Downloader() {
m_downloadManager->deleteLater();
} }
void Downloader::downloadFile(const QString &url, int timeout, bool protected_contents, const QString &username, void Downloader::downloadFile(const QString &url, int timeout, bool protected_contents, const QString &username,
@ -101,7 +100,7 @@ void Downloader::finished() {
m_timer->stop(); m_timer->stop();
// In this phase, some part of downloading process is completed. // In this phase, some part of downloading process is completed.
QUrl redirection_url = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); const QUrl redirection_url = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (redirection_url.isValid()) { if (redirection_url.isValid()) {
// Communication indicates that HTTP redirection is needed. // Communication indicates that HTTP redirection is needed.

View File

@ -76,7 +76,7 @@ class Downloader : public QObject {
private: private:
QNetworkReply *m_activeReply; QNetworkReply *m_activeReply;
SilentNetworkAccessManager *m_downloadManager; QScopedPointer<SilentNetworkAccessManager> m_downloadManager;
QTimer *m_timer; QTimer *m_timer;
QHash<QByteArray, QByteArray> m_customHeaders; QHash<QByteArray, QByteArray> m_customHeaders;
QByteArray m_inputData; QByteArray m_inputData;

View File

@ -97,11 +97,11 @@ void DownloadItem::getFileName() {
return; return;
} }
QString download_directory = qApp->downloadManager()->downloadDirectory(); const QString download_directory = qApp->downloadManager()->downloadDirectory();
QString chosen_filename = saveFileName(download_directory); QString chosen_filename = saveFileName(download_directory);
QString filename_for_prompt = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() + const QString filename_for_prompt = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() +
QDir::separator() + QDir::separator() +
QFileInfo(chosen_filename).fileName(); QFileInfo(chosen_filename).fileName();
if (m_requestFileName) { if (m_requestFileName) {
// User must provide the path where he wants to save downloaded file in. // User must provide the path where he wants to save downloaded file in.
@ -118,7 +118,7 @@ void DownloadItem::getFileName() {
return; return;
} }
QFileInfo file_info = QFileInfo(chosen_filename); const QFileInfo file_info = QFileInfo(chosen_filename);
qApp->settings()->setValue(GROUP(Downloads), Downloads::TargetExplicitDirectory, qApp->settings()->setValue(GROUP(Downloads), Downloads::TargetExplicitDirectory,
QDir::toNativeSeparators(QFileInfo(chosen_filename).absolutePath())); QDir::toNativeSeparators(QFileInfo(chosen_filename).absolutePath()));
@ -128,7 +128,7 @@ void DownloadItem::getFileName() {
m_output.setFileName(chosen_filename); m_output.setFileName(chosen_filename);
// Check file path for saving. // Check file path for saving.
QDir save_dir = QFileInfo(m_output.fileName()).dir(); const QDir save_dir = QFileInfo(m_output.fileName()).dir();
if (!save_dir.exists() && !save_dir.mkpath(save_dir.absolutePath())) { if (!save_dir.exists() && !save_dir.mkpath(save_dir.absolutePath())) {
stop(); stop();
@ -149,8 +149,8 @@ QString DownloadItem::saveFileName(const QString &directory) const {
QString path; QString path;
if (m_reply->hasRawHeader("Content-Disposition")) { if (m_reply->hasRawHeader("Content-Disposition")) {
QString value = QLatin1String(m_reply->rawHeader("Content-Disposition")); const QString value = QLatin1String(m_reply->rawHeader("Content-Disposition"));
int pos = value.indexOf(QL1S("filename=")); const int pos = value.indexOf(QL1S("filename="));
if (pos != -1) { if (pos != -1) {
QString name = value.mid(pos + 9); QString name = value.mid(pos + 9);
@ -167,7 +167,7 @@ QString DownloadItem::saveFileName(const QString &directory) const {
path = m_url.path(); path = m_url.path();
} }
QFileInfo info(path); const QFileInfo info(path);
QString base_name = info.completeBaseName(); QString base_name = info.completeBaseName();
QString end_name = info.suffix(); QString end_name = info.suffix();
@ -213,10 +213,10 @@ void DownloadItem::openFile() {
void DownloadItem::openFolder() { void DownloadItem::openFolder() {
if (m_output.exists()) { if (m_output.exists()) {
QString folder = QDir::toNativeSeparators(QFileInfo(m_output.fileName()).absoluteDir().absolutePath()); const QString folder = QDir::toNativeSeparators(QFileInfo(m_output.fileName()).absoluteDir().absolutePath());
#if defined(Q_OS_WIN32) #if defined(Q_OS_WIN32)
QString file = QDir::toNativeSeparators(m_output.fileName()); const QString file = QDir::toNativeSeparators(m_output.fileName());
if (!QProcess::startDetached(QString("explorer.exe /select, \"") + file + "\"")) { if (!QProcess::startDetached(QString("explorer.exe /select, \"") + file + "\"")) {
MessageBox::show(this, QMessageBox::Warning, tr("Cannot open directory"), tr("Cannot open output directory. Open it manually."), QString(), folder); MessageBox::show(this, QMessageBox::Warning, tr("Cannot open directory"), tr("Cannot open output directory. Open it manually."), QString(), folder);
@ -375,32 +375,32 @@ void DownloadItem::updateDownloadInfoLabel() {
return; return;
} }
qint64 bytesTotal = m_reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); const qint64 bytes_total = m_reply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
bool running = !downloadedSuccessfully(); bool running = !downloadedSuccessfully();
double speed = currentSpeed(); double speed = currentSpeed();
double timeRemaining = remainingTime(); double time_remaining = remainingTime();
QString info; QString info;
if (running) { if (running) {
QString remaining; QString remaining;
if (bytesTotal != 0) { if (bytes_total != 0) {
remaining = DownloadManager::timeString(timeRemaining); remaining = DownloadManager::timeString(time_remaining);
} }
info = QString(tr("%1 of %2 (%3 per second) - %4")).arg(DownloadManager::dataString(m_bytesReceived), info = QString(tr("%1 of %2 (%3 per second) - %4")).arg(DownloadManager::dataString(m_bytesReceived),
bytesTotal == 0 ? QSL("?") : DownloadManager::dataString(bytesTotal), bytes_total == 0 ? QSL("?") : DownloadManager::dataString(bytes_total),
DownloadManager::dataString((int)speed), DownloadManager::dataString((int)speed),
remaining); remaining);
} }
else { else {
if (m_bytesReceived == bytesTotal) { if (m_bytesReceived == bytes_total) {
info = DownloadManager::dataString(m_output.size()); info = DownloadManager::dataString(m_output.size());
} }
else { else {
info = tr("%1 of %2 - download completed").arg(DownloadManager::dataString(m_bytesReceived), info = tr("%1 of %2 - download completed").arg(DownloadManager::dataString(m_bytesReceived),
DownloadManager::dataString(bytesTotal)); DownloadManager::dataString(bytes_total));
} }
} }
@ -447,7 +447,7 @@ void DownloadItem::updateInfoAndUrlLabel() {
DownloadManager::DownloadManager(QWidget *parent) : TabContent(parent), m_ui(new Ui::DownloadManager), DownloadManager::DownloadManager(QWidget *parent) : TabContent(parent), m_ui(new Ui::DownloadManager),
m_autoSaver(new AutoSaver(this)), m_model(new DownloadModel(this)), m_autoSaver(new AutoSaver(this)), m_model(new DownloadModel(this)),
m_networkManager(SilentNetworkAccessManager::instance()), m_iconProvider(0), m_removePolicy(Never) { m_networkManager(SilentNetworkAccessManager::instance()), m_iconProvider(NULL), m_removePolicy(Never) {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->m_viewDownloads->setShowGrid(false); m_ui->m_viewDownloads->setShowGrid(false);
m_ui->m_viewDownloads->verticalHeader()->hide(); m_ui->m_viewDownloads->verticalHeader()->hide();
@ -465,19 +465,13 @@ DownloadManager::~DownloadManager() {
m_autoSaver->changeOccurred(); m_autoSaver->changeOccurred();
m_autoSaver->saveIfNeccessary(); m_autoSaver->saveIfNeccessary();
if (m_iconProvider != NULL) {
delete m_iconProvider;
}
delete m_ui;
qDebug("Destroying DownloadManager instance."); qDebug("Destroying DownloadManager instance.");
} }
int DownloadManager::activeDownloads() const { int DownloadManager::activeDownloads() const {
int count = 0; int count = 0;
foreach (DownloadItem *download, m_downloads) { foreach (const DownloadItem *download, m_downloads) {
if (download->downloading()) { if (download->downloading()) {
count++; count++;
} }
@ -490,7 +484,7 @@ int DownloadManager::downloadProgress() const {
qint64 bytes_total = 0; qint64 bytes_total = 0;
qint64 bytes_received = 0; qint64 bytes_received = 0;
foreach (DownloadItem *download, m_downloads) { foreach (const DownloadItem *download, m_downloads) {
if (download->downloading()) { if (download->downloading()) {
bytes_total += download->bytesTotal(); bytes_total += download->bytesTotal();
bytes_received += download->bytesReceived(); bytes_received += download->bytesReceived();
@ -520,9 +514,9 @@ void DownloadManager::handleUnsupportedContent(QNetworkReply *reply) {
return; return;
} }
QVariant header = reply->header(QNetworkRequest::ContentLengthHeader); const QVariant header = reply->header(QNetworkRequest::ContentLengthHeader);
bool ok; bool ok;
int size = header.toInt(&ok); const int size = header.toInt(&ok);
if (ok && size == 0) { if (ok && size == 0) {
return; return;
@ -541,7 +535,7 @@ void DownloadManager::addItem(DownloadItem *item) {
connect(item, SIGNAL(progress(qint64,qint64)), this, SLOT(itemProgress())); connect(item, SIGNAL(progress(qint64,qint64)), this, SLOT(itemProgress()));
connect(item, SIGNAL(downloadFinished()), this, SLOT(itemFinished())); connect(item, SIGNAL(downloadFinished()), this, SLOT(itemFinished()));
int row = m_downloads.count(); const int row = m_downloads.count();
m_model->beginInsertRows(QModelIndex(), row, row); m_model->beginInsertRows(QModelIndex(), row, row);
m_downloads.append(item); m_downloads.append(item);
m_model->endInsertRows(); m_model->endInsertRows();
@ -585,14 +579,14 @@ void DownloadManager::itemProgress() {
} }
void DownloadManager::updateRow(DownloadItem *item) { void DownloadManager::updateRow(DownloadItem *item) {
int row = m_downloads.indexOf(item); const int row = m_downloads.indexOf(item);
if (row == -1) { if (row == -1) {
return; return;
} }
if (!m_iconProvider) { if (m_iconProvider.isNull()) {
m_iconProvider = new QFileIconProvider(); m_iconProvider.reset(new QFileIconProvider());
} }
QIcon icon = m_iconProvider->icon(item->m_output.fileName()); QIcon icon = m_iconProvider->icon(item->m_output.fileName());
@ -662,7 +656,7 @@ void DownloadManager::save() const {
} }
void DownloadManager::load() { void DownloadManager::load() {
Settings *settings = qApp->settings(); const Settings *settings = qApp->settings();
int i = 0; int i = 0;
// Restore the policy. // Restore the policy.

View File

@ -146,11 +146,11 @@ class DownloadManager : public TabContent {
private: private:
void addItem(DownloadItem *item); void addItem(DownloadItem *item);
Ui::DownloadManager *m_ui; QScopedPointer<Ui::DownloadManager> m_ui;
AutoSaver *m_autoSaver; AutoSaver *m_autoSaver;
DownloadModel *m_model; DownloadModel *m_model;
QNetworkAccessManager *m_networkManager; QNetworkAccessManager *m_networkManager;
QFileIconProvider *m_iconProvider; QScopedPointer<QFileIconProvider> m_iconProvider;
QList<DownloadItem*> m_downloads; QList<DownloadItem*> m_downloads;
RemovePolicy m_removePolicy; RemovePolicy m_removePolicy;
QString m_downloadDirectory; QString m_downloadDirectory;

View File

@ -59,8 +59,8 @@
#include <QTextCodec> #include <QTextCodec>
GoogleSuggest::GoogleSuggest(LocationLineEdit *editor, QObject *parent) : QObject(parent), editor(editor) { GoogleSuggest::GoogleSuggest(LocationLineEdit *editor, QObject *parent)
popup = new QListWidget(); : QObject(parent), editor(editor), popup(new QListWidget()) {
popup->setWindowFlags(Qt::Popup); popup->setWindowFlags(Qt::Popup);
popup->setFocusPolicy(Qt::NoFocus); popup->setFocusPolicy(Qt::NoFocus);
popup->setFocusProxy(editor); popup->setFocusProxy(editor);
@ -74,17 +74,16 @@ GoogleSuggest::GoogleSuggest(LocationLineEdit *editor, QObject *parent) : QObjec
timer->setSingleShot(true); timer->setSingleShot(true);
timer->setInterval(500); timer->setInterval(500);
connect(popup, SIGNAL(itemClicked(QListWidgetItem*)), SLOT(doneCompletion())); connect(popup.data(), SIGNAL(itemClicked(QListWidgetItem*)), SLOT(doneCompletion()));
connect(timer, SIGNAL(timeout()), SLOT(autoSuggest())); connect(timer, SIGNAL(timeout()), SLOT(autoSuggest()));
connect(editor, SIGNAL(textEdited(QString)), timer, SLOT(start())); connect(editor, SIGNAL(textEdited(QString)), timer, SLOT(start()));
} }
GoogleSuggest::~GoogleSuggest() { GoogleSuggest::~GoogleSuggest() {
delete popup;
} }
bool GoogleSuggest::eventFilter(QObject *object, QEvent *event) { bool GoogleSuggest::eventFilter(QObject *object, QEvent *event) {
if (object != popup) { if (object != popup.data()) {
return false; return false;
} }
@ -96,7 +95,7 @@ bool GoogleSuggest::eventFilter(QObject *object, QEvent *event) {
if (event->type() == QEvent::KeyPress) { if (event->type() == QEvent::KeyPress) {
bool consumed = false; bool consumed = false;
int key = static_cast<QKeyEvent*>(event)->key(); const int key = static_cast<QKeyEvent*>(event)->key();
switch (key) { switch (key) {
case Qt::Key_Enter: case Qt::Key_Enter:
@ -139,7 +138,7 @@ void GoogleSuggest::showCompletion(const QStringList &choices) {
popup->clear(); popup->clear();
foreach (const QString &choice, choices) { foreach (const QString &choice, choices) {
new QListWidgetItem(choice, popup); new QListWidgetItem(choice, popup.data());
} }
popup->setCurrentItem(popup->item(0)); popup->setCurrentItem(popup->item(0));
@ -176,20 +175,20 @@ void GoogleSuggest::autoSuggest() {
} }
void GoogleSuggest::handleNetworkData() { void GoogleSuggest::handleNetworkData() {
QNetworkReply *reply = static_cast<QNetworkReply*>(sender()); QScopedPointer<QNetworkReply> reply(static_cast<QNetworkReply*>(sender()));
if (!reply->error()) { if (!reply->error()) {
QStringList choices; QStringList choices;
QDomDocument xml; QDomDocument xml;
QByteArray response = reply->readAll(); QByteArray response = reply->readAll();
QTextCodec *c = QTextCodec::codecForUtfText(response); const QTextCodec *c = QTextCodec::codecForUtfText(response);
xml.setContent(c->toUnicode(response)); xml.setContent(c->toUnicode(response));
QDomNodeList suggestions = xml.elementsByTagName(QSL("suggestion")); QDomNodeList suggestions = xml.elementsByTagName(QSL("suggestion"));
for (int i = 0; i < suggestions.size(); i++) { for (int i = 0; i < suggestions.size(); i++) {
QDomElement element = suggestions.at(i).toElement(); const QDomElement element = suggestions.at(i).toElement();
if (element.attributes().contains(QSL("data"))) { if (element.attributes().contains(QSL("data"))) {
choices.append(element.attribute(QSL("data"))); choices.append(element.attribute(QSL("data")));
@ -198,6 +197,4 @@ void GoogleSuggest::handleNetworkData() {
showCompletion(choices); showCompletion(choices);
} }
reply->deleteLater();
} }

View File

@ -74,7 +74,7 @@ class GoogleSuggest : public QObject {
private: private:
LocationLineEdit *editor; LocationLineEdit *editor;
QListWidget *popup; QScopedPointer<QListWidget> popup;
QTimer *timer; QTimer *timer;
}; };

View File

@ -34,8 +34,8 @@ NetworkFactory::NetworkFactory() {
QStringList NetworkFactory::extractFeedLinksFromHtmlPage(const QUrl &url, const QString &html) { QStringList NetworkFactory::extractFeedLinksFromHtmlPage(const QUrl &url, const QString &html) {
QStringList feeds; QStringList feeds;
QRegExp rx(FEED_REGEX_MATCHER, Qt::CaseInsensitive); const QRegExp rx(FEED_REGEX_MATCHER, Qt::CaseInsensitive);
QRegExp rx_href(FEED_HREF_REGEX_MATCHER, Qt::CaseInsensitive); const QRegExp rx_href(FEED_HREF_REGEX_MATCHER, Qt::CaseInsensitive);
for (int pos = 0; (pos = rx.indexIn(html, pos)) != -1; pos += rx.matchedLength()) { for (int pos = 0; (pos = rx.indexIn(html, pos)) != -1; pos += rx.matchedLength()) {
QString link_element = html.mid(pos, rx.matchedLength()); QString link_element = html.mid(pos, rx.matchedLength());
@ -130,9 +130,9 @@ QNetworkReply::NetworkError NetworkFactory::downloadIcon(const QList<QString> &u
foreach (const QString &url, urls) { foreach (const QString &url, urls) {
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
QString google_s2_with_url = QString("http://www.google.com/s2/favicons?domain=%1").arg(url.toHtmlEscaped()); const QString google_s2_with_url = QString("http://www.google.com/s2/favicons?domain=%1").arg(url.toHtmlEscaped());
#else #else
QString google_s2_with_url = QString("http://www.google.com/s2/favicons?domain=%1").arg(Qt::escape(url)); const QString google_s2_with_url = QString("http://www.google.com/s2/favicons?domain=%1").arg(Qt::escape(url));
#endif #endif
QByteArray icon_data; QByteArray icon_data;
network_result = downloadFile(google_s2_with_url, timeout, icon_data).first; network_result = downloadFile(google_s2_with_url, timeout, icon_data).first;

View File

@ -306,7 +306,7 @@ WebBrowser::~WebBrowser() {
// Remove this instance from the global list of web browsers. // Remove this instance from the global list of web browsers.
m_runningWebBrowsers.removeAll(this); m_runningWebBrowsers.removeAll(this);
// Delete members. // Delete members. Do not use scoped pointers here.
delete m_layout; delete m_layout;
delete m_zoomButtons; delete m_zoomButtons;
delete m_actionZoom; delete m_actionZoom;

View File

@ -45,9 +45,9 @@ void WebBrowserNetworkAccessManager::onAuthenticationRequired(QNetworkReply *rep
QNetworkReply *WebBrowserNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData) { QNetworkReply *WebBrowserNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData) {
if (m_page != NULL) { if (m_page != NULL) {
QNetworkRequest pageRequest = request; QNetworkRequest page_request = request;
m_page->populateNetworkRequest(pageRequest); m_page->populateNetworkRequest(page_request);
return WebBrowserNetworkAccessManager::instance()->createRequest(op, pageRequest, outgoingData); return WebBrowserNetworkAccessManager::instance()->createRequest(op, page_request, outgoingData);
} }
if (op == QNetworkAccessManager::GetOperation) { if (op == QNetworkAccessManager::GetOperation) {

View File

@ -38,17 +38,16 @@ class WebBrowserNetworkAccessManager : public BaseNetworkAccessManager {
// used by ALL web browsers and download manager. // used by ALL web browsers and download manager.
static WebBrowserNetworkAccessManager *instance(); static WebBrowserNetworkAccessManager *instance();
protected:
QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData);
protected slots: protected slots:
void onAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator); void onAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator);
private: private:
WebPage *m_page; WebPage *m_page;
static QPointer<WebBrowserNetworkAccessManager> s_instance; static QPointer<WebBrowserNetworkAccessManager> s_instance;
// QNetworkAccessManager interface
protected:
QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData);
}; };
#endif // WEBBROWSERNETWORKACCESSMANAGER_H #endif // WEBBROWSERNETWORKACCESSMANAGER_H

View File

@ -21,7 +21,7 @@ WebFactory::~WebFactory() {
} }
void WebFactory::loadState() { void WebFactory::loadState() {
Settings *settings = qApp->settings(); const Settings *settings = qApp->settings();
switchJavascript(settings->value(GROUP(Browser), SETTING(Browser::JavascriptEnabled)).toBool(), false); switchJavascript(settings->value(GROUP(Browser), SETTING(Browser::JavascriptEnabled)).toBool(), false);
switchImages(settings->value(GROUP(Browser), SETTING(Browser::ImagesEnabled)).toBool(), false); switchImages(settings->value(GROUP(Browser), SETTING(Browser::ImagesEnabled)).toBool(), false);
@ -30,8 +30,8 @@ void WebFactory::loadState() {
bool WebFactory::sendMessageViaEmail(const Message &message) { bool WebFactory::sendMessageViaEmail(const Message &message) {
if (qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailEnabled)).toBool()) { if (qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailEnabled)).toBool()) {
QString browser = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailExecutable)).toString(); const QString browser = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailExecutable)).toString();
QString arguments = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailArguments)).toString(); const QString arguments = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalEmailArguments)).toString();
return QProcess::startDetached(QString("\"") + browser + QSL("\" ") + arguments.arg(message.m_title, return QProcess::startDetached(QString("\"") + browser + QSL("\" ") + arguments.arg(message.m_title,
stripTags(message.m_contents))); stripTags(message.m_contents)));
@ -46,21 +46,20 @@ bool WebFactory::sendMessageViaEmail(const Message &message) {
bool WebFactory::openUrlInExternalBrowser(const QString &url) { bool WebFactory::openUrlInExternalBrowser(const QString &url) {
if (qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserEnabled)).toBool()) { if (qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserEnabled)).toBool()) {
QString browser = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserExecutable)).toString(); const QString browser = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserExecutable)).toString();
QString arguments = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserArguments)).toString(); const QString arguments = qApp->settings()->value(GROUP(Browser), SETTING(Browser::CustomExternalBrowserArguments)).toString();
QString call_line = "\"" + browser + "\" \"" + arguments.arg(url) + "\""; const QString call_line = "\"" + browser + "\" \"" + arguments.arg(url) + "\"";
qDebug("Running command '%s'.", qPrintable(call_line)); qDebug("Running command '%s'.", qPrintable(call_line));
bool result = QProcess::startDetached(call_line); const bool result = QProcess::startDetached(call_line);
if (!result) { if (!result) {
qDebug("External web browser call failed."); qDebug("External web browser call failed.");
} }
return result; return result;
//return QProcess::startDetached(QString("\"") + browser + QSL("\""), QStringList() << arguments.arg(url));
} }
else { else {
return QDesktopServices::openUrl(url); return QDesktopServices::openUrl(url);

View File

@ -63,6 +63,7 @@ void WebPage::finished() {
void WebPage::cleanBlockedObjects() { void WebPage::cleanBlockedObjects() {
AdBlockManager *manager = AdBlockManager::instance(); AdBlockManager *manager = AdBlockManager::instance();
if (!manager->isEnabled()) { if (!manager->isEnabled()) {
return; return;
} }
@ -101,6 +102,7 @@ void WebPage::cleanBlockedObjects() {
// Apply domain-specific element hiding rules // Apply domain-specific element hiding rules
QString element_hiding = manager->elementHidingRulesForDomain(mainFrame()->url()); QString element_hiding = manager->elementHidingRulesForDomain(mainFrame()->url());
if (element_hiding.isEmpty()) { if (element_hiding.isEmpty()) {
return; return;
} }
@ -161,7 +163,7 @@ void WebPage::populateNetworkRequest(QNetworkRequest &request) {
void WebPage::handleUnsupportedContent(QNetworkReply *reply) { void WebPage::handleUnsupportedContent(QNetworkReply *reply) {
if (reply != NULL) { if (reply != NULL) {
QUrl reply_url = reply->url(); const QUrl reply_url = reply->url();
if (reply_url.scheme() == QL1S("abp")) { if (reply_url.scheme() == QL1S("abp")) {
return; return;
@ -187,7 +189,7 @@ QString WebPage::toHtml() const {
bool WebPage::acceptNavigationRequest(QWebFrame *frame, bool WebPage::acceptNavigationRequest(QWebFrame *frame,
const QNetworkRequest &request, const QNetworkRequest &request,
QWebPage::NavigationType type) { QWebPage::NavigationType type) {
QString scheme = request.url().scheme(); const QString scheme = request.url().scheme();
if (scheme == QL1S("mailto") || scheme == QL1S("ftp")) { if (scheme == QL1S("mailto") || scheme == QL1S("ftp")) {
qWarning("Received request with scheme '%s', blocking it.", qPrintable(scheme)); qWarning("Received request with scheme '%s', blocking it.", qPrintable(scheme));

View File

@ -43,15 +43,13 @@ class WebPage : public QWebPage {
QString toHtml() const; QString toHtml() const;
QString toPlainText() const; QString toPlainText() const;
void populateNetworkRequest(QNetworkRequest &request);
bool isLoading() const; bool isLoading() const;
static bool isPointerSafeToUse(WebPage *page);
void addAdBlockRule(const AdBlockRule *rule, const QUrl &url);
QVector<AdBlockedEntry> adBlockedEntries() const; QVector<AdBlockedEntry> adBlockedEntries() const;
void populateNetworkRequest(QNetworkRequest &request);
void addAdBlockRule(const AdBlockRule *rule, const QUrl &url);
static bool isPointerSafeToUse(WebPage *page);
private slots: private slots:
void progress(int prog); void progress(int prog);

View File

@ -85,27 +85,27 @@ void WebView::searchTextViaGoogle() {
void WebView::saveCurrentPageToFile() { void WebView::saveCurrentPageToFile() {
QString selected_file; QString selected_file;
QString implicit_file_base_name = tr("source_page"); const QString implicit_file_base_name = tr("source_page");
// NOTE: It is good to always ask for destination here, since download manager // NOTE: It is good to always ask for destination here, since download manager
// is not displaying afterwards because this is *not* real download actually. // is not displaying afterwards because this is *not* real download actually.
//if (qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::AlwaysPromptForFilename)).toBool()) { //if (qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::AlwaysPromptForFilename)).toBool()) {
QString filter_html = tr("HTML web pages (*.html)"); const QString filter_html = tr("HTML web pages (*.html)");
QString filter; QString filter;
QString selected_filter; QString selected_filter;
QString filename_for_prompt = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() + const QString filename_for_prompt = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() +
QDir::separator() + implicit_file_base_name + QL1S(".html"); QDir::separator() + implicit_file_base_name + QL1S(".html");
// Add more filters here. // Add more filters here.
filter += filter_html; filter += filter_html;
selected_file = QFileDialog::getSaveFileName(this, tr("Select destination file for web page"), selected_file = QFileDialog::getSaveFileName(this, tr("Select destination file for web page"),
filename_for_prompt, filter, &selected_filter); filename_for_prompt, filter, &selected_filter);
if (!selected_file.isEmpty()) { if (!selected_file.isEmpty()) {
qApp->settings()->setValue(GROUP(Downloads), Downloads::TargetExplicitDirectory, qApp->settings()->setValue(GROUP(Downloads), Downloads::TargetExplicitDirectory,
QDir::toNativeSeparators(QFileInfo(selected_file).absolutePath())); QDir::toNativeSeparators(QFileInfo(selected_file).absolutePath()));
} }
/*} /*}
else { else {
QString base_folder = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetDirectory)).toString(); QString base_folder = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetDirectory)).toString();
@ -132,14 +132,14 @@ void WebView::saveCurrentPageToFile() {
QFile selected_file_handle(selected_file); QFile selected_file_handle(selected_file);
if (selected_file_handle.open(QIODevice::WriteOnly | QIODevice::Unbuffered)) { if (selected_file_handle.open(QIODevice::WriteOnly | QIODevice::Unbuffered)) {
QString html_text = page()->mainFrame()->toHtml(); const QString html_text = page()->mainFrame()->toHtml();
QTextStream str(&selected_file_handle); QTextStream str(&selected_file_handle);
str.setCodec("UTF-16"); str.setCodec("UTF-16");
str << html_text; str << html_text;
selected_file_handle.close(); selected_file_handle.close();
} }
else { else {
MessageBox::show(this, QMessageBox::Critical, tr("Cannot save web page"), MessageBox::show(this, QMessageBox::Critical, tr("Cannot save web page"),
tr("Web page cannot be saved because destination file is not writtable.")); tr("Web page cannot be saved because destination file is not writtable."));
} }
@ -299,8 +299,8 @@ void WebView::popupContextMenu(const QPoint &pos) {
context_menu.addAction(m_actionCopySelectedItem); context_menu.addAction(m_actionCopySelectedItem);
context_menu.addAction(m_actionSavePageAs); context_menu.addAction(m_actionSavePageAs);
QUrl hit_url = hit_result.linkUrl(); const QUrl hit_url = hit_result.linkUrl();
QUrl hit_image_url = hit_result.imageUrl(); const QUrl hit_image_url = hit_result.imageUrl();
if (hit_url.isValid()) { if (hit_url.isValid()) {
m_contextLinkUrl = hit_url; m_contextLinkUrl = hit_url;
@ -340,7 +340,7 @@ void WebView::popupContextMenu(const QPoint &pos) {
} }
void WebView::printCurrentPage() { void WebView::printCurrentPage() {
QPointer<QPrintPreviewDialog> print_preview = new QPrintPreviewDialog(this); QScopedPointer<QPrintPreviewDialog> print_preview(new QPrintPreviewDialog(this));
connect(print_preview.data(), SIGNAL(paintRequested(QPrinter*)), this, SLOT(print(QPrinter*))); connect(print_preview.data(), SIGNAL(paintRequested(QPrinter*)), this, SLOT(print(QPrinter*)));
print_preview.data()->exec(); print_preview.data()->exec();
} }
@ -355,8 +355,8 @@ void WebView::mousePressEvent(QMouseEvent *event) {
// Check if user clicked with middle mouse button on some // Check if user clicked with middle mouse button on some
// hyperlink. // hyperlink.
QUrl link_url = hit_result.linkUrl(); const QUrl link_url = hit_result.linkUrl();
QUrl image_url = hit_result.imageUrl(); const QUrl image_url = hit_result.imageUrl();
if (link_url.isValid()) { if (link_url.isValid()) {
emit linkMiddleClicked(link_url); emit linkMiddleClicked(link_url);
@ -377,10 +377,10 @@ void WebView::mousePressEvent(QMouseEvent *event) {
void WebView::mouseReleaseEvent(QMouseEvent *event) { void WebView::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() & Qt::MiddleButton) { if (event->button() & Qt::MiddleButton) {
bool are_gestures_enabled = qApp->settings()->value(GROUP(Browser), SETTING(Browser::GesturesEnabled)).toBool(); const bool are_gestures_enabled = qApp->settings()->value(GROUP(Browser), SETTING(Browser::GesturesEnabled)).toBool();
if (are_gestures_enabled) { if (are_gestures_enabled) {
QPoint release_point = event->pos(); const QPoint release_point = event->pos();
int left_move = m_gestureOrigin.x() - release_point.x(); int left_move = m_gestureOrigin.x() - release_point.x();
int right_move = -left_move; int right_move = -left_move;
int top_move = m_gestureOrigin.y() - release_point.y(); int top_move = m_gestureOrigin.y() - release_point.y();
@ -423,7 +423,7 @@ void WebView::wheelEvent(QWheelEvent *event) {
} }
bool WebView::increaseWebPageZoom() { bool WebView::increaseWebPageZoom() {
qreal new_factor = zoomFactor() + 0.1; const qreal new_factor = zoomFactor() + 0.1;
if (new_factor >= 0.0 && new_factor <= MAX_ZOOM_FACTOR) { if (new_factor >= 0.0 && new_factor <= MAX_ZOOM_FACTOR) {
setZoomFactor(new_factor); setZoomFactor(new_factor);
@ -435,7 +435,7 @@ bool WebView::increaseWebPageZoom() {
} }
bool WebView::decreaseWebPageZoom() { bool WebView::decreaseWebPageZoom() {
qreal new_factor = zoomFactor() - 0.1; const qreal new_factor = zoomFactor() - 0.1;
if (new_factor >= 0.0 && new_factor <= MAX_ZOOM_FACTOR) { if (new_factor >= 0.0 && new_factor <= MAX_ZOOM_FACTOR) {
setZoomFactor(new_factor); setZoomFactor(new_factor);
@ -447,7 +447,7 @@ bool WebView::decreaseWebPageZoom() {
} }
bool WebView::resetWebPageZoom() { bool WebView::resetWebPageZoom() {
qreal new_factor = 1.0; const qreal new_factor = 1.0;
if (new_factor != zoomFactor()) { if (new_factor != zoomFactor()) {
setZoomFactor(new_factor); setZoomFactor(new_factor);