2 * Copyright © 2022 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser PC <https://www.stoutner.com/privacy-browser-pc>.
6 * Privacy Browser PC is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser PC is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser PC. If not, see <http://www.gnu.org/licenses/>.
20 // Application headers.
21 #include "BrowserView.h"
23 #include "ui_BrowserView.h"
24 #include "databases/CookiesDatabase.h"
25 #include "databases/DomainsDatabase.h"
26 #include "filters/MouseEventFilter.h"
27 #include "helpers/SearchEngineHelper.h"
28 #include "helpers/UserAgentHelper.h"
29 #include "interceptors/UrlRequestInterceptor.h"
30 #include "windows/BrowserWindow.h"
32 // Qt framework headers.
35 // Initialize the public static variables.
36 QString BrowserView::webEngineDefaultUserAgent = QStringLiteral("");
38 // Construct the class.
39 BrowserView::BrowserView(QWidget *parent) : QWidget(parent)
41 // Initialize the variables.
42 privacyWebEngineListPointer = new QList<PrivacyWebEngine*>;
44 // Instantiate the browser view UI.
45 Ui::BrowserView browserViewUi;
48 browserViewUi.setupUi(this);
50 // Get handles for the views.
51 webEngineViewPointer = browserViewUi.webEngineView;
53 // Create an off-the-record profile (the default when no profile name is specified).
54 webEngineProfilePointer = new QWebEngineProfile(QStringLiteral(""));
56 // Create a WebEngine page.
57 webEnginePagePointer = new QWebEnginePage(webEngineProfilePointer);
59 // Set the WebEngine page.
60 webEngineViewPointer->setPage(webEnginePagePointer);
62 // Get handles for the aspects of the WebEngine.
63 webEngineHistoryPointer = webEnginePagePointer->history();
64 webEngineSettingsPointer = webEngineViewPointer->settings();
65 webEngineCookieStorePointer = webEngineProfilePointer->cookieStore();
67 // Initialize the current privacy web engine pointer.
68 currentPrivacyWebEnginePointer = new PrivacyWebEngine(webEngineViewPointer);
70 // Populate the privacy web engine list.
71 privacyWebEngineListPointer->append(currentPrivacyWebEnginePointer);
73 // Set the local storage filter.
74 webEngineCookieStorePointer->setCookieFilter([this](const QWebEngineCookieStore::FilterRequest &filterRequest)
76 //qDebug().noquote().nospace() << "Page URL: " << filterRequest.firstPartyUrl << ", Local storage URL: " << filterRequest.origin << ", Is third-party: " << filterRequest.thirdParty;
78 // Block all third party local storage requests, including the sneaky ones that don't register a first party URL.
79 if (filterRequest.thirdParty || (filterRequest.firstPartyUrl == QStringLiteral("")))
81 //qDebug() << "Request blocked.";
87 /* TODO. Waiting for a solution to <https://redmine.stoutner.com/issues/857>.
88 // Check each tab to see if this local storage request should be allowed.
89 for (PrivacyWebEngine *privacyWebEnginePointer : *privacyWebEngineListPointer)
91 //qDebug().noquote().nospace() << "Local storage: " << privacyWebEnginePointer->localStorageEnabled << ". WebEngine URL: " << webEngineViewPointer->url().host() << ". Request Host: " << filterRequest.firstPartyUrl.host();
93 // Allow this local storage request if it comes from a tab with local storage enabled.
94 if (privacyWebEnginePointer->localStorageEnabled && (webEngineViewPointer->url().host() == filterRequest.firstPartyUrl.host()))
96 //qDebug() << "Request allowed.";
104 // Allow the request if it is first party and local storage is enabled.
105 if (!filterRequest.thirdParty && currentPrivacyWebEnginePointer->localStorageEnabled)
111 //qDebug() << "Request blocked.";
113 // Block any remaining local storage requests.
117 // Process cookie changes.
118 connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), this, SLOT(cookieAdded(QNetworkCookie)));
119 connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), this, SLOT(cookieRemoved(QNetworkCookie)));
121 // Get a list of durable cookies.
122 QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
124 // Add the durable cookies to the store.
125 for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
126 addCookieToStore(*cookiePointer);
128 // Store a copy of the WebEngine default user agent.
129 webEngineDefaultUserAgent = webEngineProfilePointer->httpUserAgent();
131 // Update the URL line edit when the URL changes.
132 connect(webEngineViewPointer, SIGNAL(urlChanged(const QUrl)), this, SLOT(updateUrl(const QUrl)));
134 // Update the progress bar.
135 connect(webEngineViewPointer, SIGNAL(loadStarted()), this, SLOT(loadStarted()));
136 connect(webEngineViewPointer, SIGNAL(loadProgress(const int)), this, SLOT(loadProgress(const int)));
137 connect(webEngineViewPointer, SIGNAL(loadFinished(const bool)), this, SLOT(loadFinished()));
139 // Instantiate the mouse event filter pointer.
140 MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
142 // Install the mouse event filter.
143 qApp->installEventFilter(mouseEventFilterPointer);
145 // Process mouse forward and back commands.
146 connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
147 connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
149 // Listen for hovered link URLs.
150 connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
152 // Instantiate the URL request interceptor.
153 UrlRequestInterceptor *urlRequestInterceptorPointer = new UrlRequestInterceptor();
155 // Set the URL request interceptor.
156 webEngineProfilePointer->setUrlRequestInterceptor(urlRequestInterceptorPointer);
158 // Reapply the domain settings when the host changes.
159 connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings(QString)), this, SLOT(applyDomainSettingsWithoutReloading(QString)));
161 // Don't allow JavaScript to open windows.
162 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
164 // Allow keyboard navigation.
165 webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
167 // Enable full screen support.
168 webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
170 // Require user interaction to play media.
171 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
173 // Limit WebRTC to public IP addresses.
174 webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
176 // Set the focus on the WebEngine view.
177 webEngineViewPointer->setFocus();
180 BrowserView::~BrowserView()
182 // Delay the deletion of the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
183 webEnginePagePointer->deleteLater();
186 // The cookie is copied instead of referenced so that changes made to the cookie do not create a race condition with the display of the cookie in the dialog.
187 void BrowserView::addCookieToStore(QNetworkCookie cookie) const
192 // Check to see if the domain does not start with a `.` because Qt makes this harder than it should be. <https://doc.qt.io/qt-5/qwebenginecookiestore.html#setCookie>
193 if (!cookie.domain().startsWith(QStringLiteral(".")))
196 url.setHost(cookie.domain());
197 url.setScheme(QStringLiteral("https"));
199 // Clear the domain from the cookie.
200 cookie.setDomain(QStringLiteral(""));
203 // Add the cookie to the store.
204 webEngineCookieStorePointer->setCookie(cookie, url);
207 void BrowserView::applyApplicationSettings()
209 // Set the search engine URL.
210 searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
212 // Emit the update search engine actions signal.
213 emit updateSearchEngineActions(Settings::searchEngine());
216 // This exists as a separate function from `applyDomainSettings()` so it can be listed as a slot and function without the need for a boolean argument.
217 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
218 void BrowserView::applyDomainSettingsAndReload()
220 // Apply the domain settings. `true` reloads the website.
221 applyDomainSettings(webEngineViewPointer->url().host(), true);
224 // This exists as a separate function from `applyDomainSettings()` so it can be listed as a slot and function without the need for a boolean argument.
225 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
226 void BrowserView::applyDomainSettingsWithoutReloading(const QString &hostname)
228 // Apply the domain settings `false` does not reload the website.
229 applyDomainSettings(hostname, false);
232 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
233 void BrowserView::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
235 // Get the record for the hostname.
236 QSqlQuery domainQuery = DomainsDatabase::getDomainQuery(hostname);
238 // Check if the hostname has domain settings.
239 if (domainQuery.isValid()) // The hostname has domain settings.
241 // Get the domain record.
242 QSqlRecord domainRecord = domainQuery.record();
244 // Set the JavaScript status.
245 switch (domainRecord.field(DomainsDatabase::JAVASCRIPT).value().toInt())
247 // Set the default JavaScript status.
248 case (DomainsDatabase::SYSTEM_DEFAULT):
250 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
255 // Disable JavaScript.
256 case (DomainsDatabase::DISABLED):
258 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
263 // Enable JavaScript.
264 case (DomainsDatabase::ENABLED):
266 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
272 // Set the local storage status.
273 switch (domainRecord.field(DomainsDatabase::LOCAL_STORAGE).value().toInt())
275 // Set the default local storage status.
276 case (DomainsDatabase::SYSTEM_DEFAULT):
278 currentPrivacyWebEnginePointer->localStorageEnabled = Settings::localStorageEnabled();
283 // Disable local storage.
284 case (DomainsDatabase::DISABLED):
286 currentPrivacyWebEnginePointer->localStorageEnabled = false;
291 // Enable local storage.
292 case (DomainsDatabase::ENABLED):
294 currentPrivacyWebEnginePointer->localStorageEnabled = true;
300 // Set the DOM storage status.
301 switch (domainRecord.field(DomainsDatabase::DOM_STORAGE).value().toInt())
303 // Set the default DOM storage status.
304 case (DomainsDatabase::SYSTEM_DEFAULT):
306 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
311 // Disable DOM storage.
312 case (DomainsDatabase::DISABLED):
314 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
319 // Enable DOM storage.
320 case (DomainsDatabase::ENABLED):
322 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
328 // Set the user agent.
329 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabase::USER_AGENT).value().toString()));
331 // Check if a custom zoom factor is set.
332 if (domainRecord.field(DomainsDatabase::ZOOM_FACTOR).value().toInt())
334 // Store the current zoom factor.
335 currentZoomFactor = domainRecord.field(DomainsDatabase::CUSTOM_ZOOM_FACTOR).value().toDouble();
339 // Reset the current zoom factor.
340 currentZoomFactor = Settings::zoomFactor();
343 // Set the zoom factor. The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
344 webEngineViewPointer->setZoomFactor(currentZoomFactor);
346 // Apply the domain settings palette to the URL line edit.
347 emit updateDomainSettingsIndicator(true, domainRecord.field(DomainsDatabase::DOMAIN_NAME).value().toString());
349 else // The hostname does not have domain settings.
351 // Set the JavaScript status.
352 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
354 // Set the local storage status.
355 currentPrivacyWebEnginePointer->localStorageEnabled = Settings::localStorageEnabled();
358 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
360 // Set the user agent.
361 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
363 // Store the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
364 currentZoomFactor = Settings::zoomFactor();
366 // Set the zoom factor.
367 webEngineViewPointer->setZoomFactor(Settings::zoomFactor());
369 // Apply the no domain settings palette to the URL line edit.
370 emit updateDomainSettingsIndicator(false, QStringLiteral(""));
373 // Emit the update actions signals.
374 emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
375 emit updateLocalStorageAction(currentPrivacyWebEnginePointer->localStorageEnabled);
376 emit updateDomStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
377 emit updateUserAgentActions(webEngineProfilePointer->httpUserAgent());
378 emit updateZoomFactorAction(webEngineViewPointer->zoomFactor());
380 // Reload the website if requested.
383 webEngineViewPointer->reload();
387 void BrowserView::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
389 // Store the search engine name.
390 QString searchEngineName = searchEngineActionPointer->text();
392 // Strip out any `&` characters.
393 searchEngineName.remove('&');
395 // Store the search engine string.
396 searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
399 void BrowserView::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
401 // Get the user agent name.
402 QString userAgentName = userAgentActionPointer->text();
404 // Strip out any `&` characters.
405 userAgentName.remove('&');
407 // Apply the user agent.
408 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromTranslatedName(userAgentName));
410 // Reload the website.
411 webEngineViewPointer->reload();
414 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
415 void BrowserView::applyOnTheFlyZoomFactor(const double &zoomFactor)
417 // Update the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
418 currentZoomFactor = zoomFactor;
420 // Set the zoom factor.
421 webEngineViewPointer->setZoomFactor(zoomFactor);
424 void BrowserView::back() const
427 webEngineViewPointer->back();
430 void BrowserView::cookieAdded(const QNetworkCookie &cookie) const
432 // Add the cookie to the cookie list.
433 emit addCookie(cookie);
436 void BrowserView::cookieRemoved(const QNetworkCookie &cookie) const
438 // Remove the cookie from the cookie list.
439 emit removeCookie(cookie);
442 void BrowserView::deleteAllCookies() const
444 // Delete all the cookies.
445 webEngineCookieStorePointer->deleteAllCookies();
448 void BrowserView::deleteCookieFromStore(const QNetworkCookie &cookie) const
450 // Delete the cookie.
451 webEngineCookieStorePointer->deleteCookie(cookie);
454 void BrowserView::forward() const
457 webEngineViewPointer->forward();
460 void BrowserView::home() const
462 // Load the homepage.
463 webEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
466 void BrowserView::loadFinished() const
468 // Hide the progress bar.
469 emit hideProgressBar();
472 void BrowserView::loadInitialWebsite()
474 // Apply the application settings.
475 applyApplicationSettings();
477 // Get the arguments.
478 QStringList argumentsStringList = qApp->arguments();
480 // Check to see if the arguments lists contains a URL.
481 if (argumentsStringList.size() > 1)
483 // Load the URL from the arguments list.
484 webEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
488 // Load the homepage.
493 void BrowserView::loadProgress(const int &progress) const
495 // Show the progress bar.
496 emit showProgressBar(progress);
499 void BrowserView::loadStarted() const
501 // Show the progress bar.
502 emit showProgressBar(0);
505 void BrowserView::loadUrlFromLineEdit(QString url) const
507 // Decide if the text is more likely to be a URL or a search.
508 if (url.startsWith("file://")) // The text is likely a file URL.
511 webEngineViewPointer->load(QUrl::fromUserInput(url));
513 else if (url.contains(".")) // The text is likely a URL.
515 // Check if the URL does not start with a valid protocol.
516 if (!url.startsWith("http"))
518 // Add `https://` to the beginning of the URL.
519 url = "https://" + url;
523 webEngineViewPointer->load(QUrl::fromUserInput(url));
525 else // The text is likely a search.
528 webEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
532 void BrowserView::mouseBack() const
534 // Go back if possible.
535 if (webEngineViewPointer->isActiveWindow() && webEngineHistoryPointer->canGoBack())
537 // Clear the URL line edit focus.
538 emit clearUrlLineEditFocus();
541 webEngineViewPointer->back();
545 void BrowserView::mouseForward() const
547 // Go forward if possible.
548 if (webEngineViewPointer->isActiveWindow() && webEngineHistoryPointer->canGoForward())
550 // Clear the URL line edit focus.
551 emit clearUrlLineEditFocus();
554 webEngineViewPointer->forward();
558 void BrowserView::pageLinkHovered(const QString &linkUrl) const
560 // Emit a signal so that the browser window can update the status bar.
561 emit linkHovered(linkUrl);
564 void BrowserView::refresh() const
566 // Reload the website.
567 webEngineViewPointer->reload();
570 void BrowserView::toggleDomStorage() const
572 // Toggle DOM storage.
573 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
575 // Update the DOM storage action.
576 emit updateDomStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
578 // Reload the website.
579 webEngineViewPointer->reload();
582 void BrowserView::toggleJavaScript() const
584 // Toggle JavaScript.
585 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
587 // Update the JavaScript action.
588 emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
590 // Reload the website.
591 webEngineViewPointer->reload();
594 void BrowserView::toggleLocalStorage()
596 // Toggle local storeage.
597 currentPrivacyWebEnginePointer->localStorageEnabled = !currentPrivacyWebEnginePointer->localStorageEnabled;
599 // Update the local storage action.
600 emit updateLocalStorageAction(currentPrivacyWebEnginePointer->localStorageEnabled);
602 // Reload the website.
603 webEngineViewPointer->reload();
606 void BrowserView::updateUrl(const QUrl &url) const
608 // Update the URL line edit.
609 emit updateUrlLineEdit(url);
611 // Update the status of the forward and back buttons.
612 emit updateBackAction(webEngineHistoryPointer->canGoBack());
613 emit updateForwardAction(webEngineHistoryPointer->canGoForward());
615 // Reapply the zoom factor. This is a bug in QWebEngineView that resets the zoom with every load. <https://redmine.stoutner.com/issues/799>
616 webEngineViewPointer->setZoomFactor(currentZoomFactor);