/*
 * Copyright 2022-2023 Soren Stoutner <soren@stoutner.com>.
 *
 * This file is part of Privacy Browser PC <https://www.stoutner.com/privacy-browser-pc>.
 *
 * Privacy Browser PC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Privacy Browser PC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Privacy Browser PC.  If not, see <http://www.gnu.org/licenses/>.
 */

// Application headers.
#include "BrowserWindow.h"
#include "Settings.h"
#include "ui_SettingsGeneral.h"
#include "ui_SettingsPrivacy.h"
#include "ui_SettingsSpellCheck.h"
#include "dialogs/CookiesDialog.h"
#include "dialogs/DomainSettingsDialog.h"
#include "helpers/SearchEngineHelper.h"
#include "helpers/UserAgentHelper.h"

// KDE Frameworks headers.
#include <KActionCollection>
#include <KColorScheme>
#include <KToolBar>

// Qt toolkit headers.
#include <QFileDialog>
#include <QInputDialog>
#include <QNetworkCookie>
#include <QMenuBar>
#include <QShortcut>
#include <QStatusBar>
#include <QWebEngineFindTextResult>

// Construct the class.
BrowserWindow::BrowserWindow(bool firstWindow) : KXmlGuiWindow()
{
    // Initialize the variables.
    javaScriptEnabled = false;
    localStorageEnabled = false;

    // Instantiate the privacy tab widget pointer.
    tabWidgetPointer = new TabWidget(this);

    // Set the privacy tab widget as the central widget.
    setCentralWidget(tabWidgetPointer);

    // Get a handle for the action collection.
    KActionCollection *actionCollectionPointer = this->actionCollection();

    // Add the standard actions.
    KStandardAction::print(tabWidgetPointer, SLOT(print()), actionCollectionPointer);
    QAction *printPreviewActionPointer = KStandardAction::printPreview(tabWidgetPointer, SLOT(printPreview()), actionCollectionPointer);
    KStandardAction::quit(qApp, SLOT(closeAllWindows()), actionCollectionPointer);
    KStandardAction::redisplay(this, SLOT(refresh()), actionCollectionPointer);
    fullScreenActionPointer = KStandardAction::fullScreen(this, SLOT(toggleFullScreen()), this, actionCollectionPointer);
    QAction *backActionPointer = KStandardAction::back(this, SLOT(back()), actionCollectionPointer);
    QAction *forwardActionPointer = KStandardAction::forward(this, SLOT(forward()), actionCollectionPointer);
    KStandardAction::home(this, SLOT(home()), actionCollectionPointer);
    KStandardAction::preferences(this, SLOT(showSettingsDialog()), actionCollectionPointer);
    KStandardAction::find(this, SLOT(showFindTextActions()), actionCollectionPointer);
    findNextActionPointer = KStandardAction::findNext(this, SLOT(findNext()), actionCollectionPointer);
    findPreviousActionPointer = KStandardAction::findPrev(this, SLOT(findPrevious()), actionCollectionPointer);

    // Add the custom actions.
    QAction *newTabActionPointer = actionCollectionPointer->addAction(QLatin1String("new_tab"));
    QAction *newWindowActionPointer = actionCollectionPointer->addAction(QLatin1String("new_window"));
    userAgentPrivacyBrowserActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_privacy_browser"));
    userAgentWebEngineDefaultActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_webengine_default"));
    userAgentFirefoxLinuxActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_firefox_linux"));
    userAgentChromiumLinuxActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_chromium_linux"));
    userAgentFirefoxWindowsActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_firefox_windows"));
    userAgentChromeWindowsActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_chrome_windows"));
    userAgentEdgeWindowsActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_edge_windows"));
    userAgentSafariMacosActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_safari_macos"));
    userAgentCustomActionPointer = actionCollectionPointer->addAction(QLatin1String("user_agent_custom"));
    zoomFactorActionPointer = actionCollectionPointer->addAction(QLatin1String("zoom_factor"));
    searchEngineMojeekActionPointer = actionCollectionPointer->addAction(QLatin1String("search_engine_mojeek"));
    searchEngineMonoclesActionPointer = actionCollectionPointer->addAction(QLatin1String("search_engine_monocles"));
    searchEngineMetagerActionPointer = actionCollectionPointer->addAction(QLatin1String("search_engine_metager"));
    searchEngineGoogleActionPointer = actionCollectionPointer->addAction(QLatin1String("search_engine_google"));
    searchEngineBingActionPointer = actionCollectionPointer->addAction(QLatin1String("search_engine_bing"));
    searchEngineYahooActionPointer = actionCollectionPointer->addAction(QLatin1String("search_engine_yahoo"));
    searchEngineCustomActionPointer = actionCollectionPointer->addAction(QLatin1String("search_engine_custom"));
    QAction *domainSettingsActionPointer = actionCollectionPointer->addAction(QLatin1String("domain_settings"));
    cookiesActionPointer = actionCollectionPointer->addAction(QLatin1String("cookies"));
    javaScriptActionPointer = actionCollectionPointer->addAction(QLatin1String("javascript"));
    localStorageActionPointer = actionCollectionPointer->addAction(QLatin1String("local_storage"));
    domStorageActionPointer = actionCollectionPointer->addAction(QLatin1String("dom_storage"));
    findCaseSensitiveActionPointer = actionCollectionPointer->addAction(QLatin1String("find_case_sensitive"));
    hideFindTextActionPointer = actionCollectionPointer->addAction(QLatin1String("hide_find_actions"));

    // Create the action groups
    QActionGroup *userAgentActionGroupPointer = new QActionGroup(this);
    QActionGroup *searchEngineActionGroupPointer = new QActionGroup(this);

    // Add the actions to the groups.
    userAgentActionGroupPointer->addAction(userAgentPrivacyBrowserActionPointer);
    userAgentActionGroupPointer->addAction(userAgentWebEngineDefaultActionPointer);
    userAgentActionGroupPointer->addAction(userAgentFirefoxLinuxActionPointer);
    userAgentActionGroupPointer->addAction(userAgentChromiumLinuxActionPointer);
    userAgentActionGroupPointer->addAction(userAgentFirefoxWindowsActionPointer);
    userAgentActionGroupPointer->addAction(userAgentChromeWindowsActionPointer);
    userAgentActionGroupPointer->addAction(userAgentEdgeWindowsActionPointer);
    userAgentActionGroupPointer->addAction(userAgentSafariMacosActionPointer);
    userAgentActionGroupPointer->addAction(userAgentCustomActionPointer);
    searchEngineActionGroupPointer->addAction(searchEngineMojeekActionPointer);
    searchEngineActionGroupPointer->addAction(searchEngineMonoclesActionPointer);
    searchEngineActionGroupPointer->addAction(searchEngineMetagerActionPointer);
    searchEngineActionGroupPointer->addAction(searchEngineGoogleActionPointer);
    searchEngineActionGroupPointer->addAction(searchEngineBingActionPointer);
    searchEngineActionGroupPointer->addAction(searchEngineYahooActionPointer);
    searchEngineActionGroupPointer->addAction(searchEngineCustomActionPointer);

    // Set some actions to be checkable.
    javaScriptActionPointer->setCheckable(true);
    localStorageActionPointer->setCheckable(true);
    domStorageActionPointer->setCheckable(true);
    findCaseSensitiveActionPointer->setCheckable(true);
    userAgentPrivacyBrowserActionPointer->setCheckable(true);
    userAgentWebEngineDefaultActionPointer->setCheckable(true);
    userAgentFirefoxLinuxActionPointer->setCheckable(true);
    userAgentChromiumLinuxActionPointer->setCheckable(true);
    userAgentFirefoxWindowsActionPointer->setCheckable(true);
    userAgentChromeWindowsActionPointer->setCheckable(true);
    userAgentEdgeWindowsActionPointer->setCheckable(true);
    userAgentSafariMacosActionPointer->setCheckable(true);
    userAgentCustomActionPointer->setCheckable(true);
    searchEngineMojeekActionPointer->setCheckable(true);
    searchEngineMonoclesActionPointer->setCheckable(true);
    searchEngineMetagerActionPointer->setCheckable(true);
    searchEngineGoogleActionPointer->setCheckable(true);
    searchEngineBingActionPointer->setCheckable(true);
    searchEngineYahooActionPointer->setCheckable(true);
    searchEngineCustomActionPointer->setCheckable(true);

    // Instantiate the user agent helper.
    UserAgentHelper *userAgentHelperPointer = new UserAgentHelper();

    // Set the action text.
    newTabActionPointer->setText(i18nc("New tab action", "New Tab"));
    newWindowActionPointer->setText(i18nc("New window action", "New Window"));
    userAgentPrivacyBrowserActionPointer->setText(userAgentHelperPointer->PRIVACY_BROWSER_TRANSLATED);
    userAgentWebEngineDefaultActionPointer->setText(userAgentHelperPointer->WEB_ENGINE_DEFAULT_TRANSLATED);
    userAgentFirefoxLinuxActionPointer->setText(userAgentHelperPointer->FIREFOX_LINUX_TRANSLATED);
    userAgentChromiumLinuxActionPointer->setText(userAgentHelperPointer->CHROMIUM_LINUX_TRANSLATED);
    userAgentFirefoxWindowsActionPointer->setText(userAgentHelperPointer->FIREFOX_WINDOWS_TRANSLATED);
    userAgentChromeWindowsActionPointer->setText(userAgentHelperPointer->CHROME_WINDOWS_TRANSLATED);
    userAgentEdgeWindowsActionPointer->setText(userAgentHelperPointer->EDGE_WINDOWS_TRANSLATED);
    userAgentSafariMacosActionPointer->setText(userAgentHelperPointer->SAFARI_MACOS_TRANSLATED);
    searchEngineMojeekActionPointer->setText(i18nc("Search engine", "Mojeek"));
    searchEngineMonoclesActionPointer->setText(i18nc("Search engine", "Monocles"));
    searchEngineMetagerActionPointer->setText(i18nc("Search engine", "MetaGer"));
    searchEngineGoogleActionPointer->setText(i18nc("Search engine", "Google"));
    searchEngineBingActionPointer->setText(i18nc("Search engine", "Bing"));
    searchEngineYahooActionPointer->setText(i18nc("Search engine", "Yahoo"));
    domainSettingsActionPointer->setText(i18nc("Domain Settings action", "Domain Settings"));
    cookiesActionPointer->setText(i18nc("The Cookies action, which also displays the number of cookies", "Cookies - %1", 0));
    javaScriptActionPointer->setText(i18nc("JavaScript action", "JavaScript"));
    localStorageActionPointer->setText(i18nc("The Local Storage action", "Local Storage"));
    domStorageActionPointer->setText(i18nc("DOM Storage action", "DOM Storage"));
    findCaseSensitiveActionPointer->setText(i18nc("Find Case Sensitive action", "Find Case Sensitive"));
    hideFindTextActionPointer->setText(i18nc("Hide Find Text action", "Hide Find Text"));

    // Set the action icons.  Gnome doesn't contain some of the icons that KDE has.
    // The toolbar icons don't pick up unless the size is explicit, probably because the toolbar ends up being an intermediate size.
    newTabActionPointer->setIcon(QIcon::fromTheme(QLatin1String("tab-new")));
    newWindowActionPointer->setIcon(QIcon::fromTheme(QLatin1String("window-new")));
    userAgentPrivacyBrowserActionPointer->setIcon(QIcon(":/icons/privacy-mode.svg"));
    userAgentWebEngineDefaultActionPointer->setIcon(QIcon::fromTheme(QLatin1String("qtlogo"), QIcon::fromTheme(QLatin1String("user-group-properties"),
                                                                                                               QIcon::fromTheme(QLatin1String("contact-new")))));
    userAgentFirefoxLinuxActionPointer->setIcon(QIcon::fromTheme(QLatin1String("firefox-esr"), QIcon::fromTheme(QLatin1String("user-group-properties"),
                                                                                                                QIcon::fromTheme(QLatin1String("contact-new")))));
    userAgentChromiumLinuxActionPointer->setIcon(QIcon::fromTheme(QLatin1String("chromium"), QIcon::fromTheme(QLatin1String("user-group-properties"),
                                                                                                              QIcon::fromTheme(QLatin1String("contact-new")))));
    userAgentFirefoxWindowsActionPointer->setIcon(QIcon::fromTheme(QLatin1String("firefox-esr"), QIcon::fromTheme(QLatin1String("user-group-properties"),
                                                                                                                  QIcon::fromTheme(QLatin1String("contact-new")))));
    userAgentChromeWindowsActionPointer->setIcon(QIcon::fromTheme(QLatin1String("chromium"), QIcon::fromTheme(QLatin1String("user-group-properties"),
                                                                                                              QIcon::fromTheme(QLatin1String("contact-new")))));
    userAgentEdgeWindowsActionPointer->setIcon(QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new"))));
    userAgentSafariMacosActionPointer->setIcon(QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new"))));
    userAgentCustomActionPointer->setIcon(QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new"))));
    searchEngineMojeekActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));
    searchEngineMonoclesActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));
    searchEngineMetagerActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));
    searchEngineGoogleActionPointer->setIcon(QIcon::fromTheme(QLatin1String("im-google"), QIcon::fromTheme(QLatin1String("edit-find"))));
    searchEngineBingActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));
    searchEngineYahooActionPointer->setIcon(QIcon::fromTheme(QLatin1String("im-yahoo"), QIcon::fromTheme(QLatin1String("edit-find"))));
    searchEngineCustomActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));
    zoomFactorActionPointer->setIcon(QIcon::fromTheme(QLatin1String("zoom-fit-best")));
    domainSettingsActionPointer->setIcon(QIcon::fromTheme(QLatin1String("settings-configure"), QIcon::fromTheme(QLatin1String("preferences-desktop"))));
    cookiesActionPointer->setIcon(QIcon::fromTheme(QLatin1String("preferences-web-browser-cookies"), QIcon::fromTheme(QLatin1String("appointment-new"))));
    domStorageActionPointer->setIcon(QIcon::fromTheme(QLatin1String("code-class"), QIcon(QLatin1String("/usr/share/icons/gnome/32x32/actions/gtk-unindent-ltr.png"))));
    findCaseSensitiveActionPointer->setIcon(QIcon::fromTheme(QLatin1String("format-text-lowercase"), QIcon::fromTheme(QLatin1String("/usr/share/icons/gnome/32x32/apps/fonts.png"))));
    hideFindTextActionPointer->setIcon(QIcon::fromTheme(QLatin1String("window-close-symbolic")));

    // Create the key sequences.
    QKeySequence ctrlTKeySequence = QKeySequence(i18nc("The open new tab key sequence.", "Ctrl+T"));
    QKeySequence ctrlNKeySequence = QKeySequence(i18nc("The open new window key sequence.", "Ctrl+N"));
    QKeySequence ctrlShiftPKeySequence = QKeySequence(i18nc("The print preview key sequence.", "Ctrl+Shift+P"));
    QKeySequence ctrlAltPKeySequence = QKeySequence(i18nc("The Privacy Browser user agent key sequence.", "Ctrl+Alt+P"));
    QKeySequence ctrlAltWKeySequence = QKeySequence(i18nc("The WebEngine Default user agent key sequence.", "Ctrl+Alt+W"));
    QKeySequence ctrlAltFKeySequence = QKeySequence(i18nc("The Firefox on Linux user agent key sequence.", "Ctrl+Alt+F"));
    QKeySequence ctrlAltCKeySequence = QKeySequence(i18nc("The Chromium on Linux user agent key sequence.", "Ctrl+Alt+C"));
    QKeySequence ctrlAltShiftFKeySequence = QKeySequence(i18nc("The Firefox on Windows user agent key sequence.", "Ctrl+Alt+Shift+F"));
    QKeySequence ctrlAltShiftCKeySequence = QKeySequence(i18nc("The Chrome on Windows user agent key sequence.", "Ctrl+Alt+Shift+C"));
    QKeySequence ctrlAltEKeySequence = QKeySequence(i18nc("The Edge on Windows user agent key sequence.", "Ctrl+Alt+E"));
    QKeySequence ctrlAltSKeySequence = QKeySequence(i18nc("The Safari on macOS user agent key sequence.", "Ctrl+Alt+S"));
    QKeySequence altShiftCKeySequence = QKeySequence(i18nc("The custom user agent key sequence.", "Alt+Shift+C"));
    QKeySequence ctrlAltZKeySequence = QKeySequence(i18nc("The zoom factor key sequence.", "Ctrl+Alt+Z"));
    QKeySequence ctrlShiftMKeySequence = QKeySequence(i18nc("The Mojeek search engine key sequence.", "Ctrl+Shift+M"));
    QKeySequence ctrlShiftOKeySequence = QKeySequence(i18nc("The Monocles search engine key sequence.", "Ctrl+Shift+O"));
    QKeySequence ctrlShiftEKeySequence = QKeySequence(i18nc("The MetaGer search engine key sequence.", "Ctrl+Shift+E"));
    QKeySequence ctrlShiftGKeySequence = QKeySequence(i18nc("The Google search engine key sequence.", "Ctrl+Shift+G"));
    QKeySequence ctrlShiftBKeySequence = QKeySequence(i18nc("The Bing search engine key sequence.", "Ctrl+Shift+B"));
    QKeySequence ctrlShiftYKeySequence = QKeySequence(i18nc("The Yahoo search engine key sequence.", "Ctrl+Shift+Y"));
    QKeySequence ctrlShiftCKeySequence = QKeySequence(i18nc("The custom search engine key sequence.", "Ctrl+Shift+C"));
    QKeySequence ctrlDKeySequence = QKeySequence(i18nc("The domain settings key sequence.", "Ctrl+D"));
    QKeySequence ctrlSemicolonKeySequence = QKeySequence(i18nc("The cookies dialog key sequence.", "Ctrl+;"));

    // Set the action key sequences.
    actionCollectionPointer->setDefaultShortcut(newTabActionPointer, ctrlTKeySequence);
    actionCollectionPointer->setDefaultShortcut(newWindowActionPointer, ctrlNKeySequence);
    actionCollectionPointer->setDefaultShortcut(printPreviewActionPointer, ctrlShiftPKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentPrivacyBrowserActionPointer, ctrlAltPKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentWebEngineDefaultActionPointer, ctrlAltWKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentFirefoxLinuxActionPointer, ctrlAltFKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentChromiumLinuxActionPointer, ctrlAltCKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentFirefoxWindowsActionPointer, ctrlAltShiftFKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentChromeWindowsActionPointer, ctrlAltShiftCKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentEdgeWindowsActionPointer, ctrlAltEKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentSafariMacosActionPointer, ctrlAltSKeySequence);
    actionCollectionPointer->setDefaultShortcut(userAgentCustomActionPointer, altShiftCKeySequence);
    actionCollectionPointer->setDefaultShortcut(zoomFactorActionPointer, ctrlAltZKeySequence);
    actionCollectionPointer->setDefaultShortcut(searchEngineMojeekActionPointer, ctrlShiftMKeySequence);
    actionCollectionPointer->setDefaultShortcut(searchEngineMonoclesActionPointer, ctrlShiftOKeySequence);
    actionCollectionPointer->setDefaultShortcut(searchEngineMetagerActionPointer, ctrlShiftEKeySequence);
    actionCollectionPointer->setDefaultShortcut(searchEngineGoogleActionPointer, ctrlShiftGKeySequence);
    actionCollectionPointer->setDefaultShortcut(searchEngineBingActionPointer, ctrlShiftBKeySequence);
    actionCollectionPointer->setDefaultShortcut(searchEngineYahooActionPointer, ctrlShiftYKeySequence);
    actionCollectionPointer->setDefaultShortcut(searchEngineCustomActionPointer, ctrlShiftCKeySequence);
    actionCollectionPointer->setDefaultShortcut(domainSettingsActionPointer, ctrlDKeySequence);
    actionCollectionPointer->setDefaultShortcut(cookiesActionPointer, ctrlSemicolonKeySequence);

    // Execute the actions.
    connect(newTabActionPointer, SIGNAL(triggered()), tabWidgetPointer, SLOT(addTab()));
    connect(newWindowActionPointer, SIGNAL(triggered()), this, SLOT(newWindow()));
    connect(zoomFactorActionPointer, SIGNAL(triggered()), this, SLOT(getZoomFactorFromUser()));
    connect(cookiesActionPointer, SIGNAL(triggered()), this, SLOT(showCookiesDialog()));
    connect(domainSettingsActionPointer, SIGNAL(triggered()), this, SLOT(showDomainSettingsDialog()));

    // Update the on-the-fly menus.
    connect(tabWidgetPointer, SIGNAL(updateUserAgentActions(QString, bool)), this, SLOT(updateUserAgentActions(QString, bool)));
    connect(tabWidgetPointer, SIGNAL(updateZoomFactorAction(double)), this, SLOT(updateZoomFactorAction(double)));
    connect(tabWidgetPointer, SIGNAL(updateSearchEngineActions(QString, bool)), this, SLOT(updateSearchEngineActions(QString, bool)));

    // Apply the on-the-fly settings when selected.
    connect(userAgentActionGroupPointer, SIGNAL(triggered(QAction*)), tabWidgetPointer, SLOT(applyOnTheFlyUserAgent(QAction*)));
    connect(searchEngineActionGroupPointer, SIGNAL(triggered(QAction*)), tabWidgetPointer, SLOT(applyOnTheFlySearchEngine(QAction*)));

    // Process cookie changes.
    connect(tabWidgetPointer, SIGNAL(updateCookiesAction(int)), this, SLOT(updateCookiesAction(int)));

    // Connect the URL toolbar actions.
    connect(javaScriptActionPointer, SIGNAL(triggered()), this, SLOT(toggleJavaScript()));
    connect(localStorageActionPointer, SIGNAL(triggered()), this, SLOT(toggleLocalStorage()));
    connect(domStorageActionPointer, SIGNAL(triggered()), this, SLOT(toggleDomStorage()));

    // Update the URL toolbar actions.
    connect(tabWidgetPointer, SIGNAL(updateBackAction(bool)), backActionPointer, SLOT(setEnabled(bool)));
    connect(tabWidgetPointer, SIGNAL(updateForwardAction(bool)), forwardActionPointer, SLOT(setEnabled(bool)));
    connect(tabWidgetPointer, SIGNAL(updateJavaScriptAction(bool)), this, SLOT(updateJavaScriptAction(bool)));
    connect(tabWidgetPointer, SIGNAL(updateLocalStorageAction(bool)), this, SLOT(updateLocalStorageAction(bool)));
    connect(tabWidgetPointer, SIGNAL(updateDomStorageAction(bool)), this, SLOT(updateDomStorageAction(bool)));

    // Connect the find text actions.
    connect(findCaseSensitiveActionPointer, SIGNAL(triggered()), this, SLOT(toggleFindCaseSensitive()));
    connect(hideFindTextActionPointer, SIGNAL(triggered()), this, SLOT(hideFindTextActions()));

    // Setup the GUI based on the browserwindowui.rc file.
    setupGUI(StandardWindowOption::Default, ("browserwindowui.rc"));

    // Get lists of the actions' associated widgets.
    QList<QWidget*> userAgentAssociatedWidgetsPointerList = userAgentPrivacyBrowserActionPointer->associatedWidgets();
    QList<QWidget*> searchEngineAssociatedWidgetsPointerList = searchEngineMojeekActionPointer->associatedWidgets();

    // Get the menu widget pointers.  It is the second entry, after the main window.
    QWidget *userAgentMenuWidgetPointer = userAgentAssociatedWidgetsPointerList[1];
    QWidget *searchEngineMenuWidgetPointer = searchEngineAssociatedWidgetsPointerList[1];

    // Get the menu pointers.
    QMenu *userAgentMenuPointer = qobject_cast<QMenu*>(userAgentMenuWidgetPointer);
    QMenu *searchEngineMenuPointer = qobject_cast<QMenu*>(searchEngineMenuWidgetPointer);

    // Get the menu actions.
    userAgentMenuActionPointer = userAgentMenuPointer->menuAction();
    searchEngineMenuActionPointer = searchEngineMenuPointer->menuAction();

    // Get handles for the toolbars.
    navigationToolBarPointer = toolBar(QLatin1String("navigation_toolbar"));
    urlToolBarPointer = toolBar(QLatin1String("url_toolbar"));

    // Create the line edits.
    urlLineEditPointer = new KLineEdit();
    findTextLineEditPointer = new KLineEdit();

    // Get the line edit size policies.
    QSizePolicy urlLineEditSizePolicy = urlLineEditPointer->sizePolicy();
    QSizePolicy findTextLineEditSizePolicy = findTextLineEditPointer->sizePolicy();

    // Set the URL line edit horizontal stretch to be five times the find text line edit stretch.
    urlLineEditSizePolicy.setHorizontalStretch(5);
    findTextLineEditSizePolicy.setHorizontalStretch(1);

    // Set the policies.
    urlLineEditPointer->setSizePolicy(urlLineEditSizePolicy);
    findTextLineEditPointer->setSizePolicy(findTextLineEditSizePolicy);

    // Set the widths.
    urlLineEditPointer->setMinimumWidth(350);
    findTextLineEditPointer->setMinimumWidth(200);
    findTextLineEditPointer->setMaximumWidth(350);

    // Set the place holder text.
    urlLineEditPointer->setPlaceholderText(i18nc("The URL line edit placeholder text", "URL or Search Terms"));
    findTextLineEditPointer->setPlaceholderText(i18nc("The find line edit placeholder text", "Find Text"));

    // Show the clear button on the find line edit.
    findTextLineEditPointer->setClearButtonEnabled(true);

    // Add an edit or add domain settings action to the URL line edit.
    QAction *addOrEditDomainSettingsActionPointer = urlLineEditPointer->addAction(QIcon::fromTheme("settings-configure", QIcon::fromTheme(QLatin1String("preferences-desktop"))),
                                                                                  QLineEdit::TrailingPosition);

    // Add or edit the current domain settings.
    connect(addOrEditDomainSettingsActionPointer, SIGNAL(triggered()), this, SLOT(addOrEditDomainSettings()));

    // Create a find text label pointer.
    findTextLabelPointer = new QLabel();

    // Set the default label text.
    findTextLabelPointer->setText(QLatin1String("  ") + i18nc("Default find results.", "0/0") + QLatin1String("  "));

    // Insert the widgets into the toolbars.
    urlToolBarPointer->insertWidget(javaScriptActionPointer, urlLineEditPointer);
    findTextLineEditActionPointer = urlToolBarPointer->insertWidget(findNextActionPointer, findTextLineEditPointer);
    findTextLabelActionPointer = urlToolBarPointer->insertWidget(findNextActionPointer, findTextLabelPointer);

    // Initially hide the find text actions.
    hideFindTextActions();

    // Load a new URL from the URL line edit.
    connect(urlLineEditPointer, SIGNAL(returnKeyPressed(const QString)), this, SLOT(loadUrlFromLineEdit(const QString)));

    // Find text as it is typed.
    connect(findTextLineEditPointer, SIGNAL(textEdited(const QString &)), tabWidgetPointer, SLOT(findText(const QString &)));

    // Find next if the enter key is pressed.
    connect(findTextLineEditPointer, SIGNAL(returnKeyPressed(const QString &)), tabWidgetPointer, SLOT(findText(const QString &)));

    // Update find text when switching tabs.
    connect(tabWidgetPointer, SIGNAL(updateFindText(const QString &, const bool)), this, SLOT(updateFindText(const QString &, const bool)));

    // Update the find text results.
    connect(tabWidgetPointer, SIGNAL(updateFindTextResults(const QWebEngineFindTextResult &)), this, SLOT(updateFindTextResults(const QWebEngineFindTextResult &)));

    // Update the URL line edit on page loads.
    connect(tabWidgetPointer, SIGNAL(updateUrlLineEdit(QUrl)), this, SLOT(updateUrlLineEdit(QUrl)));

    // Update the window title.
    connect(tabWidgetPointer, SIGNAL(updateWindowTitle(const QString)), this, SLOT(updateWindowTitle(const QString)));

    // Get a handle for the status bar.
    QStatusBar *statusBarPointer = statusBar();

    // Create a progress bar.
    progressBarPointer = new QProgressBar();

    // Add the progress bar to to the status bar.
    statusBarPointer->addPermanentWidget(progressBarPointer);

    // Update the status bar with the URL when a link is hovered.
    connect(tabWidgetPointer, SIGNAL(linkHovered(QString)), statusBarPointer, SLOT(showMessage(QString)));

    // Update the progress bar.
    connect(tabWidgetPointer, SIGNAL(showProgressBar(const int)), this, SLOT(showProgressBar(const int)));
    connect(tabWidgetPointer, SIGNAL(hideProgressBar()), progressBarPointer, SLOT(hide()));

    // Update the URL line edit focus.
    connect(tabWidgetPointer, SIGNAL(clearUrlLineEditFocus()), this, SLOT(clearUrlLineEditFocus()));

    // Get the URL line edit palettes.
    normalBackgroundPalette = urlLineEditPointer->palette();
    negativeBackgroundPalette = normalBackgroundPalette;
    positiveBackgroundPalette = normalBackgroundPalette;

    // Modify the palettes.
    KColorScheme::adjustBackground(negativeBackgroundPalette, KColorScheme::NegativeBackground);
    KColorScheme::adjustBackground(positiveBackgroundPalette, KColorScheme::PositiveBackground);

    // Update the applied palette.
    connect(tabWidgetPointer, SIGNAL(updateDomainSettingsIndicator(const bool)), this, SLOT(updateDomainSettingsIndicator(const bool)));

    // Process full screen requests.
    connect(tabWidgetPointer, SIGNAL(fullScreenRequested(bool)), this, SLOT(fullScreenRequested(bool)));

    // Create keyboard shortcuts.
    QShortcut *f11ShortcutPointer = new QShortcut(QKeySequence(i18nc("The toggle full screen shortcut.", "F11")), this);
    QShortcut *escapeShortcutPointer = new QShortcut(QKeySequence::Cancel, this);

    // Connect the keyboard shortcuts.
    connect(f11ShortcutPointer, SIGNAL(activated()), fullScreenActionPointer, SLOT(trigger()));
    connect(escapeShortcutPointer, SIGNAL(activated()), this, SLOT(escape()));

    // Populate the UI.
    // This must be done here, because otherwise, if a URL is loaded, like a local file, that does not trigger a call to TabWidget::applyDomainSettings, the UI will not be fully populated.
    updateJavaScriptAction(Settings::javaScriptEnabled());
    updateLocalStorageAction(Settings::localStorageEnabled());
    updateDomStorageAction(Settings::domStorageEnabled());
    updateUserAgentActions(UserAgentHelper::getUserAgentFromDatabaseName(Settings::userAgent()), true);
    updateZoomFactorAction(Settings::zoomFactor());

    // Load the initial website if this is the first window.
    if (firstWindow)
        tabWidgetPointer->loadInitialWebsite();
}

