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