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