]> gitweb.stoutner.com Git - PrivacyBrowserPC.git/blobdiff - src/views/BrowserView.cpp
Clear the URL line edit when navigating history. https://redmine.stoutner.com/issues/841
[PrivacyBrowserPC.git] / src / views / BrowserView.cpp
index 44c170a72e46e77e5429157cca01f908b058c160..873b9476da8bd0cce0bd441e742e0f79d7febb05 100644 (file)
 
 // Application headers.
 #include "BrowserView.h"
-#include "MouseEventFilter.h"
 #include "Settings.h"
 #include "ui_BrowserView.h"
-#include "UrlRequestInterceptor.h"
+#include "filters/MouseEventFilter.h"
+#include "helpers/DomainsDatabaseHelper.h"
 #include "helpers/SearchEngineHelper.h"
 #include "helpers/UserAgentHelper.h"
+#include "interceptors/UrlRequestInterceptor.h"
 #include "windows/BrowserWindow.h"
-#include "windows/DomainSettingsWindow.h"
 
 // Qt framework headers.
 #include <QAction>
 #include <QWebEngineProfile>
 
+// Initialize the public static variables.
+QString BrowserView::webEngineDefaultUserAgent = QStringLiteral("");
+
 BrowserView::BrowserView(QWidget *parent) : QWidget(parent)
 {
     // Instantiate the browser view UI.
@@ -41,43 +44,42 @@ BrowserView::BrowserView(QWidget *parent) : QWidget(parent)
     browserViewUi.setupUi(this);
 
     // Get handles for the views.
-    backButtonPointer = browserViewUi.backButton;
-    forwardButtonPointer = browserViewUi.forwardButton;
-    QPushButton *refreshButtonPointer = browserViewUi.refreshButton;
-    QPushButton *homeButtonPointer = browserViewUi.homeButton;
-    urlLineEditPointer = browserViewUi.urlLineEdit;
-    javaScriptButtonPointer = browserViewUi.javaScript;
-    QPushButton *domainSettingsButtonPointer = browserViewUi.domainSettingsButton;
     webEngineViewPointer = browserViewUi.webEngineView;
 
+    // Create an off-the-record profile (the default when no profile name is specified).
+    webEngineProfilePointer = new QWebEngineProfile(QStringLiteral(""));
+
+    // Create a WebEngine page.
+    QWebEnginePage *webEnginePagePointer = new QWebEnginePage(webEngineProfilePointer);
+
+    // Set the WebEngine page.
+    webEngineViewPointer->setPage(webEnginePagePointer);
+
     // Get handles for the aspects of the WebEngine.
-    QWebEnginePage *webEnginePagePointer = webEngineViewPointer->page();
     webEngineHistoryPointer = webEnginePagePointer->history();
-    webEngineProfilePointer = webEnginePagePointer->profile();
     webEngineSettingsPointer = webEngineViewPointer->settings();
 
-    // Update the webengine view from the URL line edit.
-    connect(urlLineEditPointer, SIGNAL(returnKeyPressed(const QString)), this, SLOT(loadUrlFromTextBox(const QString)));
+    // Store a copy of the WebEngine default user agent.
+    webEngineDefaultUserAgent = webEngineProfilePointer->httpUserAgent();
 
-    // Update the URL line edit form the webengine view.
-    connect(webEngineViewPointer, SIGNAL(loadStarted()), this, SLOT(updateInterface()));
-    connect(webEngineViewPointer, SIGNAL(loadProgress(const int)), this, SLOT(updateInterface()));
-    connect(webEngineViewPointer, SIGNAL(loadFinished(const bool)), this, SLOT(updateInterface()));
+    // Update the URL line edit when the URL changes.
+    connect(webEngineViewPointer, SIGNAL(urlChanged(const QUrl)), this, SLOT(updateUrl(const QUrl)));
 
-    // Setup the URL bar buttons.
-    connect(backButtonPointer, SIGNAL(clicked()), webEngineViewPointer, SLOT(back()));
-    connect(forwardButtonPointer, SIGNAL(clicked()), webEngineViewPointer, SLOT(forward()));
-    connect(refreshButtonPointer, SIGNAL(clicked()), webEngineViewPointer, SLOT(reload()));
-    connect(homeButtonPointer, SIGNAL(clicked()), this, SLOT(goHome()));
-    connect(javaScriptButtonPointer, SIGNAL(clicked()), this, SLOT(toggleJavaScript()));
-    connect(domainSettingsButtonPointer, SIGNAL(clicked()), this, SLOT(openDomainSettings()));
+    // Update the progress bar.
+    connect(webEngineViewPointer, SIGNAL(loadStarted()), this, SLOT(loadStarted()));
+    connect(webEngineViewPointer, SIGNAL(loadProgress(const int)), this, SLOT(loadProgress(const int)));
+    connect(webEngineViewPointer, SIGNAL(loadFinished(const bool)), this, SLOT(loadFinished()));
 
-    // Instantiate the mouse event pointer.
-    MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter(webEngineViewPointer);
+    // Instantiate the mouse event filter pointer.
+    MouseEventFilter *mouseEventFilterPointer = new MouseEventFilter();
 
     // Install the mouse event filter.
     qApp->installEventFilter(mouseEventFilterPointer);
 
+    // Process mouse forward and back commands.
+    connect(mouseEventFilterPointer, SIGNAL(mouseBack()), this, SLOT(mouseBack()));
+    connect(mouseEventFilterPointer, SIGNAL(mouseForward()), this, SLOT(mouseForward()));
+
     // Listen for hovered link URLs.
     connect(webEnginePagePointer, SIGNAL(linkHovered(const QString)), this, SLOT(pageLinkHovered(const QString)));
 
@@ -88,14 +90,23 @@ BrowserView::BrowserView(QWidget *parent) : QWidget(parent)
     webEngineProfilePointer->setUrlRequestInterceptor(urlRequestInterceptorPointer);
 
     // Reapply the domain settings when the host changes.
-    connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings()), this, SLOT(applyDomainSettingsWithoutReloading()));
-
-    // Disable the cache.
-    webEngineProfilePointer->setHttpCacheType(QWebEngineProfile::NoCache);
+    connect(urlRequestInterceptorPointer, SIGNAL(applyDomainSettings(QString)), this, SLOT(applyDomainSettingsWithoutReloading(QString)));
 
     // Don't allow JavaScript to open windows.
     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, false);
 
