diff options
author | 2023-05-17 21:59:43 +0530 | |
---|---|---|
committer | 2023-05-17 21:59:43 +0530 | |
commit | 5f10a0f9657358fcd86c55ec065f3855bad0c160 (patch) | |
tree | 340f949dbe076db57bf62879ad150fabc884905a | |
parent | b4b5dc3397966bea899bbb5ec0f756bb745dbff1 (diff) | |
download | whatsie-5f10a0f9657358fcd86c55ec065f3855bad0c160.tar.gz whatsie-5f10a0f9657358fcd86c55ec065f3855bad0c160.zip |
feat: minor fixes + code cleanup
Diffstat (limited to '')
34 files changed, 1384 insertions, 952 deletions
diff --git a/src/about.cpp b/src/about.cpp index 81657e8..3c7f826 100644 --- a/src/about.cpp +++ b/src/about.cpp @@ -17,7 +17,7 @@ About::About(QWidget *parent) : QWidget(parent), ui(new Ui::About) { appAuthorEmail = "keshavnrj@gmail.com"; appAuthorLink = "http://ktechpit.com"; donateLink = "https://paypal.me/keshavnrj/5"; - moreAppsLink = "https://snapcraft.io/search?q=keshavnrj"; + moreAppsLink = "https://snapcraft.io/publisher/keshavnrj"; appSourceCodeLink = "https://github.com/keshavbhatt/whatsie"; appRateLink = "snap://whatsie"; @@ -42,7 +42,7 @@ About::About(QWidget *parent) : QWidget(parent), ui(new Ui::About) { ui->version->setText("Version: " + QApplication::applicationVersion()); - ui->debugInfoText->setHtml(utils::appDebugInfo()); + ui->debugInfoText->setHtml(Utils::appDebugInfo()); ui->debugInfoText->hide(); @@ -92,14 +92,9 @@ void About::on_debugInfoButton_clicked() { } } -void About::keyPressEvent(QKeyEvent *e) -{ - if (e->key() == Qt::Key_Escape) - this->close(); +void About::keyPressEvent(QKeyEvent *e) { + if (e->key() == Qt::Key_Escape) + this->close(); - QWidget::keyPressEvent(e); -} - -void About::on_donate_2_clicked() { - QDesktopServices::openUrl(QUrl("https://opencollective.com/whatsie")); + QWidget::keyPressEvent(e); } diff --git a/src/about.h b/src/about.h index cd9e978..fc946e6 100644 --- a/src/about.h +++ b/src/about.h @@ -1,36 +1,31 @@ #ifndef ABOUT_H #define ABOUT_H -#include <QWidget> #include <QKeyEvent> +#include <QWidget> namespace Ui { class About; } -class About : public QWidget -{ - Q_OBJECT +class About : public QWidget { + Q_OBJECT public: - explicit About(QWidget *parent = nullptr); - ~About(); + explicit About(QWidget *parent = nullptr); + ~About(); -protected slots: - void keyPressEvent(QKeyEvent *e); +protected: + void keyPressEvent(QKeyEvent *e) override; private slots: - void on_debugInfoButton_clicked(); - - void on_donate_2_clicked(); + void on_debugInfoButton_clicked(); private: - Ui::About *ui; + Ui::About *ui; - QString appName, appDescription, - appSourceCodeLink, appAuthorLink, - appAuthorName, appAuthorEmail, - donateLink,moreAppsLink, appRateLink; - bool isOpenSource; + QString appName, appDescription, appSourceCodeLink, appAuthorLink, + appAuthorName, appAuthorEmail, donateLink, moreAppsLink, appRateLink; + bool isOpenSource; }; #endif // ABOUT_H diff --git a/src/about.ui b/src/about.ui index b828eb2..9bad693 100644 --- a/src/about.ui +++ b/src/about.ui @@ -7,7 +7,7 @@ <x>0</x> <y>0</y> <width>522</width> - <height>486</height> + <height>487</height> </rect> </property> <property name="windowTitle"> @@ -173,13 +173,6 @@ p, li { white-space: pre-wrap; } </widget> </item> <item> - <widget class="QPushButton" name="donate_2"> - <property name="text"> - <string>Donate OpenCollective</string> - </property> - </widget> - </item> - <item> <widget class="QPushButton" name="rate"> <property name="text"> <string>Rate in Store</string> diff --git a/src/autolockeventfilter.h b/src/autolockeventfilter.h index 9c35c45..c061fe8 100644 --- a/src/autolockeventfilter.h +++ b/src/autolockeventfilter.h @@ -19,7 +19,7 @@ public: ~AutoLockEventFilter() { autoLockTimer->stop(); - autoLockTimer->deleteLater(); + delete autoLockTimer; } signals: @@ -39,18 +39,13 @@ public slots: protected: bool eventFilter(QObject *obj, QEvent *ev) { - if (ev->type() == QEvent::KeyPress - || ev->type() == QEvent::MouseMove - || ev->type() == QEvent::Wheel - || ev->type() == QEvent::TouchUpdate - || ev->type() == QEvent::MouseButtonRelease - || ev->type() == QEvent::MouseButtonPress - || ev->type() == QEvent::MouseButtonDblClick - || ev->type() == QEvent::Gesture - || ev->type() == QEvent::FocusIn - || ev->type() == QEvent::FocusOut - || ev->type() == QEvent::Enter - ) { + if (ev->type() == QEvent::KeyPress || ev->type() == QEvent::MouseMove || + ev->type() == QEvent::Wheel || ev->type() == QEvent::TouchUpdate || + ev->type() == QEvent::MouseButtonRelease || + ev->type() == QEvent::MouseButtonPress || + ev->type() == QEvent::MouseButtonDblClick || + ev->type() == QEvent::Gesture || ev->type() == QEvent::FocusIn || + ev->type() == QEvent::FocusOut || ev->type() == QEvent::Enter) { resetTimer(); } return QObject::eventFilter(obj, ev); diff --git a/src/automatictheme.cpp b/src/automatictheme.cpp index 3cf33c8..9b1f3e7 100644 --- a/src/automatictheme.cpp +++ b/src/automatictheme.cpp @@ -2,26 +2,27 @@ #include "ui_automatictheme.h" #include "sunclock.hpp" -#include <QMessageBox> AutomaticTheme::AutomaticTheme(QWidget *parent) : QWidget(parent), ui(new Ui::AutomaticTheme) { ui->setupUi(this); ui->refresh->setEnabled(false); - sunrise.setSecsSinceEpoch(settings.value("sunrise").toLongLong()); - sunset.setSecsSinceEpoch(settings.value("sunset").toLongLong()); + m_sunrise.setSecsSinceEpoch( + SettingsManager::instance().settings().value("sunrise").toLongLong()); + m_sunset.setSecsSinceEpoch( + SettingsManager::instance().settings().value("sunset").toLongLong()); - ui->sunrise->setTime(sunrise.time()); - ui->sunset->setTime(sunset.time()); + ui->sunrise->setTime(m_sunrise.time()); + ui->sunset->setTime(m_sunset.time()); QTimeZone zone = QTimeZone::systemTimeZone(); QDateTime dt = QDateTime::currentDateTime(); if (zone.isValid()) { - hour_offset = (double)zone.standardTimeOffset(dt) / (double)3600; + m_hourOffset = (double)zone.standardTimeOffset(dt) / (double)3600; } else { - settings.setValue("automaticTheme", false); + SettingsManager::instance().settings().setValue("automaticTheme", false); QMessageBox::critical( this, "Error", "Unable to get system TimeZone information.\n\nAutomatic theme " @@ -29,34 +30,34 @@ AutomaticTheme::AutomaticTheme(QWidget *parent) return; } - gPosInfoSrc = QGeoPositionInfoSource::createDefaultSource(this); + m_gPosInfoSrc = QGeoPositionInfoSource::createDefaultSource(this); - if (gPosInfoSrc) // sudo apt install geoclue-2.0 + if (m_gPosInfoSrc) // sudo apt install geoclue-2.0 { ui->refresh->setEnabled(true); - connect(gPosInfoSrc, &QGeoPositionInfoSource::positionUpdated, + connect(m_gPosInfoSrc, &QGeoPositionInfoSource::positionUpdated, this, [=](const QGeoPositionInfo &update) { QGeoCoordinate cor = update.coordinate(); if (cor.isValid()) { - this->lon = cor.longitude(); - this->lat = cor.latitude(); + this->m_longitude = cor.longitude(); + this->m_latitube = cor.latitude(); ui->refresh->setEnabled(true); - gPosInfoSrc->stopUpdates(); + m_gPosInfoSrc->stopUpdates(); } else { ui->refresh->setEnabled(false); } }); - connect(gPosInfoSrc, &QGeoPositionInfoSource::updateTimeout, [=]() { - if (!settings.value("sunrise").isValid() || - !settings.value("sunset").isValid()) { + connect(m_gPosInfoSrc, &QGeoPositionInfoSource::updateTimeout, this, [=]() { + if (!SettingsManager::instance().settings().value("sunrise").isValid() || + !SettingsManager::instance().settings().value("sunset").isValid()) { if (ui->refresh->isEnabled()) ui->refresh->click(); } }); - gPosInfoSrc->startUpdates(); + m_gPosInfoSrc->startUpdates(); } else { ui->refresh->setEnabled(false); - settings.setValue("automaticTheme", false); + SettingsManager::instance().settings().setValue("automaticTheme", false); QMessageBox::critical( this, "Error", "Unable to initialize QGeoPositionInfoSource.\n\nAutomatic theme " @@ -66,52 +67,56 @@ AutomaticTheme::AutomaticTheme(QWidget *parent) } AutomaticTheme::~AutomaticTheme() { - gPosInfoSrc->disconnect(); - gPosInfoSrc->deleteLater(); + m_gPosInfoSrc->disconnect(); + m_gPosInfoSrc->deleteLater(); delete ui; } void AutomaticTheme::on_refresh_clicked() { - QGeoCoordinate geoCor = QGeoCoordinate(this->lat, this->lon); + QGeoCoordinate geoCor = QGeoCoordinate(this->m_latitube, this->m_longitude); if (geoCor.isValid()) { - Sunclock sun(this->lat, this->lon, this->hour_offset); - sunrise.setSecsSinceEpoch( - sun.sunrise(QDateTime::currentDateTime().toTime_t())); - sunset.setSecsSinceEpoch( - sun.sunset(QDateTime::currentDateTime().toTime_t())); + Sunclock sun(this->m_latitube, this->m_longitude, this->m_hourOffset); + m_sunrise.setSecsSinceEpoch( + sun.sunrise(QDateTime::currentDateTimeUtc().toTime_t())); + m_sunset.setSecsSinceEpoch( + sun.sunset(QDateTime::currentDateTimeUtc().toTime_t())); - ui->sunrise->setTime(sunrise.time()); - ui->sunset->setTime(sunset.time()); + ui->sunrise->setTime(m_sunrise.time()); + ui->sunset->setTime(m_sunset.time()); } else { - settings.setValue("automaticTheme", false); + SettingsManager::instance().settings().setValue("automaticTheme", false); QMessageBox::critical(this, "Error", "Invalid Geo-Coordinates.\n\nPlease try again."); } } void AutomaticTheme::on_save_clicked() { - if (sunrise.toSecsSinceEpoch() == sunset.toSecsSinceEpoch()) { - settings.setValue("automaticTheme", false); - QMessageBox::critical(this, "Error", - "Invalid settings.\n\nSunrise and Sunset time cannot " - "have similar values.\n\nPlease try again."); + if (m_sunrise.toSecsSinceEpoch() == m_sunset.toSecsSinceEpoch()) { + SettingsManager::instance().settings().setValue("automaticTheme", false); + QMessageBox::critical( + this, "Error", + "Invalid SettingsManager::instance().settings().\n\nSunrise and Sunset " + "time cannot " + "have similar values.\n\nPlease try again."); } else { - settings.setValue("sunrise", sunrise.toSecsSinceEpoch()); - settings.setValue("sunset", sunset.toSecsSinceEpoch()); - settings.setValue("automaticTheme", true); + SettingsManager::instance().settings().setValue( + "sunrise", m_sunrise.toSecsSinceEpoch()); + SettingsManager::instance().settings().setValue( + "sunset", m_sunset.toSecsSinceEpoch()); + SettingsManager::instance().settings().setValue("automaticTheme", true); this->close(); } } void AutomaticTheme::on_cancel_clicked() { - settings.setValue("automaticTheme", false); + SettingsManager::instance().settings().setValue("automaticTheme", false); this->close(); } void AutomaticTheme::on_sunrise_timeChanged(const QTime &time) { - sunrise.setTime(QTime(time.hour(), time.minute(), 0)); + m_sunrise.setTime(QTime(time.hour(), time.minute(), 0)); } void AutomaticTheme::on_sunset_timeChanged(const QTime &time) { - sunset.setTime(QTime(time.hour(), time.minute(), 0)); + m_sunset.setTime(QTime(time.hour(), time.minute(), 0)); } diff --git a/src/automatictheme.h b/src/automatictheme.h index 55904e5..f013713 100644 --- a/src/automatictheme.h +++ b/src/automatictheme.h @@ -1,47 +1,45 @@ #ifndef AUTOMATICTHEME_H #define AUTOMATICTHEME_H -#include <QWidget> -#include <QGeoPositionInfoSource> #include <QDebug> +#include <QGeoPositionInfoSource> +#include <QMessageBox> #include <QTimeZone> -#include <QSettings> +#include <QWidget> + +#include "settingsmanager.h" namespace Ui { class AutomaticTheme; } -class AutomaticTheme : public QWidget -{ - Q_OBJECT +class AutomaticTheme : public QWidget { + Q_OBJECT public: - explicit AutomaticTheme(QWidget *parent = nullptr); - ~AutomaticTheme(); - + explicit AutomaticTheme(QWidget *parent = nullptr); + ~AutomaticTheme(); private slots: - void on_refresh_clicked(); + void on_refresh_clicked(); - void on_save_clicked(); + void on_save_clicked(); - void on_cancel_clicked(); + void on_cancel_clicked(); - void on_sunrise_timeChanged(const QTime &time); + void on_sunrise_timeChanged(const QTime &time); - void on_sunset_timeChanged(const QTime &time); + void on_sunset_timeChanged(const QTime &time); private: - Ui::AutomaticTheme *ui; - - QGeoPositionInfoSource *gPosInfoSrc; - QDateTime sunrise, sunset; + Ui::AutomaticTheme *ui; - double hour_offset = 0.0; - double lon = 0.0; - double lat = 0.0; + QGeoPositionInfoSource *m_gPosInfoSrc; + QDateTime m_sunrise, m_sunset; - QSettings settings; + double m_hourOffset = 0.0; + double m_longitude = 0.0; + double m_latitube = 0.0; }; #endif // AUTOMATICTHEME_H diff --git a/src/common.h b/src/common.h index f7c32b9..295dd18 100644 --- a/src/common.h +++ b/src/common.h @@ -3,7 +3,8 @@ #include <QString> // userAgent -QString defaultUserAgentStr = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"; +//QString defaultUserAgentStr = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"; +QString defaultUserAgentStr = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"; //appAutoLock int defaultAppAutoLockDuration = 30; diff --git a/src/dictionaries.cpp b/src/dictionaries.cpp index fc8e7c0..5299806 100644 --- a/src/dictionaries.cpp +++ b/src/dictionaries.cpp @@ -19,7 +19,7 @@ QString Dictionaries::GetDictionaryPath() { // the environment variable takes precedence on all platforms if (qEnvironmentVariableIsSet("QTWEBENGINE_DICTIONARIES_PATH")) { - dict_path = utils::GetEnvironmentVar("QTWEBENGINE_DICTIONARIES_PATH"); + dict_path = Utils::GetEnvironmentVar("QTWEBENGINE_DICTIONARIES_PATH"); return dict_path; } diff --git a/src/downloadmanagerwidget.cpp b/src/downloadmanagerwidget.cpp index 812c471..13643e8 100644 --- a/src/downloadmanagerwidget.cpp +++ b/src/downloadmanagerwidget.cpp @@ -1,11 +1,6 @@ #include "downloadmanagerwidget.h"
-
#include "downloadwidget.h"
-#include <QFileDialog>
-#include <QStandardPaths>
-#include <QWebEngineDownloadItem>
-
DownloadManagerWidget::DownloadManagerWidget(QWidget *parent)
: QWidget(parent), m_numDownloads(0) {
setupUi(this);
@@ -22,8 +17,7 @@ void DownloadManagerWidget::downloadRequested( Q_ASSERT(download &&
download->state() == QWebEngineDownloadItem::DownloadRequested);
QString path =
- settings
- .value("defaultDownloadLocation",
+ SettingsManager::instance().settings().value("defaultDownloadLocation",
QStandardPaths::writableLocation(
QStandardPaths::DownloadLocation) +
QDir::separator() + QApplication::applicationName())
@@ -46,7 +40,7 @@ void DownloadManagerWidget::downloadRequested( switch (msgBox.exec()) {
case QMessageBox::Save: {
QString n_proposed_file_name = path + QDir::separator() +
- utils::generateRandomId(5) + "_" +
+ Utils::generateRandomId(5) + "_" +
download->downloadFileName();
download->setDownloadFileName(n_proposed_file_name);
acceptDownload(download);
@@ -81,8 +75,7 @@ void DownloadManagerWidget::remove(DownloadWidget *downloadWidget) { }
void DownloadManagerWidget::on_open_download_dir_clicked() {
- utils::desktopOpenUrl(settings
- .value("defaultDownloadLocation",
+ Utils::desktopOpenUrl(SettingsManager::instance().settings().value("defaultDownloadLocation",
QStandardPaths::writableLocation(
QStandardPaths::DownloadLocation) +
QDir::separator() +
diff --git a/src/downloadmanagerwidget.h b/src/downloadmanagerwidget.h index 76464e8..8367041 100644 --- a/src/downloadmanagerwidget.h +++ b/src/downloadmanagerwidget.h @@ -51,10 +51,13 @@ #ifndef DOWNLOADMANAGERWIDGET_H
#define DOWNLOADMANAGERWIDGET_H
+#include "settingsmanager.h"
#include "ui_downloadmanagerwidget.h"
-
#include "utils.h"
-#include <QSettings>
+
+#include <QFileDialog>
+#include <QStandardPaths>
+#include <QWebEngineDownloadItem>
#include <QWidget>
QT_BEGIN_NAMESPACE
@@ -89,7 +92,6 @@ private: void remove(DownloadWidget *downloadWidget);
int m_numDownloads;
- QSettings settings;
};
#endif // DOWNLOADMANAGERWIDGET_H
diff --git a/src/lock.cpp b/src/lock.cpp index ffbf144..3026573 100644 --- a/src/lock.cpp +++ b/src/lock.cpp @@ -1,10 +1,5 @@ #include "lock.h" -#include "moreapps.h" #include "ui_lock.h" -#include <QDebug> -#include <QGraphicsOpacityEffect> -#include <QKeyEvent> -#include <QPropertyAnimation> #include "X11/XKBlib.h" // keep this header at bottom @@ -25,25 +20,28 @@ Lock::Lock(QWidget *parent) : QWidget(parent), ui(new Ui::Lock) { passcodeLoginAction = ui->passcodeLogin->addAction( QIcon(":/icons/green_arrow-right-line.png"), QLineEdit::TrailingPosition); passcodeLoginAction->setEnabled(false); - connect(passcodeLoginAction, &QAction::triggered, passcodeLoginAction, - [this]() { - QString password = - QByteArray::fromBase64(settings.value("asdfg").toByteArray()); - if (ui->passcodeLogin->text() == password && check_password_set()) { - isLocked = false; - this->animateOut(); - emit unLocked(); - } else { - ui->wrong->show(); - } - }); + connect( + passcodeLoginAction, &QAction::triggered, passcodeLoginAction, [this]() { + QString password = QByteArray::fromBase64(SettingsManager::instance() + .settings() + .value("asdfg") + .toByteArray()); + if (ui->passcodeLogin->text() == password && check_password_set()) { + isLocked = false; + this->animateOut(); + emit unLocked(); + } else { + ui->wrong->show(); + } + }); QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); ui->centerWidget->setGraphicsEffect(eff); animateIn(); - if (settings.value("asdfg").isValid() == false) { + if (SettingsManager::instance().settings().value("asdfg").isValid() == + false) { signUp(); } else { lock_app(); @@ -143,7 +141,10 @@ void Lock::applyThemeQuirks() { "border-bottom-left-radius: 4px;"; QString lightBg = "background-color: rgb(37, 211, 102);"; QString darkBg = "background-color: rgb(0, 117, 96);"; - if (QString::compare(settings.value("windowTheme", "light").toString(), + if (QString::compare(SettingsManager::instance() + .settings() + .value("windowTheme", "light") + .toString(), "dark", Qt::CaseInsensitive) == 0) { // light ui->bottomLine->setStyleSheet(darkBg + border); ui->bottomLine_2->setStyleSheet(darkBg + border); @@ -194,8 +195,9 @@ void Lock::on_setPass_clicked() { pass1 = ui->passcode1->text().trimmed(); pass2 = ui->passcode2->text().trimmed(); if (pass1 == pass2) { - settings.setValue("asdfg", QByteArray(pass1.toUtf8()).toBase64()); - settings.setValue("lockscreen", true); + SettingsManager::instance().settings().setValue( + "asdfg", QByteArray(pass1.toUtf8()).toBase64()); + SettingsManager::instance().settings().setValue("lockscreen", true); ui->passcode1->clear(); ui->passcode2->clear(); emit passwordSet(); @@ -207,7 +209,9 @@ void Lock::on_setPass_clicked() { } } -bool Lock::check_password_set() { return settings.value("asdfg").isValid(); } +bool Lock::check_password_set() { + return SettingsManager::instance().settings().value("asdfg").isValid(); +} void Lock::on_passcodeLogin_textChanged(const QString &arg1) { if (arg1.contains(" ")) { @@ -231,12 +235,13 @@ void Lock::lock_app() { void Lock::on_passcodeLogin_returnPressed() { passcodeLoginAction->trigger(); } bool Lock::getCapsLockOn() { - Display *d = XOpenDisplay((char *)0); + Display *d = XOpenDisplay(nullptr); bool caps_state = false; if (d) { unsigned n; XkbGetIndicatorState(d, XkbUseCoreKbd, &n); caps_state = (n & 0x01) == 1; + XCloseDisplay(d); } return caps_state; } @@ -2,9 +2,15 @@ #define LOCK_H #include <QAction> -#include <QSettings> +#include <QDebug> +#include <QGraphicsOpacityEffect> +#include <QKeyEvent> +#include <QPropertyAnimation> #include <QWidget> +#include "moreapps.h" +#include "settingsmanager.h" + namespace Ui { class Lock; } @@ -47,7 +53,6 @@ protected slots: private: Ui::Lock *ui; bool isLocked = false; - QSettings settings; QAction *passcodeLoginAction; }; diff --git a/src/main.cpp b/src/main.cpp index 5a17d78..c771f71 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,6 +1,5 @@ #include <QApplication> #include <QDebug> -#include <QSettings> #include <QWebEngineProfile> #include <QWebEngineSettings> #include <QtWebEngine> @@ -9,6 +8,7 @@ #include "common.h" #include "def.h" #include "mainwindow.h" +#include "settingsmanager.h" #include <singleapplication.h> int main(int argc, char *argv[]) { @@ -16,14 +16,18 @@ int main(int argc, char *argv[]) { QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #ifdef QT_DEBUG - qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--remote-debugging-port=9421 --ignore-gpu-blocklist --no-sandbox"); + qputenv("QTWEBENGINE_CHROMIUM_FLAGS", + "--remote-debugging-port=9421 --ignore-gpu-blocklist --no-sandbox " + "--single-process --disable-extensions"); #else - qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-logging --ignore-gpu-blocklist --no-sandbox"); //--single-process + qputenv("QTWEBENGINE_CHROMIUM_FLAGS", + "--disable-logging --ignore-gpu-blocklist --no-sandbox " + "--single-process --disable-extensions"); #endif SingleApplication instance(argc, argv, true); instance.setQuitOnLastWindowClosed(false); - instance.setWindowIcon(QIcon(":/icons/app/icon-128.png")); + instance.setWindowIcon(QIcon(":/icons/app/icon-64.png")); QApplication::setApplicationName("WhatSie"); QApplication::setDesktopFileName("com.ktechpit.whatsie"); QApplication::setOrganizationDomain("com.ktechpit"); @@ -87,16 +91,16 @@ int main(int argc, char *argv[]) { QObject::tr("Show main window of running instance of ") + QApplication::applicationName()); - parser.addOption(showCLIHelpOption); // [x] - parser.addVersionOption(); // [x] - parser.addOption(buildInfoOption); // [x] - parser.addOption(showAppWindowOption); // [x] - parser.addOption(openSettingsOption); // [x] - parser.addOption(lockAppOption); // [x] - parser.addOption(openAboutOption); // [x] - parser.addOption(toggleThemeOption); // [x] - parser.addOption(reloadAppOption); // [x] - parser.addOption(newChatOption); // [-] + parser.addOption(showCLIHelpOption); + parser.addVersionOption(); + parser.addOption(buildInfoOption); + parser.addOption(showAppWindowOption); + parser.addOption(openSettingsOption); + parser.addOption(lockAppOption); + parser.addOption(openAboutOption); + parser.addOption(toggleThemeOption); + parser.addOption(reloadAppOption); + parser.addOption(newChatOption); secondaryInstanceCLIOptions << showAppWindowOption << openSettingsOption << lockAppOption << openAboutOption @@ -165,7 +169,10 @@ int main(int argc, char *argv[]) { << "LockApp"; whatsie.alreadyRunning(); QSettings settings; - if (!settings.value("asdfg").isValid()) { + if (!SettingsManager::instance() + .settings() + .value("asdfg") + .isValid()) { whatsie.notify( QApplication::applicationName(), QObject::tr("App lock is not configured, \n" @@ -205,7 +212,7 @@ int main(int argc, char *argv[]) { qInfo() << "cmd:" << "OpenNewChatPrompt"; whatsie.alreadyRunning(); - whatsie.newChat(); //TODO: invetigate the crash + whatsie.newChat(); // TODO: invetigate the crash return; } @@ -238,7 +245,10 @@ int main(int argc, char *argv[]) { QSettings settings; if (QSystemTrayIcon::isSystemTrayAvailable() && - settings.value("startMinimized", false).toBool()) { + SettingsManager::instance() + .settings() + .value("startMinimized", false) + .toBool()) { whatsie.runMinimized(); } else { whatsie.show(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 72b6d4e..1ba43f1 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -14,9 +14,10 @@ extern int defaultAppAutoLockDuration; extern bool defaultAppAutoLock; MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), notificationsTitleRegExp("^\\([1-9]\\d*\\).*"), - trayIconNormal(":/icons/app/notification/whatsie-notify.png"), - unreadMessageCountRegExp("\\([^\\d]*(\\d+)[^\\d]*\\)") { + : QMainWindow(parent), + m_trayIconNormal(":/icons/app/notification/whatsie-notify.png"), + m_notificationsTitleRegExp("^\\([1-9]\\d*\\).*"), + m_unreadMessageCountRegExp("\\([^\\d]*(\\d+)[^\\d]*\\)") { setObjectName("MainWindow"); setWindowTitle(QApplication::applicationName()); @@ -24,7 +25,6 @@ MainWindow::MainWindow(QWidget *parent) setMinimumWidth(525); setMinimumHeight(448); restoreMainWindow(); - initThemes(); createActions(); createTrayIcon(); createWebEngine(); @@ -36,8 +36,9 @@ MainWindow::MainWindow(QWidget *parent) } void MainWindow::restoreMainWindow() { - if (settings.value("geometry").isValid()) { - restoreGeometry(settings.value("geometry").toByteArray()); + if (SettingsManager::instance().settings().value("geometry").isValid()) { + restoreGeometry( + SettingsManager::instance().settings().value("geometry").toByteArray()); QPoint pos = QCursor::pos(); auto localScreens = QGuiApplication::screens(); for (auto screen : qAsConst(localScreens)) { @@ -52,80 +53,30 @@ void MainWindow::restoreMainWindow() { } void MainWindow::initAutoLock() { - autoLockEventFilter = new AutoLockEventFilter( - settings.value("autoLockDuration", defaultAppAutoLockDuration).toInt() * + m_autoLockEventFilter = new AutoLockEventFilter( + SettingsManager::instance() + .settings() + .value("autoLockDuration", defaultAppAutoLockDuration) + .toInt() * 1000); - connect(autoLockEventFilter, &AutoLockEventFilter::autoLockTimerTimeout, this, - [=]() { - if ((settingsWidget && !settingsWidget->isVisible()) && - settings.value("appAutoLocking", defaultAppAutoLock).toBool()) { + connect(m_autoLockEventFilter, &AutoLockEventFilter::autoLockTimerTimeout, + this, [=]() { + if ((m_settingsWidget && !m_settingsWidget->isVisible()) && + SettingsManager::instance() + .settings() + .value("appAutoLocking", defaultAppAutoLock) + .toBool()) { this->lockApp(); } }); - if (settings.value("appAutoLocking", defaultAppAutoLock).toBool()) { - qApp->installEventFilter(autoLockEventFilter); + if (SettingsManager::instance() + .settings() + .value("appAutoLocking", defaultAppAutoLock) + .toBool()) { + qApp->installEventFilter(m_autoLockEventFilter); } } -void MainWindow::initThemes() { - // Light - lightPalette.setColor(QPalette::Window, QColor(240, 240, 240)); - lightPalette.setColor(QPalette::WindowText, QColor(0, 0, 0)); - lightPalette.setColor(QPalette::Button, QColor(240, 240, 240)); - lightPalette.setColor(QPalette::Light, QColor(180, 180, 180)); - lightPalette.setColor(QPalette::Midlight, QColor(200, 200, 200)); - lightPalette.setColor(QPalette::Dark, QColor(225, 225, 225)); - lightPalette.setColor(QPalette::Text, QColor(0, 0, 0)); - lightPalette.setColor(QPalette::BrightText, QColor(0, 0, 0)); - lightPalette.setColor(QPalette::ButtonText, QColor(0, 0, 0)); - lightPalette.setColor(QPalette::Base, QColor(237, 237, 237)); - lightPalette.setColor(QPalette::Shadow, QColor(20, 20, 20)); - lightPalette.setColor(QPalette::Highlight, QColor(76, 163, 224)); - lightPalette.setColor(QPalette::HighlightedText, QColor(0, 0, 0)); - lightPalette.setColor(QPalette::Link, QColor(0, 162, 232)); - lightPalette.setColor(QPalette::AlternateBase, QColor(225, 225, 225)); - lightPalette.setColor(QPalette::ToolTipBase, QColor(240, 240, 240)); - lightPalette.setColor(QPalette::ToolTipText, QColor(0, 0, 0)); - lightPalette.setColor(QPalette::LinkVisited, QColor(222, 222, 222)); - lightPalette.setColor(QPalette::Disabled, QPalette::WindowText, - QColor(115, 115, 115)); - lightPalette.setColor(QPalette::Disabled, QPalette::Text, - QColor(115, 115, 115)); - lightPalette.setColor(QPalette::Disabled, QPalette::ButtonText, - QColor(115, 115, 115)); - lightPalette.setColor(QPalette::Disabled, QPalette::Highlight, - QColor(190, 190, 190)); - lightPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, - QColor(115, 115, 115)); - - // Dark - darkPalette.setColor(QPalette::Window, QColor(17, 27, 33)); - darkPalette.setColor(QPalette::Text, Qt::white); - darkPalette.setColor(QPalette::WindowText, Qt::white); - darkPalette.setColor(QPalette::Base, QColor(32, 44, 51)); - darkPalette.setColor(QPalette::AlternateBase, QColor(95, 108, 115)); - darkPalette.setColor(QPalette::ToolTipBase, QColor(66, 66, 66)); - darkPalette.setColor(QPalette::ToolTipText, QColor(192, 192, 192)); - darkPalette.setColor(QPalette::Dark, QColor(35, 35, 35)); - darkPalette.setColor(QPalette::Shadow, QColor(20, 20, 20)); - darkPalette.setColor(QPalette::Button, QColor(17, 27, 33)); - darkPalette.setColor(QPalette::ButtonText, Qt::white); - darkPalette.setColor(QPalette::BrightText, Qt::red); - darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); - darkPalette.setColor(QPalette::Highlight, QColor(38, 140, 196)); - darkPalette.setColor(QPalette::HighlightedText, Qt::white); - darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, - QColor(127, 127, 127)); - darkPalette.setColor(QPalette::Disabled, QPalette::Window, - QColor(65, 65, 67)); - darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, - QColor(80, 80, 80)); - darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, - QColor(127, 127, 127)); - darkPalette.setColor(QPalette::Disabled, QPalette::Text, - QColor(127, 127, 127)); -} - void MainWindow::initRateWidget() { RateApp *rateApp = new RateApp(this, "snap://whatsie", 5, 5, 1000 * 30); rateApp->setWindowTitle(QApplication::applicationName() + " | " + @@ -146,11 +97,11 @@ void MainWindow::initRateWidget() { } void MainWindow::runMinimized() { - this->minimizeAction->trigger(); + this->m_minimizeAction->trigger(); notify("Whatsie", "Whatsie started minimized in tray. Click to Open."); } -MainWindow::~MainWindow() { webEngine->deleteLater(); } +MainWindow::~MainWindow() { m_webEngine->deleteLater(); } void MainWindow::loadSchemaUrl(const QString &arg) { // https://faq.whatsapp.com/iphone/how-to-link-to-whatsapp-from-a-different-app/?lang=en @@ -172,45 +123,53 @@ void MainWindow::loadSchemaUrl(const QString &arg) { } void MainWindow::updatePageTheme() { - if (webEngine && webEngine->page()) { + if (m_webEngine && m_webEngine->page()) { - QString windowTheme = settings.value("windowTheme", "light").toString(); + QString windowTheme = SettingsManager::instance() + .settings() + .value("windowTheme", "light") + .toString(); if (windowTheme == "dark") { - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "localStorage['system-theme-mode']='false'; " "localStorage.theme='\"dark\"'; "); - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "document.querySelector('body').classList.add('" + windowTheme + "');"); } else { - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "localStorage['system-theme-mode']='false'; " "localStorage.theme='\"light\"'; "); - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "document.querySelector('body').classList.remove('dark');"); } } } void MainWindow::resizeEvent(QResizeEvent *event) { - if (lockWidget != nullptr) { - lockWidget->resize(event->size()); + if (m_lockWidget != nullptr) { + m_lockWidget->resize(event->size()); } } void MainWindow::updateWindowTheme() { - qApp->setStyle(QStyleFactory::create( - settings.value("widgetStyle", "Fusion").toString())); - if (settings.value("windowTheme", "light").toString() == "dark") { - qApp->setPalette(darkPalette); - webEngine->setStyleSheet( + qApp->setStyle(QStyleFactory::create(SettingsManager::instance() + .settings() + .value("widgetStyle", "Fusion") + .toString())); + if (SettingsManager::instance() + .settings() + .value("windowTheme", "light") + .toString() == "dark") { + qApp->setPalette(Theme::getDarkPalette()); + m_webEngine->setStyleSheet( "QWebEngineView{background:rgb(17, 27, 33);}"); // whatsapp dark color } else { - qApp->setPalette(lightPalette); - webEngine->setStyleSheet( + qApp->setPalette(Theme::getLightPalette()); + m_webEngine->setStyleSheet( "QWebEngineView{background:#F0F0F0;}"); // whatsapp light color } @@ -218,13 +177,13 @@ void MainWindow::updateWindowTheme() { foreach (QWidget *w, widgets) { w->setPalette(qApp->palette()); } - setNotificationPresenter(webEngine->page()->profile()); + setNotificationPresenter(m_webEngine->page()->profile()); - if (lockWidget != nullptr) { - lockWidget->setStyleSheet( + if (m_lockWidget != nullptr) { + m_lockWidget->setStyleSheet( "QWidget#login{background-color:palette(window)};" "QWidget#signup{background-color:palette(window)};"); - lockWidget->applyThemeQuirks(); + m_lockWidget->applyThemeQuirks(); } this->update(); } @@ -234,8 +193,8 @@ void MainWindow::handleCookieAdded(const QNetworkCookie &cookie) { } void MainWindow::forceLogOut() { - if (webEngine && webEngine->page()) { - webEngine->page()->runJavaScript( + if (m_webEngine && m_webEngine->page()) { + m_webEngine->page()->runJavaScript( "window.localStorage.clear();", [=](const QVariant &result) { qDebug() << result; }); } @@ -243,8 +202,8 @@ void MainWindow::forceLogOut() { bool MainWindow::isLoggedIn() { static bool loggedIn = false; - if (webEngine && webEngine->page()) { - webEngine->page()->runJavaScript( + if (m_webEngine && m_webEngine->page()) { + m_webEngine->page()->runJavaScript( "window.localStorage.getItem('last-wid-md')", [=](const QVariant &result) { qDebug() << Q_FUNC_INFO << result; @@ -261,8 +220,8 @@ bool MainWindow::isLoggedIn() { } void MainWindow::tryLogOut() { - if (webEngine && webEngine->page()) { - webEngine->page()->runJavaScript( + if (m_webEngine && m_webEngine->page()) { + m_webEngine->page()->runJavaScript( "document.querySelector(\"span[data-testid|='menu']\").click();" "document.querySelector(\"#side > header > div > div > span > div > " "span > div > ul > li:nth-child(4) > div\").click();" @@ -280,108 +239,116 @@ void MainWindow::tryLogOut() { void MainWindow::initSettingWidget() { int screenNumber = qApp->desktop()->screenNumber(this); - if (settingsWidget == nullptr) { - settingsWidget = new SettingsWidget( - this, screenNumber, webEngine->page()->profile()->cachePath(), - webEngine->page()->profile()->persistentStoragePath()); - settingsWidget->setWindowTitle(QApplication::applicationName() + - " | Settings"); - settingsWidget->setWindowFlags(Qt::Dialog); - - connect(settingsWidget, SIGNAL(initLock()), this, SLOT(initLock())); - connect(settingsWidget, SIGNAL(changeLockPassword()), this, - SLOT(changeLockPassword())); - connect(settingsWidget, SIGNAL(appAutoLockChanged()), this, - SLOT(appAutoLockChanged())); - - connect(settingsWidget, SIGNAL(updateWindowTheme()), this, - SLOT(updateWindowTheme())); - connect(settingsWidget, SIGNAL(updatePageTheme()), this, - SLOT(updatePageTheme())); - - connect(settingsWidget, &SettingsWidget::muteToggled, settingsWidget, - [=](const bool checked) { this->toggleMute(checked); }); - connect(settingsWidget, &SettingsWidget::userAgentChanged, settingsWidget, - [=](QString userAgentStr) { - if (webEngine->page()->profile()->httpUserAgent() != + if (m_settingsWidget == nullptr) { + m_settingsWidget = new SettingsWidget( + this, screenNumber, m_webEngine->page()->profile()->cachePath(), + m_webEngine->page()->profile()->persistentStoragePath()); + m_settingsWidget->setWindowTitle(QApplication::applicationName() + + " | Settings"); + m_settingsWidget->setWindowFlags(Qt::Dialog); + + connect(m_settingsWidget, &SettingsWidget::initLock, this, + &MainWindow::initLock); + connect(m_settingsWidget, &SettingsWidget::changeLockPassword, this, + &MainWindow::changeLockPassword); + connect(m_settingsWidget, &SettingsWidget::appAutoLockChanged, this, + &MainWindow::appAutoLockChanged); + + connect(m_settingsWidget, &SettingsWidget::updateWindowTheme, this, + &MainWindow::updateWindowTheme); + connect(m_settingsWidget, &SettingsWidget::updatePageTheme, this, + &MainWindow::updatePageTheme); + + connect(m_settingsWidget, &SettingsWidget::muteToggled, this, + &MainWindow::toggleMute); + connect(m_settingsWidget, &SettingsWidget::userAgentChanged, + m_settingsWidget, [=](QString userAgentStr) { + if (m_webEngine->page()->profile()->httpUserAgent() != userAgentStr) { - settings.setValue("useragent", userAgentStr); + SettingsManager::instance().settings().setValue("useragent", + userAgentStr); this->updateSettingsUserAgentWidget(); this->askToReloadPage(); } }); - connect(settingsWidget, &SettingsWidget::autoPlayMediaToggled, - settingsWidget, [=](bool checked) { + connect(m_settingsWidget, &SettingsWidget::autoPlayMediaToggled, + m_settingsWidget, [=](bool checked) { QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); auto *webSettings = profile->settings(); webSettings->setAttribute( QWebEngineSettings::PlaybackRequiresUserGesture, checked); - webEngine->page()->profile()->settings()->setAttribute( + m_webEngine->page()->profile()->settings()->setAttribute( QWebEngineSettings::PlaybackRequiresUserGesture, checked); }); - connect(settingsWidget, &SettingsWidget::dictChanged, settingsWidget, + connect(m_settingsWidget, &SettingsWidget::dictChanged, m_settingsWidget, [=](QString dictName) { - if (webEngine && webEngine->page()) { - webEngine->page()->profile()->setSpellCheckLanguages( + if (m_webEngine && m_webEngine->page()) { + m_webEngine->page()->profile()->setSpellCheckLanguages( QStringList() << dictName); } }); - connect(settingsWidget, &SettingsWidget::spellCheckChanged, settingsWidget, - [=](bool checked) { - if (webEngine && webEngine->page()) { - webEngine->page()->profile()->setSpellCheckEnabled(checked); + connect(m_settingsWidget, &SettingsWidget::spellCheckChanged, + m_settingsWidget, [=](bool checked) { + if (m_webEngine && m_webEngine->page()) { + m_webEngine->page()->profile()->setSpellCheckEnabled(checked); } }); - connect( - settingsWidget, &SettingsWidget::zoomChanged, settingsWidget, [=]() { - if (windowState() == Qt::WindowNoState) { - double currentFactor = settings.value("zoomFactor", 1.0).toDouble(); - webEngine->page()->setZoomFactor(currentFactor); - } - }); + connect(m_settingsWidget, &SettingsWidget::zoomChanged, m_settingsWidget, + [=]() { + if (windowState() == Qt::WindowNoState) { + double currentFactor = SettingsManager::instance() + .settings() + .value("zoomFactor", 1.0) + .toDouble(); + m_webEngine->page()->setZoomFactor(currentFactor); + } + }); - connect(settingsWidget, &SettingsWidget::zoomMaximizedChanged, - settingsWidget, [=]() { + connect(m_settingsWidget, &SettingsWidget::zoomMaximizedChanged, + m_settingsWidget, [=]() { if (windowState() == Qt::WindowMaximized || windowState() == Qt::WindowFullScreen) { - double currentFactor = settings + double currentFactor = SettingsManager::instance() + .settings() .value("zoomFactorMaximized", defaultZoomFactorMaximized) .toDouble(); - webEngine->page()->setZoomFactor(currentFactor); + m_webEngine->page()->setZoomFactor(currentFactor); } }); - connect(settingsWidget, &SettingsWidget::notificationPopupTimeOutChanged, - settingsWidget, - [=]() { setNotificationPresenter(webEngine->page()->profile()); }); + connect(m_settingsWidget, &SettingsWidget::notificationPopupTimeOutChanged, + m_settingsWidget, [=]() { + setNotificationPresenter(m_webEngine->page()->profile()); + }); - connect(settingsWidget, &SettingsWidget::notify, settingsWidget, + connect(m_settingsWidget, &SettingsWidget::notify, m_settingsWidget, [=](QString message) { notify("", message); }); - connect(settingsWidget, &SettingsWidget::updateFullWidthView, - settingsWidget, [=](bool checked) { - if (webEngine && webEngine->page()) { + connect(m_settingsWidget, &SettingsWidget::updateFullWidthView, + m_settingsWidget, [=](bool checked) { + if (m_webEngine && m_webEngine->page()) { if (checked) - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "document.querySelector('body').classList.add('whatsie-" "full-view');"); else - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "document.querySelector('body').classList.remove('" "whatsie-full-view');"); } }); - settingsWidget->appLockSetChecked( - settings.value("lockscreen", false).toBool()); + m_settingsWidget->appLockSetChecked(SettingsManager::instance() + .settings() + .value("lockscreen", false) + .toBool()); - // spell checker - settingsWidget->loadDictionaries(dictionaries); + m_settingsWidget->loadDictionaries(m_dictionaries); } } @@ -394,15 +361,15 @@ void MainWindow::changeEvent(QEvent *e) { void MainWindow::handleZoomOnWindowStateChange( const QWindowStateChangeEvent *ev) { - if (settingsWidget != nullptr) { + if (m_settingsWidget != nullptr) { if (ev->oldState().testFlag(Qt::WindowMaximized) && windowState().testFlag(Qt::WindowNoState)) { - emit settingsWidget->zoomChanged(); + emit m_settingsWidget->zoomChanged(); } else if ((!ev->oldState().testFlag(Qt::WindowMaximized) && windowState().testFlag(Qt::WindowMaximized)) || (!ev->oldState().testFlag(Qt::WindowMaximized) && windowState().testFlag(Qt::WindowFullScreen))) { - emit settingsWidget->zoomMaximizedChanged(); + emit m_settingsWidget->zoomMaximizedChanged(); } } } @@ -411,22 +378,27 @@ void MainWindow::handleZoom() { if (windowState().testFlag(Qt::WindowMaximized) || windowState().testFlag(Qt::WindowFullScreen)) { double currentFactor = - settings.value("zoomFactorMaximized", defaultZoomFactorMaximized) + SettingsManager::instance() + .settings() + .value("zoomFactorMaximized", defaultZoomFactorMaximized) .toDouble(); - webEngine->page()->setZoomFactor(currentFactor); + m_webEngine->page()->setZoomFactor(currentFactor); } else if (windowState().testFlag(Qt::WindowNoState)) { - double currentFactor = settings.value("zoomFactor", 1.0).toDouble(); - webEngine->page()->setZoomFactor(currentFactor); + double currentFactor = SettingsManager::instance() + .settings() + .value("zoomFactor", 1.0) + .toDouble(); + m_webEngine->page()->setZoomFactor(currentFactor); } } void MainWindow::lockApp() { - if (lockWidget != nullptr && lockWidget->getIsLocked()) + if (m_lockWidget != nullptr && m_lockWidget->getIsLocked()) return; - if (settings.value("asdfg").isValid()) { + if (SettingsManager::instance().settings().value("asdfg").isValid()) { initLock(); - lockWidget->lock_app(); + m_lockWidget->lock_app(); } else { int ret = QMessageBox::information( this, tr(QApplication::applicationName().toUtf8()), @@ -441,13 +413,13 @@ void MainWindow::lockApp() { } void MainWindow::toggleTheme() { - if (settingsWidget != nullptr) { - settingsWidget->toggleTheme(); + if (m_settingsWidget != nullptr) { + m_settingsWidget->toggleTheme(); } } void MainWindow::showSettings(bool isAskedByCLI) { - if (lockWidget && lockWidget->getIsLocked()) { + if (m_lockWidget && m_lockWidget->getIsLocked()) { QString error = tr("Unlock to access Settings."); if (isAskedByCLI) { this->notify(QApplication::applicationName() + "| Error", error); @@ -459,28 +431,28 @@ void MainWindow::showSettings(bool isAskedByCLI) { return; } - if (webEngine == nullptr) { + if (m_webEngine == nullptr) { QMessageBox::critical( this, QApplication::applicationName() + "| Error", "Unable to initialize settings module.\nWebengine is not initialized."); return; } - if (!settingsWidget->isVisible()) { + if (!m_settingsWidget->isVisible()) { this->updateSettingsUserAgentWidget(); - settingsWidget->refresh(); + m_settingsWidget->refresh(); int screenNumber = qApp->desktop()->screenNumber(this); QRect screenRect = QGuiApplication::screens().at(screenNumber)->geometry(); - if (!screenRect.contains(settingsWidget->pos())) { - settingsWidget->move(screenRect.center() - - settingsWidget->rect().center()); + if (!screenRect.contains(m_settingsWidget->pos())) { + m_settingsWidget->move(screenRect.center() - + m_settingsWidget->rect().center()); } - settingsWidget->show(); + m_settingsWidget->show(); } } void MainWindow::updateSettingsUserAgentWidget() { - settingsWidget->updateDefaultUAButton( - webEngine->page()->profile()->httpUserAgent()); + m_settingsWidget->updateDefaultUAButton( + m_webEngine->page()->profile()->httpUserAgent()); } void MainWindow::askToReloadPage() { @@ -497,22 +469,29 @@ void MainWindow::showAbout() { about->setWindowFlag(Qt::Dialog); about->setMinimumSize(about->sizeHint()); about->adjustSize(); - about->setAttribute(Qt::WA_DeleteOnClose); + about->setAttribute(Qt::WA_DeleteOnClose, true); about->show(); } void MainWindow::closeEvent(QCloseEvent *event) { - settings.setValue("geometry", saveGeometry()); + SettingsManager::instance().settings().setValue("geometry", saveGeometry()); getPageTheme(); - QTimer::singleShot(500, settingsWidget, [=]() { settingsWidget->refresh(); }); + QTimer::singleShot(500, m_settingsWidget, + [=]() { m_settingsWidget->refresh(); }); if (QSystemTrayIcon::isSystemTrayAvailable() && - settings.value("closeButtonActionCombo", 0).toInt() == 0) { + SettingsManager::instance() + .settings() + .value("closeButtonActionCombo", 0) + .toInt() == 0) { this->hide(); event->ignore(); - if (settings.value("firstrun_tray", true).toBool()) { + if (SettingsManager::instance() + .settings() + .value("firstrun_tray", true) + .toBool()) { notify(QApplication::applicationName(), "Minimized to system tray."); - settings.setValue("firstrun_tray", false); + SettingsManager::instance().settings().setValue("firstrun_tray", false); } return; } @@ -523,28 +502,38 @@ void MainWindow::closeEvent(QCloseEvent *event) { void MainWindow::notify(QString title, QString message) { - if (settings.value("disableNotificationPopups", false).toBool() == true) { + if (SettingsManager::instance() + .settings() + .value("disableNotificationPopups", false) + .toBool() == true) { return; } if (title.isEmpty()) title = QApplication::applicationName(); - if (settings.value("notificationCombo", 1).toInt() == 0 && - trayIcon != nullptr) { - trayIcon->showMessage(title, message, - QIcon(":/icons/app/notification/whatsie-notify.png"), - settings.value("notificationTimeOut", 9000).toInt()); - trayIcon->disconnect(trayIcon, SIGNAL(messageClicked())); - connect(trayIcon, &QSystemTrayIcon::messageClicked, trayIcon, [=]() { - if (windowState().testFlag(Qt::WindowMinimized) || - !windowState().testFlag(Qt::WindowActive)) { - activateWindow(); - this->show(); - } - }); + if (SettingsManager::instance() + .settings() + .value("notificationCombo", 1) + .toInt() == 0 && + m_systemTrayIcon != nullptr) { + m_systemTrayIcon->showMessage( + title, message, QIcon(":/icons/app/notification/whatsie-notify.png"), + SettingsManager::instance() + .settings() + .value("notificationTimeOut", 9000) + .toInt()); + m_systemTrayIcon->disconnect(m_systemTrayIcon, SIGNAL(messageClicked())); + connect(m_systemTrayIcon, &QSystemTrayIcon::messageClicked, + m_systemTrayIcon, [=]() { + if (windowState().testFlag(Qt::WindowMinimized) || + !windowState().testFlag(Qt::WindowActive)) { + activateWindow(); + this->show(); + } + }); } else { - auto popup = new NotificationPopup(webEngine); + auto popup = new NotificationPopup(m_webEngine); connect(popup, &NotificationPopup::notification_clicked, popup, [=]() { if (windowState().testFlag(Qt::WindowMinimized) || !windowState().testFlag(Qt::WindowActive) || this->isHidden()) { @@ -564,98 +553,102 @@ void MainWindow::notify(QString title, QString message) { void MainWindow::createActions() { - openUrlAction = new QAction("New Chat", this); - openUrlAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_N)); - connect(openUrlAction, &QAction::triggered, this, &MainWindow::newChat); - addAction(openUrlAction); + m_openUrlAction = new QAction("New Chat", this); + m_openUrlAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_N)); + connect(m_openUrlAction, &QAction::triggered, this, &MainWindow::newChat); + addAction(m_openUrlAction); - fullscreenAction = new QAction(tr("Fullscreen"), this); - fullscreenAction->setShortcut(Qt::Key_F11); - connect(fullscreenAction, &QAction::triggered, fullscreenAction, + m_fullscreenAction = new QAction(tr("Fullscreen"), this); + m_fullscreenAction->setShortcut(Qt::Key_F11); + connect(m_fullscreenAction, &QAction::triggered, m_fullscreenAction, [=]() { setWindowState(windowState() ^ Qt::WindowFullScreen); }); - addAction(fullscreenAction); + addAction(m_fullscreenAction); - minimizeAction = new QAction(tr("Mi&nimize to tray"), this); - connect(minimizeAction, &QAction::triggered, this, &QMainWindow::hide); - addAction(minimizeAction); + m_minimizeAction = new QAction(tr("Mi&nimize to tray"), this); + connect(m_minimizeAction, &QAction::triggered, this, &QMainWindow::hide); + addAction(m_minimizeAction); QShortcut *minimizeShortcut = new QShortcut( QKeySequence(Qt::Modifier::CTRL + Qt::Key_W), this, SLOT(hide())); minimizeShortcut->setAutoRepeat(false); - restoreAction = new QAction(tr("&Restore"), this); - connect(restoreAction, &QAction::triggered, this, &QMainWindow::show); - addAction(restoreAction); - - reloadAction = new QAction(tr("Re&load"), this); - reloadAction->setShortcut(Qt::Key_F5); - connect(reloadAction, &QAction::triggered, this, [=] { this->doReload(); }); - addAction(reloadAction); - - lockAction = new QAction(tr("Loc&k"), this); - lockAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_L)); - connect(lockAction, &QAction::triggered, this, &MainWindow::lockApp); - addAction(lockAction); - - settingsAction = new QAction(tr("&Settings"), this); - settingsAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_P)); - connect(settingsAction, &QAction::triggered, this, &MainWindow::showSettings); - addAction(settingsAction); - - toggleThemeAction = new QAction(tr("&Toggle theme"), this); - toggleThemeAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_T)); - connect(toggleThemeAction, &QAction::triggered, this, + m_restoreAction = new QAction(tr("&Restore"), this); + connect(m_restoreAction, &QAction::triggered, this, &QMainWindow::show); + addAction(m_restoreAction); + + m_reloadAction = new QAction(tr("Re&load"), this); + m_reloadAction->setShortcut(Qt::Key_F5); + connect(m_reloadAction, &QAction::triggered, this, + [=]() { this->doReload(); }); + addAction(m_reloadAction); + + m_lockAction = new QAction(tr("Loc&k"), this); + m_lockAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_L)); + connect(m_lockAction, &QAction::triggered, this, &MainWindow::lockApp); + addAction(m_lockAction); + + m_settingsAction = new QAction(tr("&Settings"), this); + m_settingsAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_P)); + connect(m_settingsAction, &QAction::triggered, this, + &MainWindow::showSettings); + addAction(m_settingsAction); + + m_toggleThemeAction = new QAction(tr("&Toggle theme"), this); + m_toggleThemeAction->setShortcut( + QKeySequence(Qt::Modifier::CTRL + Qt::Key_T)); + connect(m_toggleThemeAction, &QAction::triggered, this, &MainWindow::toggleTheme); - addAction(toggleThemeAction); + addAction(m_toggleThemeAction); - aboutAction = new QAction(tr("&About"), this); - connect(aboutAction, &QAction::triggered, this, &MainWindow::showAbout); + m_aboutAction = new QAction(tr("&About"), this); + connect(m_aboutAction, &QAction::triggered, this, &MainWindow::showAbout); - quitAction = new QAction(tr("&Quit"), this); - quitAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_Q)); - connect(quitAction, &QAction::triggered, this, &MainWindow::quitApp); - addAction(quitAction); + m_quitAction = new QAction(tr("&Quit"), this); + m_quitAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_Q)); + connect(m_quitAction, &QAction::triggered, this, &MainWindow::quitApp); + addAction(m_quitAction); } void MainWindow::quitApp() { - settings.setValue("geometry", saveGeometry()); + SettingsManager::instance().settings().setValue("geometry", saveGeometry()); getPageTheme(); - QTimer::singleShot(500, &settings, [=]() { - settings.setValue("firstrun_tray", true); + QTimer::singleShot(500, this, [=]() { + SettingsManager::instance().settings().setValue("firstrun_tray", true); qApp->quit(); }); } void MainWindow::createTrayIcon() { - trayIconMenu = new QMenu(this); - trayIconMenu->setObjectName("trayIconMenu"); - trayIconMenu->addAction(minimizeAction); - trayIconMenu->addAction(restoreAction); - trayIconMenu->addSeparator(); - trayIconMenu->addAction(reloadAction); - trayIconMenu->addAction(lockAction); - trayIconMenu->addSeparator(); - trayIconMenu->addAction(openUrlAction); - trayIconMenu->addAction(toggleThemeAction); - trayIconMenu->addAction(settingsAction); - trayIconMenu->addAction(aboutAction); - trayIconMenu->addSeparator(); - trayIconMenu->addAction(quitAction); - - trayIcon = new QSystemTrayIcon(trayIconNormal, this); - trayIcon->setContextMenu(trayIconMenu); - connect(trayIconMenu, SIGNAL(aboutToShow()), this, SLOT(checkWindowState())); - - trayIcon->show(); - - connect(trayIcon, &QSystemTrayIcon::messageClicked, this, + m_trayIconMenu = new QMenu(this); + m_trayIconMenu->setObjectName("trayIconMenu"); + m_trayIconMenu->addAction(m_minimizeAction); + m_trayIconMenu->addAction(m_restoreAction); + m_trayIconMenu->addSeparator(); + m_trayIconMenu->addAction(m_reloadAction); + m_trayIconMenu->addAction(m_lockAction); + m_trayIconMenu->addSeparator(); + m_trayIconMenu->addAction(m_openUrlAction); + m_trayIconMenu->addAction(m_toggleThemeAction); + m_trayIconMenu->addAction(m_settingsAction); + m_trayIconMenu->addAction(m_aboutAction); + m_trayIconMenu->addSeparator(); + m_trayIconMenu->addAction(m_quitAction); + + m_systemTrayIcon = new QSystemTrayIcon(m_trayIconNormal, this); + m_systemTrayIcon->setContextMenu(m_trayIconMenu); + connect(m_trayIconMenu, &QMenu::aboutToShow, this, + &MainWindow::checkWindowState); + + m_systemTrayIcon->show(); + + connect(m_systemTrayIcon, &QSystemTrayIcon::messageClicked, this, &MainWindow::messageClicked); - connect(trayIcon, &QSystemTrayIcon::activated, this, + connect(m_systemTrayIcon, &QSystemTrayIcon::activated, this, &MainWindow::iconActivated); // enable show shortcuts in menu if (qApp->styleHints()->showShortcutsInContextMenus()) { - foreach (QAction *action, trayIconMenu->actions()) { + foreach (QAction *action, m_trayIconMenu->actions()) { action->setShortcutVisibleInContextMenu(true); } } @@ -663,58 +656,64 @@ void MainWindow::createTrayIcon() { void MainWindow::initLock() { - if (lockWidget == nullptr) { - lockWidget = new Lock(this); - lockWidget->setObjectName("lockWidget"); + if (m_lockWidget == nullptr) { + m_lockWidget = new Lock(this); + m_lockWidget->setObjectName("lockWidget"); - lockWidget->setWindowFlags(Qt::Widget); - lockWidget->setStyleSheet( + m_lockWidget->setWindowFlags(Qt::Widget); + m_lockWidget->setStyleSheet( "QWidget#login{background-color:palette(window)};" "QWidget#signup{background-color:palette(window)}"); - lockWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + m_lockWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - connect(lockWidget, &Lock::passwordNotSet, settingsWidget, [=]() { - settings.setValue("lockscreen", false); - settingsWidget->appLockSetChecked(false); + connect(m_lockWidget, &Lock::passwordNotSet, m_settingsWidget, [=]() { + SettingsManager::instance().settings().setValue("lockscreen", false); + m_settingsWidget->appLockSetChecked(false); }); - connect(lockWidget, &Lock::unLocked, [=]() { + connect(m_lockWidget, &Lock::unLocked, [=]() { // unlock event }); - connect(lockWidget, &Lock::passwordSet, settingsWidget, [=]() { - if (settings.value("asdfg").isValid()) { - settingsWidget->setCurrentPasswordText(QByteArray::fromBase64( - settings.value("asdfg").toString().toUtf8())); + connect(m_lockWidget, &Lock::passwordSet, m_settingsWidget, [=]() { + if (SettingsManager::instance().settings().value("asdfg").isValid()) { + m_settingsWidget->setCurrentPasswordText( + QByteArray::fromBase64(SettingsManager::instance() + .settings() + .value("asdfg") + .toString() + .toUtf8())); } else { - settingsWidget->setCurrentPasswordText("Require setup"); + m_settingsWidget->setCurrentPasswordText("Require setup"); } - settingsWidget->appLockSetChecked( - settings.value("lockscreen", false).toBool()); + m_settingsWidget->appLockSetChecked(SettingsManager::instance() + .settings() + .value("lockscreen", false) + .toBool()); }); - lockWidget->applyThemeQuirks(); + m_lockWidget->applyThemeQuirks(); } - lockWidget->setGeometry(this->rect()); + m_lockWidget->setGeometry(this->rect()); - if (settings.value("lockscreen").toBool()) { - if (settings.value("asdfg").isValid()) { - lockWidget->lock_app(); + if (SettingsManager::instance().settings().value("lockscreen").toBool()) { + if (SettingsManager::instance().settings().value("asdfg").isValid()) { + m_lockWidget->lock_app(); } else { - lockWidget->signUp(); + m_lockWidget->signUp(); } - lockWidget->show(); + m_lockWidget->show(); } else { - lockWidget->hide(); + m_lockWidget->hide(); } updateWindowTheme(); } void MainWindow::changeLockPassword() { - settings.remove("asdfg"); - settingsWidget->appLockSetChecked(false); - settingsWidget->autoAppLockSetChecked(false); - settingsWidget->updateAppLockPasswordViewer(); + SettingsManager::instance().settings().remove("asdfg"); + m_settingsWidget->appLockSetChecked(false); + m_settingsWidget->autoAppLockSetChecked(false); + m_settingsWidget->updateAppLockPasswordViewer(); tryLogOut(); QTimer::singleShot(1000, this, [=]() { if (isLoggedIn()) { @@ -727,16 +726,22 @@ void MainWindow::changeLockPassword() { } void MainWindow::appAutoLockChanged() { - bool enabled = settings.value("appAutoLocking", defaultAppAutoLock).toBool(); + bool enabled = SettingsManager::instance() + .settings() + .value("appAutoLocking", defaultAppAutoLock) + .toBool(); if (enabled) { - autoLockEventFilter->setTimeoutmillis( - settings.value("autoLockDuration", defaultAppAutoLockDuration).toInt() * + m_autoLockEventFilter->setTimeoutmillis( + SettingsManager::instance() + .settings() + .value("autoLockDuration", defaultAppAutoLockDuration) + .toInt() * 1000); - qApp->installEventFilter(autoLockEventFilter); - autoLockEventFilter->resetTimer(); + qApp->installEventFilter(m_autoLockEventFilter); + m_autoLockEventFilter->resetTimer(); } else { - autoLockEventFilter->stopTimer(); - qApp->removeEventFilter(autoLockEventFilter); + m_autoLockEventFilter->stopTimer(); + qApp->removeEventFilter(m_autoLockEventFilter); } } @@ -752,7 +757,7 @@ void MainWindow::checkWindowState() { menu->actions().at(0)->setDisabled(true); menu->actions().at(1)->setDisabled(false); } - if (lockWidget && lockWidget->getIsLocked()) { + if (m_lockWidget && m_lockWidget->getIsLocked()) { menu->actions().at(4)->setDisabled(true); } else { menu->actions().at(4)->setDisabled(false); @@ -763,13 +768,21 @@ void MainWindow::checkWindowState() { void MainWindow::initGlobalWebProfile() { QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); - profile->setHttpUserAgent( - settings.value("useragent", defaultUserAgentStr).toString()); + profile->setHttpUserAgent(SettingsManager::instance() + .settings() + .value("useragent", defaultUserAgentStr) + .toString()); QStringList dict_names; - dict_names.append(settings.value("sc_dict", "en-US").toString()); - - profile->setSpellCheckEnabled(settings.value("sc_enabled", true).toBool()); + dict_names.append(SettingsManager::instance() + .settings() + .value("sc_dict", "en-US") + .toString()); + + profile->setSpellCheckEnabled(SettingsManager::instance() + .settings() + .value("sc_enabled", true) + .toBool()); profile->setSpellCheckLanguages(dict_names); auto *webSettings = profile->settings(); @@ -794,7 +807,10 @@ void MainWindow::initGlobalWebProfile() { webSettings->setAttribute(QWebEngineSettings::JavascriptCanAccessClipboard, true); webSettings->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture, - settings.value("autoPlayMedia", false).toBool()); + SettingsManager::instance() + .settings() + .value("autoPlayMedia", false) + .toBool()); } void MainWindow::createWebEngine() { @@ -806,18 +822,18 @@ void MainWindow::createWebEngine() { widgetSize.setHorizontalStretch(1); widgetSize.setVerticalStretch(1); - dictionaries = Dictionaries::GetDictionaries(); + m_dictionaries = Dictionaries::GetDictionaries(); - WebView *webEngineView = new WebView(this, dictionaries); + WebView *webEngineView = new WebView(this, m_dictionaries); setCentralWidget(webEngineView); webEngineView->setSizePolicy(widgetSize); webEngineView->show(); - this->webEngine = webEngineView; + this->m_webEngine = webEngineView; - webEngineView->addAction(minimizeAction); - webEngineView->addAction(lockAction); - webEngineView->addAction(quitAction); + webEngineView->addAction(m_minimizeAction); + webEngineView->addAction(m_lockAction); + webEngineView->addAction(m_quitAction); createWebPage(false); } @@ -834,55 +850,69 @@ const QIcon MainWindow::getTrayIcon(const int ¬ificationCount) const { } void MainWindow::createWebPage(bool offTheRecord) { - if (offTheRecord && !otrProfile) { - otrProfile.reset(new QWebEngineProfile); + if (offTheRecord && !m_otrProfile) { + m_otrProfile.reset(new QWebEngineProfile); } auto profile = - offTheRecord ? otrProfile.get() : QWebEngineProfile::defaultProfile(); + offTheRecord ? m_otrProfile.get() : QWebEngineProfile::defaultProfile(); QStringList dict_names; - dict_names.append(settings.value("sc_dict", "en-US").toString()); - - profile->setSpellCheckEnabled(settings.value("sc_enabled", true).toBool()); + dict_names.append(SettingsManager::instance() + .settings() + .value("sc_dict", "en-US") + .toString()); + + profile->setSpellCheckEnabled(SettingsManager::instance() + .settings() + .value("sc_enabled", true) + .toBool()); profile->setSpellCheckLanguages(dict_names); - profile->setHttpUserAgent( - settings.value("useragent", defaultUserAgentStr).toString()); + profile->setHttpUserAgent(SettingsManager::instance() + .settings() + .value("useragent", defaultUserAgentStr) + .toString()); setNotificationPresenter(profile); - QWebEnginePage *page = new WebEnginePage(profile, webEngine); - if (settings.value("windowTheme", "light").toString() == "dark") { + QWebEnginePage *page = new WebEnginePage(profile, m_webEngine); + if (SettingsManager::instance() + .settings() + .value("windowTheme", "light") + .toString() == "dark") { page->setBackgroundColor(QColor(17, 27, 33)); // whatsapp dark bg color } else { page->setBackgroundColor(QColor(240, 240, 240)); // whatsapp light bg color } - webEngine->setPage(page); + m_webEngine->setPage(page); // page should be set parent of profile to prevent // Release of profile requested but WebEnginePage still not deleted. Expect // troubles ! profile->setParent(page); - auto randomValue = QRandomGenerator::global()->generateDouble() * 300; + auto randomValue = QRandomGenerator::global()->generateDouble() * 300.0; page->setUrl( QUrl("https://web.whatsapp.com?v=" + QString::number(randomValue))); connect(profile, &QWebEngineProfile::downloadRequested, - &downloadManagerWidget, &DownloadManagerWidget::downloadRequested); + &m_downloadManagerWidget, &DownloadManagerWidget::downloadRequested); - connect(page, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this, - SLOT(fullScreenRequested(QWebEngineFullScreenRequest))); + connect(page, &QWebEnginePage::fullScreenRequested, this, + &MainWindow::fullScreenRequested); - double currentFactor = settings.value("zoomFactor", 1.0).toDouble(); - webEngine->page()->setZoomFactor(currentFactor); + double currentFactor = SettingsManager::instance() + .settings() + .value("zoomFactor", 1.0) + .toDouble(); + m_webEngine->page()->setZoomFactor(currentFactor); } void MainWindow::setNotificationPresenter(QWebEngineProfile *profile) { - auto *op = webEngine->findChild<NotificationPopup *>("engineNotifier"); + auto *op = m_webEngine->findChild<NotificationPopup *>("engineNotifier"); if (op != nullptr) { op->close(); op->deleteLater(); } - auto popup = new NotificationPopup(webEngine); + auto popup = new NotificationPopup(m_webEngine); popup->setObjectName("engineNotifier"); connect(popup, &NotificationPopup::notification_clicked, popup, [=]() { if (windowState().testFlag(Qt::WindowMinimized) || @@ -894,25 +924,36 @@ void MainWindow::setNotificationPresenter(QWebEngineProfile *profile) { profile->setNotificationPresenter( [=](std::unique_ptr<QWebEngineNotification> notification) { - if (settings.value("disableNotificationPopups", false).toBool() == - true) { + if (SettingsManager::instance() + .settings() + .value("disableNotificationPopups", false) + .toBool() == true) { return; } - if (settings.value("notificationCombo", 1).toInt() == 0 && - trayIcon != nullptr) { + if (SettingsManager::instance() + .settings() + .value("notificationCombo", 1) + .toInt() == 0 && + m_systemTrayIcon != nullptr) { QIcon icon(QPixmap::fromImage(notification->icon())); - trayIcon->showMessage( - notification->title(), notification->message(), icon, - settings.value("notificationTimeOut", 9000).toInt()); - trayIcon->disconnect(trayIcon, SIGNAL(messageClicked())); - connect(trayIcon, &QSystemTrayIcon::messageClicked, trayIcon, [=]() { - if (windowState().testFlag(Qt::WindowMinimized) || - !windowState().testFlag(Qt::WindowActive) || this->isHidden()) { - this->show(); - setWindowState((windowState() & ~Qt::WindowMinimized) | - Qt::WindowActive); - } - }); + m_systemTrayIcon->showMessage(notification->title(), + notification->message(), icon, + SettingsManager::instance() + .settings() + .value("notificationTimeOut", 9000) + .toInt()); + m_systemTrayIcon->disconnect(m_systemTrayIcon, + SIGNAL(messageClicked())); + connect(m_systemTrayIcon, &QSystemTrayIcon::messageClicked, + m_systemTrayIcon, [=]() { + if (windowState().testFlag(Qt::WindowMinimized) || + !windowState().testFlag(Qt::WindowActive) || + this->isHidden()) { + this->show(); + setWindowState((windowState() & ~Qt::WindowMinimized) | + Qt::WindowActive); + } + }); } else { popup->setMinimumWidth(300); @@ -924,39 +965,39 @@ void MainWindow::setNotificationPresenter(QWebEngineProfile *profile) { void MainWindow::fullScreenRequested(QWebEngineFullScreenRequest request) { if (request.toggleOn()) { - webEngine->showFullScreen(); + m_webEngine->showFullScreen(); this->showFullScreen(); request.accept(); } else { - webEngine->showNormal(); + m_webEngine->showNormal(); this->show(); request.accept(); } } -void MainWindow::handleWebViewTitleChanged(QString title) { +void MainWindow::handleWebViewTitleChanged(const QString &title) { setWindowTitle(QApplication::applicationName() + ": " + title); - if (notificationsTitleRegExp.exactMatch(title)) { - if (notificationsTitleRegExp.capturedTexts().isEmpty() == false) { - QString capturedTitle = - notificationsTitleRegExp.capturedTexts().constFirst(); - unreadMessageCountRegExp.setMinimal(true); - if (unreadMessageCountRegExp.indexIn(capturedTitle) != -1) { - QString unreadMessageCountStr = - unreadMessageCountRegExp.capturedTexts().constLast(); - int unreadMessageCount = unreadMessageCountStr.toInt(); - - restoreAction->setText( - tr("Restore") + " | " + unreadMessageCountStr + " " + - (unreadMessageCount > 1 ? tr("messages") : tr("message"))); - trayIcon->setIcon(getTrayIcon(unreadMessageCount)); - setWindowIcon(getTrayIcon(unreadMessageCount)); - } + QRegularExpressionMatch match = m_notificationsTitleRegExp.match(title); + if (match.hasMatch()) { + QString capturedTitle = match.captured(0); + m_unreadMessageCountRegExp.setPatternOptions( + QRegularExpression::DontCaptureOption); + QRegularExpressionMatch countMatch = + m_unreadMessageCountRegExp.match(capturedTitle); + if (countMatch.hasMatch()) { + QString unreadMessageCountStr = countMatch.captured(0); + int unreadMessageCount = unreadMessageCountStr.toInt(); + + m_restoreAction->setText( + tr("Restore") + " | " + unreadMessageCountStr + " " + + (unreadMessageCount > 1 ? tr("messages") : tr("message"))); + m_systemTrayIcon->setIcon(getTrayIcon(unreadMessageCount)); + setWindowIcon(getTrayIcon(unreadMessageCount)); } } else { - trayIcon->setIcon(trayIconNormal); - setWindowIcon(trayIconNormal); + m_systemTrayIcon->setIcon(m_trayIconNormal); + setWindowIcon(m_trayIconNormal); } } @@ -966,35 +1007,38 @@ void MainWindow::handleLoadFinished(bool loaded) { checkLoadedCorrectly(); updatePageTheme(); handleZoom(); - - if (settingsWidget != nullptr) { - settingsWidget->refresh(); + if (m_settingsWidget != nullptr) { + m_settingsWidget->refresh(); } } } void MainWindow::checkLoadedCorrectly() { - if (webEngine && webEngine->page()) { + if (m_webEngine && m_webEngine->page()) { // test 1 based on the class name of body tag of the page - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "document.querySelector('body').className", [this](const QVariant &result) { if (result.toString().contains("page-version", Qt::CaseInsensitive)) { qDebug() << "Test 1 found" << result.toString(); - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "document.getElementsByTagName('body')[0].innerText = ''"); loadingQuirk("test1"); - } else if (webEngine->title().contains("Error", - Qt::CaseInsensitive)) { - utils::delete_cache(webEngine->page()->profile()->cachePath()); - utils::delete_cache( - webEngine->page()->profile()->persistentStoragePath()); - settings.setValue("useragent", defaultUserAgentStr); - utils::DisplayExceptionErrorDialog( + } else if (m_webEngine->title().contains("Error", + Qt::CaseInsensitive)) { + Utils::delete_cache(m_webEngine->page()->profile()->cachePath()); + Utils::delete_cache( + m_webEngine->page()->profile()->persistentStoragePath()); + SettingsManager::instance().settings().setValue( + "useragent", defaultUserAgentStr); + Utils::DisplayExceptionErrorDialog( "test1 handleWebViewTitleChanged(title) title: Error, " "Resetting UA, Quiting!\nUA: " + - settings.value("useragent", "DefaultUA").toString()); - quitAction->trigger(); + SettingsManager::instance() + .settings() + .value("useragent", "DefaultUA") + .toString()); + m_quitAction->trigger(); } else { qDebug() << "Test 1 loaded correctly, value:" << result.toString(); } @@ -1002,24 +1046,29 @@ void MainWindow::checkLoadedCorrectly() { } } -void MainWindow::loadingQuirk(QString test) { +void MainWindow::loadingQuirk(const QString &test) { // contains ug message apply quirk - if (correctlyLoaderRetries > -1) { + if (m_correctlyLoadedRetries > -1) { qWarning() << test << "checkLoadedCorrectly()/loadingQuirk()/doReload()" - << correctlyLoaderRetries; + << m_correctlyLoadedRetries; doReload(false, false, true); - correctlyLoaderRetries--; + m_correctlyLoadedRetries--; } else { - utils::delete_cache(webEngine->page()->profile()->cachePath()); - utils::delete_cache(webEngine->page()->profile()->persistentStoragePath()); - settings.setValue("useragent", defaultUserAgentStr); - utils::DisplayExceptionErrorDialog( + Utils::delete_cache(m_webEngine->page()->profile()->cachePath()); + Utils::delete_cache( + m_webEngine->page()->profile()->persistentStoragePath()); + SettingsManager::instance().settings().setValue("useragent", + defaultUserAgentStr); + Utils::DisplayExceptionErrorDialog( test + " checkLoadedCorrectly()/loadingQuirk() reload retries 0, Resetting " "UA, Quiting!\nUA: " + - settings.value("useragent", "DefaultUA").toString()); + SettingsManager::instance() + .settings() + .value("useragent", "DefaultUA") + .toString()); - quitAction->trigger(); + m_quitAction->trigger(); } } @@ -1027,8 +1076,10 @@ void MainWindow::loadingQuirk(QString test) { // manager void MainWindow::handleDownloadRequested(QWebEngineDownloadItem *download) { QFileDialog dialog(this); - bool usenativeFileDialog = - settings.value("useNativeFileDialog", false).toBool(); + bool usenativeFileDialog = SettingsManager::instance() + .settings() + .value("useNativeFileDialog", false) + .toBool(); if (usenativeFileDialog == false) { dialog.setOption(QFileDialog::DontUseNativeDialog, true); @@ -1046,7 +1097,10 @@ void MainWindow::handleDownloadRequested(QWebEngineDownloadItem *download) { } void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) { - if (settings.value("minimizeOnTrayIconClick", false).toBool() == false || + if (SettingsManager::instance() + .settings() + .value("minimizeOnTrayIconClick", false) + .toBool() == false || reason == QSystemTrayIcon::Context) return; if (isVisible()) { @@ -1066,8 +1120,8 @@ void MainWindow::messageClicked() { void MainWindow::doAppReload() { - if (webEngine->page()) { - webEngine->page()->disconnect(); + if (m_webEngine->page()) { + m_webEngine->page()->disconnect(); } createWebPage(false); } @@ -1083,13 +1137,13 @@ void MainWindow::newChat() { } } -void MainWindow::triggerNewChat(QString phone, QString text) { +void MainWindow::triggerNewChat(const QString &phone, const QString &text) { static QString phoneStr, textStr; - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( "openNewChatWhatsieDefined()", [this, phone, text](const QVariant &result) { if (result.toString().contains("true")) { - webEngine->page()->runJavaScript( + m_webEngine->page()->runJavaScript( QString("openNewChatWhatsie(\"%1\",\"%2\")").arg(phone, text)); } else { // create send url equivalent @@ -1097,7 +1151,7 @@ void MainWindow::triggerNewChat(QString phone, QString text) { textStr = text.isEmpty() ? "" : "text=" + text; QString urlStr = "https://web.whatsapp.com/send?" + phoneStr + "&" + textStr; - webEngine->page()->load(QUrl(urlStr)); + m_webEngine->page()->load(QUrl(urlStr)); } this->alreadyRunning(); }); @@ -1106,10 +1160,10 @@ void MainWindow::triggerNewChat(QString phone, QString text) { void MainWindow::doReload(bool byPassCache, bool isAskedByCLI, bool byLoadingQuirk) { if (byLoadingQuirk) { - webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, - byPassCache); + m_webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, + byPassCache); } else { - if (lockWidget && !lockWidget->getIsLocked()) { + if (m_lockWidget && !m_lockWidget->getIsLocked()) { this->notify(QApplication::applicationName(), QObject::tr("Reloading...")); } else { @@ -1123,40 +1177,41 @@ void MainWindow::doReload(bool byPassCache, bool isAskedByCLI, this->show(); return; } - webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, - byPassCache); + m_webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, + byPassCache); } } void MainWindow::toggleMute(const bool &checked) { - webEngine->page()->setAudioMuted(checked); + m_webEngine->page()->setAudioMuted(checked); } // get value of page theme when page is loaded -QString MainWindow::getPageTheme() { +QString MainWindow::getPageTheme() const { static QString theme = "web"; // implies light - if (webEngine && webEngine->page()) { - webEngine->page()->runJavaScript( + if (m_webEngine && m_webEngine->page()) { + m_webEngine->page()->runJavaScript( "document.querySelector('body').className;", - [this](const QVariant &result) { + [=](const QVariant &result) { theme = result.toString(); theme.contains("dark") ? theme = "dark" : theme = "light"; - settings.setValue("windowTheme", theme); + SettingsManager::instance().settings().setValue("windowTheme", theme); }); } return theme; } void MainWindow::tryLock() { - if (settings.value("asdfg").isValid()) { + if (SettingsManager::instance().settings().value("asdfg").isValid()) { initLock(); return; } - if (settings.value("asdfg").isValid() == false) { - settings.setValue("lockscreen", false); - settings.setValue("appAutoLocking", false); - settingsWidget->appAutoLockingSetChecked(false); - settingsWidget->appLockSetChecked(false); + if (SettingsManager::instance().settings().value("asdfg").isValid() == + false) { + SettingsManager::instance().settings().setValue("lockscreen", false); + SettingsManager::instance().settings().setValue("appAutoLocking", false); + m_settingsWidget->appAutoLockingSetChecked(false); + m_settingsWidget->appLockSetChecked(false); initLock(); } } diff --git a/src/mainwindow.h b/src/mainwindow.h index 4ca25d5..c5e2821 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -11,8 +11,6 @@ #include <QMessageBox> #include <QProgressBar> #include <QRadioButton> -#include <QRegExp> -#include <QSettings> #include <QStatusBar> #include <QStyle> #include <QStyleFactory> @@ -33,6 +31,7 @@ #include "rateapp.h" #include "requestinterceptor.h" #include "settingswidget.h" +#include "theme.h" #include "webenginepage.h" #include "webview.h" @@ -42,23 +41,25 @@ public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); + void loadSchemaUrl(const QString &arg); + void alreadyRunning(bool notify = false); + void runMinimized(); + void notify(QString title, QString message); + void doReload(bool byPassCache = false, bool isAskedByCLI = false, + bool byLoadingQuirk = false); + public slots: void updateWindowTheme(); void updatePageTheme(); - void handleWebViewTitleChanged(QString title); + void handleWebViewTitleChanged(const QString &title); void handleLoadFinished(bool loaded); void handleDownloadRequested(QWebEngineDownloadItem *download); - void loadSchemaUrl(const QString &arg); void showSettings(bool isAskedByCLI = false); void showAbout(); void lockApp(); - void runMinimized(); - void alreadyRunning(bool notify = false); - void notify(QString title, QString message); void toggleTheme(); - void doReload(bool byPassCache = false, bool isAskedByCLI = false, - bool byLoadingQuirk = false); void newChat(); + protected slots: void closeEvent(QCloseEvent *event) override; void resizeEvent(QResizeEvent *event) override; @@ -66,71 +67,67 @@ protected slots: private: const QIcon getTrayIcon(const int ¬ificationCount) const; - QPalette lightPalette, darkPalette; void createActions(); void createTrayIcon(); void createWebEngine(); - - QSettings settings; - QRegExp notificationsTitleRegExp; - QIcon trayIconNormal; - QRegExp unreadMessageCountRegExp; - - QAction *reloadAction; - QAction *minimizeAction; - QAction *restoreAction; - QAction *aboutAction; - QAction *settingsAction; - QAction *toggleThemeAction; - QAction *quitAction; - QAction *lockAction; - QAction *fullscreenAction; - QAction *openUrlAction; - - QMenu *trayIconMenu; - QSystemTrayIcon *trayIcon; - QWebEngineView *webEngine; - SettingsWidget *settingsWidget = nullptr; - DownloadManagerWidget downloadManagerWidget; - QScopedPointer<QWebEngineProfile> otrProfile; - Lock *lockWidget = nullptr; - int correctlyLoaderRetries = 4; - QStringList dictionaries; - AutoLockEventFilter *autoLockEventFilter = nullptr; - -private slots: - - QString getPageTheme(); - void iconActivated(QSystemTrayIcon::ActivationReason reason); - void messageClicked(); + QString getPageTheme() const; void handleCookieAdded(const QNetworkCookie &cookie); - void toggleMute(const bool &checked); void doAppReload(); void askToReloadPage(); void updateSettingsUserAgentWidget(); - void fullScreenRequested(QWebEngineFullScreenRequest request); void createWebPage(bool offTheRecord = false); void initSettingWidget(); void initGlobalWebProfile(); - void checkWindowState(); - void initLock(); void tryLock(); void checkLoadedCorrectly(); - void loadingQuirk(QString test); + void loadingQuirk(const QString &test); void setNotificationPresenter(QWebEngineProfile *profile); - void quitApp(); void initRateWidget(); - void initThemes(); void handleZoomOnWindowStateChange(const QWindowStateChangeEvent *ev); void handleZoom(); - void changeLockPassword(); void forceLogOut(); - void tryLogOut(); bool isLoggedIn(); + void tryLogOut(); void initAutoLock(); - void appAutoLockChanged(); - void triggerNewChat(QString phone, QString text); + void triggerNewChat(const QString &phone, const QString &text); void restoreMainWindow(); + + QIcon m_trayIconNormal; + QRegularExpression m_notificationsTitleRegExp; + QRegularExpression m_unreadMessageCountRegExp; + DownloadManagerWidget m_downloadManagerWidget; + QScopedPointer<QWebEngineProfile> m_otrProfile; + int m_correctlyLoadedRetries = 4; + QStringList m_dictionaries; + + QAction *m_reloadAction = nullptr; + QAction *m_minimizeAction = nullptr; + QAction *m_restoreAction = nullptr; + QAction *m_aboutAction = nullptr; + QAction *m_settingsAction = nullptr; + QAction *m_toggleThemeAction = nullptr; + QAction *m_quitAction = nullptr; + QAction *m_lockAction = nullptr; + QAction *m_fullscreenAction = nullptr; + QAction *m_openUrlAction = nullptr; + + QMenu *m_trayIconMenu = nullptr; + QSystemTrayIcon *m_systemTrayIcon = nullptr; + QWebEngineView *m_webEngine = nullptr; + SettingsWidget *m_settingsWidget = nullptr; + Lock *m_lockWidget = nullptr; + AutoLockEventFilter *m_autoLockEventFilter = nullptr; + +private slots: + void iconActivated(QSystemTrayIcon::ActivationReason reason); + void messageClicked(); + void toggleMute(const bool &checked); + void fullScreenRequested(QWebEngineFullScreenRequest request); + void checkWindowState(); + void initLock(); + void quitApp(); + void changeLockPassword(); + void appAutoLockChanged(); }; #endif // MAINWINDOW_H diff --git a/src/notificationpopup.h b/src/notificationpopup.h index 3a765e0..69aa478 100644 --- a/src/notificationpopup.h +++ b/src/notificationpopup.h @@ -1,9 +1,9 @@ #ifndef NOTIFICATIONPOPUP_H #define NOTIFICATIONPOPUP_H -#pragma once - +#include "settingsmanager.h" #include "widgets/scrolltext/scrolltext.h" + #include <QApplication> #include <QDebug> #include <QDesktopWidget> @@ -13,7 +13,6 @@ #include <QPropertyAnimation> #include <QPushButton> #include <QScreen> -#include <QSettings> #include <QSpacerItem> #include <QTimer> #include <QVBoxLayout> @@ -27,7 +26,6 @@ class NotificationPopup : public QWidget { QLabel m_icon, m_title; ScrollText m_message; std::unique_ptr<QWebEngineNotification> notification; - QSettings settings; public: NotificationPopup(QWidget *parent) : QWidget(parent) { @@ -62,7 +60,10 @@ public: image.scaledToHeight(m_icon.height(), Qt::SmoothTransformation)); this->adjustSize(); - QTimer::singleShot(settings.value("notificationTimeOut", 9000).toInt(), + QTimer::singleShot(SettingsManager::instance() + .settings() + .value("notificationTimeOut", 9000) + .toInt(), this, [=]() { onClosed(); }); animateIn(screenNumber); @@ -87,7 +88,10 @@ public: connect(notification.get(), &QWebEngineNotification::closed, this, &NotificationPopup::onClosed); - QTimer::singleShot(settings.value("notificationTimeOut", 9000).toInt(), + QTimer::singleShot(SettingsManager::instance() + .settings() + .value("notificationTimeOut", 9000) + .toInt(), notification.get(), [&]() { onClosed(); }); animateIn(screenNumber); diff --git a/src/permissiondialog.cpp b/src/permissiondialog.cpp index c0eeac6..7ca9a4d 100644 --- a/src/permissiondialog.cpp +++ b/src/permissiondialog.cpp @@ -1,9 +1,6 @@ #include "permissiondialog.h" #include "ui_permissiondialog.h" -#include <QCheckBox> -#include <QMetaEnum> -#include <QWebEnginePage> PermissionDialog::PermissionDialog(QWidget *parent) : QWidget(parent), ui(new Ui::PermissionDialog) { @@ -41,7 +38,7 @@ void PermissionDialog::addToFeaturesTable(QWebEnginePage::Feature feature, // insertRow ui->featuresTableWidget->insertRow(nextRow); - settings.beginGroup("permissions"); + SettingsManager::instance().settings().beginGroup("permissions"); // add column for (int i = 0; i < columnData.count(); i++) { @@ -50,10 +47,10 @@ void PermissionDialog::addToFeaturesTable(QWebEnginePage::Feature feature, featureCheckBox->setStyleSheet( "border:0px;margin-left:50%; margin-right:50%;"); featureCheckBox->setChecked( - settings.value(featureName, false).toBool()); + SettingsManager::instance().settings().value(featureName, false).toBool()); connect(featureCheckBox, &QCheckBox::toggled, [=](bool checked) { // save permission - settings.setValue("permissions/" + featureName, checked); + SettingsManager::instance().settings().setValue("permissions/" + featureName, checked); emit webPageFeatureChanged(feature); }); ui->featuresTableWidget->setCellWidget(nextRow, i, featureCheckBox); @@ -65,7 +62,7 @@ void PermissionDialog::addToFeaturesTable(QWebEnginePage::Feature feature, } this->update(); } - settings.endGroup(); + SettingsManager::instance().settings().endGroup(); } } diff --git a/src/permissiondialog.h b/src/permissiondialog.h index 2460a2d..0baf406 100644 --- a/src/permissiondialog.h +++ b/src/permissiondialog.h @@ -1,10 +1,13 @@ #ifndef PERMISSIONDIALOG_H #define PERMISSIONDIALOG_H -#include <QSettings> +#include <QCheckBox> +#include <QKeyEvent> +#include <QMetaEnum> #include <QWebEnginePage> #include <QWidget> -#include <QKeyEvent> + +#include "settingsmanager.h" namespace Ui { class PermissionDialog; @@ -22,13 +25,13 @@ signals: protected slots: void keyPressEvent(QKeyEvent *e); + private slots: void addToFeaturesTable(QWebEnginePage::Feature feature, QString &featureName); private: Ui::PermissionDialog *ui; - QSettings settings; }; #endif // PERMISSIONDIALOG_H diff --git a/src/rateapp.cpp b/src/rateapp.cpp index 5c370a9..c258c37 100644 --- a/src/rateapp.cpp +++ b/src/rateapp.cpp @@ -22,7 +22,7 @@ RateApp::RateApp(QWidget *parent, QString app_rating_url, int app_launch_count, showTimer = new QTimer(this); showTimer->setInterval(this->present_delay); - connect(showTimer, &QTimer::timeout, [=]() { + connect(showTimer, &QTimer::timeout, this, [=]() { qDebug() << "Rate timer timeout"; emit showRateDialog(); if (this->isVisible()) @@ -30,15 +30,26 @@ RateApp::RateApp(QWidget *parent, QString app_rating_url, int app_launch_count, }); // increase the app_launched_count by one - int app_launched = settings.value("app_launched_count", 0).toInt(); - settings.setValue("app_launched_count", app_launched + 1); + int app_launched = SettingsManager::instance() + .settings() + .value("app_launched_count", 0) + .toInt(); + SettingsManager::instance().settings().setValue("app_launched_count", + app_launched + 1); // check if app install time is set in settings - if (settings.value("app_install_time").isNull()) { - settings.setValue("app_install_time", QDateTime::currentSecsSinceEpoch()); - - } else if (settings.value("app_install_time").isValid()) { - //qDebug() << "RATEAPP should show:" << shouldShow(); + if (SettingsManager::instance() + .settings() + .value("app_install_time") + .isNull()) { + SettingsManager::instance().settings().setValue( + "app_install_time", QDateTime::currentSecsSinceEpoch()); + + } else if (SettingsManager::instance() + .settings() + .value("app_install_time") + .isValid()) { + // qDebug() << "RATEAPP should show:" << shouldShow(); if (shouldShow()) { showTimer->start(); } else { @@ -49,7 +60,10 @@ RateApp::RateApp(QWidget *parent, QString app_rating_url, int app_launch_count, } // if already reated delete this obj to free resources - if (settings.value("rated_already", false).toBool()) { + if (SettingsManager::instance() + .settings() + .value("rated_already", false) + .toBool()) { this->deleteLater(); } } @@ -70,10 +84,19 @@ void RateApp::delayShowEvent() { */ bool RateApp::shouldShow() { bool shouldShow = false; - int app_launched_count = settings.value("app_launched_count", 0).toInt(); + int app_launched_count = SettingsManager::instance() + .settings() + .value("app_launched_count", 0) + .toInt(); qint64 currentDateTime = QDateTime::currentSecsSinceEpoch(); - qint64 installed_date_time = settings.value("app_install_time").toLongLong(); - bool ratedAlready = settings.value("rated_already", false).toBool(); + qint64 installed_date_time = SettingsManager::instance() + .settings() + .value("app_install_time") + .toLongLong(); + bool ratedAlready = SettingsManager::instance() + .settings() + .value("rated_already", false) + .toBool(); if (ratedAlready) // return false if already reated; return false; @@ -99,7 +122,7 @@ void RateApp::on_rateNowBtn_clicked() { } void RateApp::on_alreadyDoneBtn_clicked() { - settings.setValue("rated_already", true); + SettingsManager::instance().settings().setValue("rated_already", true); this->close(); } @@ -109,9 +132,10 @@ void RateApp::on_laterBtn_clicked() { } void RateApp::reset() { - settings.setValue("rated_already", false); - settings.setValue("app_launched_count", 0); - settings.setValue("app_install_time", QDateTime::currentSecsSinceEpoch()); + SettingsManager::instance().settings().setValue("rated_already", false); + SettingsManager::instance().settings().setValue("app_launched_count", 0); + SettingsManager::instance().settings().setValue( + "app_install_time", QDateTime::currentSecsSinceEpoch()); } void RateApp::on_rateOnGithub_clicked() { diff --git a/src/rateapp.h b/src/rateapp.h index 50d5b98..ffb601c 100644 --- a/src/rateapp.h +++ b/src/rateapp.h @@ -1,55 +1,55 @@ #ifndef RATEAPP_H #define RATEAPP_H -#include <QWidget> -#include <QSettings> #include <QDateTime> -#include <QUrl> #include <QDesktopServices> #include <QTimer> +#include <QUrl> +#include <QWidget> + +#include "settingsmanager.h" namespace Ui { class RateApp; } -class RateApp : public QWidget -{ - Q_OBJECT +class RateApp : public QWidget { + Q_OBJECT signals: - void showRateDialog(); + void showRateDialog(); public: - explicit RateApp(QWidget *parent = nullptr , QString app_rating_url = "", - int app_launch_count = 5, int app_install_days = 5, int present_delay = 5000); - ~RateApp(); + explicit RateApp(QWidget *parent = nullptr, QString app_rating_url = "", + int app_launch_count = 5, int app_install_days = 5, + int present_delay = 5000); + ~RateApp(); public slots: - void delayShowEvent(); + void delayShowEvent(); private slots: - void on_rateNowBtn_clicked(); + void on_rateNowBtn_clicked(); - void on_alreadyDoneBtn_clicked(); + void on_alreadyDoneBtn_clicked(); - void on_laterBtn_clicked(); + void on_laterBtn_clicked(); - bool shouldShow(); - void reset(); - void on_rateOnGithub_clicked(); + bool shouldShow(); + void reset(); + void on_rateOnGithub_clicked(); - void on_donate_clicked(); + void on_donate_clicked(); - void on_donate_2_clicked(); + void on_donate_2_clicked(); private: - Ui::RateApp *ui; - QString app_rating_url; - int app_launch_count; - int app_install_days; - int present_delay; - QSettings settings; - QTimer *showTimer; + Ui::RateApp *ui; + QString app_rating_url; + int app_launch_count; + int app_install_days; + int present_delay; + QTimer *showTimer; }; #endif // RATEAPP_H diff --git a/src/requestinterceptor.h b/src/requestinterceptor.h index 95f2d48..8d8f261 100644 --- a/src/requestinterceptor.h +++ b/src/requestinterceptor.h @@ -1,41 +1,39 @@ #ifndef REQUESTINTERCEPTOR_H #define REQUESTINTERCEPTOR_H -#include <QWebEnginePage> + +#include <QApplication> #include <QDebug> #include <QObject> -#include <QWebEngineView> -#include <QApplication> +#include <QWebEnginePage> #include <QWebEngineUrlRequestInfo> #include <QWebEngineUrlRequestInterceptor> -#include <QSettings> +#include <QWebEngineView> + +#include "settingsmanager.h" -class RequestInterceptor : public QWebEngineUrlRequestInterceptor -{ - Q_OBJECT +class RequestInterceptor : public QWebEngineUrlRequestInterceptor { + Q_OBJECT signals: - void blocked(QString adUrl); -private: - QSettings m_settings; + void blocked(QString adUrl); public: - RequestInterceptor(QObject *parent = nullptr) : QWebEngineUrlRequestInterceptor(parent) - { - } + RequestInterceptor(QObject *parent = nullptr) + : QWebEngineUrlRequestInterceptor(parent) {} - void interceptRequest(QWebEngineUrlRequestInfo &info) - { - QString reqUrlStr = info.requestUrl().toString(); + void interceptRequest(QWebEngineUrlRequestInfo &info) { + QString reqUrlStr = info.requestUrl().toString(); -// if(reqUrlStr.contains("mms-type=video")|| reqUrlStr.contains("stream/video?key")){ -// if(m_settings.value("disableVideos",false).toBool()){ -// info.block(true); -// qDebug()<<"INTERCEPTOR: Blocked video - "<<reqUrlStr; -// } -// }else{ -// qDebug()<<"INTERCEPTOR:"<<reqUrlStr; -// } - qDebug()<<"INTERCEPTOR:"<<reqUrlStr; - } + // if(reqUrlStr.contains("mms-type=video")|| + // reqUrlStr.contains("stream/video?key")){ + // if(SettingsManager::instance().settings().value("disableVideos",false).toBool()){ + // info.block(true); + // qDebug()<<"INTERCEPTOR: Blocked video - "<<reqUrlStr; + // } + // }else{ + // qDebug()<<"INTERCEPTOR:"<<reqUrlStr; + // } + qDebug() << "INTERCEPTOR:" << reqUrlStr; + } }; #endif // REQUESTINTERCEPTOR_H diff --git a/src/settingsmanager.h b/src/settingsmanager.h new file mode 100644 index 0000000..2dc7c57 --- /dev/null +++ b/src/settingsmanager.h @@ -0,0 +1,21 @@ +#ifndef SETTINGSMANAGER_H +#define SETTINGSMANAGER_H + +#include <QSettings> + +class SettingsManager { +public: + static SettingsManager &instance() { + static SettingsManager instance; + return instance; + } + + QSettings &settings() { return m_settings; } + +private: + SettingsManager() {} + + QSettings m_settings; +}; + +#endif // SETTINGSMANAGER_H diff --git a/src/settingswidget.cpp b/src/settingswidget.cpp index 4bd213d..87f6d4c 100644 --- a/src/settingswidget.cpp +++ b/src/settingswidget.cpp @@ -23,48 +23,91 @@ SettingsWidget::SettingsWidget(QWidget *parent, int screenNumber, this->enginePersistentStoragePath = enginePersistentStoragePath; ui->zoomFactorSpinBox->setRange(0.25, 5.0); - ui->zoomFactorSpinBox->setValue(settings.value("zoomFactor", 1.0).toDouble()); + ui->zoomFactorSpinBox->setValue(SettingsManager::instance() + .settings() + .value("zoomFactor", 1.0) + .toDouble()); ui->zoomFactorSpinBoxMaximized->setRange(0.25, 5.0); ui->zoomFactorSpinBoxMaximized->setValue( - settings.value("zoomFactorMaximized", defaultZoomFactorMaximized) + SettingsManager::instance() + .settings() + .value("zoomFactorMaximized", defaultZoomFactorMaximized) .toDouble()); ui->closeButtonActionComboBox->setCurrentIndex( - settings.value("closeButtonActionCombo", 0).toInt()); + SettingsManager::instance() + .settings() + .value("closeButtonActionCombo", 0) + .toInt()); ui->notificationCheckBox->setChecked( - settings.value("disableNotificationPopups", false).toBool()); - ui->muteAudioCheckBox->setChecked( - settings.value("muteAudio", false).toBool()); - ui->autoPlayMediaCheckBox->setChecked( - settings.value("autoPlayMedia", false).toBool()); + SettingsManager::instance() + .settings() + .value("disableNotificationPopups", false) + .toBool()); + ui->muteAudioCheckBox->setChecked(SettingsManager::instance() + .settings() + .value("muteAudio", false) + .toBool()); + ui->autoPlayMediaCheckBox->setChecked(SettingsManager::instance() + .settings() + .value("autoPlayMedia", false) + .toBool()); ui->themeComboBox->setCurrentText( - utils::toCamelCase(settings.value("windowTheme", "light").toString())); - - ui->userAgentLineEdit->setText( - settings.value("useragent", defaultUserAgentStr).toString()); + Utils::toCamelCase(SettingsManager::instance() + .settings() + .value("windowTheme", "light") + .toString())); + + ui->userAgentLineEdit->setText(SettingsManager::instance() + .settings() + .value("useragent", defaultUserAgentStr) + .toString()); ui->userAgentLineEdit->home(true); ui->userAgentLineEdit->deselect(); - ui->enableSpellCheck->setChecked(settings.value("sc_enabled", true).toBool()); + ui->enableSpellCheck->setChecked(SettingsManager::instance() + .settings() + .value("sc_enabled", true) + .toBool()); ui->notificationTimeOutspinBox->setValue( - settings.value("notificationTimeOut", 9000).toInt() / 1000); - ui->notificationCombo->setCurrentIndex( - settings.value("notificationCombo", 1).toInt()); - ui->useNativeFileDialog->setChecked( - settings.value("useNativeFileDialog", false).toBool()); - ui->startMinimized->setChecked( - settings.value("startMinimized", false).toBool()); + SettingsManager::instance() + .settings() + .value("notificationTimeOut", 9000) + .toInt() / + 1000); + ui->notificationCombo->setCurrentIndex(SettingsManager::instance() + .settings() + .value("notificationCombo", 1) + .toInt()); + ui->useNativeFileDialog->setChecked(SettingsManager::instance() + .settings() + .value("useNativeFileDialog", false) + .toBool()); + ui->startMinimized->setChecked(SettingsManager::instance() + .settings() + .value("startMinimized", false) + .toBool()); this->appAutoLockingSetChecked( - settings.value("appAutoLocking", defaultAppAutoLock).toBool()); + SettingsManager::instance() + .settings() + .value("appAutoLocking", defaultAppAutoLock) + .toBool()); ui->autoLockDurationSpinbox->setValue( - settings.value("autoLockDuration", defaultAppAutoLockDuration).toInt()); + SettingsManager::instance() + .settings() + .value("autoLockDuration", defaultAppAutoLockDuration) + .toInt()); ui->minimizeOnTrayIconClick->setChecked( - settings.value("minimizeOnTrayIconClick", false).toBool()); + SettingsManager::instance() + .settings() + .value("minimizeOnTrayIconClick", false) + .toBool()); ui->defaultDownloadLocation->setText( - settings + SettingsManager::instance() + .settings() .value("defaultDownloadLocation", QStandardPaths::writableLocation( QStandardPaths::DownloadLocation) + @@ -74,23 +117,29 @@ SettingsWidget::SettingsWidget(QWidget *parent, int screenNumber, ui->styleComboBox->blockSignals(true); ui->styleComboBox->addItems(QStyleFactory::keys()); ui->styleComboBox->blockSignals(false); - ui->styleComboBox->setCurrentText( - settings.value("widgetStyle", "Fusion").toString()); + ui->styleComboBox->setCurrentText(SettingsManager::instance() + .settings() + .value("widgetStyle", "Fusion") + .toString()); ui->fullWidthViewCheckbox->blockSignals(true); - ui->fullWidthViewCheckbox->setChecked( - settings.value("fullWidthView", true).toBool()); + ui->fullWidthViewCheckbox->setChecked(SettingsManager::instance() + .settings() + .value("fullWidthView", true) + .toBool()); ui->fullWidthViewCheckbox->blockSignals(false); ui->automaticThemeCheckBox->blockSignals(true); - bool automaticThemeSwitching = - settings.value("automaticTheme", false).toBool(); + bool automaticThemeSwitching = SettingsManager::instance() + .settings() + .value("automaticTheme", false) + .toBool(); ui->automaticThemeCheckBox->setChecked(automaticThemeSwitching); ui->automaticThemeCheckBox->blockSignals(false); themeSwitchTimer = new QTimer(this); themeSwitchTimer->setInterval(60000); // 1 min - connect(themeSwitchTimer, &QTimer::timeout, &settings, + connect(themeSwitchTimer, &QTimer::timeout, this, [=]() { themeSwitchTimerTimeout(); }); // instantly call the timeout slot if automatic theme switching enabled @@ -100,7 +149,11 @@ SettingsWidget::SettingsWidget(QWidget *parent, int screenNumber, updateAutomaticTheme(); this->setCurrentPasswordText( - QByteArray::fromBase64(settings.value("asdfg").toString().toUtf8())); + QByteArray::fromBase64(SettingsManager::instance() + .settings() + .value("asdfg") + .toString() + .toUtf8())); applyThemeQuirks(); @@ -124,8 +177,11 @@ SettingsWidget::SettingsWidget(QWidget *parent, int screenNumber, ui->scrollArea->setMinimumWidth( ui->groupBox_8->sizeHint().width() + ui->scrollArea->sizeHint().width() + ui->scrollAreaWidgetContents->layout()->spacing()); - if (settings.value("settingsGeo").isValid()) { - this->restoreGeometry(settings.value("settingsGeo").toByteArray()); + if (SettingsManager::instance().settings().value("settingsGeo").isValid()) { + this->restoreGeometry(SettingsManager::instance() + .settings() + .value("settingsGeo") + .toByteArray()); QRect screenRect = QGuiApplication::screens().at(screenNumber)->geometry(); if (!screenRect.contains(this->pos())) { this->move(screenRect.center() - this->rect().center()); @@ -144,7 +200,8 @@ bool SettingsWidget::eventFilter(QObject *obj, QEvent *event) { } void SettingsWidget::closeEvent(QCloseEvent *event) { - settings.setValue("settingsGeo", this->saveGeometry()); + SettingsManager::instance().settings().setValue("settingsGeo", + this->saveGeometry()); QWidget::closeEvent(event); } @@ -161,13 +218,18 @@ inline bool inRange(unsigned low, unsigned high, unsigned x) { } void SettingsWidget::themeSwitchTimerTimeout() { - if (settings.value("automaticTheme", false).toBool()) { + if (SettingsManager::instance() + .settings() + .value("automaticTheme", false) + .toBool()) { // start time QDateTime sunrise; - sunrise.setSecsSinceEpoch(settings.value("sunrise").toLongLong()); + sunrise.setSecsSinceEpoch( + SettingsManager::instance().settings().value("sunrise").toLongLong()); // end time QDateTime sunset; - sunset.setSecsSinceEpoch(settings.value("sunset").toLongLong()); + sunset.setSecsSinceEpoch( + SettingsManager::instance().settings().value("sunset").toLongLong()); QDateTime currentTime = QDateTime::currentDateTime(); int sunsetSeconds = QTime(0, 0).secsTo(sunset.time()); @@ -185,8 +247,10 @@ void SettingsWidget::themeSwitchTimerTimeout() { } void SettingsWidget::updateAutomaticTheme() { - bool automaticThemeSwitching = - settings.value("automaticTheme", false).toBool(); + bool automaticThemeSwitching = SettingsManager::instance() + .settings() + .value("automaticTheme", false) + .toBool(); if (automaticThemeSwitching && !themeSwitchTimer->isActive()) { themeSwitchTimer->start(); } else if (!automaticThemeSwitching) { @@ -228,7 +292,10 @@ void SettingsWidget::loadDictionaries(QStringList dictionaries) { ui->dictComboBox->blockSignals(false); // load settings for spellcheck dictionary - QString dictionary_name = settings.value("sc_dict", "en-US").toString(); + QString dictionary_name = SettingsManager::instance() + .settings() + .value("sc_dict", "en-US") + .toString(); int pos = ui->dictComboBox->findText(dictionary_name); if (pos == -1) { pos = ui->dictComboBox->findText("en-US"); @@ -241,13 +308,19 @@ void SettingsWidget::loadDictionaries(QStringList dictionaries) { void SettingsWidget::refresh() { ui->themeComboBox->setCurrentText( - utils::toCamelCase(settings.value("windowTheme", "light").toString())); + Utils::toCamelCase(SettingsManager::instance() + .settings() + .value("windowTheme", "light") + .toString())); - ui->cookieSize->setText(utils::refreshCacheSize(persistentStoragePath())); + ui->cookieSize->setText(Utils::refreshCacheSize(persistentStoragePath())); // update dict settings at runtime // load settings for spellcheck dictionary - QString dictionary_name = settings.value("sc_dict", "en-US").toString(); + QString dictionary_name = SettingsManager::instance() + .settings() + .value("sc_dict", "en-US") + .toString(); int pos = ui->dictComboBox->findText(dictionary_name); if (pos == -1) { pos = ui->dictComboBox->findText("en-US"); @@ -258,8 +331,14 @@ void SettingsWidget::refresh() { ui->dictComboBox->setCurrentIndex(pos); // enable disable spell check - ui->enableSpellCheck->setChecked(settings.value("sc_enabled", true).toBool()); - emit updateFullWidthView(settings.value("fullWidthView", true).toBool()); + ui->enableSpellCheck->setChecked(SettingsManager::instance() + .settings() + .value("sc_enabled", true) + .toBool()); + emit updateFullWidthView(SettingsManager::instance() + .settings() + .value("fullWidthView", true) + .toBool()); } void SettingsWidget::updateDefaultUAButton(const QString engineUA) { @@ -301,18 +380,20 @@ void SettingsWidget::on_deletePersistentData_clicked() { } void SettingsWidget::clearAllData() { - utils::delete_cache(this->cachePath()); - utils::delete_cache(this->persistentStoragePath()); + Utils::delete_cache(this->cachePath()); + Utils::delete_cache(this->persistentStoragePath()); refresh(); } void SettingsWidget::on_notificationCheckBox_toggled(bool checked) { - settings.setValue("disableNotificationPopups", checked); + SettingsManager::instance().settings().setValue("disableNotificationPopups", + checked); } void SettingsWidget::on_themeComboBox_currentTextChanged(const QString &arg1) { applyThemeQuirks(); - settings.setValue("windowTheme", QString(arg1).toLower()); + SettingsManager::instance().settings().setValue("windowTheme", + QString(arg1).toLower()); emit updateWindowTheme(); emit updatePageTheme(); } @@ -344,12 +425,12 @@ void SettingsWidget::applyThemeQuirks() { } void SettingsWidget::on_muteAudioCheckBox_toggled(bool checked) { - settings.setValue("muteAudio", checked); + SettingsManager::instance().settings().setValue("muteAudio", checked); emit muteToggled(checked); } void SettingsWidget::on_autoPlayMediaCheckBox_toggled(bool checked) { - settings.setValue("autoPlayMedia", checked); + SettingsManager::instance().settings().setValue("autoPlayMedia", checked); emit autoPlayMediaToggled(checked); } @@ -362,10 +443,12 @@ void SettingsWidget::on_userAgentLineEdit_textChanged(const QString &arg1) { bool isDefault = QString::compare(arg1.trimmed(), defaultUserAgentStr, Qt::CaseInsensitive) == 0; bool isPrevious = - QString::compare( - arg1.trimmed(), - settings.value("useragent", defaultUserAgentStr).toString(), - Qt::CaseInsensitive) == 0; + QString::compare(arg1.trimmed(), + SettingsManager::instance() + .settings() + .value("useragent", defaultUserAgentStr) + .toString(), + Qt::CaseInsensitive) == 0; if (isDefault == false && arg1.trimmed().isEmpty() == false) { ui->defaultUserAgentButton->setEnabled(false); @@ -392,7 +475,8 @@ void SettingsWidget::on_setUserAgent_clicked() { void SettingsWidget::on_closeButtonActionComboBox_currentIndexChanged( int index) { - settings.setValue("closeButtonActionCombo", index); + SettingsManager::instance().settings().setValue("closeButtonActionCombo", + index); } void SettingsWidget::autoAppLockSetChecked(bool checked) { @@ -403,7 +487,11 @@ void SettingsWidget::autoAppLockSetChecked(bool checked) { void SettingsWidget::updateAppLockPasswordViewer() { this->setCurrentPasswordText( - QByteArray::fromBase64(settings.value("asdfg").toString().toUtf8())); + QByteArray::fromBase64(SettingsManager::instance() + .settings() + .value("asdfg") + .toString() + .toUtf8())); } void SettingsWidget::appLockSetChecked(bool checked) { @@ -420,7 +508,10 @@ void SettingsWidget::appAutoLockingSetChecked(bool checked) { void SettingsWidget::toggleTheme() { // disable automatic theme first - if (settings.value("automaticTheme", false).toBool()) { + if (SettingsManager::instance() + .settings() + .value("automaticTheme", false) + .toBool()) { emit notify(tr( "Automatic theme switching was disabled due to manual theme toggle.")); ui->automaticThemeCheckBox->setChecked(false); @@ -444,14 +535,15 @@ void SettingsWidget::setCurrentPasswordText(QString str) { } void SettingsWidget::on_applock_checkbox_toggled(bool checked) { - if (settings.value("asdfg").isValid()) { - settings.setValue("lockscreen", checked); - } else if (checked && !settings.value("asdfg").isValid()) { - settings.setValue("lockscreen", true); + if (SettingsManager::instance().settings().value("asdfg").isValid()) { + SettingsManager::instance().settings().setValue("lockscreen", checked); + } else if (checked && + !SettingsManager::instance().settings().value("asdfg").isValid()) { + SettingsManager::instance().settings().setValue("lockscreen", true); if (checked) showSetApplockPasswordDialog(); } else { - settings.setValue("lockscreen", false); + SettingsManager::instance().settings().setValue("lockscreen", false); if (checked) showSetApplockPasswordDialog(); } @@ -477,12 +569,12 @@ void SettingsWidget::showSetApplockPasswordDialog() { } void SettingsWidget::on_dictComboBox_currentIndexChanged(const QString &arg1) { - settings.setValue("sc_dict", arg1); + SettingsManager::instance().settings().setValue("sc_dict", arg1); emit dictChanged(arg1); } void SettingsWidget::on_enableSpellCheck_toggled(bool checked) { - settings.setValue("sc_enabled", checked); + SettingsManager::instance().settings().setValue("sc_enabled", checked); emit spellCheckChanged(checked); } @@ -534,12 +626,13 @@ void SettingsWidget::on_showPermissionsButton_clicked() { } void SettingsWidget::on_notificationTimeOutspinBox_valueChanged(int arg1) { - settings.setValue("notificationTimeOut", arg1 * 1000); + SettingsManager::instance().settings().setValue("notificationTimeOut", + arg1 * 1000); emit notificationPopupTimeOutChanged(); } void SettingsWidget::on_notificationCombo_currentIndexChanged(int index) { - settings.setValue("notificationCombo", index); + SettingsManager::instance().settings().setValue("notificationCombo", index); } void SettingsWidget::on_tryNotification_clicked() { @@ -555,8 +648,10 @@ void SettingsWidget::on_automaticThemeCheckBox_toggled(bool checked) { automaticTheme->setAttribute(Qt::WA_DeleteOnClose, true); connect(automaticTheme, &AutomaticTheme::destroyed, ui->automaticThemeCheckBox, [=]() { - bool automaticThemeSwitching = - settings.value("automaticTheme", false).toBool(); + bool automaticThemeSwitching = SettingsManager::instance() + .settings() + .value("automaticTheme", false) + .toBool(); ui->automaticThemeCheckBox->setChecked(automaticThemeSwitching); if (automaticThemeSwitching) themeSwitchTimerTimeout(); @@ -564,28 +659,30 @@ void SettingsWidget::on_automaticThemeCheckBox_toggled(bool checked) { }); automaticTheme->show(); } else { - settings.setValue("automaticTheme", false); + SettingsManager::instance().settings().setValue("automaticTheme", false); updateAutomaticTheme(); } } void SettingsWidget::on_useNativeFileDialog_toggled(bool checked) { - settings.setValue("useNativeFileDialog", checked); + SettingsManager::instance().settings().setValue("useNativeFileDialog", + checked); } void SettingsWidget::on_startMinimized_toggled(bool checked) { - settings.setValue("startMinimized", checked); + SettingsManager::instance().settings().setValue("startMinimized", checked); } void SettingsWidget::on_appAutoLockcheckBox_toggled(bool checked) { - if (settings.value("asdfg").isValid()) { - settings.setValue("appAutoLocking", checked); + if (SettingsManager::instance().settings().value("asdfg").isValid()) { + SettingsManager::instance().settings().setValue("appAutoLocking", checked); } else { QMessageBox::information(this, "App Lock Setup", "Please setup the App lock password first.", QMessageBox::Ok); - if (settings.value("asdfg").isValid() == false) { - settings.setValue("appAutoLocking", false); + if (SettingsManager::instance().settings().value("asdfg").isValid() == + false) { + SettingsManager::instance().settings().setValue("appAutoLocking", false); autoAppLockSetChecked(false); } } @@ -593,7 +690,7 @@ void SettingsWidget::on_appAutoLockcheckBox_toggled(bool checked) { } void SettingsWidget::on_autoLockDurationSpinbox_valueChanged(int arg1) { - settings.setValue("autoLockDuration", arg1); + SettingsManager::instance().settings().setValue("autoLockDuration", arg1); emit appAutoLockChanged(); } @@ -603,64 +700,78 @@ void SettingsWidget::on_resetAppAutoLockPushButton_clicked() { } void SettingsWidget::on_minimizeOnTrayIconClick_toggled(bool checked) { - settings.setValue("minimizeOnTrayIconClick", checked); + SettingsManager::instance().settings().setValue("minimizeOnTrayIconClick", + checked); } void SettingsWidget::on_styleComboBox_currentTextChanged(const QString &arg1) { applyThemeQuirks(); - settings.setValue("widgetStyle", arg1); + SettingsManager::instance().settings().setValue("widgetStyle", arg1); emit updateWindowTheme(); emit updatePageTheme(); } void SettingsWidget::on_zoomPlus_clicked() { - double currentFactor = settings.value("zoomFactor", 1.0).toDouble(); + double currentFactor = SettingsManager::instance() + .settings() + .value("zoomFactor", 1.0) + .toDouble(); double newFactor = currentFactor + 0.25; ui->zoomFactorSpinBox->setValue(newFactor); - settings.setValue("zoomFactor", ui->zoomFactorSpinBox->value()); + SettingsManager::instance().settings().setValue( + "zoomFactor", ui->zoomFactorSpinBox->value()); emit zoomChanged(); } void SettingsWidget::on_zoomMinus_clicked() { - double currentFactor = settings.value("zoomFactor", 1.0).toDouble(); + double currentFactor = SettingsManager::instance() + .settings() + .value("zoomFactor", 1.0) + .toDouble(); double newFactor = currentFactor - 0.25; ui->zoomFactorSpinBox->setValue(newFactor); - settings.setValue("zoomFactor", ui->zoomFactorSpinBox->value()); + SettingsManager::instance().settings().setValue( + "zoomFactor", ui->zoomFactorSpinBox->value()); emit zoomChanged(); } void SettingsWidget::on_zoomReset_clicked() { ui->zoomFactorSpinBox->setValue(1.0); - settings.setValue("zoomFactor", ui->zoomFactorSpinBox->value()); + SettingsManager::instance().settings().setValue( + "zoomFactor", ui->zoomFactorSpinBox->value()); emit zoomChanged(); } void SettingsWidget::on_zoomResetMaximized_clicked() { ui->zoomFactorSpinBoxMaximized->setValue(defaultZoomFactorMaximized); - settings.setValue("zoomFactorMaximized", - ui->zoomFactorSpinBoxMaximized->value()); + SettingsManager::instance().settings().setValue( + "zoomFactorMaximized", ui->zoomFactorSpinBoxMaximized->value()); emit zoomMaximizedChanged(); } void SettingsWidget::on_zoomPlusMaximized_clicked() { double currentFactor = - settings.value("zoomFactorMaximized", defaultZoomFactorMaximized) + SettingsManager::instance() + .settings() + .value("zoomFactorMaximized", defaultZoomFactorMaximized) .toDouble(); double newFactor = currentFactor + 0.25; ui->zoomFactorSpinBoxMaximized->setValue(newFactor); - settings.setValue("zoomFactorMaximized", - ui->zoomFactorSpinBoxMaximized->value()); + SettingsManager::instance().settings().setValue( + "zoomFactorMaximized", ui->zoomFactorSpinBoxMaximized->value()); emit zoomMaximizedChanged(); } void SettingsWidget::on_zoomMinusMaximized_clicked() { double currentFactor = - settings.value("zoomFactorMaximized", defaultZoomFactorMaximized) + SettingsManager::instance() + .settings() + .value("zoomFactorMaximized", defaultZoomFactorMaximized) .toDouble(); double newFactor = currentFactor - 0.25; ui->zoomFactorSpinBoxMaximized->setValue(newFactor); - settings.setValue("zoomFactorMaximized", - ui->zoomFactorSpinBoxMaximized->value()); + SettingsManager::instance().settings().setValue( + "zoomFactorMaximized", ui->zoomFactorSpinBoxMaximized->value()); emit zoomMaximizedChanged(); } @@ -670,12 +781,15 @@ void SettingsWidget::on_changeDefaultDownloadLocationPb_clicked() { dialog.setOption(QFileDialog::ShowDirsOnly); QString path; - bool usenativeFileDialog = - settings.value("useNativeFileDialog", false).toBool(); + bool usenativeFileDialog = SettingsManager::instance() + .settings() + .value("useNativeFileDialog", false) + .toBool(); if (usenativeFileDialog == false) { path = QFileDialog::getExistingDirectory( this, tr("Select download directory"), - settings + SettingsManager::instance() + .settings() .value("defaultDownloadLocation", QStandardPaths::writableLocation( QStandardPaths::DownloadLocation) + @@ -685,7 +799,8 @@ void SettingsWidget::on_changeDefaultDownloadLocationPb_clicked() { } else { path = QFileDialog::getSaveFileName( this, tr("Select download directory"), - settings + SettingsManager::instance() + .settings() .value("defaultDownloadLocation", QStandardPaths::writableLocation( QStandardPaths::DownloadLocation) + @@ -695,7 +810,8 @@ void SettingsWidget::on_changeDefaultDownloadLocationPb_clicked() { if (!path.isNull() && !path.isEmpty()) { ui->defaultDownloadLocation->setText(path); - settings.setValue("defaultDownloadLocation", path); + SettingsManager::instance().settings().setValue("defaultDownloadLocation", + path); } } @@ -720,7 +836,7 @@ void SettingsWidget::on_viewPassword_clicked() { } void SettingsWidget::on_chnageCurrentPasswordPushButton_clicked() { - if (settings.value("asdfg").isValid()) { + if (SettingsManager::instance().settings().value("asdfg").isValid()) { QMessageBox msgBox; msgBox.setText("You are about to change your current app lock password!" "\n\nThis will LogOut your current session." @@ -741,20 +857,19 @@ void SettingsWidget::on_chnageCurrentPasswordPushButton_clicked() { msgBox.exec(); } else { - settings.setValue("lockscreen", true); + SettingsManager::instance().settings().setValue("lockscreen", true); showSetApplockPasswordDialog(); } } void SettingsWidget::on_fullWidthViewCheckbox_toggled(bool checked) { - settings.setValue("fullWidthView", checked); + SettingsManager::instance().settings().setValue("fullWidthView", checked); emit updateFullWidthView(checked); } -void SettingsWidget::keyPressEvent(QKeyEvent *e) -{ - if (e->key() == Qt::Key_Escape) - this->close(); +void SettingsWidget::keyPressEvent(QKeyEvent *e) { + if (e->key() == Qt::Key_Escape) + this->close(); - QWidget::keyPressEvent(e); + QWidget::keyPressEvent(e); } diff --git a/src/settingswidget.h b/src/settingswidget.h index d533343..a569d6f 100644 --- a/src/settingswidget.h +++ b/src/settingswidget.h @@ -1,12 +1,12 @@ #ifndef SETTINGSWIDGET_H #define SETTINGSWIDGET_H +#include <QWidget> + #include "permissiondialog.h" +#include "settingsmanager.h" #include "utils.h" -#include <QSettings> -#include <QWidget> - namespace Ui { class SettingsWidget; } @@ -102,7 +102,6 @@ private slots: private: Ui::SettingsWidget *ui; QString engineCachePath, enginePersistentStoragePath; - QSettings settings; QTimer *themeSwitchTimer; }; diff --git a/src/theme.cpp b/src/theme.cpp new file mode 100644 index 0000000..742e59d --- /dev/null +++ b/src/theme.cpp @@ -0,0 +1,69 @@ +#include "theme.h" + +QPalette Theme::initLightPalette() { + QPalette lightPalette; + lightPalette.setColor(QPalette::Window, QColor(240, 240, 240)); + lightPalette.setColor(QPalette::WindowText, QColor(0, 0, 0)); + lightPalette.setColor(QPalette::Button, QColor(240, 240, 240)); + lightPalette.setColor(QPalette::Light, QColor(180, 180, 180)); + lightPalette.setColor(QPalette::Midlight, QColor(200, 200, 200)); + lightPalette.setColor(QPalette::Dark, QColor(225, 225, 225)); + lightPalette.setColor(QPalette::Text, QColor(0, 0, 0)); + lightPalette.setColor(QPalette::BrightText, QColor(0, 0, 0)); + lightPalette.setColor(QPalette::ButtonText, QColor(0, 0, 0)); + lightPalette.setColor(QPalette::Base, QColor(237, 237, 237)); + lightPalette.setColor(QPalette::Shadow, QColor(20, 20, 20)); + lightPalette.setColor(QPalette::Highlight, QColor(76, 163, 224)); + lightPalette.setColor(QPalette::HighlightedText, QColor(0, 0, 0)); + lightPalette.setColor(QPalette::Link, QColor(0, 162, 232)); + lightPalette.setColor(QPalette::AlternateBase, QColor(225, 225, 225)); + lightPalette.setColor(QPalette::ToolTipBase, QColor(240, 240, 240)); + lightPalette.setColor(QPalette::ToolTipText, QColor(0, 0, 0)); + lightPalette.setColor(QPalette::LinkVisited, QColor(222, 222, 222)); + lightPalette.setColor(QPalette::Disabled, QPalette::WindowText, + QColor(115, 115, 115)); + lightPalette.setColor(QPalette::Disabled, QPalette::Text, + QColor(115, 115, 115)); + lightPalette.setColor(QPalette::Disabled, QPalette::ButtonText, + QColor(115, 115, 115)); + lightPalette.setColor(QPalette::Disabled, QPalette::Highlight, + QColor(190, 190, 190)); + lightPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, + QColor(115, 115, 115)); + + return lightPalette; +} + +QPalette Theme::initDarkPalette() { + QPalette darkPalette; + darkPalette.setColor(QPalette::Window, QColor(17, 27, 33)); + darkPalette.setColor(QPalette::Text, Qt::white); + darkPalette.setColor(QPalette::WindowText, Qt::white); + darkPalette.setColor(QPalette::Base, QColor(32, 44, 51)); + darkPalette.setColor(QPalette::AlternateBase, QColor(95, 108, 115)); + darkPalette.setColor(QPalette::ToolTipBase, QColor(66, 66, 66)); + darkPalette.setColor(QPalette::ToolTipText, QColor(192, 192, 192)); + darkPalette.setColor(QPalette::Dark, QColor(35, 35, 35)); + darkPalette.setColor(QPalette::Shadow, QColor(20, 20, 20)); + darkPalette.setColor(QPalette::Button, QColor(17, 27, 33)); + darkPalette.setColor(QPalette::ButtonText, Qt::white); + darkPalette.setColor(QPalette::BrightText, Qt::red); + darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); + darkPalette.setColor(QPalette::Highlight, QColor(38, 140, 196)); + darkPalette.setColor(QPalette::HighlightedText, Qt::white); + darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, + QColor(127, 127, 127)); + darkPalette.setColor(QPalette::Disabled, QPalette::Window, + QColor(65, 65, 67)); + darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, + QColor(80, 80, 80)); + darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, + QColor(127, 127, 127)); + darkPalette.setColor(QPalette::Disabled, QPalette::Text, + QColor(127, 127, 127)); + return darkPalette; +} + +QPalette &Theme::getLightPalette() { return lightPalette(); } + +QPalette &Theme::getDarkPalette() { return darkPalette(); } diff --git a/src/theme.h b/src/theme.h new file mode 100644 index 0000000..71b7306 --- /dev/null +++ b/src/theme.h @@ -0,0 +1,27 @@ +#ifndef THEME_H +#define THEME_H + +#include <QColor> +#include <QDebug> +#include <QPalette> + +class Theme { +public: + static QPalette &getLightPalette(); + static QPalette &getDarkPalette(); + +private: + static QPalette &lightPalette() { + static QPalette palette = initLightPalette(); + return palette; + } + static QPalette &darkPalette() { + static QPalette palette = initDarkPalette(); + return palette; + } + + static QPalette initLightPalette(); + static QPalette initDarkPalette(); +}; + +#endif // THEME_H diff --git a/src/utils.cpp b/src/utils.cpp index c00b25d..46365e7 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -2,12 +2,12 @@ #include "def.h" #include <time.h> -utils::utils(QObject *parent) : QObject(parent) { setParent(parent); } +Utils::Utils(QObject *parent) : QObject(parent) { setParent(parent); } -utils::~utils() { this->deleteLater(); } +Utils::~Utils() { this->deleteLater(); } // calculate dir size -quint64 utils::dir_size(const QString &directory) { +quint64 Utils::dir_size(const QString &directory) { quint64 sizex = 0; QFileInfo str_info(directory); if (str_info.isDir()) { @@ -28,7 +28,7 @@ quint64 utils::dir_size(const QString &directory) { } // get the size of cache folder in human readble format -QString utils::refreshCacheSize(const QString cache_dir) { +QString Utils::refreshCacheSize(const QString cache_dir) { qint64 cache_size = dir_size(cache_dir); QString cache_unit; if (cache_size > 1024 * 1024 * 1024) { @@ -47,25 +47,25 @@ QString utils::refreshCacheSize(const QString cache_dir) { return QString::number(cache_size) + cache_unit; } -bool utils::delete_cache(const QString cache_dir) { +bool Utils::delete_cache(const QString cache_dir) { bool deleted = QDir(cache_dir).removeRecursively(); QDir(cache_dir).mkpath(cache_dir); return deleted; } // returns string with first letter capitalized -QString utils::toCamelCase(const QString &s) { +QString Utils::toCamelCase(const QString &s) { QStringList parts = s.split(' ', Qt::SkipEmptyParts); for (int i = 0; i < parts.size(); ++i) parts[i].replace(0, 1, parts[i][0].toUpper()); return parts.join(" "); } -QString utils::generateRandomId(int length) { +QString Utils::generateRandomId(int length) { return genRand(length, false, true, false); } -QString utils::genRand(int length, bool useUpper, bool useLower, +QString Utils::genRand(int length, bool useUpper, bool useLower, bool useDigits) { QString possibleCharacters; if (useUpper) { @@ -93,7 +93,7 @@ QString utils::genRand(int length, bool useUpper, bool useLower, return QString::fromLatin1(randomBytes); } -QString utils::convertSectoDay(qint64 secs) { +QString Utils::convertSectoDay(qint64 secs) { int day = secs / (24 * 3600); secs = secs % (24 * 3600); @@ -111,9 +111,28 @@ QString utils::convertSectoDay(qint64 secs) { return days; } -// static on demand path maker +/** + * @brief Returns the full path for a given file or directory name within a + * specified location. + * + * The method constructs the full path by concatenating the specified `pathname` + * with the provided `standardLocation`. If `standardLocation` is not provided, + * the default value is obtained from + * `QStandardPaths::writableLocation(QStandardPaths::DataLocation)`. + * + * @param pathname The name of the file or directory within the specified + * location. + * @param standardLocation (optional) The base directory to prepend to + * `pathname`. Default value: + * QStandardPaths::writableLocation(QStandardPaths::DataLocation). + * + * @return The full path, including the `pathname` and the `standardLocation`, + * separated by the appropriate directory separator. If the specified location + * does not exist, the method creates it using QDir::mkpath. The returned path + * ends with a directory separator. + */ QString -utils::returnPath(QString pathname, +Utils::returnPath(QString pathname, QString standardLocation = QStandardPaths::writableLocation( QStandardPaths::DataLocation)) { QChar sepe = QDir::separator(); @@ -122,10 +141,24 @@ utils::returnPath(QString pathname, return standardLocation + sepe + pathname + sepe; } -QString utils::EncodeXML(const QString &encodeMe) { - +/** + * @brief Encodes XML special characters in a given string and returns the + * encoded version. + * + * The method iterates over each character in the input `encodeMe` string and + * replaces XML special characters + * ('&', '\'', '"', '<', and '>') with their corresponding XML entities + * ('&', ''', '"', '<', and '>'). The encoded string is then + * returned. + * + * @param encodeMe The string to be encoded. + * @return The encoded version of the input string, where XML special characters + * are replaced with their corresponding entities. + */ +QString Utils::encodeXML(const QString &encodeMe) { QString temp; int length = encodeMe.size(); + for (int index = 0; index < length; index++) { QChar character(encodeMe.at(index)); @@ -159,8 +192,20 @@ QString utils::EncodeXML(const QString &encodeMe) { return temp; } -QString utils::DecodeXML(const QString &decodeMe) { - +/** + * @brief Decodes XML entities in a given string and returns the decoded + * version. + * + * The method creates a copy of the input `decodeMe` string and replaces XML + * entities + * ('&', ''', '"', '<', and '>') with their corresponding + * characters. The decoded string is then returned. + * + * @param decodeMe The string to be decoded. + * @return The decoded version of the input string, where XML entities are + * replaced with their corresponding characters. + */ +QString Utils::decodeXML(const QString &decodeMe) { QString temp(decodeMe); temp.replace("&", "&"); @@ -172,45 +217,96 @@ QString utils::DecodeXML(const QString &decodeMe) { return temp; } -QString utils::htmlToPlainText(const QString &str) { - QString out; - QTextDocument text; - text.setHtml(str); - out = text.toPlainText(); - text.deleteLater(); - return out.replace("\\\"", "'") - .replace("&", "&") - .replace(">", ">") - .replace("<", "<") - .replace("'", "'"); +/** + * @brief Retrieves the installation type based on the environment variables and + * heuristics. + * + * The method retrieves the value of the "INSTALL_TYPE" environment variable + * using QProcessEnvironment. If the "INSTALL_TYPE" variable is empty, the + * method performs heuristics to determine the installation type. It checks if + * the "SNAP" environment variable is set, in which case the installation type + * is considered as "snap". If the "SNAP" variable is not set, it checks if the + * "FLATPAK_ID" environment variable is not empty, in which case the + * installation type is considered as "flatpak". + * + * @return The installation type as a QString. It can be "snap", "flatpak", or + * an empty string if the installation type could not be determined. + */ +QString Utils::getInstallType() { + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + + // Retrieve the value of "INSTALL_TYPE" environment variable + QString installType = env.value("INSTALL_TYPE"); + + // Try guessing if it is empty + if (installType.isEmpty()) { + if (env.contains("SNAP")) { + installType = "snap"; + } else if (env.value("FLATPAK_ID").trimmed().isEmpty() == false) { + installType = "flatpak"; + } + } + + return installType.trimmed(); } -QString utils::appDebugInfo() { +/** + * @brief Retrieves debug information about the application. + * + * The method generates a formatted string containing various debug information + * about the application. It includes information such as the application name, + * version, source branch, commit hash, build datetime, Qt runtime version, Qt + * compiled version, system information, and installation mode. + * + * @return A QString containing the debug information about the application. + */ +QString Utils::appDebugInfo() { + QString installType = Utils::getInstallType(); + installType = + "<li><b>" + QObject::tr("Install mode") + ":</b> " + + QString(installType.trimmed().isEmpty() ? "Unknown" : installType) + + "</li>"; + + QString applicationName = QApplication::applicationName(); + QString version = QString(VERSIONSTR); + QString sourceBranch = QString(GIT_BRANCH); + QString commitHash = QString(GIT_HASH); + QString buildDatetime = QString::fromLatin1(BUILD_TIMESTAMP); + QString qtRuntimeVersion = QString(qVersion()); + QString qtCompiledVersion = QString(QT_VERSION_STR); + QString systemInfo = QSysInfo::prettyProductName(); + QString architecture = QSysInfo::currentCpuArchitecture(); + QString installMode = Utils::getInstallType(); QStringList debugInfo; - debugInfo << "<h3>" + QApplication::applicationName() + "</h3>" + debugInfo << "<h3>" + applicationName + "</h3>" << "<ul>" << "<li><b>" + QObject::tr("Version") + ":</b> " + - QString(VERSIONSTR) + "</li>" + version + "</li>" << "<li><b>" + QObject::tr("Source Branch") + ":</b> " + - QString(GIT_BRANCH) + "</li>" + sourceBranch + "</li>" << "<li><b>" + QObject::tr("Commit Hash") + ":</b> " + - QString(GIT_HASH) + "</li>" + commitHash + "</li>" << "<li><b>" + QObject::tr("Build Datetime") + ":</b> " + - QString::fromLatin1(BUILD_TIMESTAMP) + "</li>" + buildDatetime + "</li>" << "<li><b>" + QObject::tr("Qt Runtime Version") + ":</b> " + - QString(qVersion()) + "</li>" + qtRuntimeVersion + "</li>" << "<li><b>" + QObject::tr("Qt Compiled Version") + ":</b> " + - QString(QT_VERSION_STR) + "</li>" + qtCompiledVersion + "</li>" << "<li><b>" + QObject::tr("System") + ":</b> " + - QSysInfo::prettyProductName() + "</li>" + systemInfo + "</li>" << "<li><b>" + QObject::tr("Architecture") + ":</b> " + - QSysInfo::currentCpuArchitecture() + "</li>"; - debugInfo << "</ul>"; + architecture + "</li>" + << "<li><b>" + QObject::tr("Install mode") + ":</b> " + + QString(installMode.trimmed().isEmpty() ? "Unknown" + : installMode) + + "</li>" + << "</ul>"; + return debugInfo.join("\n"); } -void utils::DisplayExceptionErrorDialog(const QString &error_info) { +void Utils::DisplayExceptionErrorDialog(const QString &error_info) { QMessageBox message_box(QApplication::activeWindow()); message_box.setAttribute(Qt::WA_DeleteOnClose, true); message_box.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint); @@ -235,19 +331,31 @@ void utils::DisplayExceptionErrorDialog(const QString &error_info) { << "\nQt Runtime Version: " + QString(qVersion()) << "\nQt Compiled Version: " + QString(QT_VERSION_STR) << "\nSystem: " + QSysInfo::prettyProductName() - << "\nArchitecture: " + QSysInfo::currentCpuArchitecture(); + << "\nArchitecture: " + QSysInfo::currentCpuArchitecture() + << "\nInstall type: " + Utils::getInstallType(); message_box.setDetailedText(detailed_text.join("\n")); message_box.exec(); } -// Returns the same number, but rounded to one decimal place -float utils::RoundToOneDecimal(float number) { +/** + * Returns the same number, but rounded to one decimal place + * + * @brief Utils::RoundToOneDecimal + * @param number + * @return + */ +float Utils::RoundToOneDecimal(float number) { return QString::number(number, 'f', 1).toFloat(); } -// Returns a value for the environment variable name passed; -// if the env var isn't set, it returns an empty string -QString utils::GetEnvironmentVar(const QString &variable_name) { +/** + * Returns a value for the environment variable name passed; + * if the env var isn't set, it returns an empty string + * @brief Utils::GetEnvironmentVar + * @param variable_name + * @return + */ +QString Utils::GetEnvironmentVar(const QString &variable_name) { #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) // The only time this might fall down is on Linux when an // environment variable holds bytedata. Don't use this @@ -261,14 +369,24 @@ QString utils::GetEnvironmentVar(const QString &variable_name) { #endif } -void utils::desktopOpenUrl(const QString &str) { +/** + * @brief Opens the specified URL in the default desktop application. + * + * The method attempts to open the URL using the `xdg-open` command-line tool. + * If the `xdg-open` process fails to start within 1 second, it falls back to + * using `QDesktopServices` to open the URL. If both methods fail, a warning + * message is printed to the console. + * + * @param str The URL to be opened. + */ +void Utils::desktopOpenUrl(const QString &str) { QProcess *xdg_open = new QProcess(0); xdg_open->start("xdg-open", QStringList() << str); if (xdg_open->waitForStarted(1000) == false) { - // try using QdesktopServices + // Try using QDesktopServices bool opened = QDesktopServices::openUrl(QUrl(str)); if (opened == false) { - qWarning() << "failed to open url" << str; + qWarning() << "Failed to open URL:" << str; } } connect(xdg_open, @@ -282,7 +400,7 @@ void utils::desktopOpenUrl(const QString &str) { }); } -bool utils::isPhoneNumber(const QString &phoneNumber) { +bool Utils::isPhoneNumber(const QString &phoneNumber) { const QString phone = "^\\+(((\\d{2}))\\s?)?((\\d{2})|(\\((\\d{2})\\))\\s?)?(" "\\d{3,15})(\\-(\\d{3,15}))?$"; static QRegularExpression reg(phone); diff --git a/src/utils.h b/src/utils.h index c972ba4..76e8043 100644 --- a/src/utils.h +++ b/src/utils.h @@ -17,22 +17,21 @@ #include <QTextDocument> #include <QUuid> -class utils : public QObject { +class Utils : public QObject { Q_OBJECT public: - utils(QObject *parent = 0); - virtual ~utils(); -public slots: + Utils(QObject *parent = 0); + virtual ~Utils(); + static QString getInstallType(); static QString refreshCacheSize(const QString cache_dir); static bool delete_cache(const QString cache_dir); static QString toCamelCase(const QString &s); static QString generateRandomId(int length); static QString convertSectoDay(qint64 secs); static QString returnPath(QString pathname, QString standardLocation); - static QString EncodeXML(const QString &encodeMe); - static QString DecodeXML(const QString &decodeMe); - static QString htmlToPlainText(const QString &str); + static QString encodeXML(const QString &encodeMe); + static QString decodeXML(const QString &decodeMe); static QString GetEnvironmentVar(const QString &variable_name); static float RoundToOneDecimal(float number); static void DisplayExceptionErrorDialog(const QString &error_info); diff --git a/src/webenginepage.cpp b/src/webenginepage.cpp index c7b7086..7ff4d9c 100644 --- a/src/webenginepage.cpp +++ b/src/webenginepage.cpp @@ -1,9 +1,5 @@ #include "webenginepage.h" -#include <QIcon> -#include <QStyle> -#include <QWebEngineSettings> - WebEnginePage::WebEnginePage(QWebEngineProfile *profile, QObject *parent) : QWebEnginePage(profile, parent) { @@ -75,8 +71,11 @@ inline QString questionForFeature(QWebEnginePage::Feature feature) { void WebEnginePage::handleFeaturePermissionRequested(const QUrl &securityOrigin, Feature feature) { bool autoPlay = true; - if (settings.value("autoPlayMedia").isValid()) - autoPlay = settings.value("autoPlayMedia", false).toBool(); + if (SettingsManager::instance().settings().value("autoPlayMedia").isValid()) + autoPlay = SettingsManager::instance() + .settings() + .value("autoPlayMedia", false) + .toBool(); if (autoPlay && (feature == QWebEnginePage::MediaVideoCapture || feature == QWebEnginePage::MediaAudioVideoCapture)) { QWebEngineProfile *defProfile = QWebEngineProfile::defaultProfile(); @@ -92,8 +91,11 @@ void WebEnginePage::handleFeaturePermissionRequested(const QUrl &securityOrigin, QString question = questionForFeature(feature).arg(securityOrigin.host()); QString featureStr = QVariant::fromValue(feature).toString(); - settings.beginGroup("permissions"); - if (settings.value(featureStr, false).toBool()) { + SettingsManager::instance().settings().beginGroup("permissions"); + if (SettingsManager::instance() + .settings() + .value(featureStr, false) + .toBool()) { setFeaturePermission( securityOrigin, feature, QWebEnginePage::PermissionPolicy::PermissionGrantedByUser); @@ -104,29 +106,35 @@ void WebEnginePage::handleFeaturePermissionRequested(const QUrl &securityOrigin, setFeaturePermission( securityOrigin, feature, QWebEnginePage::PermissionPolicy::PermissionGrantedByUser); - settings.setValue(featureStr, true); + SettingsManager::instance().settings().setValue(featureStr, true); } else { setFeaturePermission( securityOrigin, feature, QWebEnginePage::PermissionPolicy::PermissionDeniedByUser); - settings.setValue(featureStr, false); + SettingsManager::instance().settings().setValue(featureStr, false); } } - settings.endGroup(); + SettingsManager::instance().settings().endGroup(); } void WebEnginePage::handleLoadFinished(bool ok) { // turn on Notification settings by default - if (settings.value("permissions/Notifications").isValid() == false) { - settings.beginGroup("permissions"); - settings.setValue("Notifications", true); + if (SettingsManager::instance() + .settings() + .value("permissions/Notifications") + .isValid() == false) { + SettingsManager::instance().settings().beginGroup("permissions"); + SettingsManager::instance().settings().setValue("Notifications", true); setFeaturePermission( QUrl("https://web.whatsapp.com/"), QWebEnginePage::Feature::Notifications, QWebEnginePage::PermissionPolicy::PermissionGrantedByUser); - settings.endGroup(); - } else if (settings.value("permissions/Notifications", true).toBool()) { + SettingsManager::instance().settings().endGroup(); + } else if (SettingsManager::instance() + .settings() + .value("permissions/Notifications", true) + .toBool()) { setFeaturePermission( QUrl("https://web.whatsapp.com/"), QWebEnginePage::Feature::Notifications, @@ -159,8 +167,10 @@ QStringList WebEnginePage::chooseFiles(QWebEnginePage::FileSelectionMode mode, } QFileDialog *dialog = new QFileDialog(); - bool usenativeFileDialog = - settings.value("useNativeFileDialog", false).toBool(); + bool usenativeFileDialog = SettingsManager::instance() + .settings() + .value("useNativeFileDialog", false) + .toBool(); if (usenativeFileDialog == false) { dialog->setOption(QFileDialog::DontUseNativeDialog, true); @@ -387,7 +397,10 @@ void WebEnginePage::injectMutationObserver() { } void WebEnginePage::injectFullWidthJavaScript() { - if (!settings.value("fullWidthView", true).toBool()) + if (!SettingsManager::instance() + .settings() + .value("fullWidthView", true) + .toBool()) return; QString js = R"(function updateFullWidthView(element) { diff --git a/src/webenginepage.h b/src/webenginepage.h index d039288..8f05e44 100644 --- a/src/webenginepage.h +++ b/src/webenginepage.h @@ -1,22 +1,22 @@ #ifndef WEBENGINEPAGE_H #define WEBENGINEPAGE_H -#include <QFileDialog> -#include <QWebEngineFullScreenRequest> -#include <QWebEngineNotification> -#include <QWebEngineProfile> - #include <QAuthenticator> #include <QDesktopServices> +#include <QFileDialog> +#include <QIcon> #include <QImageReader> #include <QMessageBox> +#include <QStyle> #include <QWebEngineCertificateError> -#include <QWebEnginePage> - #include <QWebEngineFullScreenRequest> +#include <QWebEngineNotification> +#include <QWebEnginePage> +#include <QWebEngineProfile> #include <QWebEngineRegisterProtocolHandlerRequest> +#include <QWebEngineSettings> -#include <QSettings> +#include "settingsmanager.h" #include "ui_certificateerrordialog.h" #include "ui_passworddialog.h" @@ -26,9 +26,6 @@ class WebEnginePage : public QWebEnginePage { public: WebEnginePage(QWebEngineProfile *profile, QObject *parent = nullptr); -private: - QSettings settings; - protected: bool acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, @@ -36,7 +33,7 @@ protected: QWebEnginePage *createWindow(QWebEnginePage::WebWindowType type) override; bool certificateError(const QWebEngineCertificateError &error) override; QStringList chooseFiles(FileSelectionMode mode, const QStringList &oldFiles, - const QStringList &acceptedMimeTypes); + const QStringList &acceptedMimeTypes) override; public slots: void handleFeaturePermissionRequested(const QUrl &securityOrigin, @@ -47,7 +44,7 @@ protected slots: void javaScriptConsoleMessage(WebEnginePage::JavaScriptConsoleMessageLevel level, const QString &message, int lineId, - const QString &sourceId); + const QString &sourceId) override; private slots: void handleAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *auth); diff --git a/src/webview.cpp b/src/webview.cpp index 8029ffd..035fb4b 100644 --- a/src/webview.cpp +++ b/src/webview.cpp @@ -7,8 +7,7 @@ #include <mainwindow.h> WebView::WebView(QWidget *parent, QStringList dictionaries) - : QWebEngineView(parent) { - dictionaries = dictionaries; + : QWebEngineView(parent), m_dictionaries(dictionaries) { QObject *parentMainWindow = this->parent(); while (!parentMainWindow->objectName().contains("MainWindow")) { @@ -99,22 +98,24 @@ void WebView::contextMenuEvent(QContextMenuEvent *event) { spellcheckAction->setCheckable(true); spellcheckAction->setChecked(pageWebengineProfile->isSpellCheckEnabled()); connect(spellcheckAction, &QAction::toggled, this, - [pageWebengineProfile, this](bool toogled) { + [pageWebengineProfile](bool toogled) { pageWebengineProfile->setSpellCheckEnabled(toogled); - settings.setValue("sc_enabled", toogled); + SettingsManager::instance().settings().setValue("sc_enabled", + toogled); }); menu->addAction(spellcheckAction); if (pageWebengineProfile->isSpellCheckEnabled()) { auto subMenu = menu->addMenu(tr("Select Language")); - for (const QString &dict : qAsConst(dictionaries)) { + for (const QString &dict : qAsConst(m_dictionaries)) { auto action = subMenu->addAction(dict); action->setCheckable(true); action->setChecked(languages.contains(dict)); - connect(action, &QAction::triggered, this, [pageWebengineProfile, dict, this]() { - pageWebengineProfile->setSpellCheckLanguages(QStringList() << dict); - settings.setValue("sc_dict", dict); - }); + connect( + action, &QAction::triggered, this, [pageWebengineProfile, dict]() { + pageWebengineProfile->setSpellCheckLanguages(QStringList() << dict); + SettingsManager::instance().settings().setValue("sc_dict", dict); + }); } } connect(menu, &QMenu::aboutToHide, menu, &QObject::deleteLater); diff --git a/src/webview.h b/src/webview.h index e03fa49..058341d 100644 --- a/src/webview.h +++ b/src/webview.h @@ -1,9 +1,10 @@ #ifndef WEBVIEW_H #define WEBVIEW_H -#include <QSettings> -#include <QWebEngineView> #include <QKeyEvent> +#include <QWebEngineView> + +#include "settingsmanager.h" class WebView : public QWebEngineView { Q_OBJECT @@ -13,13 +14,10 @@ public: protected: void contextMenuEvent(QContextMenuEvent *event) override; - -protected slots: - void wheelEvent(QWheelEvent *event); + void wheelEvent(QWheelEvent *event) override; private: - QStringList dictionaries; - QSettings settings; + QStringList m_dictionaries; }; #endif // WEBVIEW_H diff --git a/src/widgets/MoreApps/moreapps.cpp b/src/widgets/MoreApps/moreapps.cpp index b8e8c17..c333751 100644 --- a/src/widgets/MoreApps/moreapps.cpp +++ b/src/widgets/MoreApps/moreapps.cpp @@ -11,6 +11,7 @@ #include <algorithm> #include <cstdlib> #include <ctime> +#include <random> MoreApps::MoreApps(QWidget *parent, QNetworkAccessManager *nam, const QString &publisherName, const QUrl &remoteFilterUrl, @@ -217,7 +218,7 @@ void MoreApps::setRemoteIcon(const QUrl &iconUrl, QLabel *lb) { auto replyBytes = reply->readAll(); QPixmap pixmap; pixmap.loadFromData(replyBytes); - //qDebug() << "after load" << lb->size(); + // qDebug() << "after load" << lb->size(); lb->setPixmap(pixmap.scaled(lb->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } @@ -239,11 +240,10 @@ void MoreApps::showApps() { qDebug() << "showing apps..."; - std::srand(unsigned(std::time(0))); - // rand generator - auto rand = [](auto i) { return std::rand() % i; }; - // shuffle appList before adding - std::random_shuffle(mAppList.begin(), mAppList.end(), rand); + std::random_device rd; + std::mt19937 rng(rd()); + + std::shuffle(mAppList.begin(), mAppList.end(), rng); auto fallbackIconUrl = QUrl("https://dashboard.snapcraft.io/site_media/appmedia/" @@ -254,7 +254,7 @@ void MoreApps::showApps() { setRemoteIcon(fallbackIconUrl, nullptr); foreach (auto a, mAppList) { auto iconUrl = a.getIconUrl(); - //qDebug() << "pre-caching icon for" << a.getName(); + // qDebug() << "pre-caching icon for" << a.getName(); setRemoteIcon(iconUrl, nullptr); } } diff --git a/src/widgets/scrolltext/scrolltext.cpp b/src/widgets/scrolltext/scrolltext.cpp index b03b761..cac212f 100644 --- a/src/widgets/scrolltext/scrolltext.cpp +++ b/src/widgets/scrolltext/scrolltext.cpp @@ -15,7 +15,7 @@ ScrollText::ScrollText(QWidget *parent) : QWidget(parent), scrollPos(0) { setSeparator(" "); - connect(&timer, SIGNAL(timeout()), this, SLOT(timer_timeout())); + connect(&timer, &QTimer::timeout, this, &ScrollText::timer_timeout); timer.setInterval(50); } |