void BrowserWindow::addOrEditDomainSettings() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Create the domain settings dialog pointer.
    DomainSettingsDialog *domainSettingsDialogPointer;

    // Get the current domain settings name.
    QString &currentDomainSettingsName = tabWidgetPointer->getDomainSettingsName();

    // Run the commands according to the current domain settings status.
    if (currentDomainSettingsName == QStringLiteral(""))  // Domain settings are not currently applied.
    {
        // Instruct the domain settings dialog to add a new domain.
        domainSettingsDialogPointer = new DomainSettingsDialog(DomainSettingsDialog::ADD_DOMAIN, currentUrl.host());
    }
    else  // Domain settings are currently applied.
    {
        // Instruct the domain settings dialog to edit the current domain.
        domainSettingsDialogPointer = new DomainSettingsDialog(DomainSettingsDialog::EDIT_DOMAIN, currentDomainSettingsName);
    }

    // Set the dialog window title.
    domainSettingsDialogPointer->setWindowTitle(i18nc("The domain settings dialog title", "Domain Settings"));

    // Set the modality.
    domainSettingsDialogPointer->setWindowModality(Qt::WindowModality::WindowModal);;

    // Show the dialog.
    domainSettingsDialogPointer->show();

    // Reload the tabs when domain settings are updated.
    connect(domainSettingsDialogPointer, SIGNAL(domainSettingsUpdated()), tabWidgetPointer, SLOT(applyDomainSettingsAndReload()));
}