+    // Allow keyboard navigation.
+    webEngineSettingsPointer->setAttribute(QWebEngineSettings::SpatialNavigationEnabled, true);
+
+    // Enable full screen support.
+    webEngineSettingsPointer->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
+
+    // Require user interaction to play media.
+    webEngineSettingsPointer->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, true);
+
+    // Limit WebRTC to public IP addresses.
+    webEngineSettingsPointer->setAttribute(QWebEngineSettings::WebRTCPublicInterfacesOnly, true);
+
     // Set the focus on the WebEngine view.
     webEngineViewPointer->setFocus();
 }
@@ -105,48 +116,141 @@ void BrowserView::applyApplicationSettings()
     // Set the search engine URL.
     searchEngineUrl = SearchEngineHelper::getSearchUrl(Settings::searchEngine());
 
-    // Emit the search engine updated signal, which causes the on-the-fly menu to be updated.
-    emit searchEngineUpdated(Settings::searchEngine());
+    // Emit the update search engine actions signal.
+    emit updateSearchEngineActions(Settings::searchEngine());
 }
 
 // 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.
-void BrowserView::applyDomainSettingsAndReload() const
+// Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
+void BrowserView::applyDomainSettingsAndReload()
 {
     // Apply the domain settings.  `true` reloads the website.
-    applyDomainSettings(true);
+    applyDomainSettings(webEngineViewPointer->url().host(), true);
 }
 
 // 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.
-void BrowserView::applyDomainSettingsWithoutReloading() const
+// Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
+void BrowserView::applyDomainSettingsWithoutReloading(const QString &hostname)
 {
     // Apply the domain settings  `false` does not reload the website.
-    applyDomainSettings(false);
+    applyDomainSettings(hostname, false);
 }
 
-void BrowserView::applyDomainSettings(bool reloadWebsite) const
+// Once <https://redmine.stoutner.com/issues/799> has been resolved this can be `const`.
+void BrowserView::applyDomainSettings(const QString &hostname, const bool reloadWebsite)
 {
-    // Set the JavaScript status.
-    webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScript());
+    // Get the record for the hostname.
+    QSqlQuery domainQuery = DomainsDatabaseHelper::getDomainQuery(hostname);
 
