2 * Copyright 2022-2023 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 "TabWidget.h"
23 #include "ui_AddTabWidget.h"
24 #include "ui_TabWidget.h"
25 #include "databases/CookiesDatabase.h"
26 #include "databases/DomainsDatabase.h"
27 #include "dialogs/SaveDialog.h"
28 #include "filters/MouseEventFilter.h"
29 #include "helpers/SearchEngineHelper.h"
30 #include "interceptors/UrlRequestInterceptor.h"
31 #include "windows/BrowserWindow.h"
33 // KDE Framework headers.
34 #include <KIO/FileCopyJob>
35 #include <KIO/JobUiDelegate>
36 #include <KNotification>
38 // Qt toolkit headers.
40 #include <QFileDialog>
41 #include <QGraphicsScene>
42 #include <QGraphicsView>
43 #include <QPrintDialog>
44 #include <QPrintPreviewDialog>
47 // Initialize the public static variables.
48 QString TabWidget::webEngineDefaultUserAgent = QLatin1String("");
50 // Construct the class.
51 TabWidget::TabWidget(QWidget *parent) : QWidget(parent)
53 // Instantiate the user agent helper.
54 userAgentHelperPointer = new UserAgentHelper();
56 // Instantiate the UIs.
57 Ui::TabWidget tabWidgetUi;
58 Ui::AddTabWidget addTabWidgetUi;
61 tabWidgetUi.setupUi(this);
63 // Get a handle for the tab widget.
64 tabWidgetPointer = tabWidgetUi.tabWidget;
66 // Setup the add tab UI.
67 addTabWidgetUi.setupUi(tabWidgetPointer);
69 // Get handles for the add tab widgets.
70 QWidget *addTabWidgetPointer = addTabWidgetUi.addTabQWidget;
71 QPushButton *addTabButtonPointer = addTabWidgetUi.addTabButton;
73 // Display the add tab widget.
74 tabWidgetPointer->setCornerWidget(addTabWidgetPointer);
79 // Process tab events.
80 connect(tabWidgetPointer, SIGNAL(currentChanged(int)), this, SLOT(updateUiWithTabSettings()));
81 connect(addTabButtonPointer, SIGNAL(clicked()), this, SLOT(addTab()));
82 connect(tabWidgetPointer, SIGNAL(tabCloseRequested(int)), this, SLOT(deleteTab(int)));
84 // Store a copy of the WebEngine default user agent.
85 webEngineDefaultUserAgent = currentWebEngineProfilePointer->httpUserAgent();
87 // Instantiate the mouse event filter pointer.
88 MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
90 // Install the mouse event filter.
91 qApp->installEventFilter(mouseEventFilterPointer);
93 // Process mouse forward and back commands.
94 connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
95 connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
98 TabWidget::~TabWidget()
100 // Manually delete each WebEngine page.
101 for (int i = 0; i < tabWidgetPointer->count(); ++i)
103 // Get the privacy WebEngine view.
104 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->widget(i));
106 // Deletion the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
107 delete privacyWebEngineViewPointer->page();
111 // 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.
112 void TabWidget::addCookieToStore(QNetworkCookie cookie, QWebEngineCookieStore *webEngineCookieStorePointer) const
117 // 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>
118 if (!cookie.domain().startsWith(QLatin1String(".")))
121 url.setHost(cookie.domain());
122 url.setScheme(QLatin1String("https"));
124 // Clear the domain from the cookie.
125 cookie.setDomain(QLatin1String(""));
128 // Add the cookie to the store.
129 if (webEngineCookieStorePointer == nullptr)
130 currentWebEngineCookieStorePointer->setCookie(cookie, url);
132 webEngineCookieStorePointer->setCookie(cookie, url);
135 void TabWidget::addFirstTab()
137 // Create the first tab.
140 // Update the UI with the tab settings.
141 updateUiWithTabSettings();
143 // Set the focus on the current tab widget. This prevents the tab bar from showing a blue bar under the label of the first tab.
144 tabWidgetPointer->currentWidget()->setFocus();
147 PrivacyWebEngineView* TabWidget::addTab(const bool removeUrlLineEditFocus, const bool backgroundTab)
149 // Create a privacy WebEngine view.
150 PrivacyWebEngineView *privacyWebEngineViewPointer = new PrivacyWebEngineView();
153 int newTabIndex = tabWidgetPointer->addTab(privacyWebEngineViewPointer, i18nc("New tab label.", "New Tab"));
155 // Set the default tab icon.
156 tabWidgetPointer->setTabIcon(newTabIndex, defaultTabIcon);
158 // Create an off-the-record profile (the default when no profile name is specified).
159 QWebEngineProfile *webEngineProfilePointer = new QWebEngineProfile(QLatin1String(""));
161 // Create a WebEngine page.
162 QWebEnginePage *webEnginePagePointer = new QWebEnginePage(webEngineProfilePointer);
164 // Set the WebEngine page.
165 privacyWebEngineViewPointer->setPage(webEnginePagePointer);
167 // Get handles for the web engine elements.
168 QWebEngineCookieStore *webEngineCookieStorePointer = webEngineProfilePointer->cookieStore();
169 QWebEngineSettings *webEngineSettingsPointer = webEnginePagePointer->settings();
171 // Update the URL line edit when the URL changes.
172 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::urlChanged, [privacyWebEngineViewPointer, this] (const QUrl &newUrl)
174 // Only update the UI if this is the current tab.
175 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
177 // Update the URL line edit.
178 emit updateUrlLineEdit(newUrl);
180 // Update the status of the forward and back buttons.
181 emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
182 emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
185 // Reapply the zoom factor. This is a bug in QWebEngineView that resets the zoom with every load. It can be removed once <https://redmine.stoutner.com/issues/799> is fixed.
186 privacyWebEngineViewPointer->setZoomFactor(currentZoomFactor);
189 // Update the progress bar when a load is started.
190 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadStarted, [privacyWebEngineViewPointer, this] ()
192 // Store the load progress.
193 privacyWebEngineViewPointer->loadProgressInt = 0;
195 // Show the progress bar if this is the current tab.
196 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
197 emit showProgressBar(0);
200 // Update the progress bar when a load progresses.
201 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadProgress, [privacyWebEngineViewPointer, this] (const int progress)
203 // Store the load progress.
204 privacyWebEngineViewPointer->loadProgressInt = progress;
206 // Update the progress bar if this is the current tab.
207 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
208 emit showProgressBar(progress);
211 // Update the progress bar when a load finishes.
212 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadFinished, [privacyWebEngineViewPointer, this] ()
214 // Store the load progress.
215 privacyWebEngineViewPointer->loadProgressInt = -1;
217 // Hide the progress bar if this is the current tab.
218 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
219 emit hideProgressBar();
222 // Display find text results.
223 connect(webEnginePagePointer, SIGNAL(findTextFinished(const QWebEngineFindTextResult &)), this, SLOT(findTextFinished(const QWebEngineFindTextResult &)));
225 // Handle full screen requests.
226 connect(webEnginePagePointer, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this, SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
228 // Listen for hovered link URLs.
229 connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
231 // Handle file downloads.
232 connect(webEngineProfilePointer, SIGNAL(downloadRequested(QWebEngineDownloadItem *)), this, SLOT(showSaveDialog(QWebEngineDownloadItem *)));
234 // Instantiate the URL request interceptor.
235 UrlRequestInterceptor *urlRequestInterceptorPointer = new UrlRequestInterceptor();
237 // Set the URL request interceptor.
238 webEngineProfilePointer->setUrlRequestInterceptor(urlRequestInterceptorPointer);
240 // Reapply the domain settings when the host changes.
241 connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings(QString)), this, SLOT(applyDomainSettingsWithoutReloading(QString)));
243 // Set the local storage filter.
244 webEngineCookieStorePointer->setCookieFilter([privacyWebEngineViewPointer](const QWebEngineCookieStore::FilterRequest &filterRequest)
246 // Block all third party local storage requests, including the sneaky ones that don't register a first party URL.
247 if (filterRequest.thirdParty || (filterRequest.firstPartyUrl == QStringLiteral("")))
249 //qDebug().noquote().nospace() << "Third-party request blocked: " << filterRequest.origin;
255 // Allow the request if local storage is enabled.
256 if (privacyWebEngineViewPointer->localStorageEnabled)
258 //qDebug().noquote().nospace() << "Request allowed by local storage: " << filterRequest.origin;
264 //qDebug().noquote().nospace() << "Request blocked by default: " << filterRequest.origin;
266 // Block any remaining local storage requests.
270 // Disable JavaScript by default (this prevents JavaScript from being enabled on a new tab before domain settings are loaded).
271 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
273 // Don't allow JavaScript to open windows.
274 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
276 // Allow keyboard navigation.
277 webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
279 // Enable full screen support.
280 webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
282 // Require user interaction to play media.
283 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
285 // Limit WebRTC to public IP addresses.
286 webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
288 // Enable the PDF viewer (it should be enabled by default, but it is nice to be explicit in case the defaults change).
289 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PdfViewerEnabled, true);
291 // Plugins must be enabled for the PDF viewer to work. <https://doc.qt.io/qt-5/qtwebengine-features.html#pdf-file-viewing>
292 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PluginsEnabled, true);
294 // Update the cookies action.
295 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::updateCookiesAction, [privacyWebEngineViewPointer, this] (const int numberOfCookies)
297 // Update the cookie action if the specified privacy WebEngine view is the current privacy WebEngine view.
298 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
299 emit updateCookiesAction(numberOfCookies);
302 // Process cookie changes.
303 connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(addCookieToList(QNetworkCookie)));
304 connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(removeCookieFromList(QNetworkCookie)));
306 // Get a list of durable cookies.
307 QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
309 // Add the durable cookies to the store.
310 for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
311 addCookieToStore(*cookiePointer, webEngineCookieStorePointer);
313 // Update the title when it changes.
314 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::titleChanged, [this, privacyWebEngineViewPointer] (const QString &title)
316 // Get the index for this tab.
317 int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
319 // Update the title for this tab.
320 tabWidgetPointer->setTabText(tabIndex, title);
322 // Update the window title if this is the current tab.
323 if (tabIndex == tabWidgetPointer->currentIndex())
324 emit updateWindowTitle(title);
327 // Update the icon when it changes.
328 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::iconChanged, [privacyWebEngineViewPointer, this] (const QIcon &icon)
330 // Get the index for this tab.
331 int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
333 // Update the icon for this tab.
335 tabWidgetPointer->setTabIcon(tabIndex, defaultTabIcon);
337 tabWidgetPointer->setTabIcon(tabIndex, icon);
340 // Enable spell checking.
341 webEngineProfilePointer->setSpellCheckEnabled(true);
343 // Set the spell check language.
344 webEngineProfilePointer->setSpellCheckLanguages({QLatin1String("en_US")});
346 // Populate the zoom factor. This is necessary if a URL is being loaded, like a local URL, that does not trigger `applyDomainSettings()`.
347 privacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
349 // Move to the new tab if it is not a background tab.
351 tabWidgetPointer->setCurrentIndex(newTabIndex);
353 // Clear the URL line edit focus so that it populates correctly when opening a new tab from the context menu.
354 if (removeUrlLineEditFocus)
355 emit clearUrlLineEditFocus();
357 // Return the privacy WebEngine view pointer.
358 return privacyWebEngineViewPointer;
361 void TabWidget::applyApplicationSettings()
363 // Set the tab position.
364 if (Settings::tabsOnTop())
365 tabWidgetPointer->setTabPosition(QTabWidget::North);
367 tabWidgetPointer->setTabPosition(QTabWidget::South);
369 // Set the search engine URL.
370 searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
372 // Emit the update search engine actions signal.
373 emit updateSearchEngineActions(Settings::searchEngine(), true);
376 // 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.
377 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
378 void TabWidget::applyDomainSettingsAndReload()
380 // Apply the domain settings. `true` reloads the website.
381 applyDomainSettings(currentPrivacyWebEngineViewPointer->url().host(), true);
384 // 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.
385 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
386 void TabWidget::applyDomainSettingsWithoutReloading(const QString &hostname)
388 // Apply the domain settings `false` does not reload the website.
389 applyDomainSettings(hostname, false);
392 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
393 void TabWidget::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
395 // Get the record for the hostname.
396 QSqlQuery domainQuery = DomainsDatabase::getDomainQuery(hostname);
398 // Check if the hostname has domain settings.
399 if (domainQuery.isValid()) // The hostname has domain settings.
401 // Get the domain record.
402 QSqlRecord domainRecord = domainQuery.record();
404 // Store the domain settings name.
405 currentPrivacyWebEngineViewPointer->domainSettingsName = domainRecord.field(DomainsDatabase::DOMAIN_NAME).value().toString();
407 // Set the JavaScript status.
408 switch (domainRecord.field(DomainsDatabase::JAVASCRIPT).value().toInt())
410 // Set the default JavaScript status.
411 case (DomainsDatabase::SYSTEM_DEFAULT):
413 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
418 // Disable JavaScript.
419 case (DomainsDatabase::DISABLED):
421 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
426 // Enable JavaScript.
427 case (DomainsDatabase::ENABLED):
429 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
435 // Set the local storage status.
436 switch (domainRecord.field(DomainsDatabase::LOCAL_STORAGE).value().toInt())
438 // Set the default local storage status.
439 case (DomainsDatabase::SYSTEM_DEFAULT):
441 currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
446 // Disable local storage.
447 case (DomainsDatabase::DISABLED):
449 currentPrivacyWebEngineViewPointer->localStorageEnabled = false;
454 // Enable local storage.
455 case (DomainsDatabase::ENABLED):
457 currentPrivacyWebEngineViewPointer->localStorageEnabled = true;
463 // Set the DOM storage status.
464 switch (domainRecord.field(DomainsDatabase::DOM_STORAGE).value().toInt())
466 // Set the default DOM storage status. QWebEngineSettings confusingly calls this local storage.
467 case (DomainsDatabase::SYSTEM_DEFAULT):
469 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
474 // Disable DOM storage. QWebEngineSettings confusingly calls this local storage.
475 case (DomainsDatabase::DISABLED):
477 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
482 // Enable DOM storage. QWebEngineSettings confusingly calls this local storage.
483 case (DomainsDatabase::ENABLED):
485 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
491 // Set the user agent.
492 currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabase::USER_AGENT).value().toString()));
494 // Check if a custom zoom factor is set.
495 if (domainRecord.field(DomainsDatabase::ZOOM_FACTOR).value().toInt())
497 // Store the current zoom factor.
498 currentZoomFactor = domainRecord.field(DomainsDatabase::CUSTOM_ZOOM_FACTOR).value().toDouble();
502 // Reset the current zoom factor.
503 currentZoomFactor = Settings::zoomFactor();
506 // Set the zoom factor. The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
507 currentPrivacyWebEngineViewPointer->setZoomFactor(currentZoomFactor);
509 else // The hostname does not have domain settings.
511 // Reset the domain settings name.
512 currentPrivacyWebEngineViewPointer->domainSettingsName = QLatin1String("");
514 // Set the JavaScript status.
515 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
517 // Set the local storage status.
518 currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
520 // Set DOM storage. In QWebEngineSettings it is called Local Storage.
521 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
523 // Set the user agent.
524 currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
526 // Store the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
527 currentZoomFactor = Settings::zoomFactor();
529 // Set the zoom factor.
530 currentPrivacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
534 emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
535 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
536 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
537 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
538 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
539 emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
541 // Reload the website if requested.
543 currentPrivacyWebEngineViewPointer->reload();
546 void TabWidget::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
548 // Store the search engine name.
549 QString searchEngineName = searchEngineActionPointer->text();
551 // Strip out any `&` characters.
552 searchEngineName.remove('&');
554 // Store the search engine string.
555 searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
557 // Update the search engine actionas.
558 emit updateSearchEngineActions(searchEngineName, false);
561 void TabWidget::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
563 // Get the user agent name.
564 QString userAgentName = userAgentActionPointer->text();
566 // Strip out any `&` characters.
567 userAgentName.remove('&');
569 // Apply the user agent.
570 currentWebEngineProfilePointer->setHttpUserAgent(userAgentHelperPointer->getUserAgentFromTranslatedName(userAgentName));
572 // Update the user agent actions.
573 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), false);
575 // Reload the website.
576 currentPrivacyWebEngineViewPointer->reload();
579 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
580 void TabWidget::applyOnTheFlyZoomFactor(const double &zoomFactor)
582 // Update the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
583 currentZoomFactor = zoomFactor;
585 // Set the zoom factor.
586 currentPrivacyWebEngineViewPointer->setZoomFactor(zoomFactor);
589 void TabWidget::back() const
592 currentPrivacyWebEngineViewPointer->back();
595 void TabWidget::deleteAllCookies() const
597 // Delete all the cookies.
598 currentWebEngineCookieStorePointer->deleteAllCookies();
601 void TabWidget::deleteCookieFromStore(const QNetworkCookie &cookie) const
603 // Delete the cookie.
604 currentWebEngineCookieStorePointer->deleteCookie(cookie);
607 void TabWidget::deleteTab(const int tabIndex)
609 // Get the privacy WebEngine view.
610 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->widget(tabIndex));
612 // Proccess the tab delete according to the number of tabs.
613 if (tabWidgetPointer->count() > 1) // There is more than one tab.
616 tabWidgetPointer->removeTab(tabIndex);
618 // Delete the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
619 delete privacyWebEngineViewPointer->page();
621 // Delete the privacy WebEngine view.
622 delete privacyWebEngineViewPointer;
624 else // There is only one tab.
626 // Close Privacy Browser.
631 void TabWidget::findPrevious(const QString &text) const
633 // Store the current text.
634 currentPrivacyWebEngineViewPointer->findString = text;
636 // Find the previous text in the current privacy WebEngine.
637 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
638 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively|QWebEnginePage::FindBackward);
640 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindBackward);
643 void TabWidget::findText(const QString &text) const
645 // Store the current text.
646 currentPrivacyWebEngineViewPointer->findString = text;
648 // Find the text in the current privacy WebEngine.
649 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
650 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively);
652 currentPrivacyWebEngineViewPointer->findText(text);
654 // Clear the currently selected text in the WebEngine page if the find text is empty.
656 currentWebEnginePagePointer->action(QWebEnginePage::Unselect)->activate(QAction::Trigger);
659 void TabWidget::findTextFinished(const QWebEngineFindTextResult &findTextResult)
661 // Update the find text UI if it wasn't simply wiping the current find text selection. Otherwise the UI temporarially flashes `0/0`.
662 if (wipingCurrentFindTextSelection) // The current selection is being wiped.
665 wipingCurrentFindTextSelection = false;
667 else // A new search has been performed.
670 currentPrivacyWebEngineViewPointer->findTextResult = findTextResult;
673 emit updateFindTextResults(findTextResult);
677 void TabWidget::forward() const
680 currentPrivacyWebEngineViewPointer->forward();
683 void TabWidget::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest) const
686 emit fullScreenRequested(fullScreenRequest.toggleOn());
688 // Accept the request.
689 fullScreenRequest.accept();
692 std::list<QNetworkCookie>* TabWidget::getCookieList() const
694 // Return the current cookie list.
695 return currentPrivacyWebEngineViewPointer->cookieListPointer;
698 QString& TabWidget::getDomainSettingsName() const
700 // Return the domain settings name.
701 return currentPrivacyWebEngineViewPointer->domainSettingsName;
704 void TabWidget::home() const
706 // Load the homepage.
707 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
710 PrivacyWebEngineView* TabWidget::loadBlankInitialWebsite()
712 // Apply the application settings.
713 applyApplicationSettings();
715 // Return the current privacy WebEngine view pointer.
716 return currentPrivacyWebEngineViewPointer;
719 void TabWidget::loadInitialWebsite()
721 // Apply the application settings.
722 applyApplicationSettings();
724 // Get the arguments.
725 QStringList argumentsStringList = qApp->arguments();
727 // Check to see if the arguments lists contains a URL.
728 if (argumentsStringList.size() > 1)
730 // Load the URL from the arguments list.
731 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
735 // Load the homepage.
740 void TabWidget::loadUrlFromLineEdit(QString url) const
742 // Decide if the text is more likely to be a URL or a search.
743 if (url.startsWith("file://")) // The text is likely a file URL.
746 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
748 else if (url.contains(".")) // The text is likely a URL.
750 // Check if the URL does not start with a valid protocol.
751 if (!url.startsWith("http"))
753 // Add `https://` to the beginning of the URL.
754 url = "https://" + url;
758 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
760 else // The text is likely a search.
763 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
767 void TabWidget::mouseBack() const
769 // Go back if possible.
770 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoBack())
772 // Clear the URL line edit focus.
773 emit clearUrlLineEditFocus();
776 currentPrivacyWebEngineViewPointer->back();
780 void TabWidget::mouseForward() const
782 // Go forward if possible.
783 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoForward())
785 // Clear the URL line edit focus.
786 emit clearUrlLineEditFocus();
789 currentPrivacyWebEngineViewPointer->forward();
793 void TabWidget::pageLinkHovered(const QString &linkUrl) const
795 // Emit a signal so that the browser window can update the status bar.
796 emit linkHovered(linkUrl);
799 void TabWidget::print() const
804 // Set the resolution to be 300 dpi.
805 printer.setResolution(300);
807 // Create a printer dialog.
808 QPrintDialog printDialog(&printer, currentPrivacyWebEngineViewPointer);
810 // Display the dialog and print the page if instructed.
811 if (printDialog.exec() == QDialog::Accepted)
812 printWebpage(&printer);
815 void TabWidget::printPreview() const
820 // Set the resolution to be 300 dpi.
821 printer.setResolution(300);
823 // Create a print preview dialog.
824 QPrintPreviewDialog printPreviewDialog(&printer, currentPrivacyWebEngineViewPointer);
826 // Generate the print preview.
827 connect(&printPreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printWebpage(QPrinter *)));
829 // Display the dialog.
830 printPreviewDialog.exec();
833 void TabWidget::printWebpage(QPrinter *printerPointer) const
835 // Create an event loop. For some reason, the print preview doesn't produce any output unless it is run inside an event loop.
836 QEventLoop eventLoop;
838 // Print the webpage, converting the callback above into a `QWebEngineCallback<bool>`.
839 // Printing requires that the printer be a pointer, not a reference, or it will crash with much cursing.
840 currentWebEnginePagePointer->print(printerPointer, [&eventLoop](bool printSuccess)
842 // Instruct the compiler to ignore the unused parameter.
853 void TabWidget::refresh() const
855 // Reload the website.
856 currentPrivacyWebEngineViewPointer->reload();
859 void TabWidget::setTabBarVisible(const bool visible) const
861 // Set the tab bar visibility.
862 tabWidgetPointer->tabBar()->setVisible(visible);
865 void TabWidget::showSaveDialog(QWebEngineDownloadItem *webEngineDownloadItemPointer)
867 // Get the download attributes.
868 QUrl downloadUrl = webEngineDownloadItemPointer->url();
869 QString mimeTypeString = webEngineDownloadItemPointer->mimeType();
870 QString suggestedFileName = webEngineDownloadItemPointer->suggestedFileName();
871 int totalBytes = webEngineDownloadItemPointer->totalBytes();
873 // Check to see if local storage (cookies) is enabled.
874 if (currentPrivacyWebEngineViewPointer->localStorageEnabled) // Local storage (cookies) is enabled. Use WebEngine's downloader.
876 // Instantiate the save dialog.
877 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes);
879 // Display the save dialog.
880 int saveDialogResult = saveDialogPointer->exec();
882 // Process the save dialog results.
883 if (saveDialogResult == QDialog::Accepted) // Save was selected.
885 // Get the download directory.
886 QString downloadDirectory = Settings::downloadLocation();
888 // Resolve the system download directory if specified.
889 if (downloadDirectory == QLatin1String("System Download Directory"))
890 downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
892 // Display a save file dialog.
893 QString saveFilePath = QFileDialog::getSaveFileName(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory + QLatin1Char('/') + suggestedFileName);
895 // Process the save file path.
896 if (!saveFilePath.isEmpty()) // The file save path is populated.
898 // Create a save file path file info.
899 QFileInfo saveFilePathFileInfo = QFileInfo(saveFilePath);
901 // Get the canonical save path and file name.
902 QString absoluteSavePath = saveFilePathFileInfo.absolutePath();
903 QString saveFileName = saveFilePathFileInfo.fileName();
905 // Set the download directory and file name.
906 webEngineDownloadItemPointer->setDownloadDirectory(absoluteSavePath);
907 webEngineDownloadItemPointer->setDownloadFileName(saveFileName);
909 // Create a file download notification.
910 KNotification *fileDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
912 // Set the notification title.
913 fileDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
915 // Set the notification text.
916 fileDownloadNotificationPointer->setText(i18nc("Downloading notification text", "Downloading %1", saveFileName));
918 // Set the notification icon.
919 fileDownloadNotificationPointer->setIconName(QLatin1String("download"));
921 // Set the action list cancel button.
922 fileDownloadNotificationPointer->setActions(QStringList({i18nc("Download notification action","Cancel")}));
924 // Set the notification to display indefinitely.
925 fileDownloadNotificationPointer->setFlags(KNotification::Persistent);
927 // Prevent the notification from being autodeleted if it is closed. Otherwise, the updates to the notification below cause a crash.
928 fileDownloadNotificationPointer->setAutoDelete(false);
930 // Display the notification.
931 fileDownloadNotificationPointer->sendEvent();
933 // Handle clicks on the cancel button.
934 connect(fileDownloadNotificationPointer, &KNotification::action1Activated, [webEngineDownloadItemPointer, saveFileName] ()
936 // Cancel the download.
937 webEngineDownloadItemPointer->cancel();
939 // Create a file download notification.
940 KNotification *canceledDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
942 // Set the notification title.
943 canceledDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
946 canceledDownloadNotificationPointer->setText(i18nc("Download canceled notification", "%1 download canceled", saveFileName));
948 // Set the notification icon.
949 canceledDownloadNotificationPointer->setIconName(QLatin1String("download"));
951 // Display the notification.
952 canceledDownloadNotificationPointer->sendEvent();
955 // Update the notification when the download progresses.
956 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::downloadProgress, [fileDownloadNotificationPointer, saveFileName] (qint64 bytesReceived, qint64 totalBytes)
958 // Calculate the download percentage.
959 int downloadPercentage = 100 * bytesReceived / totalBytes;
961 // Set the new text. Total bytes will be 0 if the download size is unknown.
963 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1\% of %2 downloaded (%3 of %4 bytes)", downloadPercentage, saveFileName,
964 bytesReceived, totalBytes));
966 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1: %2 bytes downloaded", saveFileName, bytesReceived));
968 // Display the updated notification.
969 fileDownloadNotificationPointer->update();
972 // Update the notification when the download finishes. The save file name must be copied into the lambda or a crash occurs.
973 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::finished, [fileDownloadNotificationPointer, saveFileName, saveFilePath] ()
976 fileDownloadNotificationPointer->setText(i18nc("Download finished notification text", "%1 download finished", saveFileName));
978 // Set the URL so the file options will be displayed.
979 fileDownloadNotificationPointer->setUrls(QList<QUrl> {QUrl(saveFilePath)});
981 // Remove the actions from the notification.
982 fileDownloadNotificationPointer->setActions(QStringList());
984 // Set the notification to disappear after a timeout.
985 fileDownloadNotificationPointer->setFlags(KNotification::CloseOnTimeout);
987 // Display the updated notification.
988 fileDownloadNotificationPointer->update();
991 // Start the download.
992 webEngineDownloadItemPointer->accept();
994 else // The file save path is not populated.
996 // Cancel the download.
997 webEngineDownloadItemPointer->cancel();
1000 else // Cancel was selected.
1002 // Cancel the download.
1003 webEngineDownloadItemPointer->cancel();
1006 else // Local storage (cookies) is disabled. Use KDE's native downloader.
1007 // This must use the show command to launch a separate dialog which cancels WebEngine's automatic background download of the file to a temporary location.
1009 // Instantiate the save dialog. `true` instructs it to use the native downloader
1010 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes, suggestedFileName, true);
1012 // Connect the save button.
1013 connect(saveDialogPointer, SIGNAL(useNativeDownloader(QUrl &, QString &)), this, SLOT(useNativeDownloader(QUrl &, QString &)));
1016 saveDialogPointer->show();
1020 void TabWidget::toggleDomStorage() const
1022 // Toggle DOM storage.
1023 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1025 // Update the DOM storage action.
1026 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1028 // Reload the website.
1029 currentPrivacyWebEngineViewPointer->reload();
1032 void TabWidget::toggleFindCaseSensitive(const QString &text)
1034 // Toggle find case sensitive.
1035 currentPrivacyWebEngineViewPointer->findCaseSensitive = !currentPrivacyWebEngineViewPointer->findCaseSensitive;
1037 // Set the wiping current find text selection flag.
1038 wipingCurrentFindTextSelection = true;
1040 // Wipe the previous search. Otherwise currently highlighted words will remain highlighted.
1041 findText(QLatin1String(""));
1043 // Update the find text.
1047 void TabWidget::toggleJavaScript() const
1049 // Toggle JavaScript.
1050 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1052 // Update the JavaScript action.
1053 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1055 // Reload the website.
1056 currentPrivacyWebEngineViewPointer->reload();
1059 void TabWidget::toggleLocalStorage()
1061 // Toggle local storeage.
1062 currentPrivacyWebEngineViewPointer->localStorageEnabled = !currentPrivacyWebEngineViewPointer->localStorageEnabled;
1064 // Update the local storage action.
1065 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1067 // Reload the website.
1068 currentPrivacyWebEngineViewPointer->reload();
1071 void TabWidget::updateUiWithTabSettings()
1073 // Update the current WebEngine pointers.
1074 currentPrivacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->currentWidget());
1075 currentWebEngineSettingsPointer = currentPrivacyWebEngineViewPointer->settings();
1076 currentWebEnginePagePointer = currentPrivacyWebEngineViewPointer->page();
1077 currentWebEngineProfilePointer = currentWebEnginePagePointer->profile();
1078 currentWebEngineHistoryPointer = currentWebEnginePagePointer->history();
1079 currentWebEngineCookieStorePointer = currentWebEngineProfilePointer->cookieStore();
1081 // Clear the URL line edit focus.
1082 emit clearUrlLineEditFocus();
1084 // Update the actions.
1085 emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
1086 emit updateCookiesAction(currentPrivacyWebEngineViewPointer->cookieListPointer->size());
1087 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1088 emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
1089 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1090 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1091 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
1092 emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
1095 emit updateWindowTitle(currentPrivacyWebEngineViewPointer->title());
1096 emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
1097 emit updateUrlLineEdit(currentPrivacyWebEngineViewPointer->url());
1099 // Update the find text.
1100 emit updateFindText(currentPrivacyWebEngineViewPointer->findString, currentPrivacyWebEngineViewPointer->findCaseSensitive);
1101 emit updateFindTextResults(currentPrivacyWebEngineViewPointer->findTextResult);
1103 // Update the progress bar.
1104 if (currentPrivacyWebEngineViewPointer->loadProgressInt >= 0)
1105 emit showProgressBar(currentPrivacyWebEngineViewPointer->loadProgressInt);
1107 emit hideProgressBar();
1110 void TabWidget::useNativeDownloader(QUrl &downloadUrl, QString &suggestedFileName)
1112 // Get the download directory.
1113 QString downloadDirectory = Settings::downloadLocation();
1115 // Resolve the system download directory if specified.
1116 if (downloadDirectory == QLatin1String("System Download Directory"))
1117 downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
1119 // Create a save file dialog.
1120 QFileDialog *saveFileDialogPointer = new QFileDialog(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory);
1122 // Tell the dialog to use a save button.
1123 saveFileDialogPointer->setAcceptMode(QFileDialog::AcceptSave);
1125 // Populate the file name from the download item pointer.
1126 saveFileDialogPointer->selectFile(suggestedFileName);
1128 // Prevent interaction with the parent window while the dialog is open.
1129 saveFileDialogPointer->setWindowModality(Qt::WindowModal);
1131 // Process the saving of the file. The save file dialog pointer must be captured directly instead of by reference or nasty crashes occur.
1132 auto saveFile = [saveFileDialogPointer, downloadUrl] ()
1134 // Get the save location. The dialog box should only allow the selecting of one file location.
1135 QUrl saveLocation = saveFileDialogPointer->selectedUrls().value(0);
1137 // Create a file copy job. `-1` creates the file with default permissions.
1138 KIO::FileCopyJob *fileCopyJobPointer = KIO::file_copy(downloadUrl, saveLocation, -1, KIO::Overwrite);
1140 // Set the download job to display any error messages.
1141 fileCopyJobPointer->uiDelegate()->setAutoErrorHandlingEnabled(true);
1143 // Start the download.
1144 fileCopyJobPointer->start();
1147 // Handle clicks on the save button.
1148 connect(saveFileDialogPointer, &QDialog::accepted, this, saveFile);
1151 saveFileDialogPointer->show();