void BrowserWindow::back() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Go back.
    tabWidgetPointer->back();
}

void BrowserWindow::clearUrlLineEditFocus() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();
}

void BrowserWindow::escape() const
{
    // Process the escape according to the status of the browser.
    if (fullScreenActionPointer->isChecked())  // Full screen browsing is enabled.
    {
        // Exit full screen browsing.
        fullScreenActionPointer->trigger();
    }
    else if (!findTextLineEditPointer->text().isEmpty())  // Find text is populated.
    {
        // Clear the find text line edit.
        findTextLineEditPointer->clear();

        // Clear the search in the WebEngine.
        tabWidgetPointer->findText(QStringLiteral(""));
    }
    else if (findTextLineEditActionPointer->isVisible())  // Find text actions are visible.
    {
        // Hide the find text actions.
        hideFindTextActions();
    }
}

void BrowserWindow::findNext() const
{
    // Get the find string.
    const QString findString = findTextLineEditPointer->text();

    // Search for the text if it is not empty.
    if (!findString.isEmpty())
        tabWidgetPointer->findText(findString);
}

void BrowserWindow::findPrevious() const
{
    // Get the find string.
    const QString findString = findTextLineEditPointer->text();

    // Search for the text if it is not empty.
    if (!findString.isEmpty())
        tabWidgetPointer->findPrevious(findString);
}

