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 "filters/MouseEventFilter.h"
25 #include "helpers/DomainsDatabaseHelper.h"
26 #include "helpers/SearchEngineHelper.h"
27 #include "helpers/UserAgentHelper.h"
28 #include "interceptors/UrlRequestInterceptor.h"
29 #include "windows/BrowserWindow.h"
31 // Qt framework headers.
34 // Initialize the public static variables.
35 QString BrowserView::webEngineDefaultUserAgent = QStringLiteral("");
37 BrowserView::BrowserView(QWidget *parent) : QWidget(parent)
39 // Instantiate the browser view UI.
40 Ui::BrowserView browserViewUi;
43 browserViewUi.setupUi(this);
45 // Get handles for the views.
46 webEngineViewPointer = browserViewUi.webEngineView;
48 // Create an off-the-record profile (the default when no profile name is specified).
49 webEngineProfilePointer = new QWebEngineProfile(QStringLiteral(""));
51 // Create a WebEngine page.
52 webEnginePagePointer = new QWebEnginePage(webEngineProfilePointer);
54 // Set the WebEngine page.
55 webEngineViewPointer->setPage(webEnginePagePointer);
57 // Get handles for the aspects of the WebEngine.
58 webEngineHistoryPointer = webEnginePagePointer->history();
59 webEngineSettingsPointer = webEngineViewPointer->settings();
60 webEngineCookieStorePointer = webEngineProfilePointer->cookieStore();
62 // Store a copy of each cookie when it is added.
63 connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), this, SLOT(cookieAdded(QNetworkCookie)));
65 // Store a copy of the WebEngine default user agent.
66 webEngineDefaultUserAgent = webEngineProfilePointer->httpUserAgent();
68 // Update the URL line edit when the URL changes.
69 connect(webEngineViewPointer, SIGNAL(urlChanged(const QUrl)), this, SLOT(updateUrl(const QUrl)));
71 // Update the progress bar.
72 connect(webEngineViewPointer, SIGNAL(loadStarted()), this, SLOT(loadStarted()));
73 connect(webEngineViewPointer, SIGNAL(loadProgress(const int)), this, SLOT(loadProgress(const int)));
74 connect(webEngineViewPointer, SIGNAL(loadFinished(const bool)), this, SLOT(loadFinished()));
76 // Instantiate the mouse event filter pointer.
77 MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
79 // Install the mouse event filter.
80 qApp->installEventFilter(mouseEventFilterPointer);
82 // Process mouse forward and back commands.
83 connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
84 connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
86 // Listen for hovered link URLs.
87 connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
89 // Instantiate the URL request interceptor.
90 UrlRequestInterceptor *urlRequestInterceptorPointer = new UrlRequestInterceptor();
92 // Set the URL request interceptor.
93 webEngineProfilePointer->setUrlRequestInterceptor(urlRequestInterceptorPointer);
95 // Reapply the domain settings when the host changes.
96 connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings(QString)), this, SLOT(applyDomainSettingsWithoutReloading(QString)));
98 // Don't allow JavaScript to open windows.
99 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
101 // Allow keyboard navigation.
102 webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
104 // Enable full screen support.
105 webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
107 // Require user interaction to play media.
108 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
110 // Limit WebRTC to public IP addresses.
111 webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
113 // Set the focus on the WebEngine view.
114 webEngineViewPointer->setFocus();
117 BrowserView::~BrowserView()
119 // Delay the deletion of the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
120 webEnginePagePointer->deleteLater();
123 // 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.
124 void BrowserView::addCookieToStore(QNetworkCookie cookie) const
129 // 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>
130 if (!cookie.domain().startsWith(QStringLiteral(".")))
133 url.setHost(cookie.domain());
134 url.setScheme(QStringLiteral("https"));
136 // Clear the domain from the cookie.
137 cookie.setDomain(QStringLiteral(""));
140 // Add the cookie to the store.
141 webEngineCookieStorePointer->setCookie(cookie, url);
144 void BrowserView::applyApplicationSettings()
146 // Set the search engine URL.
147 searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
149 // Emit the update search engine actions signal.
150 emit updateSearchEngineActions(Settings::searchEngine());
153 // 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.
154 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
155 void BrowserView::applyDomainSettingsAndReload()
157 // Apply the domain settings. `true` reloads the website.
158 applyDomainSettings(webEngineViewPointer->url().host(), true);
161 // 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.
162 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
163 void BrowserView::applyDomainSettingsWithoutReloading(const QString &hostname)
165 // Apply the domain settings `false` does not reload the website.
166 applyDomainSettings(hostname, false);
169 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
170 void BrowserView::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
172 // Get the record for the hostname.
173 QSqlQuery domainQuery = DomainsDatabaseHelper::getDomainQuery(hostname);
175 // Check if the hostname has domain settings.
176 if (domainQuery.isValid()) // The hostname has domain settings.
178 // Get the domain record.
179 QSqlRecord domainRecord = domainQuery.record();
181 // Set the JavaScript status.
182 switch (domainRecord.field(DomainsDatabaseHelper::JAVASCRIPT).value().toInt())
184 case (DomainsDatabaseHelper::SYSTEM_DEFAULT):
186 // Set the default JavaScript status.
187 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScript());
192 case (DomainsDatabaseHelper::DISABLED):
194 // Disable JavaScript.
195 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
200 case (DomainsDatabaseHelper::ENABLED):
202 // Enable JavaScript.
203 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
209 // Set local storage.
210 switch (domainRecord.field(DomainsDatabaseHelper::LOCAL_STORAGE).value().toInt())
212 case (DomainsDatabaseHelper::SYSTEM_DEFAULT):
214 // Set the default local storage status.
215 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::localStorage());
220 case (DomainsDatabaseHelper::DISABLED):
222 // Disable local storage.
223 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
228 case (DomainsDatabaseHelper::ENABLED):
230 // Enable local storage.
231 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
237 // Set the user agent.
238 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabaseHelper::USER_AGENT).value().toString()));
240 // Check if a custom zoom factor is set.
241 if (domainRecord.field(DomainsDatabaseHelper::ZOOM_FACTOR).value().toInt())
243 // Store the current zoom factor.
244 currentZoomFactor = domainRecord.field(DomainsDatabaseHelper::CUSTOM_ZOOM_FACTOR).value().toDouble();
248 // Reset the current zoom factor.
249 currentZoomFactor = Settings::zoomFactor();
252 // Set the zoom factor. The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
253 webEngineViewPointer->setZoomFactor(currentZoomFactor);
255 // Apply the domain settings palette to the URL line edit.
256 emit updateDomainSettingsIndicator(true, domainRecord.field(DomainsDatabaseHelper::DOMAIN_NAME).value().toString());
258 else // The hostname does not have domain settings.
260 // Set the JavaScript status.
261 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScript());
263 // Set local storage.
264 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::localStorage());
266 // Set the user agent.
267 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
269 // Store the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
270 currentZoomFactor = Settings::zoomFactor();
272 // Set the zoom factor.
273 webEngineViewPointer->setZoomFactor(Settings::zoomFactor());
275 // Apply the no domain settings palette to the URL line edit.
276 emit updateDomainSettingsIndicator(false, QStringLiteral(""));
279 // Emit the update actions signals.
280 emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
281 emit updateLocalStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
282 emit updateUserAgentActions(webEngineProfilePointer->httpUserAgent());
283 emit updateZoomFactorAction(webEngineViewPointer->zoomFactor());
285 // Reload the website if requested.
288 webEngineViewPointer->reload();
292 void BrowserView::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
294 // Store the search engine name.
295 QString searchEngineName = searchEngineActionPointer->text();
297 // Strip out any `&` characters.
298 searchEngineName.remove('&');
300 // Store the search engine string.
301 searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
304 void BrowserView::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
306 // Get the user agent name.
307 QString userAgentName = userAgentActionPointer->text();
309 // Strip out any `&` characters.
310 userAgentName.remove('&');
312 // Apply the user agent.
313 webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromTranslatedName(userAgentName));
315 // Reload the website.
316 webEngineViewPointer->reload();
319 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
320 void BrowserView::applyOnTheFlyZoomFactor(const double &zoomFactor)
322 // Update the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
323 currentZoomFactor = zoomFactor;
325 // Set the zoom factor.
326 webEngineViewPointer->setZoomFactor(zoomFactor);
329 void BrowserView::back() const
332 webEngineViewPointer->back();
335 void BrowserView::cookieAdded(const QNetworkCookie &cookie) const
337 // Add the cookie to the cookie list.
338 emit addCookie(cookie);
341 void BrowserView::deleteAllCookies() const
343 // Delete all the cookies.
344 webEngineCookieStorePointer->deleteAllCookies();
347 void BrowserView::forward() const
350 webEngineViewPointer->forward();
353 void BrowserView::home() const
355 // Load the homepage.
356 webEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
359 void BrowserView::loadFinished() const
361 // Hide the progress bar.
362 emit hideProgressBar();
365 void BrowserView::loadInitialWebsite()
367 // Apply the application settings.
368 applyApplicationSettings();
370 // Get the arguments.
371 QStringList argumentsStringList = qApp->arguments();
373 // Check to see if the arguments lists contains a URL.
374 if (argumentsStringList.size() > 1)
376 // Load the URL from the arguments list.
377 webEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
381 // Load the homepage.
386 void BrowserView::loadProgress(const int &progress) const
388 // Show the progress bar.
389 emit showProgressBar(progress);
392 void BrowserView::loadStarted() const
394 // Show the progress bar.
395 emit showProgressBar(0);
398 void BrowserView::loadUrlFromLineEdit(QString url) const
400 // Decide if the text is more likely to be a URL or a search.
401 if (url.startsWith("file://")) // The text is likely a file URL.
404 webEngineViewPointer->load(QUrl::fromUserInput(url));
406 else if (url.contains(".")) // The text is likely a URL.
408 // Check if the URL does not start with a valid protocol.
409 if (!url.startsWith("http"))
411 // Add `https://` to the beginning of the URL.
412 url = "https://" + url;
416 webEngineViewPointer->load(QUrl::fromUserInput(url));
418 else // The text is likely a search.
421 webEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
425 void BrowserView::mouseBack() const
427 // Go back if possible.
428 if (webEngineHistoryPointer->canGoBack())
430 // Clear the URL line edit focus.
431 emit clearUrlLineEditFocus();
434 webEngineViewPointer->back();
438 void BrowserView::mouseForward() const
440 // Go forward if possible.
441 if (webEngineHistoryPointer->canGoForward())
443 // Clear the URL line edit focus.
444 emit clearUrlLineEditFocus();
447 webEngineViewPointer->forward();
451 void BrowserView::pageLinkHovered(const QString &linkUrl) const
453 // Emit a signal so that the browser window can update the status bar.
454 emit linkHovered(linkUrl);
457 void BrowserView::refresh() const
459 // Reload the website.
460 webEngineViewPointer->reload();
463 void BrowserView::toggleJavaScript() const
465 // Toggle JavaScript.
466 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
468 // Update the JavaScript icon.
469 emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
471 // Reload the website.
472 webEngineViewPointer->reload();
475 void BrowserView::toggleLocalStorage() const
477 // Toggle local storage.
478 webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
480 // Update the local storage icon.
481 emit updateLocalStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
483 // Reload the website.
484 webEngineViewPointer->reload();
487 void BrowserView::updateUrl(const QUrl &url) const
489 // Update the URL line edit.
490 emit updateUrlLineEdit(url);
492 // Update the status of the forward and back buttons.
493 emit updateBackAction(webEngineHistoryPointer->canGoBack());
494 emit updateForwardAction(webEngineHistoryPointer->canGoForward());
496 // Reapply the zoom factor. This is a bug in QWebEngineView that resets the zoom with every load. <https://redmine.stoutner.com/issues/799>
497 webEngineViewPointer->setZoomFactor(currentZoomFactor);