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);
398 // Update the search engine actionas.
399 emit updateSearchEngineActions(searchEngineName);
402 void BrowserView::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
404 // Get the user agent name.
405 QString userAgentName = userAgentActionPointer->text();
407 // Strip out any `&` characters.
408 userAgentName.remove('&');
410 // Apply the user agent.
411 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromTranslatedName(userAgentName));
413 // Update the user agent actions.
414 emit updateUserAgentActions(webEngineProfilePointer->httpUserAgent());
416 // Reload the website.
417 webEngineViewPointer->reload();
420 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
421 void BrowserView::applyOnTheFlyZoomFactor(const double &zoomFactor)
423 // Update the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
424 currentZoomFactor = zoomFactor;
426 // Set the zoom factor.
427 webEngineViewPointer->setZoomFactor(zoomFactor);
430 void BrowserView::back() const
433 webEngineViewPointer->back();
436 void BrowserView::cookieAdded(const QNetworkCookie &cookie) const
438 // Add the cookie to the cookie list.
439 emit addCookie(cookie);
442 void BrowserView::cookieRemoved(const QNetworkCookie &cookie) const
444 // Remove the cookie from the cookie list.
445 emit removeCookie(cookie);
448 void BrowserView::deleteAllCookies() const
450 // Delete all the cookies.
451 webEngineCookieStorePointer->deleteAllCookies();
454 void BrowserView::deleteCookieFromStore(const QNetworkCookie &cookie) const
456 // Delete the cookie.
457 webEngineCookieStorePointer->deleteCookie(cookie);
460 void BrowserView::forward() const
463 webEngineViewPointer->forward();
466 void BrowserView::home() const
468 // Load the homepage.
469 webEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
472 void BrowserView::loadFinished() const
474 // Hide the progress bar.
475 emit hideProgressBar();
478 void BrowserView::loadInitialWebsite()
480 // Apply the application settings.
481 applyApplicationSettings();
483 // Get the arguments.
484 QStringList argumentsStringList = qApp->arguments();
486 // Check to see if the arguments lists contains a URL.
487 if (argumentsStringList.size() > 1)
489 // Load the URL from the arguments list.
490 webEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
494 // Load the homepage.
499 void BrowserView::loadProgress(const int &progress) const
501 // Show the progress bar.
502 emit showProgressBar(progress);
505 void BrowserView::loadStarted() const
507 // Show the progress bar.
508 emit showProgressBar(0);
511 void BrowserView::loadUrlFromLineEdit(QString url) const
513 // Decide if the text is more likely to be a URL or a search.
514 if (url.startsWith("file://")) // The text is likely a file URL.
517 webEngineViewPointer->load(QUrl::fromUserInput(url));
519 else if (url.contains(".")) // The text is likely a URL.
521 // Check if the URL does not start with a valid protocol.
522 if (!url.startsWith("http"))
524 // Add `https://` to the beginning of the URL.
525 url = "https://" + url;
529 webEngineViewPointer->load(QUrl::fromUserInput(url));
531 else // The text is likely a search.
534 webEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
538 void BrowserView::mouseBack() const
540 // Go back if possible.
541 if (webEngineViewPointer->isActiveWindow() && webEngineHistoryPointer->canGoBack())
543 // Clear the URL line edit focus.
544 emit clearUrlLineEditFocus();
547 webEngineViewPointer->back();
551 void BrowserView::mouseForward() const
553 // Go forward if possible.
554 if (webEngineViewPointer->isActiveWindow() && webEngineHistoryPointer->canGoForward())
556 // Clear the URL line edit focus.
557 emit clearUrlLineEditFocus();
560 webEngineViewPointer->forward();
564 void BrowserView::pageLinkHovered(const QString &linkUrl) const
566 // Emit a signal so that the browser window can update the status bar.
567 emit linkHovered(linkUrl);
570 void BrowserView::refresh() const
572 // Reload the website.
573 webEngineViewPointer->reload();
576 void BrowserView::toggleDomStorage() const
578 // Toggle DOM storage.
579 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
581 // Update the DOM storage action.
582 emit updateDomStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
584 // Reload the website.
585 webEngineViewPointer->reload();
588 void BrowserView::toggleJavaScript() const
590 // Toggle JavaScript.
591 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
593 // Update the JavaScript action.
594 emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
596 // Reload the website.
597 webEngineViewPointer->reload();
600 void BrowserView::toggleLocalStorage()
602 // Toggle local storeage.
603 currentPrivacyWebEnginePointer->localStorageEnabled = !currentPrivacyWebEnginePointer->localStorageEnabled;
605 // Update the local storage action.
606 emit updateLocalStorageAction(currentPrivacyWebEnginePointer->localStorageEnabled);
608 // Reload the website.
609 webEngineViewPointer->reload();
612 void BrowserView::updateUrl(const QUrl &url) const
614 // Update the URL line edit.
615 emit updateUrlLineEdit(url);
617 // Update the status of the forward and back buttons.
618 emit updateBackAction(webEngineHistoryPointer->canGoBack());
619 emit updateForwardAction(webEngineHistoryPointer->canGoForward());
621 // Reapply the zoom factor. This is a bug in QWebEngineView that resets the zoom with every load. <https://redmine.stoutner.com/issues/799>
622 webEngineViewPointer->setZoomFactor(currentZoomFactor);