void BrowserWindow::forward() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Go forward.
    tabWidgetPointer->forward();
}

void BrowserWindow::fullScreenRequested(const bool toggleOn)
{
    // Toggle full screen mode.
    if (toggleOn)  // Turn full screen mode on.
    {
        // Set the window to be full screen.
        fullScreenActionPointer->setFullScreen(window(), true);

        // Hide all the bars.
        menuBar()->setVisible(false);
        navigationToolBarPointer->setVisible(false);
        urlToolBarPointer->setVisible(false);
        tabWidgetPointer->setTabBarVisible(false);
        statusBar()->setVisible(false);
    }
    else  // Turn full screen mode off.
    {
        // Set the window to not be full screen.
        fullScreenActionPointer->setFullScreen(window(), false);

        // Show all the bars.
        menuBar()->setVisible(true);
        navigationToolBarPointer->setVisible(true);
        urlToolBarPointer->setVisible(true);
        tabWidgetPointer->setTabBarVisible(true);
        statusBar()->setVisible(true);
    }
}

void BrowserWindow::getZoomFactorFromUser()
{
    // Create an OK flag.
    bool okClicked;

    // Display a dialog to get the new zoom factor from the user.  Format the double to display two decimals and have a 0.25 step.
    double newZoomFactor = QInputDialog::getDouble(this, i18nc("The on-the-fly zoom factor dialog title", "On-The-Fly Zoom Factor"),
                                                   i18nc("The instruction text of the on-the-fly zoom factor dialog", "Enter a zoom factor between 0.25 and 5.00"),
                                                   currentZoomFactor, .025, 5.00, 2, &okClicked, Qt::WindowFlags(), 0.25);

    // Update the zoom factor if the user clicked OK.
    if (okClicked)
    {
        // Update the current zoom factor.
        currentZoomFactor = newZoomFactor;

        // Set the new zoom factor.
        tabWidgetPointer->applyOnTheFlyZoomFactor(newZoomFactor);

        // Update the on-the-fly action text.
        updateZoomFactorAction(newZoomFactor);
    }
}

