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 "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 prevetns 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 // Update the cookies action.
289 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::updateCookiesAction, [privacyWebEngineViewPointer, this] (const int numberOfCookies)
291 // Update the cookie action if the specified privacy WebEngine view is the current privacy WebEngine view.
292 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
293 emit updateCookiesAction(numberOfCookies);
296 // Process cookie changes.
297 connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(addCookieToList(QNetworkCookie)));
298 connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(removeCookieFromList(QNetworkCookie)));
300 // Get a list of durable cookies.
301 QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
303 // Add the durable cookies to the store.
304 for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
305 addCookieToStore(*cookiePointer, webEngineCookieStorePointer);
307 // Update the title when it changes.
308 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::titleChanged, [this, privacyWebEngineViewPointer] (const QString &title)
310 // Get the index for this tab.
311 int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
313 // Update the title for this tab.
314 tabWidgetPointer->setTabText(tabIndex, title);
316 // Update the window title if this is the current tab.
317 if (tabIndex == tabWidgetPointer->currentIndex())
318 emit updateWindowTitle(title);
321 // Update the icon when it changes.
322 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::iconChanged, [privacyWebEngineViewPointer, this] (const QIcon &icon)
324 // Get the index for this tab.
325 int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
327 // Update the icon for this tab.
329 tabWidgetPointer->setTabIcon(tabIndex, defaultTabIcon);
331 tabWidgetPointer->setTabIcon(tabIndex, icon);
334 // Enable spell checking.
335 webEngineProfilePointer->setSpellCheckEnabled(true);
337 // Set the spell check language.
338 webEngineProfilePointer->setSpellCheckLanguages({QLatin1String("en_US")});
340 // Populate the zoom factor. This is necessary if a URL is being loaded, like a local URL, that does not trigger `applyDomainSettings()`.
341 privacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
343 // Move to the new tab if it is not a background tab.
345 tabWidgetPointer->setCurrentIndex(newTabIndex);
347 // Clear the URL line edit focus so that it populates correctly when opening a new tab from the context menu.
348 if (removeUrlLineEditFocus)
349 emit clearUrlLineEditFocus();
351 // Return the privacy WebEngine view pointer.
352 return privacyWebEngineViewPointer;
355 void TabWidget::applyApplicationSettings()
357 // Set the tab position.
358 if (Settings::tabsOnTop())
359 tabWidgetPointer->setTabPosition(QTabWidget::North);
361 tabWidgetPointer->setTabPosition(QTabWidget::South);
363 // Set the search engine URL.
364 searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
366 // Emit the update search engine actions signal.
367 emit updateSearchEngineActions(Settings::searchEngine(), true);
370 // 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.
371 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
372 void TabWidget::applyDomainSettingsAndReload()
374 // Apply the domain settings. `true` reloads the website.
375 applyDomainSettings(currentPrivacyWebEngineViewPointer->url().host(), true);
378 // 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.
379 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
380 void TabWidget::applyDomainSettingsWithoutReloading(const QString &hostname)
382 // Apply the domain settings `false` does not reload the website.
383 applyDomainSettings(hostname, false);
386 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
387 void TabWidget::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
389 // Get the record for the hostname.
390 QSqlQuery domainQuery = DomainsDatabase::getDomainQuery(hostname);
392 // Check if the hostname has domain settings.
393 if (domainQuery.isValid()) // The hostname has domain settings.
395 // Get the domain record.
396 QSqlRecord domainRecord = domainQuery.record();
398 // Store the domain settings name.
399 currentPrivacyWebEngineViewPointer->domainSettingsName = domainRecord.field(DomainsDatabase::DOMAIN_NAME).value().toString();
401 // Set the JavaScript status.
402 switch (domainRecord.field(DomainsDatabase::JAVASCRIPT).value().toInt())
404 // Set the default JavaScript status.
405 case (DomainsDatabase::SYSTEM_DEFAULT):
407 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
412 // Disable JavaScript.
413 case (DomainsDatabase::DISABLED):
415 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
420 // Enable JavaScript.
421 case (DomainsDatabase::ENABLED):
423 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
429 // Set the local storage status.
430 switch (domainRecord.field(DomainsDatabase::LOCAL_STORAGE).value().toInt())
432 // Set the default local storage status.
433 case (DomainsDatabase::SYSTEM_DEFAULT):
435 currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
440 // Disable local storage.
441 case (DomainsDatabase::DISABLED):
443 currentPrivacyWebEngineViewPointer->localStorageEnabled = false;
448 // Enable local storage.
449 case (DomainsDatabase::ENABLED):
451 currentPrivacyWebEngineViewPointer->localStorageEnabled = true;
457 // Set the DOM storage status.
458 switch (domainRecord.field(DomainsDatabase::DOM_STORAGE).value().toInt())
460 // Set the default DOM storage status. QWebEngineSettings confusingly calls this local storage.
461 case (DomainsDatabase::SYSTEM_DEFAULT):
463 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
468 // Disable DOM storage. QWebEngineSettings confusingly calls this local storage.
469 case (DomainsDatabase::DISABLED):
471 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
476 // Enable DOM storage. QWebEngineSettings confusingly calls this local storage.
477 case (DomainsDatabase::ENABLED):
479 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
485 // Set the user agent.
486 currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabase::USER_AGENT).value().toString()));
488 // Check if a custom zoom factor is set.
489 if (domainRecord.field(DomainsDatabase::ZOOM_FACTOR).value().toInt())
491 // Store the current zoom factor.
492 currentZoomFactor = domainRecord.field(DomainsDatabase::CUSTOM_ZOOM_FACTOR).value().toDouble();
496 // Reset the current zoom factor.
497 currentZoomFactor = Settings::zoomFactor();
500 // Set the zoom factor. The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
501 currentPrivacyWebEngineViewPointer->setZoomFactor(currentZoomFactor);
503 else // The hostname does not have domain settings.
505 // Reset the domain settings name.
506 currentPrivacyWebEngineViewPointer->domainSettingsName = QLatin1String("");
508 // Set the JavaScript status.
509 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
511 // Set the local storage status.
512 currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
514 // Set DOM storage. In QWebEngineSettings it is called Local Storage.
515 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
517 // Set the user agent.
518 currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
520 // Store the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
521 currentZoomFactor = Settings::zoomFactor();
523 // Set the zoom factor.
524 currentPrivacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
528 emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
529 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
530 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
531 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
532 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
533 emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
535 // Reload the website if requested.
537 currentPrivacyWebEngineViewPointer->reload();
540 void TabWidget::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
542 // Store the search engine name.
543 QString searchEngineName = searchEngineActionPointer->text();
545 // Strip out any `&` characters.
546 searchEngineName.remove('&');
548 // Store the search engine string.
549 searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
551 // Update the search engine actionas.
552 emit updateSearchEngineActions(searchEngineName, false);
555 void TabWidget::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
557 // Get the user agent name.
558 QString userAgentName = userAgentActionPointer->text();
560 // Strip out any `&` characters.
561 userAgentName.remove('&');
563 // Apply the user agent.
564 currentWebEngineProfilePointer->setHttpUserAgent(userAgentHelperPointer->getUserAgentFromTranslatedName(userAgentName));
566 // Update the user agent actions.
567 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), false);
569 // Reload the website.
570 currentPrivacyWebEngineViewPointer->reload();
573 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
574 void TabWidget::applyOnTheFlyZoomFactor(const double &zoomFactor)
576 // Update the current zoom factor. This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
577 currentZoomFactor = zoomFactor;
579 // Set the zoom factor.
580 currentPrivacyWebEngineViewPointer->setZoomFactor(zoomFactor);
583 void TabWidget::back() const
586 currentPrivacyWebEngineViewPointer->back();
589 void TabWidget::deleteAllCookies() const
591 // Delete all the cookies.
592 currentWebEngineCookieStorePointer->deleteAllCookies();
595 void TabWidget::deleteCookieFromStore(const QNetworkCookie &cookie) const
597 // Delete the cookie.
598 currentWebEngineCookieStorePointer->deleteCookie(cookie);
601 void TabWidget::deleteTab(const int tabIndex)
603 // Get the privacy WebEngine view.
604 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->widget(tabIndex));
606 // Proccess the tab delete according to the number of tabs.
607 if (tabWidgetPointer->count() > 1) // There is more than one tab.
610 tabWidgetPointer->removeTab(tabIndex);
612 // Delete the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
613 delete privacyWebEngineViewPointer->page();
615 // Delete the privacy WebEngine view.
616 delete privacyWebEngineViewPointer;
618 else // There is only one tab.
620 // Close Privacy Browser.
625 void TabWidget::findPrevious(const QString &text) const
627 // Store the current text.
628 currentPrivacyWebEngineViewPointer->findString = text;
630 // Find the previous text in the current privacy WebEngine.
631 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
632 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively|QWebEnginePage::FindBackward);
634 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindBackward);
637 void TabWidget::findText(const QString &text) const
639 // Store the current text.
640 currentPrivacyWebEngineViewPointer->findString = text;
642 // Find the text in the current privacy WebEngine.
643 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
644 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively);
646 currentPrivacyWebEngineViewPointer->findText(text);
648 // Clear the currently selected text in the WebEngine page if the find text is empty.
650 currentWebEnginePagePointer->action(QWebEnginePage::Unselect)->activate(QAction::Trigger);
653 void TabWidget::findTextFinished(const QWebEngineFindTextResult &findTextResult)
655 // Update the find text UI if it wasn't simply wiping the current find text selection. Otherwise the UI temporarially flashes `0/0`.
656 if (wipingCurrentFindTextSelection) // The current selection is being wiped.
659 wipingCurrentFindTextSelection = false;
661 else // A new search has been performed.
664 currentPrivacyWebEngineViewPointer->findTextResult = findTextResult;
667 emit updateFindTextResults(findTextResult);
671 void TabWidget::forward() const
674 currentPrivacyWebEngineViewPointer->forward();
677 void TabWidget::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest) const
680 emit fullScreenRequested(fullScreenRequest.toggleOn());
682 // Accept the request.
683 fullScreenRequest.accept();
686 std::list<QNetworkCookie>* TabWidget::getCookieList() const
688 // Return the current cookie list.
689 return currentPrivacyWebEngineViewPointer->cookieListPointer;
692 QString& TabWidget::getDomainSettingsName() const
694 // Return the domain settings name.
695 return currentPrivacyWebEngineViewPointer->domainSettingsName;
698 void TabWidget::home() const
700 // Load the homepage.
701 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
704 PrivacyWebEngineView* TabWidget::loadBlankInitialWebsite()
706 // Apply the application settings.
707 applyApplicationSettings();
709 // Return the current privacy WebEngine view pointer.
710 return currentPrivacyWebEngineViewPointer;
713 void TabWidget::loadInitialWebsite()
715 // Apply the application settings.
716 applyApplicationSettings();
718 // Get the arguments.
719 QStringList argumentsStringList = qApp->arguments();
721 // Check to see if the arguments lists contains a URL.
722 if (argumentsStringList.size() > 1)
724 // Load the URL from the arguments list.
725 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
729 // Load the homepage.
734 void TabWidget::loadUrlFromLineEdit(QString url) const
736 // Decide if the text is more likely to be a URL or a search.
737 if (url.startsWith("file://")) // The text is likely a file URL.
740 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
742 else if (url.contains(".")) // The text is likely a URL.
744 // Check if the URL does not start with a valid protocol.
745 if (!url.startsWith("http"))
747 // Add `https://` to the beginning of the URL.
748 url = "https://" + url;
752 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
754 else // The text is likely a search.
757 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
761 void TabWidget::mouseBack() const
763 // Go back if possible.
764 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoBack())
766 // Clear the URL line edit focus.
767 emit clearUrlLineEditFocus();
770 currentPrivacyWebEngineViewPointer->back();
774 void TabWidget::mouseForward() const
776 // Go forward if possible.
777 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoForward())
779 // Clear the URL line edit focus.
780 emit clearUrlLineEditFocus();
783 currentPrivacyWebEngineViewPointer->forward();
787 void TabWidget::pageLinkHovered(const QString &linkUrl) const
789 // Emit a signal so that the browser window can update the status bar.
790 emit linkHovered(linkUrl);
793 void TabWidget::print() const
798 // Set the resolution to be 300 dpi.
799 printer.setResolution(300);
801 // Create a printer dialog.
802 QPrintDialog printDialog(&printer, currentPrivacyWebEngineViewPointer);
804 // Display the dialog and print the page if instructed.
805 if (printDialog.exec() == QDialog::Accepted)
806 printWebpage(&printer);
809 void TabWidget::printPreview() const
814 // Set the resolution to be 300 dpi.
815 printer.setResolution(300);
817 // Create a print preview dialog.
818 QPrintPreviewDialog printPreviewDialog(&printer, currentPrivacyWebEngineViewPointer);
820 // Generate the print preview.
821 connect(&printPreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printWebpage(QPrinter *)));
823 // Display the dialog.
824 printPreviewDialog.exec();
827 void TabWidget::printWebpage(QPrinter *printerPointer) const
829 // Create an event loop. For some reason, the print preview doesn't produce any output unless it is run inside an event loop.
830 QEventLoop eventLoop;
832 // Print the webpage, converting the callback above into a `QWebEngineCallback<bool>`.
833 // Printing requires that the printer be a pointer, not a reference, or it will crash with much cursing.
834 currentWebEnginePagePointer->print(printerPointer, [&eventLoop](bool printSuccess)
836 // Instruct the compiler to ignore the unused parameter.
847 void TabWidget::refresh() const
849 // Reload the website.
850 currentPrivacyWebEngineViewPointer->reload();
853 void TabWidget::setTabBarVisible(const bool visible) const
855 // Set the tab bar visibility.
856 tabWidgetPointer->tabBar()->setVisible(visible);
859 void TabWidget::showSaveDialog(QWebEngineDownloadItem *webEngineDownloadItemPointer)
861 // Get the download attributes.
862 QUrl downloadUrl = webEngineDownloadItemPointer->url();
863 QString mimeTypeString = webEngineDownloadItemPointer->mimeType();
864 QString suggestedFileName = webEngineDownloadItemPointer->suggestedFileName();
865 int totalBytes = webEngineDownloadItemPointer->totalBytes();
867 // Check to see if local storage (cookies) is enabled.
868 if (currentPrivacyWebEngineViewPointer->localStorageEnabled) // Local storage (cookies) is enabled. Use WebEngine's downloader.
870 // Instantiate the save dialog.
871 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes);
873 // Display the save dialog.
874 int saveDialogResult = saveDialogPointer->exec();
876 // Process the save dialog results.
877 if (saveDialogResult == QDialog::Accepted) // Save was selected.
879 // Get the download directory.
880 QString downloadDirectory = Settings::downloadLocation();
882 // Resolve the system download directory if specified.
883 if (downloadDirectory == QLatin1String("System Download Directory"))
884 downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
886 // Display a save file dialog.
887 QString saveFilePath = QFileDialog::getSaveFileName(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory + QLatin1Char('/') + suggestedFileName);
889 // Process the save file path.
890 if (!saveFilePath.isEmpty()) // The file save path is populated.
892 // Create a save file path file info.
893 QFileInfo saveFilePathFileInfo = QFileInfo(saveFilePath);
895 // Get the canonical save path and file name.
896 QString absoluteSavePath = saveFilePathFileInfo.absolutePath();
897 QString saveFileName = saveFilePathFileInfo.fileName();
899 // Set the download directory and file name.
900 webEngineDownloadItemPointer->setDownloadDirectory(absoluteSavePath);
901 webEngineDownloadItemPointer->setDownloadFileName(saveFileName);
903 // Create a file download notification.
904 KNotification *fileDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
906 // Set the notification title.
907 fileDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
909 // Set the notification text.
910 fileDownloadNotificationPointer->setText(i18nc("Downloading notification text", "Downloading %1", saveFileName));
912 // Set the notification icon.
913 fileDownloadNotificationPointer->setIconName(QLatin1String("download"));
915 // Set the action list cancel button.
916 fileDownloadNotificationPointer->setActions(QStringList({i18nc("Download notification action","Cancel")}));
918 // Set the notification to display indefinitely.
919 fileDownloadNotificationPointer->setFlags(KNotification::Persistent);
921 // Prevent the notification from being autodeleted if it is closed. Otherwise, the updates to the notification below cause a crash.
922 fileDownloadNotificationPointer->setAutoDelete(false);
924 // Display the notification.
925 fileDownloadNotificationPointer->sendEvent();
927 // Handle clicks on the cancel button.
928 connect(fileDownloadNotificationPointer, &KNotification::action1Activated, [webEngineDownloadItemPointer, saveFileName] ()
930 // Cancel the download.
931 webEngineDownloadItemPointer->cancel();
933 // Create a file download notification.
934 KNotification *canceledDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
936 // Set the notification title.
937 canceledDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
940 canceledDownloadNotificationPointer->setText(i18nc("Download canceled notification", "%1 download canceled", saveFileName));
942 // Set the notification icon.
943 canceledDownloadNotificationPointer->setIconName(QLatin1String("download"));
945 // Display the notification.
946 canceledDownloadNotificationPointer->sendEvent();
949 // Update the notification when the download progresses.
950 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::downloadProgress, [fileDownloadNotificationPointer, saveFileName] (qint64 bytesReceived, qint64 totalBytes)
952 // Calculate the download percentage.
953 int downloadPercentage = 100 * bytesReceived / totalBytes;
955 // Set the new text. Total bytes will be 0 if the download size is unknown.
957 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1\% of %2 downloaded (%3 of %4 bytes)", downloadPercentage, saveFileName,
958 bytesReceived, totalBytes));
960 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1: %2 bytes downloaded", saveFileName, bytesReceived));
962 // Display the updated notification.
963 fileDownloadNotificationPointer->update();
966 // Update the notification when the download finishes. The save file name must be copied into the lambda or a crash occurs.
967 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::finished, [fileDownloadNotificationPointer, saveFileName, saveFilePath] ()
970 fileDownloadNotificationPointer->setText(i18nc("Download finished notification text", "%1 download finished", saveFileName));
972 // Set the URL so the file options will be displayed.
973 fileDownloadNotificationPointer->setUrls(QList<QUrl> {QUrl(saveFilePath)});
975 // Remove the actions from the notification.
976 fileDownloadNotificationPointer->setActions(QStringList());
978 // Set the notification to disappear after a timeout.
979 fileDownloadNotificationPointer->setFlags(KNotification::CloseOnTimeout);
981 // Display the updated notification.
982 fileDownloadNotificationPointer->update();
985 // Start the download.
986 webEngineDownloadItemPointer->accept();
988 else // The file save path is not populated.
990 // Cancel the download.
991 webEngineDownloadItemPointer->cancel();
994 else // Cancel was selected.
996 // Cancel the download.
997 webEngineDownloadItemPointer->cancel();
1000 else // Local storage (cookies) is disabled. Use KDE's native downloader.
1001 // 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.
1003 // Instantiate the save dialog. `true` instructs it to use the native downloader
1004 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes, suggestedFileName, true);
1006 // Connect the save button.
1007 connect(saveDialogPointer, SIGNAL(useNativeDownloader(QUrl &, QString &)), this, SLOT(useNativeDownloader(QUrl &, QString &)));
1010 saveDialogPointer->show();
1014 void TabWidget::toggleDomStorage() const
1016 // Toggle DOM storage.
1017 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1019 // Update the DOM storage action.
1020 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1022 // Reload the website.
1023 currentPrivacyWebEngineViewPointer->reload();
1026 void TabWidget::toggleFindCaseSensitive(const QString &text)
1028 // Toggle find case sensitive.
1029 currentPrivacyWebEngineViewPointer->findCaseSensitive = !currentPrivacyWebEngineViewPointer->findCaseSensitive;
1031 // Set the wiping current find text selection flag.
1032 wipingCurrentFindTextSelection = true;
1034 // Wipe the previous search. Otherwise currently highlighted words will remain highlighted.
1035 findText(QLatin1String(""));
1037 // Update the find text.
1041 void TabWidget::toggleJavaScript() const
1043 // Toggle JavaScript.
1044 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1046 // Update the JavaScript action.
1047 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1049 // Reload the website.
1050 currentPrivacyWebEngineViewPointer->reload();
1053 void TabWidget::toggleLocalStorage()
1055 // Toggle local storeage.
1056 currentPrivacyWebEngineViewPointer->localStorageEnabled = !currentPrivacyWebEngineViewPointer->localStorageEnabled;
1058 // Update the local storage action.
1059 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1061 // Reload the website.
1062 currentPrivacyWebEngineViewPointer->reload();
1065 void TabWidget::updateUiWithTabSettings()
1067 // Update the current WebEngine pointers.
1068 currentPrivacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->currentWidget());
1069 currentWebEngineSettingsPointer = currentPrivacyWebEngineViewPointer->settings();
1070 currentWebEnginePagePointer = currentPrivacyWebEngineViewPointer->page();
1071 currentWebEngineProfilePointer = currentWebEnginePagePointer->profile();
1072 currentWebEngineHistoryPointer = currentWebEnginePagePointer->history();
1073 currentWebEngineCookieStorePointer = currentWebEngineProfilePointer->cookieStore();
1075 // Clear the URL line edit focus.
1076 emit clearUrlLineEditFocus();
1078 // Update the actions.
1079 emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
1080 emit updateCookiesAction(currentPrivacyWebEngineViewPointer->cookieListPointer->size());
1081 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1082 emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
1083 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1084 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1085 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
1086 emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
1089 emit updateWindowTitle(currentPrivacyWebEngineViewPointer->title());
1090 emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
1091 emit updateUrlLineEdit(currentPrivacyWebEngineViewPointer->url());
1093 // Update the find text.
1094 emit updateFindText(currentPrivacyWebEngineViewPointer->findString, currentPrivacyWebEngineViewPointer->findCaseSensitive);
1095 emit updateFindTextResults(currentPrivacyWebEngineViewPointer->findTextResult);
1097 // Update the progress bar.
1098 if (currentPrivacyWebEngineViewPointer->loadProgressInt >= 0)
1099 emit showProgressBar(currentPrivacyWebEngineViewPointer->loadProgressInt);
1101 emit hideProgressBar();
1104 void TabWidget::useNativeDownloader(QUrl &downloadUrl, QString &suggestedFileName)
1106 // Get the download directory.
1107 QString downloadDirectory = Settings::downloadLocation();
1109 // Resolve the system download directory if specified.
1110 if (downloadDirectory == QLatin1String("System Download Directory"))
1111 downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
1113 // Create a save file dialog.
1114 QFileDialog *saveFileDialogPointer = new QFileDialog(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory);
1116 // Tell the dialog to use a save button.
1117 saveFileDialogPointer->setAcceptMode(QFileDialog::AcceptSave);
1119 // Populate the file name from the download item pointer.
1120 saveFileDialogPointer->selectFile(suggestedFileName);
1122 // Prevent interaction with the parent window while the dialog is open.
1123 saveFileDialogPointer->setWindowModality(Qt::WindowModal);
1125 // Process the saving of the file. The save file dialog pointer must be captured directly instead of by reference or nasty crashes occur.
1126 auto saveFile = [saveFileDialogPointer, downloadUrl] ()
1128 // Get the save location. The dialog box should only allow the selecting of one file location.
1129 QUrl saveLocation = saveFileDialogPointer->selectedUrls().value(0);
1131 // Create a file copy job. `-1` creates the file with default permissions.
1132 KIO::FileCopyJob *fileCopyJobPointer = KIO::file_copy(downloadUrl, saveLocation, -1, KIO::Overwrite);
1134 // Set the download job to display any error messages.
1135 fileCopyJobPointer->uiDelegate()->setAutoErrorHandlingEnabled(true);
1137 // Start the download.
1138 fileCopyJobPointer->start();
1141 // Handle clicks on the save button.
1142 connect(saveFileDialogPointer, &QDialog::accepted, this, saveFile);
1145 saveFileDialogPointer->show();