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