void BrowserWindow::hideFindTextActions() const
{
    // Hide the find text actions.
    findTextLineEditActionPointer->setVisible(false);
    findTextLabelActionPointer->setVisible(false);
    findNextActionPointer->setVisible(false);
    findPreviousActionPointer->setVisible(false);
    findCaseSensitiveActionPointer->setVisible(false);
    hideFindTextActionPointer->setVisible(false);
}

void BrowserWindow::home() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Go home.
    tabWidgetPointer->home();
}

void BrowserWindow::loadUrlFromLineEdit(const QString &url) const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Load the URL.
    tabWidgetPointer->loadUrlFromLineEdit(url);
}

void BrowserWindow::newWindow() const
{
    // Display a new instance of Privacy Browser.
    (new BrowserWindow)->show();
}

void BrowserWindow::refresh() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Refresh the web page.
    tabWidgetPointer->refresh();
}

void BrowserWindow::showCookiesDialog()
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Instantiate the cookie settings dialog.
    CookiesDialog *cookiesDialogPointer = new CookiesDialog(tabWidgetPointer->getCookieList());

    // Show the dialog.
    cookiesDialogPointer->show();

    // Connect the dialog signals.
    connect(cookiesDialogPointer, SIGNAL(addCookie(QNetworkCookie)), tabWidgetPointer, SLOT(addCookieToStore(QNetworkCookie)));
    connect(cookiesDialogPointer, SIGNAL(deleteAllCookies()), tabWidgetPointer, SLOT(deleteAllCookies()));
    connect(cookiesDialogPointer, SIGNAL(deleteCookie(QNetworkCookie)), tabWidgetPointer, SLOT(deleteCookieFromStore(QNetworkCookie)));
}

void BrowserWindow::showDownloadLocationBrowseDialog() const
{
    // Get the current download location.
    QString currentDownloadLocation = downloadLocationComboBoxPointer->currentText();

    // Resolve the system download directory if specified.
    if (currentDownloadLocation == QStringLiteral("System Download Directory"))
        currentDownloadLocation = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);

    // Get the new download location.
    QString newDownloadLocation = QFileDialog::getExistingDirectory(configDialogPointer, i18nc("Select download location dialog caption", "Select Download Location"), currentDownloadLocation);

    // Populate the download location combo box according to the new download location.
    if (newDownloadLocation == QStandardPaths::writableLocation(QStandardPaths::DownloadLocation))  // The default download location was selected.
    {
        // Populate the download location with the default text.
        downloadLocationComboBoxPointer->setCurrentText("System Download Directory");
    }
    else if (newDownloadLocation != QStringLiteral(""))  // A different directory was selected.
    {
        // Populate the download location.
        downloadLocationComboBoxPointer->setCurrentText(newDownloadLocation);
    }
}