-    // Update the JavaScript button.
-    if (Settings::javaScript())
+    // Check if the hostname has domain settings.
+    if (domainQuery.isValid())  // The hostname has domain settings.
     {
-        javaScriptButtonPointer->setIcon(QIcon(":/icons/javascript-warning"));
+        // Get the domain record.
+        QSqlRecord domainRecord = domainQuery.record();
+
+        // Set the JavaScript status.
+        switch (domainRecord.field(DomainsDatabaseHelper::JAVASCRIPT).value().toInt())
+        {
+            case (DomainsDatabaseHelper::SYSTEM_DEFAULT):
+            {
+                // Set the default JavaScript status.
+                webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScript());
+
+                break;
+            }
+
+            case (DomainsDatabaseHelper::DISABLED):
+            {
+                // Disable JavaScript.
+                webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
+
+                break;
+            }
+
+            case (DomainsDatabaseHelper::ENABLED):
+            {
+                // Enable JavaScript.
+                webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
+
+                break;
+            }
+        }
+
+        // Set local storage.
+        switch (domainRecord.field(DomainsDatabaseHelper::LOCAL_STORAGE).value().toInt())
+        {
+            case (DomainsDatabaseHelper::SYSTEM_DEFAULT):
+            {
+                // Set the default local storage status.
+                webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::localStorage());
+
+                break;
+            }
+
+            case (DomainsDatabaseHelper::DISABLED):
+            {
+                // Disable local storage.
+                webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
+
+                break;
+            }
+
+            case (DomainsDatabaseHelper::ENABLED):
+            {
+                // Enable local storage.
+                webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
+
+                break;
+            }
+        }
+
+        // Set the user agent.
+        webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getResultingDomainSettingsUserAgent(domainRecord.field(DomainsDatabaseHelper::USER_AGENT).value().toString()));
+
+        // Check if a custom zoom factor is set.
+        if (domainRecord.field(DomainsDatabaseHelper::ZOOM_FACTOR).value().toInt())
+        {
+            // Store the current zoom factor.
+            currentZoomFactor = domainRecord.field(DomainsDatabaseHelper::CUSTOM_ZOOM_FACTOR).value().toDouble();
+        }
+        else
+        {
+            // Reset the current zoom factor.
+            currentZoomFactor = Settings::zoomFactor();
+        }
+
+        // Set the zoom factor.    The use of `currentZoomFactor` can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
+        webEngineViewPointer->setZoomFactor(currentZoomFactor);
+
+        // Apply the domain settings palette to the URL line edit.
+        emit updateDomainSettingsIndicator(true, domainRecord.field(DomainsDatabaseHelper::DOMAIN_NAME).value().toString());
     }
-    else
+    else  // The hostname does not have domain settings.
     {
-        javaScriptButtonPointer->setIcon(QIcon(":/icons/privacy-mode"));
-    }
+        // Set the JavaScript status.
+        webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, Settings::javaScript());
 
-    // Apply the user agent.
-    webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgent(Settings::userAgent()));
+        // Set local storage.
+        webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, Settings::localStorage());
 
-    // Set the zoom factor.
-    webEngineViewPointer->setZoomFactor(Settings::zoomFactor());
+        // Set the user agent.
+        webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()));
+
+        // Store the current zoom factor.  This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
+        currentZoomFactor = Settings::zoomFactor();
+
+        // Set the zoom factor.
+        webEngineViewPointer->setZoomFactor(Settings::zoomFactor());
+
+        // Apply the no domain settings palette to the URL line edit.
+        emit updateDomainSettingsIndicator(false, QStringLiteral(""));
+    }
 
-    // Emit the on-the-fly menu update signals.
-    emit userAgentUpdated(Settings::userAgent());
-    emit zoomFactorUpdated(Settings::zoomFactor());
+    // Emit the update actions signals.
+    emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
+    emit updateLocalStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
+    emit updateUserAgentActions(webEngineProfilePointer->httpUserAgent());
+    emit updateZoomFactorAction(webEngineViewPointer->zoomFactor());
 
     // Reload the website if requested.
     if (reloadWebsite)
