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 "dialogs/SaveDialog.h"
27 #include "filters/MouseEventFilter.h"
28 #include "helpers/SearchEngineHelper.h"
29 #include "windows/BrowserWindow.h"
31 // KDE Framework headers.
32 #include <KIO/FileCopyJob>
33 #include <KIO/JobUiDelegate>
34 #include <KNotification>
36 // Qt toolkit headers.
38 #include <QFileDialog>
39 #include <QGraphicsScene>
40 #include <QGraphicsView>
41 #include <QMessageBox>
42 #include <QPrintDialog>
43 #include <QPrintPreviewDialog>
46 // Initialize the public static variables.
47 QString TabWidget::webEngineDefaultUserAgent = QLatin1String("");
49 // Construct the class.
50 TabWidget::TabWidget(QWidget *windowPointer) : QWidget(windowPointer)
52 // Create a QProcess to check if KDE is running.
53 QProcess *checkIfRunningKdeQProcessPointer = new QProcess();
55 // Create an argument string list that contains `ksmserver` (KDE Session Manager).
56 QStringList argument = QStringList(QLatin1String("ksmserver"));
58 // Run `pidof` to check for the presence of `ksmserver`.
59 checkIfRunningKdeQProcessPointer->start(QLatin1String("pidof"), argument);
61 // Monitor any standard output.
62 connect(checkIfRunningKdeQProcessPointer, &QProcess::readyReadStandardOutput, [this]
64 // If there is any standard output, `ksmserver` is running.
68 // Instantiate the user agent helper.
69 userAgentHelperPointer = new UserAgentHelper();
71 // Instantiate the UIs.
72 Ui::TabWidget tabWidgetUi;
73 Ui::AddTabWidget addTabWidgetUi;
76 tabWidgetUi.setupUi(this);
78 // Get a handle for the tab widget.
79 qTabWidgetPointer = tabWidgetUi.tabWidget;
81 // Setup the add tab UI.
82 addTabWidgetUi.setupUi(qTabWidgetPointer);
84 // Get handles for the add tab widgets.
85 QWidget *addTabWidgetPointer = addTabWidgetUi.addTabQWidget;
86 QPushButton *addTabButtonPointer = addTabWidgetUi.addTabButton;
88 // Display the add tab widget.
89 qTabWidgetPointer->setCornerWidget(addTabWidgetPointer);
91 // Create the loading favorite icon movie.
92 loadingFavoriteIconMoviePointer = new QMovie();
94 // Set the loading favorite icon movie file name.
95 loadingFavoriteIconMoviePointer->setFileName(QStringLiteral(":/icons/loading.gif"));
97 // Stop the loading favorite icon movie if the window is destroyed. Otherwise, the app will crash if there is more than one window open and a window is closed while at tab is loading.
98 connect(windowPointer, SIGNAL(destroyed()), this, SLOT(stopLoadingFavoriteIconMovie()));
100 // Add the first tab.
103 // Process tab events.
104 connect(qTabWidgetPointer, SIGNAL(currentChanged(int)), this, SLOT(updateUiWithTabSettings()));
105 connect(addTabButtonPointer, SIGNAL(clicked()), this, SLOT(addTab()));
106 connect(qTabWidgetPointer, SIGNAL(tabCloseRequested(int)), this, SLOT(deleteTab(int)));
108 // Store a copy of the WebEngine default user agent.
109 webEngineDefaultUserAgent = currentWebEngineProfilePointer->httpUserAgent();
111 // Instantiate the mouse event filter pointer.
112 MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
114 // Install the mouse event filter.
115 qApp->installEventFilter(mouseEventFilterPointer);
117 // Process mouse forward and back commands.
118 connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
119 connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
122 TabWidget::~TabWidget()
124 // Get the number of tabs.
125 int numberOfTabs = qTabWidgetPointer->count();
127 // Manually delete each WebEngine page.
128 for (int i = 0; i < numberOfTabs; ++i)
130 // Get the privacy WebEngine view.
131 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->widget(i));
133 // Deletion the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
134 delete privacyWebEngineViewPointer->page();
138 // 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.
139 void TabWidget::addCookieToStore(QNetworkCookie cookie, QWebEngineCookieStore *webEngineCookieStorePointer) const
144 // 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>
145 if (!cookie.domain().startsWith(QLatin1String(".")))
148 url.setHost(cookie.domain());
149 url.setScheme(QLatin1String("https"));
151 // Clear the domain from the cookie.
152 cookie.setDomain(QLatin1String(""));
155 // Add the cookie to the store.
156 if (webEngineCookieStorePointer == nullptr)
157 currentWebEngineCookieStorePointer->setCookie(cookie, url);
159 webEngineCookieStorePointer->setCookie(cookie, url);
162 void TabWidget::addFirstTab()
164 // Create the first tab.
167 // Update the UI with the tab settings.
168 updateUiWithTabSettings();
170 // 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.
171 qTabWidgetPointer->currentWidget()->setFocus();
174 PrivacyWebEngineView* TabWidget::addTab(const bool removeUrlLineEditFocus, const bool backgroundTab)
176 // Create a privacy WebEngine view.
177 PrivacyWebEngineView *privacyWebEngineViewPointer = new PrivacyWebEngineView();
180 int newTabIndex = qTabWidgetPointer->addTab(privacyWebEngineViewPointer, i18nc("New tab label.", "New Tab"));
182 // Set the default tab icon.
183 qTabWidgetPointer->setTabIcon(newTabIndex, defaultFavoriteIcon);
185 // Get handles for the WebEngine page and profile.
186 QWebEnginePage *webEnginePagePointer = privacyWebEngineViewPointer->page();
187 QWebEngineProfile *webEngineProfilePointer = webEnginePagePointer->profile();
189 // Get handles for the web engine elements.
190 QWebEngineCookieStore *webEngineCookieStorePointer = webEngineProfilePointer->cookieStore();
191 QWebEngineSettings *webEngineSettingsPointer = webEnginePagePointer->settings();
193 // Update the URL line edit when the URL changes.
194 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::urlChanged, [this, privacyWebEngineViewPointer] (const QUrl &newUrl)
196 // Only update the UI if this is the current tab.
197 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
199 // Update the URL line edit.
200 emit updateUrlLineEdit(newUrl);
202 // Update the status of the forward and back buttons.
203 emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
204 emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
208 // Update the title when it changes.
209 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::titleChanged, [this, privacyWebEngineViewPointer] (const QString &title)
211 // Get the index for this tab.
212 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
214 // Update the title for this tab.
215 qTabWidgetPointer->setTabText(tabIndex, title);
217 // Update the window title if this is the current tab.
218 if (tabIndex == qTabWidgetPointer->currentIndex())
219 emit updateWindowTitle(title);
222 // Connect the loading favorite icon movie to the tab icon.
223 connect(loadingFavoriteIconMoviePointer, &QMovie::frameChanged, [this, privacyWebEngineViewPointer]
225 // Get the index for this tab.
226 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
228 // Display the loading favorite icon if this tab is loading.
229 if (privacyWebEngineViewPointer->isLoading)
230 qTabWidgetPointer->setTabIcon(tabIndex, loadingFavoriteIconMoviePointer->currentPixmap());
233 // Update the icon when it changes.
234 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::iconChanged, [this, privacyWebEngineViewPointer] (const QIcon &newFavoriteIcon)
236 // Store the favorite icon in the privacy web engine view.
237 if (newFavoriteIcon.isNull())
238 privacyWebEngineViewPointer->favoriteIcon = defaultFavoriteIcon;
240 privacyWebEngineViewPointer->favoriteIcon = newFavoriteIcon;
242 // Get the index for this tab.
243 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
245 // Update the icon for this tab.
246 if (newFavoriteIcon.isNull())
247 qTabWidgetPointer->setTabIcon(tabIndex, defaultFavoriteIcon);
249 qTabWidgetPointer->setTabIcon(tabIndex, newFavoriteIcon);
252 // Update the progress bar and the favorite icon when a load is started.
253 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadStarted, [this, privacyWebEngineViewPointer] ()
255 // Set the privacy web engine view to be loading.
256 privacyWebEngineViewPointer->isLoading = true;
258 // Store the load progress.
259 privacyWebEngineViewPointer->loadProgressInt = 0;
261 // Show the progress bar if this is the current tab.
262 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
263 emit showProgressBar(0);
265 // Start the loading favorite icon movie.
266 loadingFavoriteIconMoviePointer->start();
269 // Update the progress bar when a load progresses.
270 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadProgress, [this, privacyWebEngineViewPointer] (const int progress)
272 // Store the load progress.
273 privacyWebEngineViewPointer->loadProgressInt = progress;
275 // Update the progress bar if this is the current tab.
276 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
277 emit showProgressBar(progress);
280 // Update the progress bar when a load finishes.
281 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadFinished, [this, privacyWebEngineViewPointer] ()
283 // Set the privacy web engine view to be not loading.
284 privacyWebEngineViewPointer->isLoading = false;
286 // Store the load progress.
287 privacyWebEngineViewPointer->loadProgressInt = -1;
289 // Hide the progress bar if this is the current tab.
290 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
291 emit hideProgressBar();
293 // Get the index for this tab.
294 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
296 // Display the current favorite icon
297 qTabWidgetPointer->setTabIcon(tabIndex, privacyWebEngineViewPointer->favoriteIcon);
299 // Create a no tabs loading variable.
300 bool noTabsLoading = true;
302 // Get the number of tabs.
303 int numberOfTabs = qTabWidgetPointer->count();
305 // Check to see if any other tabs are loading.
306 for (int i = 0; i < numberOfTabs; i++)
308 // Get the privacy WebEngine view for the tab.
309 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView*>(qTabWidgetPointer->widget(i));
311 // Check to see if it is currently loading. If at least one tab is loading, this flag will end up being marked `false` when the for loop has finished.
312 if (privacyWebEngineViewPointer->isLoading)
313 noTabsLoading = false;
316 // Stop the loading favorite icon movie if there are no loading tabs.
318 loadingFavoriteIconMoviePointer->stop();
321 // Display HTTP Ping blocked dialogs.
322 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::displayHttpPingBlockedDialog, [this, privacyWebEngineViewPointer] (const QString &httpPingUrl)
324 // Only display the HTTP Ping blocked dialog if this is the current tab.
325 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
327 // Instantiate an HTTP ping blocked message box.
328 QMessageBox httpPingBlockedMessageBox;
331 httpPingBlockedMessageBox.setIcon(QMessageBox::Information);
333 // Set the window title.
334 httpPingBlockedMessageBox.setWindowTitle(i18nc("HTTP Ping blocked dialog title", "HTTP Ping Blocked"));
337 httpPingBlockedMessageBox.setText(i18nc("HTTP Ping blocked dialog text", "This request has been blocked because it sends a naughty HTTP ping to %1.", httpPingUrl));
339 // Set the standard button.
340 httpPingBlockedMessageBox.setStandardButtons(QMessageBox::Ok);
342 // Display the message box.
343 httpPingBlockedMessageBox.exec();
347 // Update the zoom factor when changed by CTRL-Scrolling. This can be modified when <https://redmine.stoutner.com/issues/845> is fixed.
348 connect(webEnginePagePointer, &QWebEnginePage::contentsSizeChanged, [webEnginePagePointer, this] ()
350 // Only update the zoom factor action text if this is the current tab.
351 if (webEnginePagePointer == currentWebEnginePagePointer)
352 emit updateZoomFactorAction(webEnginePagePointer->zoomFactor());
355 // Display find text results.
356 connect(webEnginePagePointer, SIGNAL(findTextFinished(const QWebEngineFindTextResult &)), this, SLOT(findTextFinished(const QWebEngineFindTextResult &)));
358 // Handle full screen requests.
359 connect(webEnginePagePointer, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this, SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
361 // Listen for hovered link URLs.
362 connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
364 // Handle file downloads.
365 connect(webEngineProfilePointer, SIGNAL(downloadRequested(QWebEngineDownloadItem *)), this, SLOT(showSaveDialog(QWebEngineDownloadItem *)));
367 // Set the local storage filter.
368 webEngineCookieStorePointer->setCookieFilter([privacyWebEngineViewPointer](const QWebEngineCookieStore::FilterRequest &filterRequest)
370 // Block all third party local storage requests, including the sneaky ones that don't register a first party URL.
371 if (filterRequest.thirdParty || (filterRequest.firstPartyUrl == QStringLiteral("")))
373 //qDebug().noquote().nospace() << "Third-party request blocked: " << filterRequest.origin;
379 // Allow the request if local storage is enabled.
380 if (privacyWebEngineViewPointer->localStorageEnabled)
382 //qDebug().noquote().nospace() << "Request allowed by local storage: " << filterRequest.origin;
388 //qDebug().noquote().nospace() << "Request blocked by default: " << filterRequest.origin;
390 // Block any remaining local storage requests.
394 // Disable JavaScript by default (this prevents JavaScript from being enabled on a new tab before domain settings are loaded).
395 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
397 // Don't allow JavaScript to open windows.
398 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
400 // Allow keyboard navigation between links and input fields.
401 webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, Settings::spatialNavigation());
403 // Enable full screen support.
404 webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
406 // Require user interaction to play media.
407 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
409 // Limit WebRTC to public IP addresses.
410 webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
412 // Enable the PDF viewer (it should be enabled by default, but it is nice to be explicit in case the defaults change).
413 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PdfViewerEnabled, true);
415 // Plugins must be enabled for the PDF viewer to work. <https://doc.qt.io/qt-5/qtwebengine-features.html#pdf-file-viewing>
416 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PluginsEnabled, true);
418 // Update the cookies action.
419 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::updateCookiesAction, [this, privacyWebEngineViewPointer] (const int numberOfCookies)
421 // Update the cookie action if the specified privacy WebEngine view is the current privacy WebEngine view.
422 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
423 emit updateCookiesAction(numberOfCookies);
426 // Process cookie changes.
427 connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(addCookieToList(QNetworkCookie)));
428 connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(removeCookieFromList(QNetworkCookie)));
430 // Get a list of durable cookies.
431 QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
433 // Add the durable cookies to the store.
434 for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
435 addCookieToStore(*cookiePointer, webEngineCookieStorePointer);
437 // Enable spell checking.
438 webEngineProfilePointer->setSpellCheckEnabled(true);
440 // Set the spell check language.
441 webEngineProfilePointer->setSpellCheckLanguages(Settings::spellCheckLanguages());
443 // Populate the zoom factor. This is necessary if a URL is being loaded, like a local URL, that does not trigger `applyDomainSettings()`.
444 privacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
446 // Update the UI when domain settings are applied.
447 connect(privacyWebEngineViewPointer, SIGNAL(updateUi(const PrivacyWebEngineView*)), this, SLOT(updateUiFromWebEngineView(const PrivacyWebEngineView*)));
449 // Move to the new tab if it is not a background tab.
451 qTabWidgetPointer->setCurrentIndex(newTabIndex);
453 // Clear the URL line edit focus so that it populates correctly when opening a new tab from the context menu.
454 if (removeUrlLineEditFocus)
455 emit clearUrlLineEditFocus();
457 // Return the privacy WebEngine view pointer.
458 return privacyWebEngineViewPointer;
461 void TabWidget::applyApplicationSettings()
463 // Set the tab position.
464 if (Settings::tabsOnTop())
465 qTabWidgetPointer->setTabPosition(QTabWidget::North);
467 qTabWidgetPointer->setTabPosition(QTabWidget::South);
469 // Get the number of tabs.
470 int numberOfTabs = qTabWidgetPointer->count();
472 // Apply the spatial navigation settings to each WebEngine.
473 for (int i = 0; i < numberOfTabs; ++i) {
474 // Get the WebEngine view pointer.
475 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->widget(i));
477 // Apply the spatial navigation settings to each page.
478 privacyWebEngineViewPointer->page()->settings()->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, Settings::spatialNavigation());
481 // Set the search engine URL.
482 searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
484 // Emit the update search engine actions signal.
485 emit updateSearchEngineActions(Settings::searchEngine(), true);
488 void TabWidget::applyDomainSettingsAndReload()
490 // Apply the domain settings. `true` reloads the website.
491 currentPrivacyWebEngineViewPointer->applyDomainSettings(currentPrivacyWebEngineViewPointer->url().host(), true);
494 void TabWidget::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
496 // Store the search engine name.
497 QString searchEngineName = searchEngineActionPointer->text();
499 // Strip out any `&` characters.
500 searchEngineName.remove('&');
502 // Store the search engine string.
503 searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
505 // Update the search engine actions.
506 emit updateSearchEngineActions(searchEngineName, false);
509 void TabWidget::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
511 // Get the user agent name.
512 QString userAgentName = userAgentActionPointer->text();
514 // Strip out any `&` characters.
515 userAgentName.remove('&');
517 // Apply the user agent.
518 currentWebEngineProfilePointer->setHttpUserAgent(userAgentHelperPointer->getUserAgentFromTranslatedName(userAgentName));
520 // Update the user agent actions.
521 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), false);
523 // Reload the website.
524 currentPrivacyWebEngineViewPointer->reload();
527 void TabWidget::applyOnTheFlyZoomFactor(const double &zoomFactor) const
529 // Set the zoom factor.
530 currentPrivacyWebEngineViewPointer->setZoomFactor(zoomFactor);
533 void TabWidget::applySpellCheckLanguages() const
535 // Get the number of tab.
536 int numberOfTabs = qTabWidgetPointer->count();
538 // Set the spell check languages for each tab.
539 for (int i = 0; i < numberOfTabs; ++i)
541 // Get the WebEngine view pointer.
542 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->widget(i));
544 // Get the WebEngine page pointer.
545 QWebEnginePage *webEnginePagePointer = privacyWebEngineViewPointer->page();
547 // Get the WebEngine profile pointer.
548 QWebEngineProfile *webEngineProfilePointer = webEnginePagePointer->profile();
550 // Set the spell check languages.
551 webEngineProfilePointer->setSpellCheckLanguages(Settings::spellCheckLanguages());
555 void TabWidget::back() const
558 currentPrivacyWebEngineViewPointer->back();
561 void TabWidget::deleteAllCookies() const
563 // Delete all the cookies.
564 currentWebEngineCookieStorePointer->deleteAllCookies();
567 void TabWidget::deleteCookieFromStore(const QNetworkCookie &cookie) const
569 // Delete the cookie.
570 currentWebEngineCookieStorePointer->deleteCookie(cookie);
573 void TabWidget::deleteTab(const int tabIndex)
575 // Get the privacy WebEngine view.
576 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->widget(tabIndex));
578 // Process the tab delete according to the number of tabs.
579 if (qTabWidgetPointer->count() > 1) // There is more than one tab.
582 qTabWidgetPointer->removeTab(tabIndex);
584 // Delete the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
585 delete privacyWebEngineViewPointer->page();
587 // Delete the privacy WebEngine view.
588 delete privacyWebEngineViewPointer;
590 else // There is only one tab.
592 // Close Privacy Browser.
597 void TabWidget::findPrevious(const QString &text) const
599 // Store the current text.
600 currentPrivacyWebEngineViewPointer->findString = text;
602 // Find the previous text in the current privacy WebEngine.
603 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
604 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively|QWebEnginePage::FindBackward);
606 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindBackward);
609 void TabWidget::findText(const QString &text) const
611 // Store the current text.
612 currentPrivacyWebEngineViewPointer->findString = text;
614 // Find the text in the current privacy WebEngine.
615 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
616 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively);
618 currentPrivacyWebEngineViewPointer->findText(text);
620 // Clear the currently selected text in the WebEngine page if the find text is empty.
622 currentWebEnginePagePointer->action(QWebEnginePage::Unselect)->activate(QAction::Trigger);
625 void TabWidget::findTextFinished(const QWebEngineFindTextResult &findTextResult)
627 // Update the find text UI if it wasn't simply wiping the current find text selection. Otherwise the UI temporarily flashes `0/0`.
628 if (wipingCurrentFindTextSelection) // The current selection is being wiped.
631 wipingCurrentFindTextSelection = false;
633 else // A new search has been performed.
636 currentPrivacyWebEngineViewPointer->findTextResult = findTextResult;
639 emit updateFindTextResults(findTextResult);
643 void TabWidget::forward() const
646 currentPrivacyWebEngineViewPointer->forward();
649 void TabWidget::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest) const
652 emit fullScreenRequested(fullScreenRequest.toggleOn());
654 // Accept the request.
655 fullScreenRequest.accept();
658 std::list<QNetworkCookie>* TabWidget::getCookieList() const
660 // Return the current cookie list.
661 return currentPrivacyWebEngineViewPointer->cookieListPointer;
664 QString& TabWidget::getDomainSettingsName() const
666 // Return the domain settings name.
667 return currentPrivacyWebEngineViewPointer->domainSettingsName;
670 void TabWidget::home() const
672 // Load the homepage.
673 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
676 PrivacyWebEngineView* TabWidget::loadBlankInitialWebsite()
678 // Apply the application settings.
679 applyApplicationSettings();
681 // Return the current privacy WebEngine view pointer.
682 return currentPrivacyWebEngineViewPointer;
685 void TabWidget::loadInitialWebsite()
687 // Apply the application settings.
688 applyApplicationSettings();
690 // Get the arguments.
691 QStringList argumentsStringList = qApp->arguments();
693 // Check to see if the arguments lists contains a URL.
694 if (argumentsStringList.size() > 1)
696 // Load the URL from the arguments list.
697 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
701 // Load the homepage.
706 void TabWidget::loadUrlFromLineEdit(QString url) const
708 // Decide if the text is more likely to be a URL or a search.
709 if (url.startsWith("file://")) // The text is likely a file URL.
712 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
714 else if (url.contains(".")) // The text is likely a URL.
716 // Check if the URL does not start with a valid protocol.
717 if (!url.startsWith("http"))
719 // Add `https://` to the beginning of the URL.
720 url = "https://" + url;
724 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
726 else // The text is likely a search.
729 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
733 void TabWidget::mouseBack() const
735 // Go back if possible.
736 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoBack())
738 // Clear the URL line edit focus.
739 emit clearUrlLineEditFocus();
742 currentPrivacyWebEngineViewPointer->back();
746 void TabWidget::mouseForward() const
748 // Go forward if possible.
749 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoForward())
751 // Clear the URL line edit focus.
752 emit clearUrlLineEditFocus();
755 currentPrivacyWebEngineViewPointer->forward();
759 void TabWidget::pageLinkHovered(const QString &linkUrl) const
761 // Emit a signal so that the browser window can update the status bar.
762 emit linkHovered(linkUrl);
765 void TabWidget::stopLoadingFavoriteIconMovie() const
767 // Stop the loading favorite icon movie. Otherwise, the browser will crash if a second window is closed while a tab in it is loading. <https://redmine.stoutner.com/issues/1010>
768 loadingFavoriteIconMoviePointer->stop();
771 void TabWidget::print() const
776 // Set the resolution to be 300 dpi.
777 printer.setResolution(300);
779 // Create a printer dialog.
780 QPrintDialog printDialog(&printer, currentPrivacyWebEngineViewPointer);
782 // Display the dialog and print the page if instructed.
783 if (printDialog.exec() == QDialog::Accepted)
784 printWebpage(&printer);
787 void TabWidget::printPreview() const
792 // Set the resolution to be 300 dpi.
793 printer.setResolution(300);
795 // Create a print preview dialog.
796 QPrintPreviewDialog printPreviewDialog(&printer, currentPrivacyWebEngineViewPointer);
798 // Generate the print preview.
799 connect(&printPreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printWebpage(QPrinter *)));
801 // Display the dialog.
802 printPreviewDialog.exec();
805 void TabWidget::printWebpage(QPrinter *printerPointer) const
807 // Create an event loop. For some reason, the print preview doesn't produce any output unless it is run inside an event loop.
808 QEventLoop eventLoop;
810 // Print the webpage, converting the callback above into a `QWebEngineCallback<bool>`.
811 // Printing requires that the printer be a pointer, not a reference, or it will crash with much cursing.
812 currentWebEnginePagePointer->print(printerPointer, [&eventLoop](bool printSuccess)
814 // Instruct the compiler to ignore the unused parameter.
825 void TabWidget::refresh() const
827 // Reload the website.
828 currentPrivacyWebEngineViewPointer->reload();
831 void TabWidget::reloadAndBypassCache() const
833 // Reload the website, bypassing the cache.
834 currentWebEnginePagePointer->triggerAction(QWebEnginePage::ReloadAndBypassCache);
838 void TabWidget::setTabBarVisible(const bool visible) const
840 // Set the tab bar visibility.
841 qTabWidgetPointer->tabBar()->setVisible(visible);
844 void TabWidget::showSaveDialog(QWebEngineDownloadItem *webEngineDownloadItemPointer)
846 // Get the download attributes.
847 QUrl downloadUrl = webEngineDownloadItemPointer->url();
848 QString mimeTypeString = webEngineDownloadItemPointer->mimeType();
849 QString suggestedFileName = webEngineDownloadItemPointer->suggestedFileName();
850 int totalBytes = webEngineDownloadItemPointer->totalBytes();
852 // Check to see if Privacy Browser is not running KDE or if local storage (cookies) is enabled.
853 if (!isRunningKde || currentPrivacyWebEngineViewPointer->localStorageEnabled) // KDE is not running or local storage (cookies) is enabled. Use WebEngine's downloader.
855 // Instantiate the save dialog.
856 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes);
858 // Display the save dialog.
859 int saveDialogResult = saveDialogPointer->exec();
861 // Process the save dialog results.
862 if (saveDialogResult == QDialog::Accepted) // Save was selected.
864 // Get the download directory.
865 QString downloadDirectory = Settings::downloadLocation();
867 // Resolve the system download directory if specified.
868 if (downloadDirectory == QLatin1String("System Download Directory"))
869 downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
871 // Get a file path from the file picker.
872 QString saveFilePath = QFileDialog::getSaveFileName(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory + QLatin1Char('/') + suggestedFileName);
874 // Process the save file path.
875 if (!saveFilePath.isEmpty()) // The file save path is populated.
877 // Create a save file path file info.
878 QFileInfo saveFilePathFileInfo = QFileInfo(saveFilePath);
880 // Get the canonical save path and file name.
881 QString absoluteSavePath = saveFilePathFileInfo.absolutePath();
882 QString saveFileName = saveFilePathFileInfo.fileName();
884 // Set the download directory and file name.
885 webEngineDownloadItemPointer->setDownloadDirectory(absoluteSavePath);
886 webEngineDownloadItemPointer->setDownloadFileName(saveFileName);
888 // Create a file download notification.
889 KNotification *fileDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
891 // Set the notification title.
892 fileDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
894 // Set the notification text.
895 fileDownloadNotificationPointer->setText(i18nc("Downloading notification text", "Downloading %1", saveFileName));
897 // Set the notification icon.
898 fileDownloadNotificationPointer->setIconName(QLatin1String("download"));
900 // Set the action list cancel button.
901 fileDownloadNotificationPointer->setActions(QStringList({i18nc("Download notification action","Cancel")}));
903 // Set the notification to display indefinitely.
904 fileDownloadNotificationPointer->setFlags(KNotification::Persistent);
906 // Prevent the notification from being autodeleted if it is closed. Otherwise, the updates to the notification below cause a crash.
907 fileDownloadNotificationPointer->setAutoDelete(false);
909 // Display the notification.
910 fileDownloadNotificationPointer->sendEvent();
912 // Handle clicks on the cancel button.
913 connect(fileDownloadNotificationPointer, &KNotification::action1Activated, [webEngineDownloadItemPointer, saveFileName] ()
915 // Cancel the download.
916 webEngineDownloadItemPointer->cancel();
918 // Create a file download notification.
919 KNotification *canceledDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
921 // Set the notification title.
922 canceledDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
925 canceledDownloadNotificationPointer->setText(i18nc("Download canceled notification", "%1 download canceled", saveFileName));
927 // Set the notification icon.
928 canceledDownloadNotificationPointer->setIconName(QLatin1String("download"));
930 // Display the notification.
931 canceledDownloadNotificationPointer->sendEvent();
934 // Update the notification when the download progresses.
935 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::downloadProgress, [fileDownloadNotificationPointer, saveFileName] (qint64 bytesReceived, qint64 totalBytes)
937 // Set the new text. Total bytes will be 0 if the download size is unknown.
940 // Calculate the download percentage.
941 int downloadPercentage = 100 * bytesReceived / totalBytes;
943 // Set the file download notification text.
944 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1\% of %2 downloaded (%3 of %4 bytes)", downloadPercentage, saveFileName,
945 bytesReceived, totalBytes));
949 // Set the file download notification text.
950 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1: %2 bytes downloaded", saveFileName, bytesReceived));
953 // Display the updated notification.
954 fileDownloadNotificationPointer->update();
957 // Update the notification when the download finishes. The save file name must be copied into the lambda or a crash occurs.
958 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::finished, [fileDownloadNotificationPointer, saveFileName, saveFilePath] ()
961 fileDownloadNotificationPointer->setText(i18nc("Download finished notification text", "%1 download finished", saveFileName));
963 // Set the URL so the file options will be displayed.
964 fileDownloadNotificationPointer->setUrls(QList<QUrl> {QUrl(saveFilePath)});
966 // Remove the actions from the notification.
967 fileDownloadNotificationPointer->setActions(QStringList());
969 // Set the notification to disappear after a timeout.
970 fileDownloadNotificationPointer->setFlags(KNotification::CloseOnTimeout);
972 // Display the updated notification.
973 fileDownloadNotificationPointer->update();
976 // Start the download.
977 webEngineDownloadItemPointer->accept();
979 else // The file save path is not populated.
981 // Cancel the download.
982 webEngineDownloadItemPointer->cancel();
985 else // Cancel was selected.
987 // Cancel the download.
988 webEngineDownloadItemPointer->cancel();
991 else // KDE is running and local storage (cookies) is disabled. Use KDE's native downloader.
992 // 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.
994 // Instantiate the save dialog. `true` instructs it to use the native downloader
995 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes, suggestedFileName, true);
997 // Connect the save button.
998 connect(saveDialogPointer, SIGNAL(useNativeKdeDownloader(QUrl &, QString &)), this, SLOT(useNativeKdeDownloader(QUrl &, QString &)));
1001 saveDialogPointer->show();
1005 void TabWidget::toggleDomStorage() const
1007 // Toggle DOM storage.
1008 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1010 // Update the DOM storage action.
1011 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1013 // Reload the website.
1014 currentPrivacyWebEngineViewPointer->reload();
1017 void TabWidget::toggleFindCaseSensitive(const QString &text)
1019 // Toggle find case sensitive.
1020 currentPrivacyWebEngineViewPointer->findCaseSensitive = !currentPrivacyWebEngineViewPointer->findCaseSensitive;
1022 // Set the wiping current find text selection flag.
1023 wipingCurrentFindTextSelection = true;
1025 // Wipe the previous search. Otherwise currently highlighted words will remain highlighted.
1026 findText(QLatin1String(""));
1028 // Update the find text.
1032 void TabWidget::toggleJavaScript() const
1034 // Toggle JavaScript.
1035 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1037 // Update the JavaScript action.
1038 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1040 // Reload the website.
1041 currentPrivacyWebEngineViewPointer->reload();
1044 void TabWidget::toggleLocalStorage()
1046 // Toggle local storage.
1047 currentPrivacyWebEngineViewPointer->localStorageEnabled = !currentPrivacyWebEngineViewPointer->localStorageEnabled;
1049 // Update the local storage action.
1050 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1052 // Reload the website.
1053 currentPrivacyWebEngineViewPointer->reload();
1056 void TabWidget::updateUiFromWebEngineView(const PrivacyWebEngineView *privacyWebEngineViewPointer) const
1058 // Only update the UI if the signal was emitted from the current privacy WebEngine.
1059 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
1062 emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
1063 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1064 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1065 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1066 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
1067 emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
1071 void TabWidget::updateUiWithTabSettings()
1073 // Update the current WebEngine pointers.
1074 currentPrivacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->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::useNativeKdeDownloader(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 warning and error messages.
1141 fileCopyJobPointer->uiDelegate()->setAutoWarningHandlingEnabled(true);
1142 fileCopyJobPointer->uiDelegate()->setAutoErrorHandlingEnabled(true);
1144 // Start the download.
1145 fileCopyJobPointer->start();
1148 // Handle clicks on the save button.
1149 connect(saveFileDialogPointer, &QDialog::accepted, this, saveFile);
1152 saveFileDialogPointer->show();