void BrowserWindow::showDomainSettingsDialog() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Instantiate the domain settings dialog.
    DomainSettingsDialog *domainSettingsDialogPointer = new DomainSettingsDialog();

    // Show the dialog.
    domainSettingsDialogPointer->show();

    // Reload the tabs when domain settings are updated.
    connect(domainSettingsDialogPointer, SIGNAL(domainSettingsUpdated()), tabWidgetPointer, SLOT(applyDomainSettingsAndReload()));
}

void BrowserWindow::showFindTextActions() const
{
    // Show the find text actions.
    findTextLineEditActionPointer->setVisible(true);
    findTextLabelActionPointer->setVisible(true);
    findNextActionPointer->setVisible(true);
    findPreviousActionPointer->setVisible(true);
    findCaseSensitiveActionPointer->setVisible(true);
    hideFindTextActionPointer->setVisible(true);

    // Set the focus on the find line edit.
    findTextLineEditPointer->setFocus();

    // Select all the text in the find line edit.
    findTextLineEditPointer->selectAll();
}

void BrowserWindow::showProgressBar(const int &progress) const
{
    // Set the progress bar value.
    progressBarPointer->setValue(progress);

    // Show the progress bar.
    progressBarPointer->show();
}

void BrowserWindow::showSettingsDialog()
{
    // Create the settings widgets.
    QWidget *privacySettingsWidgetPointer = new QWidget;
    QWidget *generalSettingsWidgetPointer = new QWidget;
    QWidget *spellCheckSettingsWidgetPointer = new QWidget;

    // Instantiate the settings UI.
    Ui::PrivacySettings privacySettingsUi;
    Ui::GeneralSettings generalSettingsUi;
    Ui::SpellCheckSettings spellCheckSettingsUi;

    // Setup the UI to display the settings widgets.
    privacySettingsUi.setupUi(privacySettingsWidgetPointer);
    generalSettingsUi.setupUi(generalSettingsWidgetPointer);
    spellCheckSettingsUi.setupUi(spellCheckSettingsWidgetPointer);

    // Get handles for the widgets.
    QComboBox *userAgentComboBoxPointer = privacySettingsUi.kcfg_userAgent;
    userAgentLabelPointer = privacySettingsUi.userAgentLabel;
    QComboBox *searchEngineComboBoxPointer = generalSettingsUi.kcfg_searchEngine;
    searchEngineLabelPointer = generalSettingsUi.searchEngineLabel;
    downloadLocationComboBoxPointer = generalSettingsUi.kcfg_downloadLocation;
    QPushButton *browseButtonPointer = generalSettingsUi.browseButton;
    QListWidget *spellCheckListWidgetPointer = spellCheckSettingsUi.spellCheckListWidget;

    // Populate the combo box labels.
    updateUserAgentLabel(userAgentComboBoxPointer->currentText());
    updateSearchEngineLabel(searchEngineComboBoxPointer->currentText());

    // Update the labels when the combo boxes change.
    connect(userAgentComboBoxPointer, SIGNAL(currentTextChanged(const QString)), this, SLOT(updateUserAgentLabel(const QString)));
    connect(searchEngineComboBoxPointer, SIGNAL(currentTextChanged(const QString)), this, SLOT(updateSearchEngineLabel(const QString)));

    // Connect the download location directory browse button.
    connect(browseButtonPointer, SIGNAL(clicked()), this, SLOT(showDownloadLocationBrowseDialog()));

    // Create a dictionaries QDir from the `QTWEBENGINE_DICTIONARIES_PATH` environment variable.
    QDir dictionariesDir = QDir(qEnvironmentVariable("QTWEBENGINE_DICTIONARIES_PATH"));

    // Get a dictionaries string list.
    QStringList dictionariesStringList = dictionariesDir.entryList(QStringList(QLatin1String("*.bdic")), QDir::Files | QDir::NoSymLinks);

    // Remove the `.bdic` file extensions from the dictionaries list.
    dictionariesStringList.replaceInStrings(QLatin1String(".bdic"), QLatin1String(""));

    // Get a list of the enabled spell check languages.
    QStringList enabledSpellCheckLanguagesList = Settings::spellCheckLanguages();

    // Add each dictionary to the spell check list widget.
    foreach(QString dictionaryString, dictionariesStringList)
    {
        // Create a new list widget item pointer.
        QListWidgetItem *listWidgetItemPointer = new QListWidgetItem();

        // Create a dictionary check box widget with the name of the dictionary string.
        QCheckBox *dictionaryCheckBoxWidget = new QCheckBox(dictionaryString);

        // Check the language if it is currently enabled.
        if (enabledSpellCheckLanguagesList.contains(dictionaryString))
            dictionaryCheckBoxWidget->setCheckState(Qt::Checked);
        else
            dictionaryCheckBoxWidget->setCheckState(Qt::Unchecked);

        // Add the list widget item to the spell check list widget.
        spellCheckListWidgetPointer->addItem(listWidgetItemPointer);

        // Set the list widget item check box widget.
        spellCheckListWidgetPointer->setItemWidget(listWidgetItemPointer, dictionaryCheckBoxWidget);
    }

    // Get a handle for the KConfig skeleton.
    KConfigSkeleton *kConfigSkeletonPointer = Settings::self();

    // Instantiate a settings config dialog from the settings.kcfg file.
    configDialogPointer = new KConfigDialog(this, QLatin1String("settings"), kConfigSkeletonPointer);

    // Create a settings icon string.
    QString settingsIconString;

    // Get a settings icon that matches the theme.
    if (QIcon::hasThemeIcon("breeze-settings"))
    {
        // KDE uses breeze-settings.
        settingsIconString = QLatin1String("breeze-settings");
    }
    else
    {
        // Gnome uses preferences-desktop.
        settingsIconString = QLatin1String("preferences-desktop");
    }

    // Add the settings widgets as config dialog pages.
    configDialogPointer->addPage(privacySettingsWidgetPointer, i18nc("Settings tab title", "Privacy"), QLatin1String("privacybrowser"));
    configDialogPointer->addPage(generalSettingsWidgetPointer, i18nc("Settings tab title", "General"), settingsIconString);
    configDialogPointer->addPage(spellCheckSettingsWidgetPointer, i18nc("Settings tab title", "Spell Check"), QLatin1String("tools-check-spelling"));

    // Get handles for the buttons.
    QPushButton *applyButtonPointer = configDialogPointer->button(QDialogButtonBox::Apply);
    QPushButton *okButtonPointer = configDialogPointer->button(QDialogButtonBox::Ok);

    // Prevent interaction with the parent window while the dialog is open.
    configDialogPointer->setWindowModality(Qt::WindowModal);

    // Make it so.
    configDialogPointer->show();

    // TODO.  KConfigDialog does not respect expanding size policies.  <https://redmine.stoutner.com/issues/823>
    //configDialogPointer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    //privacySettingsWidgetPointer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    //generalSettingsWidgetPointer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    //configDialogPointer->adjustSize();

    // Expand the config dialog.
    configDialogPointer->resize(1000, 500);

    // Create a save spell check languages lambda.
    auto saveSpellCheckLanguages = [spellCheckListWidgetPointer, kConfigSkeletonPointer, this] ()
    {
        // Create a list of enabled languages.
        QStringList newSpellCheckLanguages = QStringList();

        // Get a count of all the languages.
        int allLanguagesCount = spellCheckListWidgetPointer->count();

        // Get a list of all the checked languages.
        for (int i = 0; i < allLanguagesCount; ++i) {
            // Get the language item.
            QListWidgetItem *languageItemPointer = spellCheckListWidgetPointer->item(i);

            // Get the language check box.
            QCheckBox *languageCheckBoxPointer = qobject_cast<QCheckBox*>(spellCheckListWidgetPointer->itemWidget(languageItemPointer));

            // Add the item to the enabled languages if it is checked.
            if (languageCheckBoxPointer->checkState() == Qt::Checked)
            {
                // Get the text.
                QString languageString = languageCheckBoxPointer->text();

                // Remove all instances of `&`, which may have been added automatically when creating the check box text.
                languageString.remove(QChar('&'));

                // Add the language string to the list.
                newSpellCheckLanguages.append(languageString);
            }
        }

        // Update the spell check languages.
        if (Settings::spellCheckLanguages() != newSpellCheckLanguages)
        {
            // Update the spell check languages.
            Settings::setSpellCheckLanguages(newSpellCheckLanguages);

            // Write the settings to disk.
            kConfigSkeletonPointer->save();
        }

        // Apply the spell check languages.
        tabWidgetPointer->applySpellCheckLanguages();
    };

    // Process
    connect(applyButtonPointer, &QPushButton::clicked, this, saveSpellCheckLanguages);
    connect(okButtonPointer, &QPushButton::clicked, this, saveSpellCheckLanguages);

    // Apply the settings handled by KConfig.
    connect(configDialogPointer, SIGNAL(settingsChanged(QString)), tabWidgetPointer, SLOT(applyApplicationSettings()));
    connect(configDialogPointer, SIGNAL(settingsChanged(QString)), tabWidgetPointer, SLOT(applyDomainSettingsAndReload()));
}

