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() << "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("")))
82 // Check each tab to see if this local storage request should be allowed.
83 for (PrivacyWebEngine *privacyWebEnginePointer : *privacyWebEngineListPointer)
85 // Allow this local storage request if it comes from a tab with local storage enabled.
86 if (privacyWebEnginePointer->localStorageEnabled && (webEngineViewPointer->url().host() == filterRequest.firstPartyUrl.host()))
90 // Block any remaining local storage requests.
94 // Process cookie changes.
95 connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), this, SLOT(cookieAdded(QNetworkCookie)));
96 connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), this, SLOT(cookieRemoved(QNetworkCookie)));
98 // Get a list of durable cookies.
99 QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
101 // Add the durable cookies to the store.
102 for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
103 addCookieToStore(*cookiePointer);
105 // Store a copy of the WebEngine default user agent.
106 webEngineDefaultUserAgent = webEngineProfilePointer->httpUserAgent();
108 // Update the URL line edit when the URL changes.
109 connect(webEngineViewPointer, SIGNAL(urlChanged(const QUrl)), this, SLOT(updateUrl(const QUrl)));
111 // Update the progress bar.
112 connect(webEngineViewPointer, SIGNAL(loadStarted()), this, SLOT(loadStarted()));
113 connect(webEngineViewPointer, SIGNAL(loadProgress(const int)), this, SLOT(loadProgress(const int)));
114 connect(webEngineViewPointer, SIGNAL(loadFinished(const bool)), this, SLOT(loadFinished()));
116 // Instantiate the mouse event filter pointer.
117 MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
119 // Install the mouse event filter.
120 qApp->installEventFilter(mouseEventFilterPointer);
122 // Process mouse forward and back commands.
123 connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
124 connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
126 // Listen for hovered link URLs.
127 connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
129 // Instantiate the URL request interceptor.
130 UrlRequestInterceptor *urlRequestInterceptorPointer = new UrlRequestInterceptor();
132 // Set the URL request interceptor.
133 webEngineProfilePointer->setUrlRequestInterceptor(urlRequestInterceptorPointer);
135 // Reapply the domain settings when the host changes.
136 connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings(QString)), this, SLOT(applyDomainSettingsWithoutReloading(QString)));
138 // Don't allow JavaScript to open windows.
139 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
141 // Allow keyboard navigation.
142 webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
144 // Enable full screen support.
145 webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
147 // Require user interaction to play media.
148 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
150 // Limit WebRTC to public IP addresses.
151 webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
153 // Set the focus on the WebEngine view.
154 webEngineViewPointer->setFocus();
157 BrowserView::~BrowserView()
159 // Delay the deletion of the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
160 webEnginePagePointer->deleteLater();
163 // 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.
164 void BrowserView::addCookieToStore(QNetworkCookie cookie) const
169 // 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>
170 if (!cookie.domain().startsWith(QStringLiteral(".")))
173 url.setHost(cookie.domain());
174 url.setScheme(QStringLiteral("https"));
176 // Clear the domain from the cookie.
177 cookie.setDomain(QStringLiteral(""));
180 // Add the cookie to the store.
181 webEngineCookieStorePointer->setCookie(cookie, url);
184 void BrowserView::applyApplicationSettings()
186 // Set the search engine URL.
187 searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
189 // Emit the update search engine actions signal.
190 emit updateSearchEngineActions(Settings::searchEngine());
193 // 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.
194 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
195 void BrowserView::applyDomainSettingsAndReload()
197 // Apply the domain settings. `true` reloads the website.
198 applyDomainSettings(webEngineViewPointer->url().host(), true);
201 // 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.
202 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
203 void BrowserView::applyDomainSettingsWithoutReloading(const QString &hostname)
205 // Apply the domain settings `false` does not reload the website.
206 applyDomainSettings(hostname, false);
209 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
210 void BrowserView::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
212 // Get the record for the hostname.
213 QSqlQuery domainQuery = DomainsDatabase::getDomainQuery(hostname);
215 // Check if the hostname has domain settings.
216 if (domainQuery.isValid()) // The hostname has domain settings.
218 // Get the domain record.
219 QSqlRecord domainRecord = domainQuery.record();
221 // Set the JavaScript status.
222 switch (domainRecord.field(DomainsDatabase::JAVASCRIPT).value().toInt())
224 // Set the default JavaScript status.
225 case (DomainsDatabase::SYSTEM_DEFAULT):
227 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
232 // Disable JavaScript.
233 case (DomainsDatabase::DISABLED):
235 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
240 // Enable JavaScript.
241 case (DomainsDatabase::ENABLED):
243 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
249 // Set the local storage status.
250 switch (domainRecord.field(DomainsDatabase::LOCAL_STORAGE).value().toInt())
252 // Set the default local storage status.
253 case (DomainsDatabase::SYSTEM_DEFAULT):
255 currentPrivacyWebEnginePointer->localStorageEnabled = Settings::localStorageEnabled();
260 // Disable local storage.
261 case (DomainsDatabase::DISABLED):
263 currentPrivacyWebEnginePointer->localStorageEnabled = false;
268 // Enable local storage.
269 case (DomainsDatabase::ENABLED):
271 currentPrivacyWebEnginePointer->localStorageEnabled = true;
277 // Set the DOM storage status.
278 switch (domainRecord.field(DomainsDatabase::DOM_STORAGE).value().toInt())
280 // Set the default DOM storage status.
281 case (DomainsDatabase::SYSTEM_DEFAULT):
283 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
288 // Disable DOM storage.
289 case (DomainsDatabase::DISABLED):
291 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
296 // Enable DOM storage.
297 case (DomainsDatabase::ENABLED):
299 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
305 // Set the user agent.
306 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabase::USER_AGENT).value().toString()));
308 // Check if a custom zoom factor is set.
309 if (domainRecord.field(DomainsDatabase::ZOOM_FACTOR).value().toInt())
311 // Store the current zoom factor.
312 currentZoomFactor = domainRecord.field(DomainsDatabase::CUSTOM_ZOOM_FACTOR).value().toDouble();
316 // Reset the current zoom factor.
317 currentZoomFactor = Settings::zoomFactor();
320 // Set the zoom factor. The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
321 webEngineViewPointer->setZoomFactor(currentZoomFactor);
323 // Apply the domain settings palette to the URL line edit.
324 emit updateDomainSettingsIndicator(true, domainRecord.field(DomainsDatabase::DOMAIN_NAME).value().toString());
326 else // The hostname does not have domain settings.
328 // Set the JavaScript status.
329 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
331 // Set the local storage status.
332 currentPrivacyWebEnginePointer->localStorageEnabled = Settings::localStorageEnabled();
335 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
337 // Set the user agent.
338 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
340 // Store the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
341 currentZoomFactor = Settings::zoomFactor();
343 // Set the zoom factor.
344 webEngineViewPointer->setZoomFactor(Settings::zoomFactor());
346 // Apply the no domain settings palette to the URL line edit.
347 emit updateDomainSettingsIndicator(false, QStringLiteral(""));
350 // Emit the update actions signals.
351 emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
352 emit updateLocalStorageAction(currentPrivacyWebEnginePointer->localStorageEnabled);
353 emit updateDomStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
354 emit updateUserAgentActions(webEngineProfilePointer->httpUserAgent());
355 emit updateZoomFactorAction(webEngineViewPointer->zoomFactor());
357 // Reload the website if requested.
360 webEngineViewPointer->reload();
364 void BrowserView::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
366 // Store the search engine name.
367 QString searchEngineName = searchEngineActionPointer->text();
369 // Strip out any `&` characters.
370 searchEngineName.remove('&');
372 // Store the search engine string.
373 searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
376 void BrowserView::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
378 // Get the user agent name.
379 QString userAgentName = userAgentActionPointer->text();
381 // Strip out any `&` characters.
382 userAgentName.remove('&');
384 // Apply the user agent.
385 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromTranslatedName(userAgentName));
387 // Reload the website.
388 webEngineViewPointer->reload();
391 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
392 void BrowserView::applyOnTheFlyZoomFactor(const double &zoomFactor)
394 // Update the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
395 currentZoomFactor = zoomFactor;
397 // Set the zoom factor.
398 webEngineViewPointer->setZoomFactor(zoomFactor);
401 void BrowserView::back() const
404 webEngineViewPointer->back();
407 void BrowserView::cookieAdded(const QNetworkCookie &cookie) const
409 // Add the cookie to the cookie list.
410 emit addCookie(cookie);
413 void BrowserView::cookieRemoved(const QNetworkCookie &cookie) const
415 // Remove the cookie from the cookie list.
416 emit removeCookie(cookie);
419 void BrowserView::deleteAllCookies() const
421 // Delete all the cookies.
422 webEngineCookieStorePointer->deleteAllCookies();
425 void BrowserView::deleteCookieFromStore(const QNetworkCookie &cookie) const
427 // Delete the cookie.
428 webEngineCookieStorePointer->deleteCookie(cookie);
431 void BrowserView::forward() const
434 webEngineViewPointer->forward();
437 void BrowserView::home() const
439 // Load the homepage.
440 webEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
443 void BrowserView::loadFinished() const
445 // Hide the progress bar.
446 emit hideProgressBar();
449 void BrowserView::loadInitialWebsite()
451 // Apply the application settings.
452 applyApplicationSettings();
454 // Get the arguments.
455 QStringList argumentsStringList = qApp->arguments();
457 // Check to see if the arguments lists contains a URL.
458 if (argumentsStringList.size() > 1)
460 // Load the URL from the arguments list.
461 webEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
465 // Load the homepage.
470 void BrowserView::loadProgress(const int &progress) const
472 // Show the progress bar.
473 emit showProgressBar(progress);
476 void BrowserView::loadStarted() const
478 // Show the progress bar.
479 emit showProgressBar(0);
482 void BrowserView::loadUrlFromLineEdit(QString url) const
484 // Decide if the text is more likely to be a URL or a search.
485 if (url.startsWith("file://")) // The text is likely a file URL.
488 webEngineViewPointer->load(QUrl::fromUserInput(url));
490 else if (url.contains(".")) // The text is likely a URL.
492 // Check if the URL does not start with a valid protocol.
493 if (!url.startsWith("http"))
495 // Add `https://` to the beginning of the URL.
496 url = "https://" + url;
500 webEngineViewPointer->load(QUrl::fromUserInput(url));
502 else // The text is likely a search.
505 webEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
509 void BrowserView::mouseBack() const
511 // Go back if possible.
512 if (webEngineHistoryPointer->canGoBack())
514 // Clear the URL line edit focus.
515 emit clearUrlLineEditFocus();
518 webEngineViewPointer->back();
522 void BrowserView::mouseForward() const
524 // Go forward if possible.
525 if (webEngineHistoryPointer->canGoForward())
527 // Clear the URL line edit focus.
528 emit clearUrlLineEditFocus();
531 webEngineViewPointer->forward();
535 void BrowserView::pageLinkHovered(const QString &linkUrl) const
537 // Emit a signal so that the browser window can update the status bar.
538 emit linkHovered(linkUrl);
541 void BrowserView::refresh() const
543 // Reload the website.
544 webEngineViewPointer->reload();
547 void BrowserView::toggleDomStorage() const
549 // Toggle DOM storage.
550 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
552 // Update the DOM storage action.
553 emit updateDomStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
555 // Reload the website.
556 webEngineViewPointer->reload();
559 void BrowserView::toggleJavaScript() const
561 // Toggle JavaScript.
562 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
564 // Update the JavaScript action.
565 emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
567 // Reload the website.
568 webEngineViewPointer->reload();
571 void BrowserView::toggleLocalStorage()
573 // Toggle local storeage.
574 currentPrivacyWebEnginePointer->localStorageEnabled = !currentPrivacyWebEnginePointer->localStorageEnabled;
576 // Update the local storage action.
577 emit updateLocalStorageAction(currentPrivacyWebEnginePointer->localStorageEnabled);
579 // Reload the website.
580 webEngineViewPointer->reload();
583 void BrowserView::updateUrl(const QUrl &url) const
585 // Update the URL line edit.
586 emit updateUrlLineEdit(url);
588 // Update the status of the forward and back buttons.
589 emit updateBackAction(webEngineHistoryPointer->canGoBack());
590 emit updateForwardAction(webEngineHistoryPointer->canGoForward());
592 // Reapply the zoom factor. This is a bug in QWebEngineView that resets the zoom with every load. <https://redmine.stoutner.com/issues/799>
593 webEngineViewPointer->setZoomFactor(currentZoomFactor);