]> gitweb.stoutner.com Git - PrivacyBrowserPC.git/blob - src/widgets/TabWidget.cpp
Implement tabbed browsing.
[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 void TabWidget::addTab()
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, SIGNAL(urlChanged(const QUrl)), this, SLOT(updateUrl(const QUrl)));
170
171
172     // Update the progress bar.
173     connect(privacyWebEngineViewPointer, SIGNAL(loadStarted()), this, SLOT(loadStarted()));
174     connect(privacyWebEngineViewPointer, SIGNAL(loadProgress(const int)), this, SLOT(loadProgress(const int)));
175     connect(privacyWebEngineViewPointer, SIGNAL(loadFinished(const bool)), this, SLOT(loadFinished()));
176
177     // Handle full screen requests.
178     connect(webEnginePagePointer, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this, SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
179
180     // Listen for hovered link URLs.
181     connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
182
183     // Handle file downloads.
184     connect(webEngineProfilePointer, SIGNAL(downloadRequested(QWebEngineDownloadItem *)), this, SLOT(showSaveDialog(QWebEngineDownloadItem *)));
185
186     // Instantiate the URL request interceptor.
187     UrlRequestInterceptor *urlRequestInterceptorPointer = new UrlRequestInterceptor();
188
189     // Set the URL request interceptor.
190     webEngineProfilePointer->setUrlRequestInterceptor(urlRequestInterceptorPointer);
191
192     // Reapply the domain settings when the host changes.
193     connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings(QString)), this, SLOT(applyDomainSettingsWithoutReloading(QString)));
194
195     // Set the local storage filter.
196     webEngineCookieStorePointer->setCookieFilter([privacyWebEngineViewPointer](const QWebEngineCookieStore::FilterRequest &filterRequest)
197     {
198         // Block all third party local storage requests, including the sneaky ones that don't register a first party URL.
199         if (filterRequest.thirdParty || (filterRequest.firstPartyUrl == QStringLiteral("")))
200         {
201             //qDebug().noquote().nospace() << "Third-party request blocked:  " << filterRequest.origin;
202
203             // Return false.
204             return false;
205         }
206
207         // Allow the request if local storage is enabled.
208         if (privacyWebEngineViewPointer->localStorageEnabled)
209         {
210             //qDebug().noquote().nospace() << "Request allowed by local storage:  " << filterRequest.origin;
211
212             // Return true.
213             return true;
214         }
215
216         //qDebug().noquote().nospace() << "Request blocked by default:  " << filterRequest.origin;
217
218         // Block any remaining local storage requests.
219         return false;
220     });
221
222     // Disable JavaScript by default (this prevetns JavaScript from being enabled on a new tab before domain settings are loaded).
223     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
224
225     // Don't allow JavaScript to open windows.
226     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
227
228     // Allow keyboard navigation.
229     webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
230
231     // Enable full screen support.
232     webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
233
234     // Require user interaction to play media.
235     webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
236
237     // Limit WebRTC to public IP addresses.
238     webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
239
240     // Define an update cookie count lambda.
241     auto updateCookieCount = [privacyWebEngineViewPointer, this] (const int numberOfCookies)
242     {
243         // Update the cookie action if the specified privacy WebEngine view is the current privacy WebEngine view.
244         if (privacyWebEngineViewPointer == currentPrivacyWebEngineViewPointer)
245             emit updateCookiesAction(numberOfCookies);
246     };
247
248     // Update the cookies action.
249     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::updateCookiesAction, this, updateCookieCount);
250
251     // Process cookie changes.
252     connect(webEngineCookieStorePointer, SIGNAL(cookieAdded(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(addCookieToList(QNetworkCookie)));
253     connect(webEngineCookieStorePointer, SIGNAL(cookieRemoved(QNetworkCookie)), privacyWebEngineViewPointer, SLOT(removeCookieFromList(QNetworkCookie)));
254
255     // Get a list of durable cookies.
256     QList<QNetworkCookie*> *durableCookiesListPointer = CookiesDatabase::getCookies();
257
258     // Add the durable cookies to the store.
259     for (QNetworkCookie *cookiePointer : *durableCookiesListPointer)
260         addCookieToStore(*cookiePointer, webEngineCookieStorePointer);
261
262     // Define an update tab title lambda.
263     auto updateTabTitle = [privacyWebEngineViewPointer, this] (const QString &title)
264     {
265         // Get the index for this tab.
266         int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
267
268         // Update the title for this tab.
269         tabWidgetPointer->setTabText(tabIndex, title);
270     };
271
272     // Update the title when it changes.
273     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::titleChanged, this, updateTabTitle);
274
275     // Define an update tab icon lambda.
276     auto updateTabIcon = [privacyWebEngineViewPointer, this] (const QIcon &icon)
277     {
278         // Get the index for this tab.
279         int tabIndex = tabWidgetPointer->indexOf(privacyWebEngineViewPointer);
280
281         // Update the icon for this tab.
282         if (icon.isNull())
283             tabWidgetPointer->setTabIcon(tabIndex, defaultTabIcon);
284         else
285             tabWidgetPointer->setTabIcon(tabIndex, icon);
286     };
287
288     // Update the icon when it changes.
289     connect(privacyWebEngineViewPointer, &PrivacyWebEngineView::iconChanged, this, updateTabIcon);
290
291     // Move to the new tab.
292     tabWidgetPointer->setCurrentIndex(newTabIndex);
293 }
294
295 void TabWidget::applyApplicationSettings()
296 {
297     // Set the tab position.
298     if (Settings::tabsOnTop())
299         tabWidgetPointer->setTabPosition(QTabWidget::North);
300     else
301         tabWidgetPointer->setTabPosition(QTabWidget::South);
302
303     // Set the search engine URL.
304     searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
305
306     // Emit the update search engine actions signal.
307     emit updateSearchEngineActions(Settings::searchEngine(), true);
308 }
309
310 // 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.
311 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
312 void TabWidget::applyDomainSettingsAndReload()
313 {
314     // Apply the domain settings.  `true` reloads the website.
315     applyDomainSettings(currentPrivacyWebEngineViewPointer->url().host(), true);
316 }
317
318 // 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.
319 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
320 void TabWidget::applyDomainSettingsWithoutReloading(const QString &hostname)
321 {
322     // Apply the domain settings  `false` does not reload the website.
323     applyDomainSettings(hostname, false);
324 }
325
326 // Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
327 void TabWidget::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
328 {
329     // Get the record for the hostname.
330     QSqlQuery domainQuery = DomainsDatabase::getDomainQuery(hostname);
331
332     // Check if the hostname has domain settings.
333     if (domainQuery.isValid())  // The hostname has domain settings.
334     {
335         // Get the domain record.
336         QSqlRecord domainRecord = domainQuery.record();
337
338         // Store the domain settings name.
339         currentPrivacyWebEngineViewPointer->domainSettingsName = domainRecord.field(DomainsDatabase::DOMAIN_NAME).value().toString();
340
341         // Set the JavaScript status.
342         switch (domainRecord.field(DomainsDatabase::JAVASCRIPT).value().toInt())
343         {
344             // Set the default JavaScript status.
345             case (DomainsDatabase::SYSTEM_DEFAULT):
346             {
347                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
348
349                 break;
350             }
351
352             // Disable JavaScript.
353             case (DomainsDatabase::DISABLED):
354             {
355                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
356
357                 break;
358             }
359
360             // Enable JavaScript.
361             case (DomainsDatabase::ENABLED):
362             {
363                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
364
365                 break;
366             }
367         }
368
369         // Set the local storage status.
370         switch (domainRecord.field(DomainsDatabase::LOCAL_STORAGE).value().toInt())
371         {
372             // Set the default local storage status.
373             case (DomainsDatabase::SYSTEM_DEFAULT):
374             {
375                 currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
376
377                 break;
378             }
379
380             // Disable local storage.
381             case (DomainsDatabase::DISABLED):
382             {
383                 currentPrivacyWebEngineViewPointer->localStorageEnabled = false;
384
385                 break;
386             }
387
388             // Enable local storage.
389             case (DomainsDatabase::ENABLED):
390             {
391                 currentPrivacyWebEngineViewPointer->localStorageEnabled = true;
392
393                 break;
394             }
395         }
396
397         // Set the DOM storage status.
398         switch (domainRecord.field(DomainsDatabase::DOM_STORAGE).value().toInt())
399         {
400             // Set the default DOM storage status.
401             case (DomainsDatabase::SYSTEM_DEFAULT):
402             {
403                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
404
405                 break;
406             }
407
408             // Disable DOM storage.
409             case (DomainsDatabase::DISABLED):
410             {
411                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
412
413                 break;
414             }
415
416             // Enable DOM storage.
417             case (DomainsDatabase::ENABLED):
418             {
419                 currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
420
421                 break;
422             }
423         }
424
425         // Set the user agent.
426         currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabase::USER_AGENT).value().toString()));
427
428         // Check if a custom zoom factor is set.
429         if (domainRecord.field(DomainsDatabase::ZOOM_FACTOR).value().toInt())
430         {
431             // Store the current zoom factor.
432             currentZoomFactor = domainRecord.field(DomainsDatabase::CUSTOM_ZOOM_FACTOR).value().toDouble();
433         }
434         else
435         {
436             // Reset the current zoom factor.
437             currentZoomFactor = Settings::zoomFactor();
438         }
439
440         // Set the zoom factor.    The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
441         currentPrivacyWebEngineViewPointer->setZoomFactor(currentZoomFactor);
442     }
443     else  // The hostname does not have domain settings.
444     {
445         // Reset the domain settings name.
446         currentPrivacyWebEngineViewPointer->domainSettingsName = QStringLiteral("");
447
448         // Set the JavaScript status.
449         currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScriptEnabled());
450
451         // Set the local storage status.
452         //currentPrivacyWebEngineViewPointer->localStorageEnabled = Settings::localStorageEnabled();
453
454         // Set DOM storage.
455         currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::domStorageEnabled());
456
457         // Set the user agent.
458         currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
459
460         // Store the current zoom factor.  This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
461         currentZoomFactor = Settings::zoomFactor();
462
463         // Set the zoom factor.
464         currentPrivacyWebEngineViewPointer->setZoomFactor(Settings::zoomFactor());
465     }
466
467     // Update the UI.
468     emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QStringLiteral(""));
469     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
470     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
471     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
472     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
473     emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
474
475     // Reload the website if requested.
476     if (reloadWebsite)
477         currentPrivacyWebEngineViewPointer->reload();
478 }
479
480 void TabWidget::applyOnTheFlySearchEngine(QAction *searchEngineActionPointer)
481 {
482     // Store the search engine name.
483     QString searchEngineName = searchEngineActionPointer->text();
484
485     // Strip out any `&` characters.
486     searchEngineName.remove('&');
487
488     // Store the search engine string.
489     searchEngineUrl = SearchEngineHelper::getSearchUrl(searchEngineName);
490
491     // Update the search engine actionas.
492     emit updateSearchEngineActions(searchEngineName, false);
493 }
494
495 void TabWidget::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
496 {
497     // Get the user agent name.
498     QString userAgentName = userAgentActionPointer->text();
499
500     // Strip out any `&` characters.
501     userAgentName.remove('&');
502
503     // Apply the user agent.
504     currentWebEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromTranslatedName(userAgentName));
505
506     // Update the user agent actions.
507     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), false);
508
509     // Reload the website.
510     currentPrivacyWebEngineViewPointer->reload();
511 }
512
513 // This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
514 void TabWidget::applyOnTheFlyZoomFactor(const double &zoomFactor)
515 {
516     // Update the current zoom factor.  This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
517     currentZoomFactor = zoomFactor;
518
519     // Set the zoom factor.
520     currentPrivacyWebEngineViewPointer->setZoomFactor(zoomFactor);
521 }
522
523 void TabWidget::back() const
524 {
525     // Go back.
526     currentPrivacyWebEngineViewPointer->back();
527 }
528
529 void TabWidget::deleteAllCookies() const
530 {
531     // Delete all the cookies.
532     currentWebEngineCookieStorePointer->deleteAllCookies();
533 }
534
535 void TabWidget::deleteCookieFromStore(const QNetworkCookie &cookie) const
536 {
537     // Delete the cookie.
538     currentWebEngineCookieStorePointer->deleteCookie(cookie);
539 }
540
541 void TabWidget::deleteTab(const int tabIndex)
542 {
543     // Get the privacy WebEngine view.
544     PrivacyWebEngineView *privacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->widget(tabIndex));
545
546     // Proccess the tab delete according to the number of tabs.
547     if (tabWidgetPointer->count() > 1)  // There is more than one tab.
548     {
549         // Delete the tab.
550         tabWidgetPointer->removeTab(tabIndex);
551
552         // Delete the WebEngine page to prevent the following error:  `Release of profile requested but WebEnginePage still not deleted. Expect troubles !`
553         delete privacyWebEngineViewPointer->page();
554
555         // Delete the privacy WebEngine view.
556         delete privacyWebEngineViewPointer;
557     }
558     else  // There is only one tab.
559     {
560         // Close Privacy Browser.
561         window()->close();
562     }
563 }
564
565 void TabWidget::forward() const
566 {
567     // Go forward.
568     currentPrivacyWebEngineViewPointer->forward();
569 }
570
571 void TabWidget::fullScreenRequested(QWebEngineFullScreenRequest fullScreenRequest) const
572 {
573     // Make it so.
574     emit fullScreenRequested(fullScreenRequest.toggleOn());
575
576     // Accept the request.
577     fullScreenRequest.accept();
578 }
579
580 std::list<QNetworkCookie>* TabWidget::getCookieList() const
581 {
582     // Return the current cookie list.
583     return currentPrivacyWebEngineViewPointer->cookieListPointer;
584 }
585
586 QString& TabWidget::getDomainSettingsName() const
587 {
588     // Return the domain settings name.
589     return currentPrivacyWebEngineViewPointer->domainSettingsName;
590 }
591
592 void TabWidget::home() const
593 {
594     // Load the homepage.
595     currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
596 }
597
598 void TabWidget::loadFinished() const
599 {
600     // Hide the progress bar.
601     emit hideProgressBar();
602 }
603
604 void TabWidget::loadInitialWebsite()
605 {
606     // Apply the application settings.
607     applyApplicationSettings();
608
609     // Get the arguments.
610     QStringList argumentsStringList = qApp->arguments();
611
612     // Check to see if the arguments lists contains a URL.
613     if (argumentsStringList.size() > 1)
614     {
615         // Load the URL from the arguments list.
616         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
617     }
618     else
619     {
620         // Load the homepage.
621         home();
622     }
623 }
624
625 void TabWidget::loadProgress(const int &progress) const
626 {
627     // Show the progress bar.
628     emit showProgressBar(progress);
629 }
630
631 void TabWidget::loadStarted() const
632 {
633     // Show the progress bar.
634     emit showProgressBar(0);
635 }
636
637 void TabWidget::loadUrlFromLineEdit(QString url) const
638 {
639     // Decide if the text is more likely to be a URL or a search.
640     if (url.startsWith("file://"))  // The text is likely a file URL.
641     {
642         // Load the URL.
643         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
644     }
645     else if (url.contains("."))  // The text is likely a URL.
646     {
647         // Check if the URL does not start with a valid protocol.
648         if (!url.startsWith("http"))
649         {
650             // Add `https://` to the beginning of the URL.
651             url = "https://" + url;
652         }
653
654         // Load the URL.
655         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(url));
656     }
657     else  // The text is likely a search.
658     {
659         // Load the search.
660         currentPrivacyWebEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
661     }
662 }
663
664 void TabWidget::mouseBack() const
665 {
666     // Go back if possible.
667     if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoBack())
668     {
669         // Clear the URL line edit focus.
670         emit clearUrlLineEditFocus();
671
672         // Go back.
673         currentPrivacyWebEngineViewPointer->back();
674     }
675 }
676
677 void TabWidget::mouseForward() const
678 {
679     // Go forward if possible.
680     if (currentPrivacyWebEngineViewPointer->isActiveWindow() && currentWebEngineHistoryPointer->canGoForward())
681     {
682         // Clear the URL line edit focus.
683         emit clearUrlLineEditFocus();
684
685         // Go forward.
686         currentPrivacyWebEngineViewPointer->forward();
687     }
688 }
689
690 void TabWidget::pageLinkHovered(const QString &linkUrl) const
691 {
692     // Emit a signal so that the browser window can update the status bar.
693     emit linkHovered(linkUrl);
694 }
695
696 void TabWidget::print() const
697 {
698     // Create a printer.
699     QPrinter printer;
700
701     // Set the resolution to be 300 dpi.
702     printer.setResolution(300);
703
704     // Create a printer dialog.
705     QPrintDialog printDialog(&printer, currentPrivacyWebEngineViewPointer);
706
707     // Display the dialog and print the page if instructed.
708     if (printDialog.exec() == QDialog::Accepted)
709         printWebpage(&printer);
710 }
711
712 void TabWidget::printPreview() const
713 {
714     // Create a printer.
715     QPrinter printer;
716
717     // Set the resolution to be 300 dpi.
718     printer.setResolution(300);
719
720     // Create a print preview dialog.
721     QPrintPreviewDialog printPreviewDialog(&printer, currentPrivacyWebEngineViewPointer);
722
723     // Generate the print preview.
724     connect(&printPreviewDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printWebpage(QPrinter *)));
725
726     // Display the dialog.
727     printPreviewDialog.exec();
728 }
729
730 void TabWidget::printWebpage(QPrinter *printerPointer) const
731 {
732     // Create an event loop.  For some reason, the print preview doesn't produce any output unless it is run inside an event loop.
733     QEventLoop eventLoop;
734
735     // Print the webpage, converting the callback above into a `QWebEngineCallback<bool>`.
736     // Printing requires that the printer be a pointer, not a reference, or it will crash with much cursing.
737     currentWebEnginePagePointer->print(printerPointer, [&eventLoop](bool printSuccess)
738     {
739         // Instruct the compiler to ignore the unused parameter.
740         (void) printSuccess;
741
742         // Quit the loop.
743         eventLoop.quit();
744     });
745
746     // Execute the loop.
747     eventLoop.exec();
748 }
749
750 void TabWidget::refresh() const
751 {
752     // Reload the website.
753     currentPrivacyWebEngineViewPointer->reload();
754 }
755
756 void TabWidget::setTabBarVisible(const bool visible) const
757 {
758     // Set the tab bar visibility.
759     tabWidgetPointer->tabBar()->setVisible(visible);
760 }
761
762 void TabWidget::showSaveDialog(QWebEngineDownloadItem *downloadItemPointer) const
763 {
764     // Instantiate the save dialog.
765     SaveDialog *saveDialogPointer = new SaveDialog(downloadItemPointer);
766
767     // Connect the save button.
768     connect(saveDialogPointer, SIGNAL(showSaveFilePickerDialog(QUrl &, QString &)), this, SLOT(showSaveFilePickerDialog(QUrl &, QString &)));
769
770     // Show the dialog.
771     saveDialogPointer->show();
772 }
773
774 void TabWidget::showSaveFilePickerDialog(QUrl &downloadUrl, QString &suggestedFileName)
775 {
776     // Get the download location.
777     QString downloadDirectory = Settings::downloadLocation();
778
779     // Resolve the system download directory if specified.
780     if (downloadDirectory == QStringLiteral("System Download Directory"))
781         downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
782
783     // Create a save file dialog.
784     QFileDialog *saveFileDialogPointer = new QFileDialog(this, i18nc("Save file dialog caption", "Save File"), downloadDirectory);
785
786     // Tell the dialog to use a save button.
787     saveFileDialogPointer->setAcceptMode(QFileDialog::AcceptSave);
788
789     // Populate the file name from the download item pointer.
790     saveFileDialogPointer->selectFile(suggestedFileName);
791
792     // Prevent interaction with the parent window while the dialog is open.
793     saveFileDialogPointer->setWindowModality(Qt::WindowModal);
794
795     // Process the saving of the file.  The save file dialog pointer must be captured directly instead of by reference or nasty crashes occur.
796     auto saveFile = [saveFileDialogPointer, &downloadUrl] () {
797         // Get the save location.  The dialog box should only allow the selecting of one file location.
798         QUrl saveLocation = saveFileDialogPointer->selectedUrls().value(0);
799
800         // Create a file copy job.  `-1` creates the file with default permissions.
801         KIO::FileCopyJob *fileCopyJobPointer = KIO::file_copy(downloadUrl, saveLocation, -1, KIO::Overwrite);
802
803         // Set the download job to display any error messages.
804         fileCopyJobPointer->uiDelegate()->setAutoErrorHandlingEnabled(true);
805
806         // Start the download.
807         fileCopyJobPointer->start();
808     };
809
810     // Handle clicks on the save button.
811     connect(saveFileDialogPointer, &QDialog::accepted, this, saveFile);
812
813     // Show the dialog.
814     saveFileDialogPointer->show();
815 }
816
817 void TabWidget::toggleDomStorage() const
818 {
819     // Toggle DOM storage.
820     currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
821
822     // Update the DOM storage action.
823     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
824
825     // Reload the website.
826     currentPrivacyWebEngineViewPointer->reload();
827 }
828
829 void TabWidget::toggleJavaScript() const
830 {
831     // Toggle JavaScript.
832     currentWebEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
833
834     // Update the JavaScript action.
835     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
836
837     // Reload the website.
838     currentPrivacyWebEngineViewPointer->reload();
839 }
840
841 void TabWidget::toggleLocalStorage()
842 {
843     // Toggle local storeage.
844     currentPrivacyWebEngineViewPointer->localStorageEnabled = !currentPrivacyWebEngineViewPointer->localStorageEnabled;
845
846     // Update the local storage action.
847     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
848
849     // Reload the website.
850     currentPrivacyWebEngineViewPointer->reload();
851 }
852
853 void TabWidget::updateUiWithTabSettings()
854 {
855     // Update the current WebEngine pointers.
856     currentPrivacyWebEngineViewPointer = qobject_cast<PrivacyWebEngineView *>(tabWidgetPointer->currentWidget());
857     currentWebEngineSettingsPointer = currentPrivacyWebEngineViewPointer->settings();
858     currentWebEnginePagePointer = currentPrivacyWebEngineViewPointer->page();
859     currentWebEngineProfilePointer = currentWebEnginePagePointer->profile();
860     currentWebEngineHistoryPointer = currentWebEnginePagePointer->history();
861     currentWebEngineCookieStorePointer = currentWebEngineProfilePointer->cookieStore();
862
863     // Clear the URL line edit focus.
864     emit clearUrlLineEditFocus();
865
866     // Update the UI.
867     emit updateDomainSettingsIndicator(currentPrivacyWebEngineViewPointer->domainSettingsName != QStringLiteral(""));
868     emit updateJavaScriptAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
869     emit updateLocalStorageAction(currentPrivacyWebEngineViewPointer->localStorageEnabled);
870     emit updateDomStorageAction(currentWebEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
871     emit updateUserAgentActions(currentWebEngineProfilePointer->httpUserAgent(), true);
872     emit updateZoomFactorAction(currentPrivacyWebEngineViewPointer->zoomFactor());
873     emit updateUrlLineEdit(currentPrivacyWebEngineViewPointer->url());
874     emit updateCookiesAction(currentPrivacyWebEngineViewPointer->cookieListPointer->size());
875 }
876
877 void TabWidget::updateUrl(const QUrl &url) const
878 {
879     // Update the URL line edit.
880     emit updateUrlLineEdit(url);
881
882     // Update the status of the forward and back buttons.
883     emit updateBackAction(currentWebEngineHistoryPointer->canGoBack());
884     emit updateForwardAction(currentWebEngineHistoryPointer->canGoForward());
885
886     // Reapply the zoom factor.  This is a bug in QWebEngineView that resets the zoom with every load.  <https://redmine.stoutner.com/issues/799>
887     currentPrivacyWebEngineViewPointer->setZoomFactor(currentZoomFactor);
888 }