QSize BrowserWindow::sizeHint() const
{
    // Return the default window size.
    return QSize(1500, 1200);
}

void BrowserWindow::toggleDomStorage() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Toggle DOM storage.
    tabWidgetPointer->toggleDomStorage();
}

void BrowserWindow::toggleFindCaseSensitive() const
{
    // Get the current find string.
    const QString findString = findTextLineEditPointer->text();

    // Toggle find case sensitive.
    tabWidgetPointer->toggleFindCaseSensitive(findString);
}

void BrowserWindow::toggleJavaScript() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Toggle JavaScript.
    tabWidgetPointer->toggleJavaScript();
}

void BrowserWindow::toggleLocalStorage() const
{
    // Remove the focus from the URL line edit.
    urlLineEditPointer->clearFocus();

    // Toggle local storage.
    tabWidgetPointer->toggleLocalStorage();
}

void BrowserWindow::toggleFullScreen()
{
    // Toggle the full screen status.
    if (fullScreenActionPointer->isChecked())  // Enable full screen browsing mode.
    {
        // Enable full screen mode.
        fullScreenActionPointer->setFullScreen(window(), true);

        // Hide the menu bar if specified.
        if (Settings::fullScreenHideMenuBar())
            menuBar()->setVisible(false);

        // Hide the toolbars if specified.
        if (Settings::fullScreenHideToolBars())
        {
            navigationToolBarPointer->setVisible(false);
            urlToolBarPointer->setVisible(false);
        }

        // Hide the tab bar if specified.
        if (Settings::fullScreenHideTabBar())
            tabWidgetPointer->setTabBarVisible(false);

        // Hide the status bar if specified.
        if (Settings::fullScreenHideStatusBar())
            statusBar()->setVisible(false);
    }
    else  // Disable full screen browsing mode.
    {
        // Disable full screen mode.
        fullScreenActionPointer->setFullScreen(window(), false);

        // Show the menu bar.
        menuBar()->setVisible(true);

        // Show the toolbars.
        navigationToolBarPointer->setVisible(true);
        urlToolBarPointer->setVisible(true);

        // Show the tab bar.
        tabWidgetPointer->setTabBarVisible(true);

        // Show the status bar.
        statusBar()->setVisible(true);
    }
}

void BrowserWindow::updateCookiesAction(const int numberOfCookies) const
{
    // Update the action text.
    cookiesActionPointer->setText(i18nc("The Cookies action, which also displays the number of cookies", "Cookies - %1", numberOfCookies));
}

void BrowserWindow::updateDomStorageAction(const bool &isEnabled) const
{
    // Set the action checked status.
    domStorageActionPointer->setChecked(isEnabled);
}

void BrowserWindow::updateDomainSettingsIndicator(const bool status)
{
    // Set the domain palette according to the status.
    if (status)
        urlLineEditPointer->setPalette(positiveBackgroundPalette);
    else
        urlLineEditPointer->setPalette(normalBackgroundPalette);
}

void BrowserWindow::updateFindText(const QString &text, const bool findCaseSensitive) const
{
    // Set the text.
    findTextLineEditPointer->setText(text);

    // Set the find case sensitive action checked status.
    findCaseSensitiveActionPointer->setChecked(findCaseSensitive);
}

void BrowserWindow::updateFindTextResults(const QWebEngineFindTextResult &findTextResult) const
{
    // Update the find text label.
    findTextLabelPointer->setText(QStringLiteral("  %1/%2  ").arg(findTextResult.activeMatch()).arg(findTextResult.numberOfMatches()));

    // Set the background color according to the find status.
    if (findTextLineEditPointer->text().isEmpty())
        findTextLineEditPointer->setPalette(normalBackgroundPalette);
    else if (findTextResult.numberOfMatches() == 0)
        findTextLineEditPointer->setPalette(negativeBackgroundPalette);
    else
        findTextLineEditPointer->setPalette(positiveBackgroundPalette);
}

void BrowserWindow::updateJavaScriptAction(const bool &isEnabled)
{
    // Update the JavaScript status.
    javaScriptEnabled = isEnabled;

    // Set the icon according to the status.
    if (javaScriptEnabled)
        javaScriptActionPointer->setIcon(QIcon(QLatin1String(":/icons/javascript-warning.svg")));
    else
        javaScriptActionPointer->setIcon(QIcon(QLatin1String(":/icons/privacy-mode.svg")));

    // Set the action checked status.
    javaScriptActionPointer->setChecked(javaScriptEnabled);

    // Update the status of the DOM storage action.
    domStorageActionPointer->setEnabled(javaScriptEnabled & localStorageEnabled);
}

void BrowserWindow::updateLocalStorageAction(const bool &isEnabled)
{
    // Update the local storage status.
    localStorageEnabled = isEnabled;

    // Update the icon.  On Gnome, the toolbar icons don't pick up unless the size is explicit, probably because the toolbar ends up being an intermediate size.
    if (localStorageEnabled)
        localStorageActionPointer->setIcon(QIcon::fromTheme(QLatin1String("disk-quota-high"), QIcon(QLatin1String("/usr/share/icons/gnome/32x32/actions/filesaveas.png"))));
    else
        localStorageActionPointer->setIcon(QIcon::fromTheme(QLatin1String("disk-quota"), QIcon(QLatin1String("/usr/share/icons/gnome/32x32/apps/kfm.png"))));

    // Set the action checked status.
    localStorageActionPointer->setChecked(localStorageEnabled);

    // Update the status of the DOM storage action.
    domStorageActionPointer->setEnabled(localStorageEnabled & javaScriptEnabled);
}