@@ -176,22 +280,44 @@ void BrowserView::applyOnTheFlyUserAgent(QAction *userAgentActionPointer) const
     userAgentName.remove('&');
 
     // Apply the user agent.
-    webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgent(userAgentName));
+    webEngineProfilePointer->setHttpUserAgent(UserAgentHelper::getUserAgentFromTranslatedName(userAgentName));
 
     // Reload the website.
     webEngineViewPointer->reload();
 }
 
-void BrowserView::applyOnTheFlyZoomFactor(const double &zoomFactor) const
+// This can be const once <https://redmine.stoutner.com/issues/799> has been resolved.
+void BrowserView::applyOnTheFlyZoomFactor(const double &zoomFactor)
 {
+    // Update the current zoom factor.  This can be removed once <https://redmine.stoutner.com/issues/799> has been resolved.
+    currentZoomFactor = zoomFactor;
+
     // Set the zoom factor.
     webEngineViewPointer->setZoomFactor(zoomFactor);
 }
 
-void BrowserView::goHome() const
+void BrowserView::back() const
+{
+    // Go back.
+    webEngineViewPointer->back();
+}
+
+void BrowserView::forward() const
+{
+    // Go forward.
+    webEngineViewPointer->forward();
+}
+
+void BrowserView::home() const
 {
     // Load the homepage.
-    webEngineViewPointer->setUrl(QUrl::fromUserInput(Settings::homepage()));
+    webEngineViewPointer->load(QUrl::fromUserInput(Settings::homepage()));
+}
+
+void BrowserView::loadFinished() const
+{
+    // Hide the progress bar.
+    emit hideProgressBar();
 }
 
 void BrowserView::loadInitialWebsite()
@@ -206,80 +332,77 @@ void BrowserView::loadInitialWebsite()
     if (argumentsStringList.size() > 1)
     {
         // Load the URL from the arguments list.
-        webEngineViewPointer->setUrl(QUrl::fromUserInput(argumentsStringList.at(1)));
+        webEngineViewPointer->load(QUrl::fromUserInput(argumentsStringList.at(1)));
     }
     else
     {
         // Load the homepage.
-        goHome();
+        home();
     }
 }
 
-void BrowserView::loadUrlFromTextBox(QString urlFromUser) const
+void BrowserView::loadProgress(const int &progress) const
+{
+    // Show the progress bar.
+    emit showProgressBar(progress);
+}
+
+void BrowserView::loadStarted() const
 {
-    // Remove the focus from the URL line edit.
-    urlLineEditPointer->clearFocus();
+    // Show the progress bar.
+    emit showProgressBar(0);
+}
 
+void BrowserView::loadUrlFromLineEdit(QString url) const
+{
     // Decide if the text is more likely to be a URL or a search.
-    if (urlFromUser.contains("."))  // The text is likely a URL.
+    if (url.startsWith("file://"))  // The text is likely a file URL.
+    {
+        // Load the URL.
+        webEngineViewPointer->load(QUrl::fromUserInput(url));
+    }
+    else if (url.contains("."))  // The text is likely a URL.
     {
         // Check if the URL does not start with a valid protocol.
-        if (!urlFromUser.startsWith("http") && !urlFromUser.startsWith("file://"))
+        if (!url.startsWith("http"))
         {
             // Add `https://` to the beginning of the URL.
-            urlFromUser = "https://" + urlFromUser;
+            url = "https://" + url;
         }
 
         // Load the URL.
-        webEngineViewPointer->setUrl(QUrl::fromUserInput(urlFromUser));
+        webEngineViewPointer->load(QUrl::fromUserInput(url));
     }
     else  // The text is likely a search.
     {
         // Load the search.
-        webEngineViewPointer->setUrl(QUrl::fromUserInput(searchEngineUrl + urlFromUser));
+        webEngineViewPointer->load(QUrl::fromUserInput(searchEngineUrl + url));
     }
 }
 
