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 // Manually delete each WebEngine page.
125 for (int i = 0; i < qTabWidgetPointer->count(); ++i)
127 // Get the privacy WebEngine view.
128 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->widget(i));
130 // Deletion the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
131 delete privacyWebEngineViewPointer->page();
135 // 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.
136 void TabWidget::addCookieToStore(QNetworkCookie cookie, QWebEngineCookieStore *webEngineCookieStorePointer) const
141 // 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>
142 if (!cookie.domain().startsWith(QLatin1String(".")))
145 url.setHost(cookie.domain());
146 url.setScheme(QLatin1String("https"));
148 // Clear the domain from the cookie.
149 cookie.setDomain(QLatin1String(""));
152 // Add the cookie to the store.
153 if (webEngineCookieStorePointer == nullptr)
154 currentWebEngineCookieStorePointer->setCookie(cookie, url);
156 webEngineCookieStorePointer->setCookie(cookie, url);
159 void TabWidget::addFirstTab()
161 // Create the first tab.
164 // Update the UI with the tab settings.
165 updateUiWithTabSettings();
167 // 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.
168 qTabWidgetPointer->currentWidget()->setFocus();
171 PrivacyWebEngineView* TabWidget::addTab(const bool removeUrlLineEditFocus, const bool backgroundTab)
173 // Create a privacy WebEngine view.
174 PrivacyWebEngineView *privacyWebEngineViewPointer = new PrivacyWebEngineView();
177 int newTabIndex = qTabWidgetPointer->addTab(privacyWebEngineViewPointer, i18nc("New tab label.", "New Tab"));
179 // Set the default tab icon.
180 qTabWidgetPointer->setTabIcon(newTabIndex, defaultFavoriteIcon);
182 // Get handles for the WebEngine page and profile.
183 QWebEnginePage *webEnginePagePointer = privacyWebEngineViewPointer->page();
184 QWebEngineProfile *webEngineProfilePointer = webEnginePagePointer->profile();
186 // Get handles for the web engine elements.
187 QWebEngineCookieStore *webEngineCookieStorePointer = webEngineProfilePointer->cookieStore();
188 QWebEngineSettings *webEngineSettingsPointer = webEnginePagePointer->settings();
190 // Update the URL line edit when the URL changes.
191 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::urlChanged, [this, privacyWebEngineViewPointer] (const QUrl &newUrl)
193 // Only update the UI if this is the current tab.
194 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
196 // Update the URL line edit.
197 emit updateUrlLineEdit(newUrl);
199 // Update the status of the forward and back buttons.
200 emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
201 emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
205 // Update the title when it changes.
206 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::titleChanged, [this, privacyWebEngineViewPointer] (const QString &title)
208 // Get the index for this tab.
209 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
211 // Update the title for this tab.
212 qTabWidgetPointer->setTabText(tabIndex, title);
214 // Update the window title if this is the current tab.
215 if (tabIndex == qTabWidgetPointer->currentIndex())
216 emit updateWindowTitle(title);
219 // Connect the loading favorite icon movie to the tab icon.
220 connect(loadingFavoriteIconMoviePointer, &QMovie::frameChanged, [this, privacyWebEngineViewPointer]
222 // Get the index for this tab.
223 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
225 // Display the loading favorite icon if this tab is loading.
226 if (privacyWebEngineViewPointer->isLoading)
227 qTabWidgetPointer->setTabIcon(tabIndex, loadingFavoriteIconMoviePointer->currentPixmap());
230 // Update the icon when it changes.
231 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::iconChanged, [this, privacyWebEngineViewPointer] (const QIcon &newFavoriteIcon)
233 // Store the favorite icon in the privacy web engine view.
234 if (newFavoriteIcon.isNull())
235 privacyWebEngineViewPointer->favoriteIcon = defaultFavoriteIcon;
237 privacyWebEngineViewPointer->favoriteIcon = newFavoriteIcon;
239 // Get the index for this tab.
240 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
242 // Update the icon for this tab.
243 if (newFavoriteIcon.isNull())
244 qTabWidgetPointer->setTabIcon(tabIndex, defaultFavoriteIcon);
246 qTabWidgetPointer->setTabIcon(tabIndex, newFavoriteIcon);
249 // Update the progress bar and the favorite icon when a load is started.
250 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadStarted, [this, privacyWebEngineViewPointer] ()
252 // Set the privacy web engine view to be loading.
253 privacyWebEngineViewPointer->isLoading = true;
255 // Store the load progress.
256 privacyWebEngineViewPointer->loadProgressInt = 0;
258 // Show the progress bar if this is the current tab.
259 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
260 emit showProgressBar(0);
262 // Start the loading favorite icon movie.
263 loadingFavoriteIconMoviePointer->start();
266 // Update the progress bar when a load progresses.
267 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadProgress, [this, privacyWebEngineViewPointer] (const int progress)
269 // Store the load progress.
270 privacyWebEngineViewPointer->loadProgressInt = progress;
272 // Update the progress bar if this is the current tab.
273 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
274 emit showProgressBar(progress);
277 // Update the progress bar when a load finishes.
278 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadFinished, [this, privacyWebEngineViewPointer] ()
280 // Set the privacy web engine view to be not loading.
281 privacyWebEngineViewPointer->isLoading = false;
283 // Store the load progress.
284 privacyWebEngineViewPointer->loadProgressInt = -1;
286 // Hide the progress bar if this is the current tab.
287 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
288 emit hideProgressBar();
290 // Get the index for this tab.
291 int tabIndex = qTabWidgetPointer->indexOf(privacyWebEngineViewPointer);
293 // Display the current favorite icon
294 qTabWidgetPointer->setTabIcon(tabIndex, privacyWebEngineViewPointer->favoriteIcon);
296 // Create a no tabs loading variable.
297 bool noTabsLoading = true;
299 // Check to see if any other tabs are loading.
300 for (int i = 0; i < qTabWidgetPointer->count(); i++)
302 // Get the privacy WebEngine view for the tab.
303 PrivacyWebEngineView *webEngineViewPointer = qobject_cast<PrivacyWebEngineView*>(qTabWidgetPointer->widget(i));
305 // Check to see if it is currently loading.
306 if (webEngineViewPointer->isLoading)
307 noTabsLoading = false;
310 // Stop the loading favorite icon movie if there are no loading tabs.
312 loadingFavoriteIconMoviePointer->stop();
315 // Display HTTP Ping blocked dialogs.
316 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::displayHttpPingBlockedDialog, [this, privacyWebEngineViewPointer] (const QString &httpPingUrl)
318 // Only display the HTTP Ping blocked dialog if this is the current tab.
319 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
321 // Instantiate an HTTP ping blocked message box.
322 QMessageBox httpPingBlockedMessageBox;
325 httpPingBlockedMessageBox.setIcon(QMessageBox::Information);
327 // Set the window title.
328 httpPingBlockedMessageBox.setWindowTitle(i18nc("HTTP Ping blocked dialog title", "HTTP Ping Blocked"));
331 httpPingBlockedMessageBox.setText(i18nc("HTTP Ping blocked dialog text", "This request has been blocked because it sends a naughty HTTP ping to %1.", httpPingUrl));
333 // Set the standard button.
334 httpPingBlockedMessageBox.setStandardButtons(QMessageBox::Ok);
336 // Display the message box.
337 httpPingBlockedMessageBox.exec();
341 // Update the zoom factor when changed by CTRL-Scrolling. This can be modified when <https://redmine.stoutner.com/issues/845> is fixed.
342 connect(webEnginePagePointer, &QWebEnginePage::contentsSizeChanged, [webEnginePagePointer, this] ()
344 // Only update the zoom factor action text if this is the current tab.
345 if (webEnginePagePointer == currentWebEnginePagePointer)
346 emit updateZoomFactorAction(webEnginePagePointer->zoomFactor());
349 // Display find text results.
350 connect(webEnginePagePointer, SIGNAL(findTextFinished(const QWebEngineFindTextResult &)), this, SLOT(findTextFinished(const QWebEngineFindTextResult &)));
352 // Handle full screen requests.
353 connect(webEnginePagePointer, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this, SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
355 // Listen for hovered link URLs.
356 connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
358 // Handle file downloads.
359 connect(webEngineProfilePointer, SIGNAL(downloadRequested(QWebEngineDownloadItem *)), this, SLOT(showSaveDialog(QWebEngineDownloadItem *)));
361 // Set the local storage filter.
362 webEngineCookieStorePointer->setCookieFilter([privacyWebEngineViewPointer](const QWebEngineCookieStore::FilterRequest &filterRequest)
364 // Block all third party local storage requests, including the sneaky ones that don't register a first party URL.
365 if (filterRequest.thirdParty || (filterRequest.firstPartyUrl == QStringLiteral("")))
367 //qDebug().noquote().nospace() << "Third-party request blocked: " << filterRequest.origin;
373 // Allow the request if local storage is enabled.
374 if (privacyWebEngineViewPointer->localStorageEnabled)
376 //qDebug().noquote().nospace() << "Request allowed by local storage: " << filterRequest.origin;
382 //qDebug().noquote().nospace() << "Request blocked by default: " << filterRequest.origin;
384 // Block any remaining local storage requests.
388 // Disable JavaScript by default (this prevents JavaScript from being enabled on a new tab before domain settings are loaded).
389 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
391 // Don't allow JavaScript to open windows.
392 webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
394 // Allow keyboard navigation.
395 webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
397 // Enable full screen support.
398 webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
400 // Require user interaction to play media.
401 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
403 // Limit WebRTC to public IP addresses.
404 webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
406 // Enable the PDF viewer (it should be enabled by default, but it is nice to be explicit in case the defaults change).
407 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PdfViewerEnabled, true);
409 // Plugins must be enabled for the PDF viewer to work. <https://doc.qt.io/qt-5/qtwebengine-features.html#pdf-file-viewing>
410 webEngineSettingsPointer->setAttribute(QWebEngineSettings::PluginsEnabled, true);
412 // Update the cookies action.
413 connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::updateCookiesAction, [this, privacyWebEngineViewPointer] (const int numberOfCookies)
415 // Update the cookie action if the specified privacy WebEngine view is the current privacy WebEngine view.
416 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
417 emit updateCookiesAction(numberOfCookies);
420 // Process cookie changes.
421 connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(addCookieToList(QNetworkCookie)));
422 connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(removeCookieFromList(QNetworkCookie)));
424 // Get a list of durable cookies.
425 QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
427 // Add the durable cookies to the store.
428 for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
429 addCookieToStore(*cookiePointer, webEngineCookieStorePointer);
431 // Enable spell checking.
432 webEngineProfilePointer->setSpellCheckEnabled(true);
434 // Set the spell check language.
435 webEngineProfilePointer->setSpellCheckLanguages(Settings::spellCheckLanguages());
437 // Populate the zoom factor. This is necessary if a URL is being loaded, like a local URL, that does not trigger `applyDomainSettings()`.
438 privacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
440 // Update the UI when domain settings are applied.
441 connect(privacyWebEngineViewPointer, SIGNAL(updateUi(const PrivacyWebEngineView*)), this, SLOT(updateUiFromWebEngineView(const PrivacyWebEngineView*)));
443 // Move to the new tab if it is not a background tab.
445 qTabWidgetPointer->setCurrentIndex(newTabIndex);
447 // Clear the URL line edit focus so that it populates correctly when opening a new tab from the context menu.
448 if (removeUrlLineEditFocus)
449 emit clearUrlLineEditFocus();
451 // Return the privacy WebEngine view pointer.
452 return privacyWebEngineViewPointer;
455 void TabWidget::applyApplicationSettings()
457 // Set the tab position.
458 if (Settings::tabsOnTop())
459 qTabWidgetPointer->setTabPosition(QTabWidget::North);
461 qTabWidgetPointer->setTabPosition(QTabWidget::South);
463 // Set the search engine URL.
464 searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
466 // Emit the update search engine actions signal.
467 emit updateSearchEngineActions(Settings::searchEngine(), true);
470 void TabWidget::applyDomainSettingsAndReload()
472 // Apply the domain settings. `true` reloads the website.
473 currentPrivacyWebEngineViewPointer->applyDomainSettings(currentPrivacyWebEngineViewPointer->url().host(), true);
476 void TabWidget::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
478 // Store the search engine name.
479 QString searchEngineName = searchEngineActionPointer->text();
481 // Strip out any `&` characters.
482 searchEngineName.remove('&');
484 // Store the search engine string.
485 searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
487 // Update the search engine actions.
488 emit updateSearchEngineActions(searchEngineName, false);
491 void TabWidget::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
493 // Get the user agent name.
494 QString userAgentName = userAgentActionPointer->text();
496 // Strip out any `&` characters.
497 userAgentName.remove('&');
499 // Apply the user agent.
500 currentWebEngineProfilePointer->setHttpUserAgent(userAgentHelperPointer->getUserAgentFromTranslatedName(userAgentName));
502 // Update the user agent actions.
503 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), false);
505 // Reload the website.
506 currentPrivacyWebEngineViewPointer->reload();
509 void TabWidget::applyOnTheFlyZoomFactor(const double &zoomFactor) const
511 // Set the zoom factor.
512 currentPrivacyWebEngineViewPointer->setZoomFactor(zoomFactor);
515 void TabWidget::applySpellCheckLanguages() const
517 // Get the number of tab.
518 int numberOfTabs = qTabWidgetPointer->count();
520 // Set the spell check languages for each tab.
521 for (int i = 0; i < numberOfTabs; ++i)
523 // Get the WebEngine view pointer.
524 PrivacyWebEngineView *webEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->currentWidget());
526 // Get the WebEngine page pointer.
527 QWebEnginePage *webEnginePagePointer = webEngineViewPointer->page();
529 // Get the WebEngine profile pointer.
530 QWebEngineProfile *webEngineProfilePointer = webEnginePagePointer->profile();
532 // Set the spell check languages.
533 webEngineProfilePointer->setSpellCheckLanguages(Settings::spellCheckLanguages());
537 void TabWidget::back() const
540 currentPrivacyWebEngineViewPointer->back();
543 void TabWidget::deleteAllCookies() const
545 // Delete all the cookies.
546 currentWebEngineCookieStorePointer->deleteAllCookies();
549 void TabWidget::deleteCookieFromStore(const QNetworkCookie &cookie) const
551 // Delete the cookie.
552 currentWebEngineCookieStorePointer->deleteCookie(cookie);
555 void TabWidget::deleteTab(const int tabIndex)
557 // Get the privacy WebEngine view.
558 PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->widget(tabIndex));
560 // Process the tab delete according to the number of tabs.
561 if (qTabWidgetPointer->count() > 1) // There is more than one tab.
564 qTabWidgetPointer->removeTab(tabIndex);
566 // Delete the WebEngine page to prevent the following error: `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
567 delete privacyWebEngineViewPointer->page();
569 // Delete the privacy WebEngine view.
570 delete privacyWebEngineViewPointer;
572 else // There is only one tab.
574 // Close Privacy Browser.
579 void TabWidget::findPrevious(const QString &text) const
581 // Store the current text.
582 currentPrivacyWebEngineViewPointer->findString = text;
584 // Find the previous text in the current privacy WebEngine.
585 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
586 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively|QWebEnginePage::FindBackward);
588 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindBackward);
591 void TabWidget::findText(const QString &text) const
593 // Store the current text.
594 currentPrivacyWebEngineViewPointer->findString = text;
596 // Find the text in the current privacy WebEngine.
597 if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
598 currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively);
600 currentPrivacyWebEngineViewPointer->findText(text);
602 // Clear the currently selected text in the WebEngine page if the find text is empty.
604 currentWebEnginePagePointer->action(QWebEnginePage::Unselect)->activate(QAction::Trigger);
607 void TabWidget::findTextFinished(const QWebEngineFindTextResult &findTextResult)
609 // Update the find text UI if it wasn't simply wiping the current find text selection. Otherwise the UI temporarily flashes `0/0`.
610 if (wipingCurrentFindTextSelection) // The current selection is being wiped.
613 wipingCurrentFindTextSelection = false;
615 else // A new search has been performed.
618 currentPrivacyWebEngineViewPointer->findTextResult = findTextResult;
621 emit updateFindTextResults(findTextResult);
625 void TabWidget::forward() const
628 currentPrivacyWebEngineViewPointer->forward();
631 void TabWidget::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest) const
634 emit fullScreenRequested(fullScreenRequest.toggleOn());
636 // Accept the request.
637 fullScreenRequest.accept();
640 std::list<QNetworkCookie>* TabWidget::getCookieList() const
642 // Return the current cookie list.
643 return currentPrivacyWebEngineViewPointer->cookieListPointer;
646 QString& TabWidget::getDomainSettingsName() const
648 // Return the domain settings name.
649 return currentPrivacyWebEngineViewPointer->domainSettingsName;
652 void TabWidget::home() const
654 // Load the homepage.
655 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
658 PrivacyWebEngineView* TabWidget::loadBlankInitialWebsite()
660 // Apply the application settings.
661 applyApplicationSettings();
663 // Return the current privacy WebEngine view pointer.
664 return currentPrivacyWebEngineViewPointer;
667 void TabWidget::loadInitialWebsite()
669 // Apply the application settings.
670 applyApplicationSettings();
672 // Get the arguments.
673 QStringList argumentsStringList = qApp->arguments();
675 // Check to see if the arguments lists contains a URL.
676 if (argumentsStringList.size() > 1)
678 // Load the URL from the arguments list.
679 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
683 // Load the homepage.
688 void TabWidget::loadUrlFromLineEdit(QString url) const
690 // Decide if the text is more likely to be a URL or a search.
691 if (url.startsWith("file://")) // The text is likely a file URL.
694 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
696 else if (url.contains(".")) // The text is likely a URL.
698 // Check if the URL does not start with a valid protocol.
699 if (!url.startsWith("http"))
701 // Add `https://` to the beginning of the URL.
702 url = "https://" + url;
706 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
708 else // The text is likely a search.
711 currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
715 void TabWidget::mouseBack() const
717 // Go back if possible.
718 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoBack())
720 // Clear the URL line edit focus.
721 emit clearUrlLineEditFocus();
724 currentPrivacyWebEngineViewPointer->back();
728 void TabWidget::mouseForward() const
730 // Go forward if possible.
731 if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoForward())
733 // Clear the URL line edit focus.
734 emit clearUrlLineEditFocus();
737 currentPrivacyWebEngineViewPointer->forward();
741 void TabWidget::pageLinkHovered(const QString &linkUrl) const
743 // Emit a signal so that the browser window can update the status bar.
744 emit linkHovered(linkUrl);
747 void TabWidget::stopLoadingFavoriteIconMovie() const
749 // 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>
750 loadingFavoriteIconMoviePointer->stop();
753 void TabWidget::print() const
758 // Set the resolution to be 300 dpi.
759 printer.setResolution(300);
761 // Create a printer dialog.
762 QPrintDialog printDialog(&printer, currentPrivacyWebEngineViewPointer);
764 // Display the dialog and print the page if instructed.
765 if (printDialog.exec() == QDialog::Accepted)
766 printWebpage(&printer);
769 void TabWidget::printPreview() const
774 // Set the resolution to be 300 dpi.
775 printer.setResolution(300);
777 // Create a print preview dialog.
778 QPrintPreviewDialog printPreviewDialog(&printer, currentPrivacyWebEngineViewPointer);
780 // Generate the print preview.
781 connect(&printPreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printWebpage(QPrinter *)));
783 // Display the dialog.
784 printPreviewDialog.exec();
787 void TabWidget::printWebpage(QPrinter *printerPointer) const
789 // Create an event loop. For some reason, the print preview doesn't produce any output unless it is run inside an event loop.
790 QEventLoop eventLoop;
792 // Print the webpage, converting the callback above into a `QWebEngineCallback<bool>`.
793 // Printing requires that the printer be a pointer, not a reference, or it will crash with much cursing.
794 currentWebEnginePagePointer->print(printerPointer, [&eventLoop](bool printSuccess)
796 // Instruct the compiler to ignore the unused parameter.
807 void TabWidget::refresh() const
809 // Reload the website.
810 currentPrivacyWebEngineViewPointer->reload();
813 void TabWidget::setTabBarVisible(const bool visible) const
815 // Set the tab bar visibility.
816 qTabWidgetPointer->tabBar()->setVisible(visible);
819 void TabWidget::showSaveDialog(QWebEngineDownloadItem *webEngineDownloadItemPointer)
821 // Get the download attributes.
822 QUrl downloadUrl = webEngineDownloadItemPointer->url();
823 QString mimeTypeString = webEngineDownloadItemPointer->mimeType();
824 QString suggestedFileName = webEngineDownloadItemPointer->suggestedFileName();
825 int totalBytes = webEngineDownloadItemPointer->totalBytes();
827 // Check to see if Privacy Browser is not running KDE or if local storage (cookies) is enabled.
828 if (!isRunningKde || currentPrivacyWebEngineViewPointer->localStorageEnabled) // KDE is not running or local storage (cookies) is enabled. Use WebEngine's downloader.
830 // Instantiate the save dialog.
831 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes);
833 // Display the save dialog.
834 int saveDialogResult = saveDialogPointer->exec();
836 // Process the save dialog results.
837 if (saveDialogResult == QDialog::Accepted) // Save was selected.
839 // Get the download directory.
840 QString downloadDirectory = Settings::downloadLocation();
842 // Resolve the system download directory if specified.
843 if (downloadDirectory == QLatin1String("System Download Directory"))
844 downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
846 // Get a file path from the file picker.
847 QString saveFilePath = QFileDialog::getSaveFileName(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory + QLatin1Char('/') + suggestedFileName);
849 // Process the save file path.
850 if (!saveFilePath.isEmpty()) // The file save path is populated.
852 // Create a save file path file info.
853 QFileInfo saveFilePathFileInfo = QFileInfo(saveFilePath);
855 // Get the canonical save path and file name.
856 QString absoluteSavePath = saveFilePathFileInfo.absolutePath();
857 QString saveFileName = saveFilePathFileInfo.fileName();
859 // Set the download directory and file name.
860 webEngineDownloadItemPointer->setDownloadDirectory(absoluteSavePath);
861 webEngineDownloadItemPointer->setDownloadFileName(saveFileName);
863 // Create a file download notification.
864 KNotification *fileDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
866 // Set the notification title.
867 fileDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
869 // Set the notification text.
870 fileDownloadNotificationPointer->setText(i18nc("Downloading notification text", "Downloading %1", saveFileName));
872 // Set the notification icon.
873 fileDownloadNotificationPointer->setIconName(QLatin1String("download"));
875 // Set the action list cancel button.
876 fileDownloadNotificationPointer->setActions(QStringList({i18nc("Download notification action","Cancel")}));
878 // Set the notification to display indefinitely.
879 fileDownloadNotificationPointer->setFlags(KNotification::Persistent);
881 // Prevent the notification from being autodeleted if it is closed. Otherwise, the updates to the notification below cause a crash.
882 fileDownloadNotificationPointer->setAutoDelete(false);
884 // Display the notification.
885 fileDownloadNotificationPointer->sendEvent();
887 // Handle clicks on the cancel button.
888 connect(fileDownloadNotificationPointer, &KNotification::action1Activated, [webEngineDownloadItemPointer, saveFileName] ()
890 // Cancel the download.
891 webEngineDownloadItemPointer->cancel();
893 // Create a file download notification.
894 KNotification *canceledDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
896 // Set the notification title.
897 canceledDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
900 canceledDownloadNotificationPointer->setText(i18nc("Download canceled notification", "%1 download canceled", saveFileName));
902 // Set the notification icon.
903 canceledDownloadNotificationPointer->setIconName(QLatin1String("download"));
905 // Display the notification.
906 canceledDownloadNotificationPointer->sendEvent();
909 // Update the notification when the download progresses.
910 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::downloadProgress, [fileDownloadNotificationPointer, saveFileName] (qint64 bytesReceived, qint64 totalBytes)
912 // Set the new text. Total bytes will be 0 if the download size is unknown.
915 // Calculate the download percentage.
916 int downloadPercentage = 100 * bytesReceived / totalBytes;
918 // Set the file download notification text.
919 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1\% of %2 downloaded (%3 of %4 bytes)", downloadPercentage, saveFileName,
920 bytesReceived, totalBytes));
924 // Set the file download notification text.
925 fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1: %2 bytes downloaded", saveFileName, bytesReceived));
928 // Display the updated notification.
929 fileDownloadNotificationPointer->update();
932 // Update the notification when the download finishes. The save file name must be copied into the lambda or a crash occurs.
933 connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::finished, [fileDownloadNotificationPointer, saveFileName, saveFilePath] ()
936 fileDownloadNotificationPointer->setText(i18nc("Download finished notification text", "%1 download finished", saveFileName));
938 // Set the URL so the file options will be displayed.
939 fileDownloadNotificationPointer->setUrls(QList<QUrl> {QUrl(saveFilePath)});
941 // Remove the actions from the notification.
942 fileDownloadNotificationPointer->setActions(QStringList());
944 // Set the notification to disappear after a timeout.
945 fileDownloadNotificationPointer->setFlags(KNotification::CloseOnTimeout);
947 // Display the updated notification.
948 fileDownloadNotificationPointer->update();
951 // Start the download.
952 webEngineDownloadItemPointer->accept();
954 else // The file save path is not populated.
956 // Cancel the download.
957 webEngineDownloadItemPointer->cancel();
960 else // Cancel was selected.
962 // Cancel the download.
963 webEngineDownloadItemPointer->cancel();
966 else // KDE is running and local storage (cookies) is disabled. Use KDE's native downloader.
967 // 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.
969 // Instantiate the save dialog. `true` instructs it to use the native downloader
970 SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes, suggestedFileName, true);
972 // Connect the save button.
973 connect(saveDialogPointer, SIGNAL(useNativeKdeDownloader(QUrl &, QString &)), this, SLOT(useNativeKdeDownloader(QUrl &, QString &)));
976 saveDialogPointer->show();
980 void TabWidget::toggleDomStorage() const
982 // Toggle DOM storage.
983 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
985 // Update the DOM storage action.
986 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
988 // Reload the website.
989 currentPrivacyWebEngineViewPointer->reload();
992 void TabWidget::toggleFindCaseSensitive(const QString &text)
994 // Toggle find case sensitive.
995 currentPrivacyWebEngineViewPointer->findCaseSensitive = !currentPrivacyWebEngineViewPointer->findCaseSensitive;
997 // Set the wiping current find text selection flag.
998 wipingCurrentFindTextSelection = true;
1000 // Wipe the previous search. Otherwise currently highlighted words will remain highlighted.
1001 findText(QLatin1String(""));
1003 // Update the find text.
1007 void TabWidget::toggleJavaScript() const
1009 // Toggle JavaScript.
1010 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1012 // Update the JavaScript action.
1013 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1015 // Reload the website.
1016 currentPrivacyWebEngineViewPointer->reload();
1019 void TabWidget::toggleLocalStorage()
1021 // Toggle local storage.
1022 currentPrivacyWebEngineViewPointer->localStorageEnabled = !currentPrivacyWebEngineViewPointer->localStorageEnabled;
1024 // Update the local storage action.
1025 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1027 // Reload the website.
1028 currentPrivacyWebEngineViewPointer->reload();
1031 void TabWidget::updateUiFromWebEngineView(const PrivacyWebEngineView *privacyWebEngineViewPointer) const
1033 // Only update the UI if the signal was emitted from the current privacy WebEngine.
1034 if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
1037 emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
1038 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1039 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1040 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1041 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
1042 emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
1046 void TabWidget::updateUiWithTabSettings()
1048 // Update the current WebEngine pointers.
1049 currentPrivacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(qTabWidgetPointer->currentWidget());
1050 currentWebEngineSettingsPointer = currentPrivacyWebEngineViewPointer->settings();
1051 currentWebEnginePagePointer = currentPrivacyWebEngineViewPointer->page();
1052 currentWebEngineProfilePointer = currentWebEnginePagePointer->profile();
1053 currentWebEngineHistoryPointer = currentWebEnginePagePointer->history();
1054 currentWebEngineCookieStorePointer = currentWebEngineProfilePointer->cookieStore();
1056 // Clear the URL line edit focus.
1057 emit clearUrlLineEditFocus();
1059 // Update the actions.
1060 emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
1061 emit updateCookiesAction(currentPrivacyWebEngineViewPointer->cookieListPointer->size());
1062 emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1063 emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
1064 emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1065 emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1066 emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
1067 emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
1070 emit updateWindowTitle(currentPrivacyWebEngineViewPointer->title());
1071 emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
1072 emit updateUrlLineEdit(currentPrivacyWebEngineViewPointer->url());
1074 // Update the find text.
1075 emit updateFindText(currentPrivacyWebEngineViewPointer->findString, currentPrivacyWebEngineViewPointer->findCaseSensitive);
1076 emit updateFindTextResults(currentPrivacyWebEngineViewPointer->findTextResult);
1078 // Update the progress bar.
1079 if (currentPrivacyWebEngineViewPointer->loadProgressInt >= 0)
1080 emit showProgressBar(currentPrivacyWebEngineViewPointer->loadProgressInt);
1082 emit hideProgressBar();
1085 void TabWidget::useNativeKdeDownloader(QUrl &downloadUrl, QString &suggestedFileName)
1087 // Get the download directory.
1088 QString downloadDirectory = Settings::downloadLocation();
1090 // Resolve the system download directory if specified.
1091 if (downloadDirectory == QLatin1String("System Download Directory"))
1092 downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
1094 // Create a save file dialog.
1095 QFileDialog *saveFileDialogPointer = new QFileDialog(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory);
1097 // Tell the dialog to use a save button.
1098 saveFileDialogPointer->setAcceptMode(QFileDialog::AcceptSave);
1100 // Populate the file name from the download item pointer.
1101 saveFileDialogPointer->selectFile(suggestedFileName);
1103 // Prevent interaction with the parent window while the dialog is open.
1104 saveFileDialogPointer->setWindowModality(Qt::WindowModal);
1106 // Process the saving of the file. The save file dialog pointer must be captured directly instead of by reference or nasty crashes occur.
1107 auto saveFile = [saveFileDialogPointer, downloadUrl] ()
1109 // Get the save location. The dialog box should only allow the selecting of one file location.
1110 QUrl saveLocation = saveFileDialogPointer->selectedUrls().value(0);
1112 // Create a file copy job. `-1` creates the file with default permissions.
1113 KIO::FileCopyJob *fileCopyJobPointer = KIO::file_copy(downloadUrl, saveLocation, -1, KIO::Overwrite);
1115 // Set the download job to display any warning and error messages.
1116 fileCopyJobPointer->uiDelegate()->setAutoWarningHandlingEnabled(true);
1117 fileCopyJobPointer->uiDelegate()->setAutoErrorHandlingEnabled(true);
1119 // Start the download.
1120 fileCopyJobPointer->start();
1123 // Handle clicks on the save button.
1124 connect(saveFileDialogPointer, &QDialog::accepted, this, saveFile);
1127 saveFileDialogPointer->show();