void BrowserWindow::updateSearchEngineActions(const QString &searchEngine, const bool &updateCustomSearchEngineStatus)
{
    // Initialize the custom search engine flag.
    bool customSearchEngine = false;

    if (searchEngine == "Mojeek")  // Mojeek.
    {
        // Check the Mojeek user agent action.
        searchEngineMojeekActionPointer->setChecked(true);

        // Update the search engine menu action icon.
        searchEngineMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));

        // Update the search engine menu action text.
        searchEngineMenuActionPointer->setText(i18nc("The main search engine menu action", "Search Engine - Mojeek"));
    }
    else if (searchEngine == "Monocles")  // Monocles.
    {
        // Check the Monocles user agent action.
        searchEngineMonoclesActionPointer->setChecked(true);

        // Update the search engine menu action icon.
        searchEngineMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));

        // Update the search engine menu action text.
        searchEngineMenuActionPointer->setText(i18nc("The main search engine menu action", "Search Engine - Monocles"));
    }
    else if (searchEngine == "MetaGer")  // MetaGer.
    {
        // Check the MetaGer user agent action.
        searchEngineMetagerActionPointer->setChecked(true);

        // Update the search engine menu action icon.
        searchEngineMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));

        // Update the search engine menu action text.
        searchEngineMenuActionPointer->setText(i18nc("The main search engine menu action", "Search Engine - MetaGer"));
    }
    else if (searchEngine == "Google")  // Google.
    {
        // Check the Google user agent action.
        searchEngineGoogleActionPointer->setChecked(true);

        // Update the search engine menu action icon.
        searchEngineMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("im-google"), QIcon::fromTheme(QLatin1String("edit-find"))));

        // Update the search engine menu action text.
        searchEngineMenuActionPointer->setText(i18nc("The main search engine menu action", "Search Engine - Google"));
    }
    else if (searchEngine == "Bing")  // Bing.
    {
        // Check the Bing user agent action.
        searchEngineBingActionPointer->setChecked(true);

        // Update the search engine menu action icon.
        searchEngineMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));

        // Update the search engine menu action text.
        searchEngineMenuActionPointer->setText(i18nc("The main search engine menu action", "Search Engine - Bing"));
    }
    else if (searchEngine == "Yahoo")  // Yahoo.
    {
        // Check the Yahoo user agent action.
        searchEngineYahooActionPointer->setChecked(true);

        // Update the search engine menu action icon.
        searchEngineMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("im-yahoo"), QIcon::fromTheme(QLatin1String("edit-find"))));

        // Update the search engine menu action text.
        searchEngineMenuActionPointer->setText(i18nc("The main search engine menu action", "Search Engine - Yahoo"));
    }
    else  // Custom search engine.
    {
        // Check the user agent.
        searchEngineCustomActionPointer->setChecked(true);

        // Update the search engine menu action icon.
        searchEngineMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("edit-find")));

        // Update the search engine menu action text.
        searchEngineMenuActionPointer->setText(i18nc("The main search engine menu action", "Search Engine - Custom"));

        // Set the custom search engine text.
        searchEngineCustomActionPointer->setText(searchEngine);

        // Set the custom search engine flag.
        customSearchEngine = true;
    }

    // Update the custom search engine enabled boolean.
    if (updateCustomSearchEngineStatus)
        customSearchEngineEnabled = customSearchEngine;

    // Format the custom search engine.
    if (customSearchEngineEnabled)
    {
        // Enable the custom search engine.
        searchEngineCustomActionPointer->setEnabled(true);
    }
    else
    {
        // Disable the custom search engine.
        searchEngineCustomActionPointer->setEnabled(false);

        // Reset the custom search engine text.
        searchEngineCustomActionPointer->setText(i18nc("@action", "Custom"));
    }
}

void BrowserWindow::updateUserAgentActions(const QString &userAgent, const bool &updateCustomUserAgentStatus)
{
    // Initialize the custom user agent flag.
    bool customUserAgent = false;

    // Check the indicated on-the-fly user agent.
    if (userAgent == UserAgentHelper::PRIVACY_BROWSER_USER_AGENT)  // Privacy Browser.
    {
        // Check the Privacy Browser user agent action.
        userAgentPrivacyBrowserActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon(":/icons/privacy-mode.svg"));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Privacy Browser"));
    }
    else if (userAgent == TabWidget::webEngineDefaultUserAgent)  // WebEngine default.
    {
        // check the WebEngine default user agent action.
        userAgentWebEngineDefaultActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("qtlogo"), QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new")))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - WebEngine default"));
    }
    else if (userAgent == UserAgentHelper::FIREFOX_LINUX_USER_AGENT)  // Firefox on Linux.
    {
        // Check the Firefox on Linux user agent action.
        userAgentFirefoxLinuxActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("firefox-esr"), QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new")))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Firefox on Linux"));
    }
    else if (userAgent == UserAgentHelper::CHROMIUM_LINUX_USER_AGENT)  // Chromium on Linux.
    {
        // Check the Chromium on Linux user agent action.
        userAgentChromiumLinuxActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("chromium"), QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new")))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Chromium on Linux"));
    }
    else if (userAgent == UserAgentHelper::FIREFOX_WINDOWS_USER_AGENT)  // Firefox on Windows.
    {
        // Check the Firefox on Windows user agent action.
        userAgentFirefoxWindowsActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("firefox-esr"), QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new")))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Firefox on Windows"));
    }
    else if (userAgent == UserAgentHelper::CHROME_WINDOWS_USER_AGENT)  // Chrome on Windows.
    {
        // Check the Chrome on Windows user agent action.
        userAgentChromeWindowsActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("chromium"), QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new")))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Chrome on Windows"));
    }
    else if (userAgent == UserAgentHelper::EDGE_WINDOWS_USER_AGENT)  // Edge on Windows.
    {
        // Check the Edge on Windows user agent action.
        userAgentEdgeWindowsActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new"))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Edge on Windows"));
    }
    else if (userAgent == UserAgentHelper::SAFARI_MACOS_USER_AGENT)  // Safari on macOS.
    {
        // Check the Safari on macOS user agent action.
        userAgentSafariMacosActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new"))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Safari on macOS"));
    }
    else  // Custom user agent.
    {
        // Check the user agent.
        userAgentCustomActionPointer->setChecked(true);

        // Update the user agent menu action icon.
        userAgentMenuActionPointer->setIcon(QIcon::fromTheme(QLatin1String("user-group-properties"), QIcon::fromTheme(QLatin1String("contact-new"))));

        // Update the user agent menu action text.
        userAgentMenuActionPointer->setText(i18nc("The main user agent menu action", "User Agent - Custom"));

        // Set the custom user agent text.
        userAgentCustomActionPointer->setText(userAgent);

        // Set the custom user agent flag.
        customUserAgent = true;
    }

    // Update the custom user agent enabled boolean.
    // This is not done when the current user agent is a custom one but it is temporarially being changed via on-the-fly settings so that the user can switch back to the custom user agent.
    if (updateCustomUserAgentStatus)
        customUserAgentEnabled = customUserAgent;


    // Format the custom user agent.
    if (customUserAgentEnabled)
    {
        // Enable the custom user agent.
        userAgentCustomActionPointer->setEnabled(true);
    }
    else
    {
        // Disable the custom user agent.
        userAgentCustomActionPointer->setEnabled(false);

        // Reset the custom user agent text.
        userAgentCustomActionPointer->setText(i18nc("@action", "Custom"));
    }
}

void BrowserWindow::updateZoomFactorAction(const double &zoomFactor)
{
    // Set the current zoom factor.
    currentZoomFactor = zoomFactor;

    // Update the zoom factor action text, formatting the double with 2 decimal places.
    zoomFactorActionPointer->setText(ki18nc("@action", "Zoom Factor - %1").subs(zoomFactor, 0, '0', 2).toString());
}

void BrowserWindow::updateSearchEngineLabel(const QString &searchEngineString) const
{
    // Update the search engine label.
    searchEngineLabelPointer->setText(SearchEngineHelper::getSearchUrl(searchEngineString));
}

void BrowserWindow::updateUrlLineEdit(const QUrl &newUrl)
{
    // Update the URL line edit if it does not have focus.
    if (!urlLineEditPointer->hasFocus())
    {
        // Get the new URL string.
        QString newUrlString = newUrl.toString();

        // Update the URL line edit.
        urlLineEditPointer->setText(newUrlString);

        // Set the focus if the new URL is blank.
        if (newUrlString == QStringLiteral(""))
            urlLineEditPointer->setFocus();
    }

    // Store the current URL.
    currentUrl = newUrl;
}

void BrowserWindow::updateUserAgentLabel(const QString &userAgentDatabaseName) const
{
    // Update the user agent label.
    userAgentLabelPointer->setText(UserAgentHelper::getUserAgentFromDatabaseName(userAgentDatabaseName));
}

void BrowserWindow::updateWindowTitle(const QString &title)
{
    // Update the window title.
    setWindowTitle(title);
}