-void BrowserView::openDomainSettings() const
+void BrowserView::mouseBack() const
 {
-    // Get a list of the top level widgets.
-    const QWidgetList topLevelWidgets = QApplication::topLevelWidgets();
-
-    // Initialize a domain settings window exists boolean.
-    bool domainSettingsWindowExists = false;
-
-    // Iterate through the top level widgets.
-    for (QWidget *widgetPointer : topLevelWidgets)
+    // Go back if possible.
+    if (webEngineHistoryPointer->canGoBack())
     {
-        // Check for an existing domain settings window.
-        if (widgetPointer->objectName() == QStringLiteral("domain_settings"))
-        {
-            // Show the existing domain settings window if it is hidden.
-            widgetPointer->show();
-
-            // Raise the existing domain settings window if it is below other windows.
-            widgetPointer->raise();
-
-            // Restore the existing domain settings window if it has been minimized.
-            if (widgetPointer->isMinimized()) {
-                widgetPointer->showNormal();
-            }
+        // Clear the URL line edit focus.
+        emit clearUrlLineEditFocus();
 
-            // Activate the existing domain settings window, which brings its virtual desktop into focus.
-            widgetPointer->activateWindow();
-
-            // Update the domain settings window exists boolean.
-            domainSettingsWindowExists = true;
-        }
+        // Go back.
+        webEngineViewPointer->back();
     }
+}
 
-    if (!domainSettingsWindowExists)
+void BrowserView::mouseForward() const
+{
+    // Go forward if possible.
+    if (webEngineHistoryPointer->canGoForward())
     {
-        // Instantiate the domain settings window.
-        DomainSettingsWindow *domainSettingsWindowPointer = new DomainSettingsWindow();
+        // Clear the URL line edit focus.
+        emit clearUrlLineEditFocus();
 
-        // Show the window.
-        domainSettingsWindowPointer->show();
+        // Go forward.
+        webEngineViewPointer->forward();
     }
 }
 
@@ -289,38 +412,45 @@ void BrowserView::pageLinkHovered(const QString &linkUrl) const
     emit linkHovered(linkUrl);
 }
 
+void BrowserView::refresh() const
+{
+    // Reload the website.
+    webEngineViewPointer->reload();
+}
+
 void BrowserView::toggleJavaScript() const
 {
     // Toggle JavaScript.
     webEngineSettingsPointer->setAttribute(QWebEngineSettings::JavascriptEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
 
-    // Update the JavaScript button.
-    if (webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled))
-    {
-        javaScriptButtonPointer->setIcon(QIcon(":/icons/javascript-warning"));
-    }
-    else
-    {
-        javaScriptButtonPointer->setIcon(QIcon(":/icons/privacy-mode"));
-    }
+    // Update the JavaScript icon.
+    emit updateJavaScriptAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::JavascriptEnabled));
 
     // Reload the website.
     webEngineViewPointer->reload();
 }
 
-void BrowserView::updateInterface() const
+void BrowserView::toggleLocalStorage() const
 {
-    // Update the URL line edit if it does not have focus.
-    if (!urlLineEditPointer->hasFocus())
-    {
-        // Update the URL line edit.
-        urlLineEditPointer->setText(webEngineViewPointer->url().toString());
-    }
+    // Toggle local storage.
+    webEngineSettingsPointer->setAttribute(QWebEngineSettings::LocalStorageEnabled, !webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
+
+    // Update the local storage icon.
+    emit updateLocalStorageAction(webEngineSettingsPointer->testAttribute(QWebEngineSettings::LocalStorageEnabled));
+
+    // Reload the website.
+    webEngineViewPointer->reload();
+}
+
+void BrowserView::updateUrl(const QUrl &url) const
+{
+    // Update the URL line edit.
+    emit updateUrlLineEdit(url);
 
     // Update the status of the forward and back buttons.
-    backButtonPointer->setEnabled(webEngineHistoryPointer->canGoBack());
-    forwardButtonPointer->setEnabled(webEngineHistoryPointer->canGoForward());
+    emit updateBackAction(webEngineHistoryPointer->canGoBack());
+    emit updateForwardAction(webEngineHistoryPointer->canGoForward());
 
-    // Reapply the zoom factor.  This is a bug in QWebEngineView that resets the zoom with every load.  Hopefully it will be fixed in Qt6.  <https://bugreports.qt.io/browse/QTBUG-51992>
-    webEngineViewPointer->setZoomFactor(Settings::zoomFactor());
+    // Reapply the zoom factor.  This is a bug in QWebEngineView that resets the zoom with every load.  <https://redmine.stoutner.com/issues/799>
+    webEngineViewPointer->setZoomFactor(currentZoomFactor);
 }