]> gitweb.stoutner.com Git - PrivacyBrowserPC.git/blob - src/widgets/TabWidget.cpp
Add DevTools. https://redmine.stoutner.com/issues/1126
[PrivacyBrowserPC.git] / src / widgets / TabWidget.cpp
1 /*
2  * Copyright 2022-2023 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser PC <https://www.stoutner.com/privacy-browser-pc>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 // Application headers.
21 #include "DevToolsWebEngineView.h"
22 #include "TabWidget.h"
23 #include "Settings.h"
24 #include "ui_AddTabWidget.h"
25 #include "ui_Tab.h"
26 #include "ui_TabWidget.h"
27 #include "databases/CookiesDatabase.h"
28 #include "dialogs/SaveDialog.h"
29 #include "filters/MouseEventFilter.h"
30 #include "helpers/SearchEngineHelper.h"
31 #include "windows/BrowserWindow.h"
32
33 // KDE Framework headers.
34 #include <KIO/FileCopyJob>
35 #include <KIO/JobUiDelegate>
36 #include <KNotification>
37
38 // Qt toolkit headers.
39 #include <QAction>
40 #include <QFileDialog>
41 #include <QGraphicsScene>
42 #include <QGraphicsView>
43 #include <QMessageBox>
44 #include <QPrintDialog>
45 #include <QPrintPreviewDialog>
46 #include <QPrinter>
47
48 // Initialize the public static variables.
49 QString TabWidget::webEngineDefaultUserAgent = QLatin1String("");
50
51 // Construct the class.
52 TabWidget::TabWidget(QWidget *windowPointer) : QWidget(windowPointer)
53 {
54     // Create a QProcess to check if KDE is running.
55     QProcess *checkIfRunningKdeQProcessPointer = new QProcess();
56
57     // Create an argument string list that contains `ksmserver` (KDE Session Manager).
58     QStringList argument = QStringList(QLatin1String("ksmserver"));
59
60     // Run `pidof` to check for the presence of `ksmserver`.
61     checkIfRunningKdeQProcessPointer->start(QLatin1String("pidof"), argument);
62
63     // Monitor any standard output.
64     connect(checkIfRunningKdeQProcessPointer, &QProcess::readyReadStandardOutput, [this]
65     {
66         // If there is any standard output, `ksmserver` is running.
67         isRunningKde = true;
68     });
69
70     // Instantiate the user agent helper.
71     userAgentHelperPointer = new UserAgentHelper();
72
73     // Instantiate the UIs.
74     Ui::TabWidget tabWidgetUi;
75     Ui::AddTabWidget addTabWidgetUi;
76
77     // Setup the main UI.
78     tabWidgetUi.setupUi(this);
79
80     // Get a handle for the tab widget.
81     qTabWidgetPointer = tabWidgetUi.tabWidget;
82
83     // Setup the add tab UI.
84     addTabWidgetUi.setupUi(qTabWidgetPointer);
85
86     // Get handles for the add tab widgets.
87     QWidget *addTabWidgetPointer = addTabWidgetUi.addTabQWidget;
88     QPushButton *addTabButtonPointer = addTabWidgetUi.addTabButton;
89
90     // Display the add tab widget.
91     qTabWidgetPointer->setCornerWidget(addTabWidgetPointer);
92
93     // Create the loading favorite icon movie.
94     loadingFavoriteIconMoviePointer = new QMovie();
95
96     // Set the loading favorite icon movie file name.
97     loadingFavoriteIconMoviePointer->setFileName(QStringLiteral(":/icons/loading.gif"));
98
99     // 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.
100     connect(windowPointer, SIGNAL(destroyed()), this, SLOT(stopLoadingFavoriteIconMovie()));
101
102     // Add the first tab.
103     addFirstTab();
104
105     // Process tab events.
106     connect(qTabWidgetPointer, SIGNAL(currentChanged(int)), this, SLOT(updateUiWithTabSettings()));
107     connect(addTabButtonPointer, SIGNAL(clicked()), this, SLOT(addTab()));
108     connect(qTabWidgetPointer, SIGNAL(tabCloseRequested(int)), this, SLOT(deleteTab(int)));
109
110     // Store a copy of the WebEngine default user agent.
111     webEngineDefaultUserAgent = currentWebEngineProfilePointer->httpUserAgent();
112
113     // Instantiate the mouse event filter pointer.
114     MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
115
116     // Install the mouse event filter.
117     qApp->installEventFilter(mouseEventFilterPointer);
118
119     // Process mouse forward and back commands.
120     connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
121     connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
122 }
123
124 TabWidget::~TabWidget()
125 {
126     // Get the number of tabs.
127     int numberOfTabs = qTabWidgetPointer->count();
128
129     // Manually delete each WebEngine page.
130     for (int i = 0; i < numberOfTabs; ++i)
131     {
132         // Get the tab splitter widget.
133         QWidget *tabSplitterWidgetPointer = qTabWidgetPointer->widget(i);
134
135         // Get the WebEngine views.
136         PrivacyWebEngineView *privacyWebEngineViewPointer = tabSplitterWidgetPointer->findChild<PrivacyWebEngineView *>();
137         DevToolsWebEngineView *devToolsWebEngineViewPointer = tabSplitterWidgetPointer->findChild<DevToolsWebEngineView *>();
138
139         // Deletion the WebEngine pages to prevent the following error:  `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
140         delete privacyWebEngineViewPointer->page();
141         delete devToolsWebEngineViewPointer->page();
142     }
143 }
144
145 // 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.
146 void TabWidget::addCookieToStore(QNetworkCookie cookie, QWebEngineCookieStore *webEngineCookieStorePointer) const
147 {
148     // Create a URL.
149     QUrl url;
150
151     // 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>
152     if (!cookie.domain().startsWith(QLatin1String(".")))
153     {
154         // Populate the URL.
155         url.setHost(cookie.domain());
156         url.setScheme(QLatin1String("https"));
157
158         // Clear the domain from the cookie.
159         cookie.setDomain(QLatin1String(""));
160     }
161
162     // Add the cookie to the store.
163     if (webEngineCookieStorePointer == nullptr)
164         currentWebEngineCookieStorePointer->setCookie(cookie, url);
165     else
166         webEngineCookieStorePointer->setCookie(cookie, url);
167 }
168
169 void TabWidget::addFirstTab()
170 {
171     // Create the first tab.
172     addTab();
173
174     // Update the UI with the tab settings.
175     updateUiWithTabSettings();
176
177     // 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.
178     qTabWidgetPointer->currentWidget()->setFocus();
179 }
180
181 PrivacyWebEngineView* TabWidget::addTab(const bool removeUrlLineEditFocus, const bool backgroundTab, const QString urlString)
182 {
183     // Create a splitter widget.
184     QSplitter *splitterPointer = new QSplitter();
185
186     // Set the splitter to be vertical.
187     splitterPointer->setOrientation(Qt::Vertical);
188
189     // Set the splitter handle size.
190     splitterPointer->setHandleWidth(5);
191
192     // Create the WebEngines.
193     PrivacyWebEngineView *privacyWebEngineViewPointer = new PrivacyWebEngineView();
194     DevToolsWebEngineView *devToolsWebEngineViewPointer = new DevToolsWebEngineView();
195
196     // Add the WebEngines to the splitter.
197     splitterPointer->addWidget(privacyWebEngineViewPointer);
198     splitterPointer->addWidget(devToolsWebEngineViewPointer);
199
200     // Add a new tab.
201     int newTabIndex = qTabWidgetPointer->addTab(splitterPointer, i18nc("New tab label.", "New Tab"));
202
203     // Set the default tab icon.
204     qTabWidgetPointer->setTabIcon(newTabIndex, defaultFavoriteIcon);
205
206     // Get handles for the WebEngine components.
207     QWebEnginePage *webEnginePagePointer = privacyWebEngineViewPointer->page();
208     QWebEngineProfile *webEngineProfilePointer = webEnginePagePointer->profile();
209     QWebEngineCookieStore *webEngineCookieStorePointer = webEngineProfilePointer->cookieStore();
210     QWebEngineSettings *webEngineSettingsPointer = webEnginePagePointer->settings();
211
212     // Set the development tools WebEngine.  This must be done here to preserve the bottom half of the window as the initial development tools size.
213     webEnginePagePointer->setDevToolsPage(devToolsWebEngineViewPointer->page());
214
215     // Initially hide the development tools WebEngine.
216     devToolsWebEngineViewPointer->setVisible(false);
217
218     // Initially disable the development tools WebEngine.
219     webEnginePagePointer->setDevToolsPage(nullptr);
220
221     // Disable JavaScript on the development tools WebEngine to prevent error messages from being written to the console.
222     devToolsWebEngineViewPointer->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
223
224     // Update the URL line edit when the URL changes.
225     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::urlChanged, [this, privacyWebEngineViewPointer] (const QUrl &newUrl)
226     {
227         // Only update the UI if this is the current tab.
228         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
229         {
230             // Update the URL line edit.
231             emit updateUrlLineEdit(newUrl);
232
233             // Update the status of the forward and back buttons.
234             emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
235             emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
236         }
237     });
238
239     // Update the title when it changes.
240     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::titleChanged, [this, splitterPointer] (const QString &title)
241     {
242         // Get the index for this tab.
243         int tabIndex = qTabWidgetPointer->indexOf(splitterPointer);
244
245         // Update the title for this tab.
246         qTabWidgetPointer->setTabText(tabIndex, title);
247
248         // Update the window title if this is the current tab.
249         if (tabIndex == qTabWidgetPointer->currentIndex())
250             emit updateWindowTitle(title);
251     });
252
253     // Connect the loading favorite icon movie to the tab icon.
254     connect(loadingFavoriteIconMoviePointer, &QMovie::frameChanged, [this, splitterPointer, privacyWebEngineViewPointer]
255     {
256         // Get the index for this tab.
257         int tabIndex = qTabWidgetPointer->indexOf(splitterPointer);
258
259         // Display the loading favorite icon if this tab is loading.
260         if (privacyWebEngineViewPointer->isLoading)
261             qTabWidgetPointer->setTabIcon(tabIndex, loadingFavoriteIconMoviePointer->currentPixmap());
262     });
263
264     // Update the icon when it changes.
265     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::iconChanged, [this, splitterPointer, privacyWebEngineViewPointer] (const QIcon &newFavoriteIcon)
266     {
267         // Store the favorite icon in the privacy web engine view.
268         if (newFavoriteIcon.isNull())
269             privacyWebEngineViewPointer->favoriteIcon = defaultFavoriteIcon;
270         else
271             privacyWebEngineViewPointer->favoriteIcon = newFavoriteIcon;
272
273         // Get the index for this tab.
274         int tabIndex = qTabWidgetPointer->indexOf(splitterPointer);
275
276         // Update the icon for this tab.
277         if (newFavoriteIcon.isNull())
278             qTabWidgetPointer->setTabIcon(tabIndex, defaultFavoriteIcon);
279         else
280             qTabWidgetPointer->setTabIcon(tabIndex, newFavoriteIcon);
281     });
282
283     // Update the progress bar and the favorite icon when a load is started.
284     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadStarted, [this, privacyWebEngineViewPointer] ()
285     {
286         // Set the privacy web engine view to be loading.
287         privacyWebEngineViewPointer->isLoading = true;
288
289         // Store the load progress.
290         privacyWebEngineViewPointer->loadProgressInt = 0;
291
292         // Show the progress bar if this is the current tab.
293         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
294             emit showProgressBar(0);
295
296         // Start the loading favorite icon movie.
297         loadingFavoriteIconMoviePointer->start();
298     });
299
300     // Update the progress bar when a load progresses.
301     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadProgress, [this, privacyWebEngineViewPointer] (const int progress)
302     {
303         // Store the load progress.
304         privacyWebEngineViewPointer->loadProgressInt = progress;
305
306         // Update the progress bar if this is the current tab.
307         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
308             emit showProgressBar(progress);
309     });
310
311     // Update the progress bar when a load finishes.
312     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadFinished, [this, splitterPointer, privacyWebEngineViewPointer] ()
313     {
314         // Set the privacy web engine view to be not loading.
315         privacyWebEngineViewPointer->isLoading = false;
316
317         // Store the load progress.
318         privacyWebEngineViewPointer->loadProgressInt = -1;
319
320         // Hide the progress bar if this is the current tab.
321         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
322             emit hideProgressBar();
323
324         // Get the index for this tab.
325         int tabIndex = qTabWidgetPointer->indexOf(splitterPointer);
326
327         // Display the current favorite icon
328         qTabWidgetPointer->setTabIcon(tabIndex, privacyWebEngineViewPointer->favoriteIcon);
329
330         // Create a no tabs loading variable.
331         bool noTabsLoading = true;
332
333         // Get the number of tabs.
334         int numberOfTabs = qTabWidgetPointer->count();
335
336         // Check to see if any other tabs are loading.
337         for (int i = 0; i < numberOfTabs; i++)
338         {
339             // Get the privacy WebEngine view for the tab.
340             PrivacyWebEngineView *privacyWebEngineViewPointer = qTabWidgetPointer->widget(i)->findChild<PrivacyWebEngineView *>();
341
342             // 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.
343             if (privacyWebEngineViewPointer->isLoading)
344                 noTabsLoading = false;
345         }
346
347         // Stop the loading favorite icon movie if there are no loading tabs.
348         if (noTabsLoading)
349             loadingFavoriteIconMoviePointer->stop();
350     });
351
352     // Display HTTP Ping blocked dialogs.
353     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::displayHttpPingBlockedDialog, [this, privacyWebEngineViewPointer] (const QString &httpPingUrl)
354     {
355         // Only display the HTTP Ping blocked dialog if this is the current tab.
356         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
357         {
358             // Instantiate an HTTP ping blocked message box.
359             QMessageBox httpPingBlockedMessageBox;
360
361             // Set the icon.
362             httpPingBlockedMessageBox.setIcon(QMessageBox::Information);
363
364             // Set the window title.
365             httpPingBlockedMessageBox.setWindowTitle(i18nc("HTTP Ping blocked dialog title", "HTTP Ping Blocked"));
366
367             // Set the text.
368             httpPingBlockedMessageBox.setText(i18nc("HTTP Ping blocked dialog text", "This request has been blocked because it sends a naughty HTTP ping to %1.", httpPingUrl));
369
370             // Set the standard button.
371             httpPingBlockedMessageBox.setStandardButtons(QMessageBox::Ok);
372
373             // Display the message box.
374             httpPingBlockedMessageBox.exec();
375         }
376     });
377
378     // Update the zoom actions when changed by CTRL-Scrolling.  This can be modified when <https://redmine.stoutner.com/issues/845> is fixed.
379     connect(webEnginePagePointer, &QWebEnginePage::contentsSizeChanged, [webEnginePagePointer, this] ()
380     {
381         // Only update the zoom actions if this is the current tab.
382         if (webEnginePagePointer == currentWebEnginePagePointer)
383             emit updateZoomActions(webEnginePagePointer->zoomFactor());
384     });
385
386     // Display find text results.
387     connect(webEnginePagePointer, SIGNAL(findTextFinished(const QWebEngineFindTextResult &)), this, SLOT(findTextFinished(const QWebEngineFindTextResult &)));
388
389     // Handle full screen requests.
390     connect(webEnginePagePointer, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this, SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
391
392     // Listen for hovered link URLs.
393     connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
394
395     // Handle file downloads.
396     connect(webEngineProfilePointer, SIGNAL(downloadRequested(QWebEngineDownloadItem *)), this, SLOT(showSaveDialog(QWebEngineDownloadItem *)));
397
398     // Set the local storage filter.
399     webEngineCookieStorePointer->setCookieFilter([privacyWebEngineViewPointer](const QWebEngineCookieStore::FilterRequest &filterRequest)
400     {
401         // Block all third party local storage requests, including the sneaky ones that don't register a first party URL.
402         if (filterRequest.thirdParty || (filterRequest.firstPartyUrl == QStringLiteral("")))
403         {
404             //qDebug().noquote().nospace() << "Third-party request blocked:  " << filterRequest.origin;
405
406             // Return false.
407             return false;
408         }
409
410         // Allow the request if local storage is enabled.
411         if (privacyWebEngineViewPointer->localStorageEnabled)
412         {
413             //qDebug().noquote().nospace() << "Request allowed by local storage:  " << filterRequest.origin;
414
415             // Return true.
416             return true;
417         }
418
419         //qDebug().noquote().nospace() << "Request blocked by default:  " << filterRequest.origin;
420
421         // Block any remaining local storage requests.
422         return false;
423     });
424
425     // Disable JavaScript by default (this prevents JavaScript from being enabled on a new tab before domain settings are loaded).
426     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
427
428     // Don't allow JavaScript to open windows.
429     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
430
431     // Allow keyboard navigation between links and input fields.
432     webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, Settings::spatialNavigation());
433
434     // Enable full screen support.
435     webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
436
437     // Require user interaction to play media.
438     webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
439
440     // Limit WebRTC to public IP addresses.
441     webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
442
443     // Enable the PDF viewer (it should be enabled by default, but it is nice to be explicit in case the defaults change).
444     webEngineSettingsPointer->setAttribute(QWebEngineSettings::PdfViewerEnabled, true);
445
446     // Plugins must be enabled for the PDF viewer to work.  <https://doc.qt.io/qt-5/qtwebengine-features.html#pdf-file-viewing>
447     webEngineSettingsPointer->setAttribute(QWebEngineSettings::PluginsEnabled, true);
448
449     // Update the cookies action.
450     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::updateCookiesAction, [this, privacyWebEngineViewPointer] (const int numberOfCookies)
451     {
452         // Update the cookie action if the specified privacy WebEngine view is the current privacy WebEngine view.
453         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
454             emit updateCookiesAction(numberOfCookies);
455     });
456
457     // Process cookie changes.
458     connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(addCookieToList(QNetworkCookie)));
459     connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(removeCookieFromList(QNetworkCookie)));
460
461     // Get a list of durable cookies.
462     QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
463
464     // Add the durable cookies to the store.
465     for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
466         addCookieToStore(*cookiePointer, webEngineCookieStorePointer);
467
468     // Enable spell checking.
469     webEngineProfilePointer->setSpellCheckEnabled(true);
470
471     // Set the spell check language.
472     webEngineProfilePointer->setSpellCheckLanguages(Settings::spellCheckLanguages());
473
474     // Populate the zoom factor.  This is necessary if a URL is being loaded, like a local URL, that does not trigger `applyDomainSettings()`.
475     privacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
476
477     // Update the UI when domain settings are applied.
478     connect(privacyWebEngineViewPointer, SIGNAL(updateUi(const PrivacyWebEngineView*)), this, SLOT(updateUiFromWebEngineView(const PrivacyWebEngineView*)));
479
480     // Move to the new tab if it is not a background tab.
481     if (!backgroundTab)
482         qTabWidgetPointer->setCurrentIndex(newTabIndex);
483
484     // Clear the URL line edit focus so that it populates correctly when opening a new tab from the context menu.
485     if (removeUrlLineEditFocus)
486         emit clearUrlLineEditFocus();
487
488     if (urlString != nullptr)
489         privacyWebEngineViewPointer->load(QUrl::fromUserInput(urlString));
490
491     // Return the privacy WebEngine view pointer.
492     return privacyWebEngineViewPointer;
493 }
494
495 void TabWidget::applyApplicationSettings()
496 {
497     // Set the tab position.
498     if (Settings::tabsOnTop())
499         qTabWidgetPointer->setTabPosition(QTabWidget::North);
500     else
501         qTabWidgetPointer->setTabPosition(QTabWidget::South);
502
503     // Get the number of tabs.
504     int numberOfTabs = qTabWidgetPointer->count();
505
506     // Apply the spatial navigation settings to each WebEngine.
507     for (int i = 0; i < numberOfTabs; ++i) {
508         // Get the WebEngine view pointer.
509         PrivacyWebEngineView *privacyWebEngineViewPointer = qTabWidgetPointer->widget(i)->findChild<PrivacyWebEngineView *>();
510
511         // Apply the spatial navigation settings to each page.
512         privacyWebEngineViewPointer->page()->settings()->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, Settings::spatialNavigation());
513     }
514
515     // Set the search engine URL.
516     searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
517
518     // Emit the update search engine actions signal.
519     emit updateSearchEngineActions(Settings::searchEngine(), true);
520 }
521
522 void TabWidget::applyDomainSettingsAndReload()
523 {
524     // Get the number of tabs.
525     int numberOfTabs = qTabWidgetPointer->count();
526
527     // Apply the domain settings to each WebEngine.
528     for (int i = 0; i < numberOfTabs; ++i) {
529         // Get the WebEngine view pointer.
530         PrivacyWebEngineView *privacyWebEngineViewPointer = qTabWidgetPointer->widget(i)->findChild<PrivacyWebEngineView *>();
531
532         // Apply the spatial navigation settings to each page.
533         privacyWebEngineViewPointer->applyDomainSettings(privacyWebEngineViewPointer->url().host(), true);
534     }
535 }
536
537 void TabWidget::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
538 {
539     // Store the search engine name.
540     QString searchEngineName = searchEngineActionPointer->text();
541
542     // Strip out any `&` characters.
543     searchEngineName.remove('&');
544
545     // Store the search engine string.
546     searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
547
548     // Update the search engine actions.
549     emit updateSearchEngineActions(searchEngineName, false);
550 }
551
552 void TabWidget::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
553 {
554     // Get the user agent name.
555     QString userAgentName = userAgentActionPointer->text();
556
557     // Strip out any `&` characters.
558     userAgentName.remove('&');
559
560     // Apply the user agent.
561     currentWebEngineProfilePointer->setHttpUserAgent(userAgentHelperPointer->getUserAgentFromTranslatedName(userAgentName));
562
563     // Update the user agent actions.
564     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), false);
565
566     // Reload the website.
567     currentPrivacyWebEngineViewPointer->reload();
568 }
569
570 void TabWidget::applyOnTheFlyZoomFactor(const double &zoomFactor) const
571 {
572     // Set the zoom factor.
573     currentPrivacyWebEngineViewPointer->setZoomFactor(zoomFactor);
574 }
575
576 void TabWidget::applySpellCheckLanguages() const
577 {
578     // Get the number of tab.
579     int numberOfTabs = qTabWidgetPointer->count();
580
581     // Set the spell check languages for each tab.
582     for (int i = 0; i < numberOfTabs; ++i)
583     {
584         // Get the WebEngine view pointer.
585         PrivacyWebEngineView *privacyWebEngineViewPointer = qTabWidgetPointer->widget(i)->findChild<PrivacyWebEngineView *>();
586
587         // Get the WebEngine page pointer.
588         QWebEnginePage *webEnginePagePointer = privacyWebEngineViewPointer->page();
589
590         // Get the WebEngine profile pointer.
591         QWebEngineProfile *webEngineProfilePointer = webEnginePagePointer->profile();
592
593         // Set the spell check languages.
594         webEngineProfilePointer->setSpellCheckLanguages(Settings::spellCheckLanguages());
595     }
596 }
597
598 void TabWidget::back() const
599 {
600     // Go back.
601     currentPrivacyWebEngineViewPointer->back();
602 }
603
604 void TabWidget::deleteAllCookies() const
605 {
606     // Delete all the cookies.
607     currentWebEngineCookieStorePointer->deleteAllCookies();
608 }
609
610 void TabWidget::deleteCookieFromStore(const QNetworkCookie &cookie) const
611 {
612     // Delete the cookie.
613     currentWebEngineCookieStorePointer->deleteCookie(cookie);
614 }
615
616 void TabWidget::deleteTab(const int tabIndex)
617 {
618     // Get the tab splitter widget.
619     QWidget *tabSplitterWidgetPointer = qTabWidgetPointer->widget(tabIndex);
620
621     // Get the WebEngine views.
622     PrivacyWebEngineView *privacyWebEngineViewPointer = tabSplitterWidgetPointer->findChild<PrivacyWebEngineView *>();
623     DevToolsWebEngineView *devToolsWebEngineViewPointer = tabSplitterWidgetPointer->findChild<DevToolsWebEngineView *>();
624
625     // Process the tab delete according to the number of tabs.
626     if (qTabWidgetPointer->count() > 1)  // There is more than one tab.
627     {
628         // Remove the tab.
629         qTabWidgetPointer->removeTab(tabIndex);
630
631         // Delete the WebEngine pages to prevent the following error:  `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
632         delete privacyWebEngineViewPointer->page();
633         delete devToolsWebEngineViewPointer->page();
634
635         // Delete the WebEngine views.
636         delete privacyWebEngineViewPointer;
637         delete devToolsWebEngineViewPointer;
638
639         // Delete the tab splitter widget.
640         delete tabSplitterWidgetPointer;
641     }
642     else  // There is only one tab.
643     {
644         // Close Privacy Browser.
645         window()->close();
646     }
647 }
648
649 void TabWidget::findPrevious(const QString &text) const
650 {
651     // Store the current text.
652     currentPrivacyWebEngineViewPointer->findString = text;
653
654     // Find the previous text in the current privacy WebEngine.
655     if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
656         currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively|QWebEnginePage::FindBackward);
657     else
658         currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindBackward);
659 }
660
661 void TabWidget::findText(const QString &text) const
662 {
663     // Store the current text.
664     currentPrivacyWebEngineViewPointer->findString = text;
665
666     // Find the text in the current privacy WebEngine.
667     if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
668         currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively);
669     else
670         currentPrivacyWebEngineViewPointer->findText(text);
671
672     // Clear the currently selected text in the WebEngine page if the find text is empty.
673     if (text.isEmpty())
674         currentWebEnginePagePointer->action(QWebEnginePage::Unselect)->activate(QAction::Trigger);
675 }
676
677 void TabWidget::findTextFinished(const QWebEngineFindTextResult &findTextResult)
678 {
679     // Update the find text UI if it wasn't simply wiping the current find text selection.  Otherwise the UI temporarily flashes `0/0`.
680     if (wipingCurrentFindTextSelection)  // The current selection is being wiped.
681     {
682         // Reset the flag.
683         wipingCurrentFindTextSelection = false;
684     }
685     else  // A new search has been performed.
686     {
687         // Store the result.
688         currentPrivacyWebEngineViewPointer->findTextResult = findTextResult;
689
690         // Update the UI.
691         emit updateFindTextResults(findTextResult);
692     }
693 }
694
695 void TabWidget::forward() const
696 {
697     // Go forward.
698     currentPrivacyWebEngineViewPointer->forward();
699 }
700
701 void TabWidget::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest) const
702 {
703     // Make it so.
704     emit fullScreenRequested(fullScreenRequest.toggleOn());
705
706     // Accept the request.
707     fullScreenRequest.accept();
708 }
709
710 std::list<QNetworkCookie>* TabWidget::getCookieList() const
711 {
712     // Return the current cookie list.
713     return currentPrivacyWebEngineViewPointer->cookieListPointer;
714 }
715
716 QIcon TabWidget::getCurrentTabFavoritIcon() const
717 {
718     // Return the current Privacy WebEngine favorite icon.
719     return currentPrivacyWebEngineViewPointer->favoriteIcon;
720 }
721
722 QString TabWidget::getCurrentTabTitle() const
723 {
724     // Return the current Privacy WebEngine title.
725     return currentPrivacyWebEngineViewPointer->title();
726 }
727
728 QString TabWidget::getCurrentTabUrl() const
729 {
730     // Return the current Privacy WebEngine URL as a string.
731     return currentPrivacyWebEngineViewPointer->url().toString();
732 }
733
734 QString& TabWidget::getDomainSettingsName() const
735 {
736     // Return the domain settings name.
737     return currentPrivacyWebEngineViewPointer->domainSettingsName;
738 }
739
740 void TabWidget::home() const
741 {
742     // Load the homepage.
743     currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
744 }
745
746 PrivacyWebEngineView* TabWidget::loadBlankInitialWebsite()
747 {
748     // Apply the application settings.
749     applyApplicationSettings();
750
751     // Return the current privacy WebEngine view pointer.
752     return currentPrivacyWebEngineViewPointer;
753 }
754
755 void TabWidget::loadInitialWebsite()
756 {
757     // Apply the application settings.
758     applyApplicationSettings();
759
760     // Get the arguments.
761     QStringList argumentsStringList = qApp->arguments();
762
763     // Check to see if the arguments lists contains a URL.
764     if (argumentsStringList.size() > 1)
765     {
766         // Load the URL from the arguments list.
767         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
768     }
769     else
770     {
771         // Load the homepage.
772         home();
773     }
774 }
775
776 void TabWidget::loadUrlFromLineEdit(QString url) const
777 {
778     // Decide if the text is more likely to be a URL or a search.
779     if (url.startsWith("file://") || url.startsWith("view-source:"))  // The text is likely a file or view source URL.
780     {
781         // Load the URL.
782         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
783     }
784     else if (url.contains("."))  // The text is likely a URL.
785     {
786         // Check if the URL does not start with a valid protocol.
787         if (!url.startsWith("http"))
788         {
789             // Add `https://` to the beginning of the URL.
790             url = "https://" + url;
791         }
792
793         // Load the URL.
794         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
795     }
796     else  // The text is likely a search.
797     {
798         // Load the search.
799         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
800     }
801 }
802
803 void TabWidget::mouseBack() const
804 {
805     // Go back if possible.
806     if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoBack())
807     {
808         // Clear the URL line edit focus.
809         emit clearUrlLineEditFocus();
810
811         // Go back.
812         currentPrivacyWebEngineViewPointer->back();
813     }
814 }
815
816 void TabWidget::mouseForward() const
817 {
818     // Go forward if possible.
819     if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoForward())
820     {
821         // Clear the URL line edit focus.
822         emit clearUrlLineEditFocus();
823
824         // Go forward.
825         currentPrivacyWebEngineViewPointer->forward();
826     }
827 }
828
829 void TabWidget::pageLinkHovered(const QString &linkUrl) const
830 {
831     // Emit a signal so that the browser window can update the status bar.
832     emit linkHovered(linkUrl);
833 }
834
835 void TabWidget::stopLoadingFavoriteIconMovie() const
836 {
837     // 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>
838     loadingFavoriteIconMoviePointer->stop();
839 }
840
841 void TabWidget::print() const
842 {
843     // Create a printer.
844     QPrinter printer;
845
846     // Set the resolution to be 300 dpi.
847     printer.setResolution(300);
848
849     // Create a printer dialog.
850     QPrintDialog printDialog(&printer, currentPrivacyWebEngineViewPointer);
851
852     // Display the dialog and print the page if instructed.
853     if (printDialog.exec() == QDialog::Accepted)
854         printWebpage(&printer);
855 }
856
857 void TabWidget::printPreview() const
858 {
859     // Create a printer.
860     QPrinter printer;
861
862     // Set the resolution to be 300 dpi.
863     printer.setResolution(300);
864
865     // Create a print preview dialog.
866     QPrintPreviewDialog printPreviewDialog(&printer, currentPrivacyWebEngineViewPointer);
867
868     // Generate the print preview.
869     connect(&printPreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printWebpage(QPrinter *)));
870
871     // Display the dialog.
872     printPreviewDialog.exec();
873 }
874
875 void TabWidget::printWebpage(QPrinter *printerPointer) const
876 {
877     // Create an event loop.  For some reason, the print preview doesn't produce any output unless it is run inside an event loop.
878     QEventLoop eventLoop;
879
880     // Print the webpage, converting the callback above into a `QWebEngineCallback<bool>`.
881     // Printing requires that the printer be a pointer, not a reference, or it will crash with much cursing.
882     currentWebEnginePagePointer->print(printerPointer, [&eventLoop](bool printSuccess)
883     {
884         // Instruct the compiler to ignore the unused parameter.
885         (void) printSuccess;
886
887         // Quit the loop.
888         eventLoop.quit();
889     });
890
891     // Execute the loop.
892     eventLoop.exec();
893 }
894
895 void TabWidget::refresh() const
896 {
897     // Reload the website.
898     currentPrivacyWebEngineViewPointer->reload();
899 }
900
901 void TabWidget::reloadAndBypassCache() const
902 {
903     // Reload the website, bypassing the cache.
904     currentWebEnginePagePointer->triggerAction(QWebEnginePage::ReloadAndBypassCache);
905 }
906
907 void TabWidget::saveArchive()
908 {
909     // Get the suggested file name.
910     QString suggestedFileName = currentPrivacyWebEngineViewPointer->url().host() + ".mht";
911
912     // Get the download directory.
913     QString downloadDirectory = Settings::downloadLocation();
914
915     // Resolve the system download directory if specified.
916     if (downloadDirectory == QLatin1String("System Download Directory"))
917         downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
918
919     // Get a file path from the file picker.
920     QString saveFilePath = QFileDialog::getSaveFileName(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory + QLatin1Char('/') + suggestedFileName);
921
922     // Save the webpage as an archive if the file save path is populated.
923     if (!saveFilePath.isEmpty())
924     {
925         // Set the saving archive flag.  Otherwise, a second download tries to run.
926         savingArchive = true;
927
928         // Save the archive.
929         currentWebEnginePagePointer->save(saveFilePath);
930     }
931 }
932
933 void TabWidget::setTabBarVisible(const bool visible) const
934 {
935     // Set the tab bar visibility.
936     qTabWidgetPointer->tabBar()->setVisible(visible);
937 }
938
939 void TabWidget::showSaveDialog(QWebEngineDownloadItem *webEngineDownloadItemPointer)
940 {
941     // Only show the save dialog if an archive is not currently being saved.  Otherwise, two save dialogs will be shown.
942     if (!savingArchive)
943     {
944         // Get the download attributes.
945         QUrl downloadUrl = webEngineDownloadItemPointer->url();
946         QString mimeTypeString = webEngineDownloadItemPointer->mimeType();
947         QString suggestedFileName = webEngineDownloadItemPointer->suggestedFileName();
948         int totalBytes = webEngineDownloadItemPointer->totalBytes();
949
950         // Check to see if Privacy Browser is not running KDE or if local storage (cookies) is enabled.
951         if (!isRunningKde || currentPrivacyWebEngineViewPointer->localStorageEnabled)  // KDE is not running or local storage (cookies) is enabled.  Use WebEngine's downloader.
952         {
953             // Instantiate the save dialog.
954             SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes);
955
956             // Display the save dialog.
957             int saveDialogResult = saveDialogPointer->exec();
958
959             // Process the save dialog results.
960             if (saveDialogResult == QDialog::Accepted)  // Save was selected.
961             {
962                 // Get the download directory.
963                 QString downloadDirectory = Settings::downloadLocation();
964
965                 // Resolve the system download directory if specified.
966                 if (downloadDirectory == QLatin1String("System Download Directory"))
967                     downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
968
969                 // Get a file path from the file picker.
970                 QString saveFilePath = QFileDialog::getSaveFileName(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory + QLatin1Char('/') + suggestedFileName);
971
972                 // Process the save file path.
973                 if (!saveFilePath.isEmpty())  // The file save path is populated.
974                 {
975                     // Create a save file path file info.
976                     QFileInfo saveFilePathFileInfo = QFileInfo(saveFilePath);
977
978                     // Get the canonical save path and file name.
979                     QString absoluteSavePath = saveFilePathFileInfo.absolutePath();
980                     QString saveFileName = saveFilePathFileInfo.fileName();
981
982                     // Set the download directory and file name.
983                     webEngineDownloadItemPointer->setDownloadDirectory(absoluteSavePath);
984                     webEngineDownloadItemPointer->setDownloadFileName(saveFileName);
985
986                     // Create a file download notification.
987                     KNotification *fileDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
988
989                     // Set the notification title.
990                     fileDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
991
992                     // Set the notification text.
993                     fileDownloadNotificationPointer->setText(i18nc("Downloading notification text", "Downloading %1", saveFileName));
994
995                     // Get the download icon from the theme.
996                     QIcon downloadIcon = QIcon::fromTheme(QLatin1String("download"), QIcon::fromTheme(QLatin1String("document-save")));
997
998                     // Set the notification icon.
999                     fileDownloadNotificationPointer->setIconName(downloadIcon.name());
1000
1001                     // Set the action list cancel button.
1002                     fileDownloadNotificationPointer->setActions(QStringList({i18nc("Download notification action","Cancel")}));
1003
1004                     // Prevent the notification from being autodeleted if it is closed.  Otherwise, the updates to the notification below cause a crash.
1005                     fileDownloadNotificationPointer->setAutoDelete(false);
1006
1007                     // Handle clicks on the cancel button.
1008                     connect(fileDownloadNotificationPointer, &KNotification::action1Activated, [webEngineDownloadItemPointer, saveFileName] ()
1009                     {
1010                         // Cancel the download.
1011                         webEngineDownloadItemPointer->cancel();
1012
1013                         // Create a file download notification.
1014                         KNotification *canceledDownloadNotificationPointer = new KNotification(QLatin1String("FileDownload"));
1015
1016                         // Set the notification title.
1017                         canceledDownloadNotificationPointer->setTitle(i18nc("Download notification title", "Download"));
1018
1019                         // Set the new text.
1020                         canceledDownloadNotificationPointer->setText(i18nc("Download canceled notification", "%1 download canceled", saveFileName));
1021
1022                         // Set the notification icon.
1023                         canceledDownloadNotificationPointer->setIconName(QLatin1String("download"));
1024
1025                         // Display the notification.
1026                         canceledDownloadNotificationPointer->sendEvent();
1027                     });
1028
1029                     // Update the notification when the download progresses.
1030                     connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::downloadProgress, [fileDownloadNotificationPointer, saveFileName] (qint64 bytesReceived, qint64 totalBytes)
1031                     {
1032                         // Set the new text.  Total bytes will be 0 if the download size is unknown.
1033                         if (totalBytes > 0)
1034                         {
1035                             // Calculate the download percentage.
1036                             int downloadPercentage = 100 * bytesReceived / totalBytes;
1037
1038                             // Set the file download notification text.
1039                             fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1\% of %2 downloaded (%3 of %4 bytes)", downloadPercentage, saveFileName,
1040                                                                         bytesReceived, totalBytes));
1041                         }
1042                         else
1043                         {
1044                             // Set the file download notification text.
1045                             fileDownloadNotificationPointer->setText(i18nc("Download progress notification text", "%1:  %2 bytes downloaded", saveFileName, bytesReceived));
1046                         }
1047
1048                         // Display the updated notification.
1049                         fileDownloadNotificationPointer->update();
1050                     });
1051
1052                     // Update the notification when the download finishes.  The save file name must be copied into the lambda or a crash occurs.
1053                     connect(webEngineDownloadItemPointer, &QWebEngineDownloadItem::finished, [fileDownloadNotificationPointer, saveFileName, saveFilePath] ()
1054                     {
1055                         // Set the new text.
1056                         fileDownloadNotificationPointer->setText(i18nc("Download finished notification text", "%1 download finished", saveFileName));
1057
1058                         // Set the URL so the file options will be displayed.
1059                         fileDownloadNotificationPointer->setUrls(QList<QUrl> {QUrl(saveFilePath)});
1060
1061                         // Remove the actions from the notification.
1062                         fileDownloadNotificationPointer->setActions(QStringList());
1063
1064                         // Set the notification to disappear after a timeout.
1065                         fileDownloadNotificationPointer->setFlags(KNotification::CloseOnTimeout);
1066
1067                         // Display the updated notification.
1068                         fileDownloadNotificationPointer->update();
1069                     });
1070
1071                     // Display the notification.
1072                     fileDownloadNotificationPointer->sendEvent();
1073
1074                     // Start the download.
1075                     webEngineDownloadItemPointer->accept();
1076                 }
1077                 else  // The file save path is not populated.
1078                 {
1079                     // Cancel the download.
1080                     webEngineDownloadItemPointer->cancel();
1081                 }
1082             }
1083             else  // Cancel was selected.
1084             {
1085                 // Cancel the download.
1086                 webEngineDownloadItemPointer->cancel();
1087             }
1088         }
1089         else  // KDE is running and local storage (cookies) is disabled.  Use KDE's native downloader.
1090             // 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.
1091         {
1092             // Instantiate the save dialog.  `true` instructs it to use the native downloader
1093             SaveDialog *saveDialogPointer = new SaveDialog(downloadUrl, mimeTypeString, totalBytes, suggestedFileName, true);
1094
1095             // Connect the save button.
1096             connect(saveDialogPointer, SIGNAL(useNativeKdeDownloader(QUrl &, QString &)), this, SLOT(useNativeKdeDownloader(QUrl &, QString &)));
1097
1098             // Show the dialog.
1099             saveDialogPointer->show();
1100         }
1101     }
1102
1103     // Reset the saving archive flag.
1104     savingArchive = false;
1105 }
1106
1107 void TabWidget::toggleDeveloperTools(const bool enabled) const
1108 {
1109     // Get a handle for the current developer tools WebEngine.
1110     DevToolsWebEngineView *devToolsWebEngineViewPointer = qTabWidgetPointer->currentWidget()->findChild<DevToolsWebEngineView *>();
1111
1112     if (enabled)
1113     {
1114         // Set the zoom factor on the development tools WebEngine.
1115         devToolsWebEngineViewPointer->setZoomFactor(currentWebEnginePagePointer->zoomFactor());
1116
1117         // Enable the development tools.
1118         currentWebEnginePagePointer->setDevToolsPage(devToolsWebEngineViewPointer->page());
1119
1120         // Enable JavaScript on the development tools WebEngine.
1121         devToolsWebEngineViewPointer->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
1122
1123         // Display the developer tools.
1124         devToolsWebEngineViewPointer->setVisible(true);
1125     }
1126     else
1127     {
1128         // Disable JavaScript on the development tools WebEngine to prevent error messages from being written to the console.
1129         devToolsWebEngineViewPointer->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
1130
1131         // Disable the development tools.
1132         currentWebEnginePagePointer->setDevToolsPage(nullptr);
1133
1134         // Hide the developer tools.
1135         devToolsWebEngineViewPointer->setVisible(false);
1136     }
1137 }
1138
1139 void TabWidget::toggleDomStorage() const
1140 {
1141     // Toggle DOM storage.
1142     currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1143
1144     // Update the DOM storage action.
1145     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1146
1147     // Reload the website.
1148     currentPrivacyWebEngineViewPointer->reload();
1149 }
1150
1151 void TabWidget::toggleFindCaseSensitive(const QString &text)
1152 {
1153     // Toggle find case sensitive.
1154     currentPrivacyWebEngineViewPointer->findCaseSensitive = !currentPrivacyWebEngineViewPointer->findCaseSensitive;
1155
1156     // Set the wiping current find text selection flag.
1157     wipingCurrentFindTextSelection = true;
1158
1159     // Wipe the previous search.  Otherwise currently highlighted words will remain highlighted.
1160     findText(QLatin1String(""));
1161
1162     // Update the find text.
1163     findText(text);
1164 }
1165
1166 void TabWidget::toggleJavaScript() const
1167 {
1168     // Toggle JavaScript.
1169     currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1170
1171     // Update the JavaScript action.
1172     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1173
1174     // Reload the website.
1175     currentPrivacyWebEngineViewPointer->reload();
1176 }
1177
1178 void TabWidget::toggleLocalStorage()
1179 {
1180     // Toggle local storage.
1181     currentPrivacyWebEngineViewPointer->localStorageEnabled = !currentPrivacyWebEngineViewPointer->localStorageEnabled;
1182
1183     // Update the local storage action.
1184     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1185
1186     // Reload the website.
1187     currentPrivacyWebEngineViewPointer->reload();
1188 }
1189
1190 void TabWidget::updateUiFromWebEngineView(const PrivacyWebEngineView *privacyWebEngineViewPointer) const
1191 {
1192     // Only update the UI if the signal was emitted from the current privacy WebEngine.
1193     if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
1194     {
1195         // Update the UI.
1196         emit updateDefaultZoomFactor(currentPrivacyWebEngineViewPointer->defaultZoomFactor);
1197         emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
1198         emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1199         emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1200         emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1201         emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
1202         emit updateZoomActions(currentPrivacyWebEngineViewPointer->zoomFactor());
1203     }
1204 }
1205
1206 void TabWidget::updateUiWithTabSettings()
1207 {
1208     // Update the current WebEngine pointers.
1209     currentPrivacyWebEngineViewPointer = qTabWidgetPointer->currentWidget()->findChild<PrivacyWebEngineView *>();
1210     currentWebEngineSettingsPointer = currentPrivacyWebEngineViewPointer->settings();
1211     currentWebEnginePagePointer = currentPrivacyWebEngineViewPointer->page();
1212     currentWebEngineProfilePointer = currentWebEnginePagePointer->profile();
1213     currentWebEngineHistoryPointer = currentWebEnginePagePointer->history();
1214     currentWebEngineCookieStorePointer = currentWebEngineProfilePointer->cookieStore();
1215
1216     // Clear the URL line edit focus.
1217     emit clearUrlLineEditFocus();
1218
1219     // Get a handle for the development tools WebEngine view.
1220     DevToolsWebEngineView *devToolsWebEngineViewPointer = qTabWidgetPointer->currentWidget()->findChild<DevToolsWebEngineView *>();
1221
1222     // Update the actions.
1223     emit updateDefaultZoomFactor(currentPrivacyWebEngineViewPointer->defaultZoomFactor);
1224     emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
1225     emit updateCookiesAction(currentPrivacyWebEngineViewPointer->cookieListPointer->size());
1226     emit updateDeveloperToolsAction(devToolsWebEngineViewPointer->isVisible());
1227     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
1228     emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
1229     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
1230     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
1231     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
1232     emit updateZoomActions(currentPrivacyWebEngineViewPointer->zoomFactor());
1233
1234     // Update the URL.
1235     emit updateWindowTitle(currentPrivacyWebEngineViewPointer->title());
1236     emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QLatin1String(""));
1237     emit updateUrlLineEdit(currentPrivacyWebEngineViewPointer->url());
1238
1239     // Update the find text.
1240     emit updateFindText(currentPrivacyWebEngineViewPointer->findString, currentPrivacyWebEngineViewPointer->findCaseSensitive);
1241     emit updateFindTextResults(currentPrivacyWebEngineViewPointer->findTextResult);
1242
1243     // Update the progress bar.
1244     if (currentPrivacyWebEngineViewPointer->loadProgressInt >= 0)
1245         emit showProgressBar(currentPrivacyWebEngineViewPointer->loadProgressInt);
1246     else
1247         emit hideProgressBar();
1248 }
1249
1250 void TabWidget::useNativeKdeDownloader(QUrl &downloadUrl, QString &suggestedFileName)
1251 {
1252     // Get the download directory.
1253     QString downloadDirectory = Settings::downloadLocation();
1254
1255     // Resolve the system download directory if specified.
1256     if (downloadDirectory == QLatin1String("System Download Directory"))
1257         downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
1258
1259     // Create a save file dialog.
1260     QFileDialog *saveFileDialogPointer = new QFileDialog(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory);
1261
1262     // Tell the dialog to use a save button.
1263     saveFileDialogPointer->setAcceptMode(QFileDialog::AcceptSave);
1264
1265     // Populate the file name from the download item pointer.
1266     saveFileDialogPointer->selectFile(suggestedFileName);
1267
1268     // Prevent interaction with the parent window while the dialog is open.
1269     saveFileDialogPointer->setWindowModality(Qt::WindowModal);
1270
1271     // Process the saving of the file.  The save file dialog pointer must be captured directly instead of by reference or nasty crashes occur.
1272     auto saveFile = [saveFileDialogPointer, downloadUrl] ()
1273     {
1274         // Get the save location.  The dialog box should only allow the selecting of one file location.
1275         QUrl saveLocation = saveFileDialogPointer->selectedUrls().value(0);
1276
1277         // Create a file copy job.  `-1` creates the file with default permissions.
1278         KIO::FileCopyJob *fileCopyJobPointer = KIO::file_copy(downloadUrl, saveLocation, -1, KIO::Overwrite);
1279
1280         // Set the download job to display any warning and error messages.
1281         fileCopyJobPointer->uiDelegate()->setAutoWarningHandlingEnabled(true);
1282         fileCopyJobPointer->uiDelegate()->setAutoErrorHandlingEnabled(true);
1283
1284         // Start the download.
1285         fileCopyJobPointer->start();
1286     };
1287
1288     // Handle clicks on the save button.
1289     connect(saveFileDialogPointer, &QDialog::accepted, this, saveFile);
1290
1291     // Show the dialog.
1292     saveFileDialogPointer->show();
1293 }