]> gitweb.stoutner.com Git - PrivacyBrowserPC.git/blob - src/widgets/TabWidget.cpp
3a1b54f33f2028f411b5eefadb14d346f794bb13
[PrivacyBrowserPC.git] / src / widgets / TabWidget.cpp
1 /*
2  * Copyright © 2022 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 "databases/DomainsDatabase.h"
27 #include "dialogs/SaveDialog.h"
28 #include "filters/MouseEventFilter.h"
29 #include "helpers/SearchEngineHelper.h"
30 #include "helpers/UserAgentHelper.h"
31 #include "interceptors/UrlRequestInterceptor.h"
32 #include "windows/BrowserWindow.h"
33
34 // KDE Framework headers.
35 #include <KIO/FileCopyJob>
36 #include <KIO/JobUiDelegate>
37
38 // Qt toolkit headers.
39 #include <QAction>
40 #include <QFileDialog>
41 #include <QGraphicsScene>
42 #include <QGraphicsView>
43 #include <QPrintDialog>
44 #include <QPrintPreviewDialog>
45 #include <QPrinter>
46
47 // Initialize the public static variables.
48 QString TabWidget::webEngineDefaultUserAgent = QStringLiteral("");
49
50 // Construct the class.
51 TabWidget::TabWidget(QWidget *parent) : QWidget(parent)
52 {
53     // Instantiate the UIs.
54     Ui::TabWidget tabWidgetUi;
55     Ui::AddTabWidget addTabWidgetUi;
56
57     // Setup the main UI.
58     tabWidgetUi.setupUi(this);
59
60     // Get a handle for the tab widget.
61     tabWidgetPointer = tabWidgetUi.tabWidget;
62
63     // Setup the add tab UI.
64     addTabWidgetUi.setupUi(tabWidgetPointer);
65
66     // Get handles for the add tab widgets.
67     QWidget *addTabWidgetPointer = addTabWidgetUi.addTabQWidget;
68     QPushButton *addTabButtonPointer = addTabWidgetUi.addTabButton;
69
70     // Display the add tab widget.
71     tabWidgetPointer->setCornerWidget(addTabWidgetPointer);
72
73     // Add the first tab.
74     addFirstTab();
75
76     // Process tab events.
77     connect(tabWidgetPointer, SIGNAL(currentChanged(int)), this, SLOT(updateUiWithTabSettings()));
78     connect(addTabButtonPointer, SIGNAL(clicked()), this, SLOT(addTab()));
79     connect(tabWidgetPointer, SIGNAL(tabCloseRequested(int)), this, SLOT(deleteTab(int)));
80
81     // Store a copy of the WebEngine default user agent.
82     webEngineDefaultUserAgent = currentWebEngineProfilePointer->httpUserAgent();
83
84     // Instantiate the mouse event filter pointer.
85     MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
86
87     // Install the mouse event filter.
88     qApp->installEventFilter(mouseEventFilterPointer);
89
90     // Process mouse forward and back commands.
91     connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
92     connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
93 }
94
95 TabWidget::~TabWidget()
96 {
97     // Manually delete each WebEngine page.
98     for (int i = 0; i < tabWidgetPointer->count(); ++i)
99     {
100         // Get the privacy WebEngine view.
101         PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->widget(i));
102
103         // Deletion the WebEngine page to prevent the following error:  `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
104         delete privacyWebEngineViewPointer->page();
105     }
106 }
107
108 // 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.
109 void TabWidget::addCookieToStore(QNetworkCookie cookie, QWebEngineCookieStore *webEngineCookieStorePointer) const
110 {
111     // Create a url.
112     QUrl url;
113
114     // 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>
115     if (!cookie.domain().startsWith(QStringLiteral(".")))
116     {
117         // Populate the URL.
118         url.setHost(cookie.domain());
119         url.setScheme(QStringLiteral("https"));
120
121         // Clear the domain from the cookie.
122         cookie.setDomain(QStringLiteral(""));
123     }
124
125     // Add the cookie to the store.
126     if (webEngineCookieStorePointer == nullptr)
127         currentWebEngineCookieStorePointer->setCookie(cookie, url);
128     else
129         webEngineCookieStorePointer->setCookie(cookie, url);
130 }
131
132 void TabWidget::addFirstTab()
133 {
134     // Create the first tab.
135     addTab();
136
137     // Update the UI with the tab settings.
138     updateUiWithTabSettings();
139
140     // 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.
141     tabWidgetPointer->currentWidget()->setFocus();
142 }
143
144 PrivacyWebEngineView* TabWidget::addTab(const bool focusNewWebEngineView)
145 {
146     // Create a privacy WebEngine view.
147     PrivacyWebEngineView *privacyWebEngineViewPointer = new PrivacyWebEngineView();
148
149     // Add a new tab.
150     int newTabIndex = tabWidgetPointer->addTab(privacyWebEngineViewPointer, i18nc("New tab label.", "New Tab"));
151
152     // Set the default tab icon.
153     tabWidgetPointer->setTabIcon(newTabIndex, defaultTabIcon);
154
155     // Create an off-the-record profile (the default when no profile name is specified).
156     QWebEngineProfile *webEngineProfilePointer = new QWebEngineProfile(QStringLiteral(""));
157
158     // Create a WebEngine page.
159     QWebEnginePage *webEnginePagePointer = new QWebEnginePage(webEngineProfilePointer);
160
161     // Set the WebEngine page.
162     privacyWebEngineViewPointer->setPage(webEnginePagePointer);
163
164     // Get handles for the web engine elements.
165     QWebEngineCookieStore *webEngineCookieStorePointer = webEngineProfilePointer->cookieStore();
166     QWebEngineSettings *webEngineSettingsPointer = webEnginePagePointer->settings();
167
168     // Update the URL line edit when the URL changes.
169     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::urlChanged, [privacyWebEngineViewPointer, this] (const QUrl &newUrl)
170     {
171         // Only update the UI if this is the current tab.
172         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
173         {
174             // Update the URL line edit.
175             emit updateUrlLineEdit(newUrl);
176
177             // Update the status of the forward and back buttons.
178             emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
179             emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
180         }
181
182         // Reapply the zoom factor.  This is a bug in QWebEngineView that resets the zoom with every load.  It can be removed once <https://redmine.stoutner.com/issues/799> is fixed.
183         privacyWebEngineViewPointer->setZoomFactor(currentZoomFactor);
184     });
185
186     // Update the progress bar when a load is started.
187     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadStarted, [privacyWebEngineViewPointer, this] ()
188     {
189         // Store the load progress.
190         privacyWebEngineViewPointer->loadProgressInt = 0;
191
192         // Show the progress bar if this is the current tab.
193         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
194             emit showProgressBar(0);
195     });
196
197     // Update the progress bar when a load progresses.
198     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadProgress, [privacyWebEngineViewPointer, this] (const int progress)
199     {
200         // Store the load progress.
201         privacyWebEngineViewPointer->loadProgressInt = progress;
202
203         // Update the progress bar if this is the current tab.
204         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
205             emit showProgressBar(progress);
206     });
207
208     // Update the progress bar when a load finishes.
209     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::loadFinished, [privacyWebEngineViewPointer, this] ()
210     {
211         // Store the load progress.
212         privacyWebEngineViewPointer->loadProgressInt = -1;
213
214         // Hide the progress bar if this is the current tab.
215         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
216             emit hideProgressBar();
217     });
218
219     // Display find text results.
220     connect(webEnginePagePointer, SIGNAL(findTextFinished(const QWebEngineFindTextResult &)), this, SLOT(findTextFinished(const QWebEngineFindTextResult &)));
221
222     // Handle full screen requests.
223     connect(webEnginePagePointer, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this, SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
224
225     // Listen for hovered link URLs.
226     connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
227
228     // Handle file downloads.
229     connect(webEngineProfilePointer, SIGNAL(downloadRequested(QWebEngineDownloadItem *)), this, SLOT(showSaveDialog(QWebEngineDownloadItem *)));
230
231     // Instantiate the URL request interceptor.
232     UrlRequestInterceptor *urlRequestInterceptorPointer = new UrlRequestInterceptor();
233
234     // Set the URL request interceptor.
235     webEngineProfilePointer->setUrlRequestInterceptor(urlRequestInterceptorPointer);
236
237     // Reapply the domain settings when the host changes.
238     connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings(QString)), this, SLOT(applyDomainSettingsWithoutReloading(QString)));
239
240     // Set the local storage filter.
241     webEngineCookieStorePointer->setCookieFilter([privacyWebEngineViewPointer](const QWebEngineCookieStore::FilterRequest &filterRequest)
242     {
243         // Block all third party local storage requests, including the sneaky ones that don't register a first party URL.
244         if (filterRequest.thirdParty || (filterRequest.firstPartyUrl == QStringLiteral("")))
245         {
246             //qDebug().noquote().nospace() << "Third-party request blocked:  " << filterRequest.origin;
247
248             // Return false.
249             return false;
250         }
251
252         // Allow the request if local storage is enabled.
253         if (privacyWebEngineViewPointer->localStorageEnabled)
254         {
255             //qDebug().noquote().nospace() << "Request allowed by local storage:  " << filterRequest.origin;
256
257             // Return true.
258             return true;
259         }
260
261         //qDebug().noquote().nospace() << "Request blocked by default:  " << filterRequest.origin;
262
263         // Block any remaining local storage requests.
264         return false;
265     });
266
267     // Disable JavaScript by default (this prevetns JavaScript from being enabled on a new tab before domain settings are loaded).
268     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
269
270     // Don't allow JavaScript to open windows.
271     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
272
273     // Allow keyboard navigation.
274     webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
275
276     // Enable full screen support.
277     webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
278
279     // Require user interaction to play media.
280     webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
281
282     // Limit WebRTC to public IP addresses.
283     webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
284
285     // Update the cookies action.
286     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::updateCookiesAction, [privacyWebEngineViewPointer, this] (const int numberOfCookies)
287     {
288         // Update the cookie action if the specified privacy WebEngine view is the current privacy WebEngine view.
289         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
290             emit updateCookiesAction(numberOfCookies);
291     });
292
293     // Process cookie changes.
294     connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(addCookieToList(QNetworkCookie)));
295     connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(removeCookieFromList(QNetworkCookie)));
296
297     // Get a list of durable cookies.
298     QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
299
300     // Add the durable cookies to the store.
301     for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
302         addCookieToStore(*cookiePointer, webEngineCookieStorePointer);
303
304     // Update the title when it changes.
305     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::titleChanged, [this, privacyWebEngineViewPointer] (const QString &title)
306     {
307         // Get the index for this tab.
308         int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
309
310         // Update the title for this tab.
311         tabWidgetPointer->setTabText(tabIndex, title);
312
313         // Update the window title if this is the current tab.
314         if (tabIndex == tabWidgetPointer->currentIndex())
315             emit updateWindowTitle(title);
316     });
317
318     // Update the icon when it changes.
319     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::iconChanged, [privacyWebEngineViewPointer, this] (const QIcon &icon)
320     {
321         // Get the index for this tab.
322         int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
323
324         // Update the icon for this tab.
325         if (icon.isNull())
326             tabWidgetPointer->setTabIcon(tabIndex, defaultTabIcon);
327         else
328             tabWidgetPointer->setTabIcon(tabIndex, icon);
329     });
330
331     // Enable spell checking.
332     webEngineProfilePointer->setSpellCheckEnabled(true);
333
334     // Set the spell check language.
335     webEngineProfilePointer->setSpellCheckLanguages({QStringLiteral("en_US")});
336
337     // Move to the new tab.
338     tabWidgetPointer->setCurrentIndex(newTabIndex);
339
340     // Clear the URL line edit focus so that it populates correctly when opening a new tab from the context menu.
341     if (focusNewWebEngineView)
342         emit clearUrlLineEditFocus();
343
344     // Return the privacy WebEngine view pointer.
345     return privacyWebEngineViewPointer;
346 }
347
348 void TabWidget::applyApplicationSettings()
349 {
350     // Set the tab position.
351     if (Settings::tabsOnTop())
352         tabWidgetPointer->setTabPosition(QTabWidget::North);
353     else
354         tabWidgetPointer->setTabPosition(QTabWidget::South);
355
356     // Set the search engine URL.
357     searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
358
359     // Emit the update search engine actions signal.
360     emit updateSearchEngineActions(Settings::searchEngine(), true);
361 }
362
363 // This exists as a separate function from `applyDomainSettings()` so it can be listed as a slot and function without the need for a boolean argument.
364 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
365 void TabWidget::applyDomainSettingsAndReload()
366 {
367     // Apply the domain settings.  `true` reloads the website.
368     applyDomainSettings(currentPrivacyWebEngineViewPointer->url().host(), true);
369 }
370
371 // This exists as a separate function from `applyDomainSettings()` so it can be listed as a slot and function without the need for a boolean argument.
372 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
373 void TabWidget::applyDomainSettingsWithoutReloading(const QString &hostname)
374 {
375     // Apply the domain settings  `false` does not reload the website.
376     applyDomainSettings(hostname, false);
377 }
378
379 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
380 void TabWidget::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
381 {
382     // Get the record for the hostname.
383     QSqlQuery domainQuery = DomainsDatabase::getDomainQuery(hostname);
384
385     // Check if the hostname has domain settings.
386     if (domainQuery.isValid())  // The hostname has domain settings.
387     {
388         // Get the domain record.
389         QSqlRecord domainRecord = domainQuery.record();
390
391         // Store the domain settings name.
392         currentPrivacyWebEngineViewPointer->domainSettingsName = domainRecord.field(DomainsDatabase::DOMAIN_NAME).value().toString();
393
394         // Set the JavaScript status.
395         switch (domainRecord.field(DomainsDatabase::JAVASCRIPT).value().toInt())
396         {
397             // Set the default JavaScript status.
398             case (DomainsDatabase::SYSTEM_DEFAULT):
399             {
400                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
401
402                 break;
403             }
404
405             // Disable JavaScript.
406             case (DomainsDatabase::DISABLED):
407             {
408                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
409
410                 break;
411             }
412
413             // Enable JavaScript.
414             case (DomainsDatabase::ENABLED):
415             {
416                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
417
418                 break;
419             }
420         }
421
422         // Set the local storage status.
423         switch (domainRecord.field(DomainsDatabase::LOCAL_STORAGE).value().toInt())
424         {
425             // Set the default local storage status.
426             case (DomainsDatabase::SYSTEM_DEFAULT):
427             {
428                 currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
429
430                 break;
431             }
432
433             // Disable local storage.
434             case (DomainsDatabase::DISABLED):
435             {
436                 currentPrivacyWebEngineViewPointer->localStorageEnabled = false;
437
438                 break;
439             }
440
441             // Enable local storage.
442             case (DomainsDatabase::ENABLED):
443             {
444                 currentPrivacyWebEngineViewPointer->localStorageEnabled = true;
445
446                 break;
447             }
448         }
449
450         // Set the DOM storage status.
451         switch (domainRecord.field(DomainsDatabase::DOM_STORAGE).value().toInt())
452         {
453             // Set the default DOM storage status.
454             case (DomainsDatabase::SYSTEM_DEFAULT):
455             {
456                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
457
458                 break;
459             }
460
461             // Disable DOM storage.
462             case (DomainsDatabase::DISABLED):
463             {
464                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
465
466                 break;
467             }
468
469             // Enable DOM storage.
470             case (DomainsDatabase::ENABLED):
471             {
472                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
473
474                 break;
475             }
476         }
477
478         // Set the user agent.
479         currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabase::USER_AGENT).value().toString()));
480
481         // Check if a custom zoom factor is set.
482         if (domainRecord.field(DomainsDatabase::ZOOM_FACTOR).value().toInt())
483         {
484             // Store the current zoom factor.
485             currentZoomFactor = domainRecord.field(DomainsDatabase::CUSTOM_ZOOM_FACTOR).value().toDouble();
486         }
487         else
488         {
489             // Reset the current zoom factor.
490             currentZoomFactor = Settings::zoomFactor();
491         }
492
493         // Set the zoom factor.    The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
494         currentPrivacyWebEngineViewPointer->setZoomFactor(currentZoomFactor);
495     }
496     else  // The hostname does not have domain settings.
497     {
498         // Reset the domain settings name.
499         currentPrivacyWebEngineViewPointer->domainSettingsName = QStringLiteral("");
500
501         // Set the JavaScript status.
502         currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
503
504         // Set the local storage status.
505         currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
506
507         // Set DOM storage.  In QWebEngineSettings it is called Local Storage.
508         currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
509
510         // Set the user agent.
511         currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
512
513         // Store the current zoom factor.  This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
514         currentZoomFactor = Settings::zoomFactor();
515
516         // Set the zoom factor.
517         currentPrivacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
518     }
519
520     // Update the UI.
521     emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QStringLiteral(""));
522     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
523     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
524     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
525     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
526     emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
527
528     // Reload the website if requested.
529     if (reloadWebsite)
530         currentPrivacyWebEngineViewPointer->reload();
531 }
532
533 void TabWidget::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
534 {
535     // Store the search engine name.
536     QString searchEngineName = searchEngineActionPointer->text();
537
538     // Strip out any `&` characters.
539     searchEngineName.remove('&');
540
541     // Store the search engine string.
542     searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
543
544     // Update the search engine actionas.
545     emit updateSearchEngineActions(searchEngineName, false);
546 }
547
548 void TabWidget::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
549 {
550     // Get the user agent name.
551     QString userAgentName = userAgentActionPointer->text();
552
553     // Strip out any `&` characters.
554     userAgentName.remove('&');
555
556     // Apply the user agent.
557     currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromTranslatedName(userAgentName));
558
559     // Update the user agent actions.
560     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), false);
561
562     // Reload the website.
563     currentPrivacyWebEngineViewPointer->reload();
564 }
565
566 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
567 void TabWidget::applyOnTheFlyZoomFactor(const double &zoomFactor)
568 {
569     // Update the current zoom factor.  This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
570     currentZoomFactor = zoomFactor;
571
572     // Set the zoom factor.
573     currentPrivacyWebEngineViewPointer->setZoomFactor(zoomFactor);
574 }
575
576 void TabWidget::back() const
577 {
578     // Go back.
579     currentPrivacyWebEngineViewPointer->back();
580 }
581
582 void TabWidget::deleteAllCookies() const
583 {
584     // Delete all the cookies.
585     currentWebEngineCookieStorePointer->deleteAllCookies();
586 }
587
588 void TabWidget::deleteCookieFromStore(const QNetworkCookie &cookie) const
589 {
590     // Delete the cookie.
591     currentWebEngineCookieStorePointer->deleteCookie(cookie);
592 }
593
594 void TabWidget::deleteTab(const int tabIndex)
595 {
596     // Get the privacy WebEngine view.
597     PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->widget(tabIndex));
598
599     // Proccess the tab delete according to the number of tabs.
600     if (tabWidgetPointer->count() > 1)  // There is more than one tab.
601     {
602         // Delete the tab.
603         tabWidgetPointer->removeTab(tabIndex);
604
605         // Delete the WebEngine page to prevent the following error:  `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
606         delete privacyWebEngineViewPointer->page();
607
608         // Delete the privacy WebEngine view.
609         delete privacyWebEngineViewPointer;
610     }
611     else  // There is only one tab.
612     {
613         // Close Privacy Browser.
614         window()->close();
615     }
616 }
617
618 void TabWidget::findPrevious(const QString &text) const
619 {
620     // Store the current text.
621     currentPrivacyWebEngineViewPointer->findString = text;
622
623     // Find the previous text in the current privacy WebEngine.
624     if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
625         currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively|QWebEnginePage::FindBackward);
626     else
627         currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindBackward);
628 }
629
630 void TabWidget::findText(const QString &text) const
631 {
632     // Store the current text.
633     currentPrivacyWebEngineViewPointer->findString = text;
634
635     // Find the text in the current privacy WebEngine.
636     if (currentPrivacyWebEngineViewPointer->findCaseSensitive)
637         currentPrivacyWebEngineViewPointer->findText(text, QWebEnginePage::FindCaseSensitively);
638     else
639         currentPrivacyWebEngineViewPointer->findText(text);
640
641     // Clear the currently selected text in the WebEngine page if the find text is empty.
642     if (text.isEmpty())
643         currentWebEnginePagePointer->action(QWebEnginePage::Unselect)->activate(QAction::Trigger);
644 }
645
646 void TabWidget::findTextFinished(const QWebEngineFindTextResult &findTextResult)
647 {
648     // Update the find text UI if it wasn't simply wiping the current find text selection.  Otherwise the UI temporarially flashes `0/0`.
649     if (wipingCurrentFindTextSelection)  // The current selection is being wiped.
650     {
651         // Reset the flag.
652         wipingCurrentFindTextSelection = false;
653     }
654     else  // A new search has been performed.
655     {
656         // Store the result.
657         currentPrivacyWebEngineViewPointer->findTextResult = findTextResult;
658
659         // Update the UI.
660         emit updateFindTextResults(findTextResult);
661     }
662 }
663
664 void TabWidget::forward() const
665 {
666     // Go forward.
667     currentPrivacyWebEngineViewPointer->forward();
668 }
669
670 void TabWidget::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest) const
671 {
672     // Make it so.
673     emit fullScreenRequested(fullScreenRequest.toggleOn());
674
675     // Accept the request.
676     fullScreenRequest.accept();
677 }
678
679 std::list<QNetworkCookie>* TabWidget::getCookieList() const
680 {
681     // Return the current cookie list.
682     return currentPrivacyWebEngineViewPointer->cookieListPointer;
683 }
684
685 QString& TabWidget::getDomainSettingsName() const
686 {
687     // Return the domain settings name.
688     return currentPrivacyWebEngineViewPointer->domainSettingsName;
689 }
690
691 void TabWidget::home() const
692 {
693     // Load the homepage.
694     currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
695 }
696
697 PrivacyWebEngineView* TabWidget::loadBlankInitialWebsite()
698 {
699     // Apply the application settings.
700     applyApplicationSettings();
701
702     // Return the current privacy WebEngine view pointer.
703     return currentPrivacyWebEngineViewPointer;
704 }
705
706 void TabWidget::loadInitialWebsite()
707 {
708     // Apply the application settings.
709     applyApplicationSettings();
710
711     // Get the arguments.
712     QStringList argumentsStringList = qApp->arguments();
713
714     // Check to see if the arguments lists contains a URL.
715     if (argumentsStringList.size() > 1)
716     {
717         // Load the URL from the arguments list.
718         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
719     }
720     else
721     {
722         // Load the homepage.
723         home();
724     }
725 }
726
727 void TabWidget::loadUrlFromLineEdit(QString url) const
728 {
729     // Decide if the text is more likely to be a URL or a search.
730     if (url.startsWith("file://"))  // The text is likely a file URL.
731     {
732         // Load the URL.
733         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
734     }
735     else if (url.contains("."))  // The text is likely a URL.
736     {
737         // Check if the URL does not start with a valid protocol.
738         if (!url.startsWith("http"))
739         {
740             // Add `https://` to the beginning of the URL.
741             url = "https://" + url;
742         }
743
744         // Load the URL.
745         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
746     }
747     else  // The text is likely a search.
748     {
749         // Load the search.
750         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
751     }
752 }
753
754 void TabWidget::mouseBack() const
755 {
756     // Go back if possible.
757     if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoBack())
758     {
759         // Clear the URL line edit focus.
760         emit clearUrlLineEditFocus();
761
762         // Go back.
763         currentPrivacyWebEngineViewPointer->back();
764     }
765 }
766
767 void TabWidget::mouseForward() const
768 {
769     // Go forward if possible.
770     if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoForward())
771     {
772         // Clear the URL line edit focus.
773         emit clearUrlLineEditFocus();
774
775         // Go forward.
776         currentPrivacyWebEngineViewPointer->forward();
777     }
778 }
779
780 void TabWidget::pageLinkHovered(const QString &linkUrl) const
781 {
782     // Emit a signal so that the browser window can update the status bar.
783     emit linkHovered(linkUrl);
784 }
785
786 void TabWidget::print() const
787 {
788     // Create a printer.
789     QPrinter printer;
790
791     // Set the resolution to be 300 dpi.
792     printer.setResolution(300);
793
794     // Create a printer dialog.
795     QPrintDialog printDialog(&printer, currentPrivacyWebEngineViewPointer);
796
797     // Display the dialog and print the page if instructed.
798     if (printDialog.exec() == QDialog::Accepted)
799         printWebpage(&printer);
800 }
801
802 void TabWidget::printPreview() const
803 {
804     // Create a printer.
805     QPrinter printer;
806
807     // Set the resolution to be 300 dpi.
808     printer.setResolution(300);
809
810     // Create a print preview dialog.
811     QPrintPreviewDialog printPreviewDialog(&printer, currentPrivacyWebEngineViewPointer);
812
813     // Generate the print preview.
814     connect(&printPreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printWebpage(QPrinter *)));
815
816     // Display the dialog.
817     printPreviewDialog.exec();
818 }
819
820 void TabWidget::printWebpage(QPrinter *printerPointer) const
821 {
822     // Create an event loop.  For some reason, the print preview doesn't produce any output unless it is run inside an event loop.
823     QEventLoop eventLoop;
824
825     // Print the webpage, converting the callback above into a `QWebEngineCallback<bool>`.
826     // Printing requires that the printer be a pointer, not a reference, or it will crash with much cursing.
827     currentWebEnginePagePointer->print(printerPointer, [&eventLoop](bool printSuccess)
828     {
829         // Instruct the compiler to ignore the unused parameter.
830         (void) printSuccess;
831
832         // Quit the loop.
833         eventLoop.quit();
834     });
835
836     // Execute the loop.
837     eventLoop.exec();
838 }
839
840 void TabWidget::refresh() const
841 {
842     // Reload the website.
843     currentPrivacyWebEngineViewPointer->reload();
844 }
845
846 void TabWidget::setTabBarVisible(const bool visible) const
847 {
848     // Set the tab bar visibility.
849     tabWidgetPointer->tabBar()->setVisible(visible);
850 }
851
852 void TabWidget::showSaveDialog(QWebEngineDownloadItem *downloadItemPointer) const
853 {
854     // Instantiate the save dialog.
855     SaveDialog *saveDialogPointer = new SaveDialog(downloadItemPointer);
856
857     // Connect the save button.
858     connect(saveDialogPointer, SIGNAL(showSaveFilePickerDialog(QUrl &, QString &)), this, SLOT(showSaveFilePickerDialog(QUrl &, QString &)));
859
860     // Show the dialog.
861     saveDialogPointer->show();
862 }
863
864 void TabWidget::showSaveFilePickerDialog(QUrl &downloadUrl, QString &suggestedFileName)
865 {
866     // Get the download location.
867     QString downloadDirectory = Settings::downloadLocation();
868
869     // Resolve the system download directory if specified.
870     if (downloadDirectory == QStringLiteral("System Download Directory"))
871         downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
872
873     // Create a save file dialog.
874     QFileDialog *saveFileDialogPointer = new QFileDialog(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory);
875
876     // Tell the dialog to use a save button.
877     saveFileDialogPointer->setAcceptMode(QFileDialog::AcceptSave);
878
879     // Populate the file name from the download item pointer.
880     saveFileDialogPointer->selectFile(suggestedFileName);
881
882     // Prevent interaction with the parent window while the dialog is open.
883     saveFileDialogPointer->setWindowModality(Qt::WindowModal);
884
885     // Process the saving of the file.  The save file dialog pointer must be captured directly instead of by reference or nasty crashes occur.
886     auto saveFile = [saveFileDialogPointer, &downloadUrl] () {
887         // Get the save location.  The dialog box should only allow the selecting of one file location.
888         QUrl saveLocation = saveFileDialogPointer->selectedUrls().value(0);
889
890         // Create a file copy job.  `-1` creates the file with default permissions.
891         KIO::FileCopyJob *fileCopyJobPointer = KIO::file_copy(downloadUrl, saveLocation, -1, KIO::Overwrite);
892
893         // Set the download job to display any error messages.
894         fileCopyJobPointer->uiDelegate()->setAutoErrorHandlingEnabled(true);
895
896         // Start the download.
897         fileCopyJobPointer->start();
898     };
899
900     // Handle clicks on the save button.
901     connect(saveFileDialogPointer, &QDialog::accepted, this, saveFile);
902
903     // Show the dialog.
904     saveFileDialogPointer->show();
905 }
906
907 void TabWidget::toggleDomStorage() const
908 {
909     // Toggle DOM storage.
910     currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
911
912     // Update the DOM storage action.
913     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
914
915     // Reload the website.
916     currentPrivacyWebEngineViewPointer->reload();
917 }
918
919 void TabWidget::toggleFindCaseSensitive(const QString &text)
920 {
921     // Toggle find case sensitive.
922     currentPrivacyWebEngineViewPointer->findCaseSensitive = !currentPrivacyWebEngineViewPointer->findCaseSensitive;
923
924     // Set the wiping current find text selection flag.
925     wipingCurrentFindTextSelection = true;
926
927     // Wipe the previous search.  Otherwise currently highlighted words will remain highlighted.
928     findText(QStringLiteral(""));
929
930     // Update the find text.
931     findText(text);
932 }
933
934 void TabWidget::toggleJavaScript() const
935 {
936     // Toggle JavaScript.
937     currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
938
939     // Update the JavaScript action.
940     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
941
942     // Reload the website.
943     currentPrivacyWebEngineViewPointer->reload();
944 }
945
946 void TabWidget::toggleLocalStorage()
947 {
948     // Toggle local storeage.
949     currentPrivacyWebEngineViewPointer->localStorageEnabled = !currentPrivacyWebEngineViewPointer->localStorageEnabled;
950
951     // Update the local storage action.
952     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
953
954     // Reload the website.
955     currentPrivacyWebEngineViewPointer->reload();
956 }
957
958 void TabWidget::updateUiWithTabSettings()
959 {
960     // Update the current WebEngine pointers.
961     currentPrivacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->currentWidget());
962     currentWebEngineSettingsPointer = currentPrivacyWebEngineViewPointer->settings();
963     currentWebEnginePagePointer = currentPrivacyWebEngineViewPointer->page();
964     currentWebEngineProfilePointer = currentWebEnginePagePointer->profile();
965     currentWebEngineHistoryPointer = currentWebEnginePagePointer->history();
966     currentWebEngineCookieStorePointer = currentWebEngineProfilePointer->cookieStore();
967
968     // Clear the URL line edit focus.
969     emit clearUrlLineEditFocus();
970
971     // Update the actions.
972     emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
973     emit updateCookiesAction(currentPrivacyWebEngineViewPointer->cookieListPointer->size());
974     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
975     emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
976     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
977     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
978     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
979     emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
980
981     // Update the URL.
982     emit updateWindowTitle(currentPrivacyWebEngineViewPointer->title());
983     emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QStringLiteral(""));
984     emit updateUrlLineEdit(currentPrivacyWebEngineViewPointer->url());
985
986     // Update the find text.
987     emit updateFindText(currentPrivacyWebEngineViewPointer->findString, currentPrivacyWebEngineViewPointer->findCaseSensitive);
988     emit updateFindTextResults(currentPrivacyWebEngineViewPointer->findTextResult);
989
990     // Update the progress bar.
991     if (currentPrivacyWebEngineViewPointer->loadProgressInt >= 0)
992         emit showProgressBar(currentPrivacyWebEngineViewPointer->loadProgressInt);
993     else
994         emit hideProgressBar();
995 }