From 9ea334d08f42f3c362e86499dc3c0ed658bb428c Mon Sep 17 00:00:00 2001 From: keshavbhatt Date: Mon, 5 Apr 2021 02:11:25 +0530 Subject: src init --- src/webenginepage.h | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/webenginepage.h (limited to 'src/webenginepage.h') diff --git a/src/webenginepage.h b/src/webenginepage.h new file mode 100644 index 0000000..7ec1a69 --- /dev/null +++ b/src/webenginepage.h @@ -0,0 +1,49 @@ +#ifndef WEBENGINEPAGE_H +#define WEBENGINEPAGE_H + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "ui_certificateerrordialog.h" +#include "ui_passworddialog.h" + +class WebEnginePage : public QWebEnginePage +{ + Q_OBJECT +public: + WebEnginePage(QWebEngineProfile *profile, QObject *parent = nullptr); + +protected: + bool acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame) override; + QWebEnginePage* createWindow(QWebEnginePage::WebWindowType type) override; + bool certificateError(const QWebEngineCertificateError &error) override; + QStringList chooseFiles(FileSelectionMode mode, const QStringList &oldFiles, const QStringList &acceptedMimeTypes); + +public slots: + void handleFeaturePermissionRequested(const QUrl &securityOrigin, QWebEnginePage::Feature feature); + void handleLoadFinished(bool ok); + +private slots: + void handleAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *auth); + void handleProxyAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *auth, const QString &proxyHost); + void handleRegisterProtocolHandlerRequested(QWebEngineRegisterProtocolHandlerRequest request); +#if !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) + void handleSelectClientCertificate(QWebEngineClientCertificateSelection clientCertSelection); +#endif + void fullScreenRequestedByPage(QWebEngineFullScreenRequest request); +}; + +#endif // WEBENGINEPAGE_H -- cgit v1.2.3 From 278aefb57859f56cea18d4d4917244172e2154d4 Mon Sep 17 00:00:00 2001 From: keshavbhatt Date: Sat, 10 Apr 2021 21:55:43 +0530 Subject: follow set permission in page --- src/webenginepage.cpp | 76 ++++++++++++++++++++++++++++++++------------------- src/webenginepage.h | 4 +++ 2 files changed, 52 insertions(+), 28 deletions(-) (limited to 'src/webenginepage.h') diff --git a/src/webenginepage.cpp b/src/webenginepage.cpp index 4478d6d..33c89f9 100644 --- a/src/webenginepage.cpp +++ b/src/webenginepage.cpp @@ -2,17 +2,15 @@ #include #include +#include WebEnginePage::WebEnginePage(QWebEngineProfile *profile, QObject *parent) : QWebEnginePage(profile, parent) { // Connect signals and slots - connect(this, &QWebEnginePage::featurePermissionRequested, - this, &WebEnginePage::handleFeaturePermissionRequested); - connect(this, &QWebEnginePage::loadFinished, - this, &WebEnginePage::handleLoadFinished); profile->setHttpUserAgent(profile->httpUserAgent().replace("QtWebEngine/5.13.0","")); + connect(this, &QWebEnginePage::loadFinished,this, &WebEnginePage::handleLoadFinished); connect(this, &QWebEnginePage::authenticationRequired, this, &WebEnginePage::handleAuthenticationRequired); connect(this, &QWebEnginePage::featurePermissionRequested, this, &WebEnginePage::handleFeaturePermissionRequested); connect(this, &QWebEnginePage::proxyAuthenticationRequired, this, &WebEnginePage::handleProxyAuthenticationRequired); @@ -68,37 +66,59 @@ 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( autoPlay && (feature == QWebEnginePage::MediaVideoCapture || feature == QWebEnginePage::MediaAudioVideoCapture)) + { + QWebEngineProfile *defProfile = QWebEngineProfile::defaultProfile(); + auto* webSettings = defProfile->settings(); + webSettings->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture,false); + + profile()->settings()->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture,false); + } + QString title = tr("Permission Request"); QString question = questionForFeature(feature).arg(securityOrigin.host()); - if (!question.isEmpty() && QMessageBox::question(view()->window(), title, question) == QMessageBox::Yes) - setFeaturePermission(securityOrigin, feature, PermissionGrantedByUser); - else - setFeaturePermission(securityOrigin, feature, PermissionDeniedByUser); + + QString featureStr = QVariant::fromValue(feature).toString(); + settings.beginGroup("permissions"); + if(settings.value(featureStr,false).toBool()){ + setFeaturePermission(securityOrigin, feature, QWebEnginePage::PermissionPolicy::PermissionGrantedByUser); + }else{ + if (!question.isEmpty() && QMessageBox::question(view()->window(), title, question) == QMessageBox::Yes) + { + setFeaturePermission(securityOrigin, feature, QWebEnginePage::PermissionPolicy::PermissionGrantedByUser); + settings.setValue(featureStr,true); + }else{ + setFeaturePermission(securityOrigin, feature, QWebEnginePage::PermissionPolicy::PermissionDeniedByUser); + settings.setValue(featureStr,false); + } + } + settings.endGroup(); } void WebEnginePage::handleLoadFinished(bool ok) { Q_UNUSED(ok); - setFeaturePermission( - QUrl("https://web.whatsapp.com/"), - QWebEnginePage::Feature::Notifications, - QWebEnginePage::PermissionPolicy::PermissionGrantedByUser - ); - setFeaturePermission( - QUrl("https://web.whatsapp.com/"), - QWebEnginePage::Feature::MediaAudioCapture, - QWebEnginePage::PermissionPolicy::PermissionGrantedByUser - ); - setFeaturePermission( - QUrl("https://web.whatsapp.com/"), - QWebEnginePage::Feature::MediaVideoCapture, - QWebEnginePage::PermissionPolicy::PermissionGrantedByUser - ); - setFeaturePermission( - QUrl("https://web.whatsapp.com/"), - QWebEnginePage::Feature::MediaAudioVideoCapture, - QWebEnginePage::PermissionPolicy::PermissionGrantedByUser - ); + //turn on Notification settings by default + if(settings.value("permissions/Notifications").isValid()==false) + { + settings.beginGroup("permissions"); + 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()) { + setFeaturePermission( + QUrl("https://web.whatsapp.com/"), + QWebEnginePage::Feature::Notifications, + QWebEnginePage::PermissionPolicy::PermissionGrantedByUser + ); + } } void WebEnginePage::fullScreenRequestedByPage(QWebEngineFullScreenRequest request) diff --git a/src/webenginepage.h b/src/webenginepage.h index 7ec1a69..a8241d0 100644 --- a/src/webenginepage.h +++ b/src/webenginepage.h @@ -17,6 +17,8 @@ #include #include +#include + #include "ui_certificateerrordialog.h" #include "ui_passworddialog.h" @@ -26,6 +28,8 @@ class WebEnginePage : public QWebEnginePage public: WebEnginePage(QWebEngineProfile *profile, QObject *parent = nullptr); +private: + QSettings settings; protected: bool acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame) override; QWebEnginePage* createWindow(QWebEnginePage::WebWindowType type) override; -- cgit v1.2.3 From 8cfbcf4bebd152527f110fdbf203ef1aac593f1e Mon Sep 17 00:00:00 2001 From: Keshav Date: Sat, 7 May 2022 20:03:17 +0530 Subject: chore: clean UA & disable js debug in app stdout --- src/webenginepage.cpp | 18 +++++++++++++++-- src/webenginepage.h | 55 +++++++++++++++++++++++++++++++-------------------- 2 files changed, 50 insertions(+), 23 deletions(-) (limited to 'src/webenginepage.h') diff --git a/src/webenginepage.cpp b/src/webenginepage.cpp index 451d187..9a35761 100644 --- a/src/webenginepage.cpp +++ b/src/webenginepage.cpp @@ -6,8 +6,13 @@ WebEnginePage::WebEnginePage(QWebEngineProfile *profile, QObject *parent) : QWebEnginePage(profile, parent) { - profile->setHttpUserAgent( - profile->httpUserAgent().replace("QtWebEngine/5.13.0", "")); + + auto userAgent = profile->httpUserAgent(); + auto webengineversion = userAgent.split("QtWebEngine").last().split(" ").first(); + auto toRemove = "QtWebEngine"+webengineversion; + auto cleanUserAgent = userAgent.remove(toRemove).replace(" ", " "); + profile->setHttpUserAgent(cleanUserAgent); + connect(this, &QWebEnginePage::loadFinished, this, &WebEnginePage::handleLoadFinished); connect(this, &QWebEnginePage::authenticationRequired, this, @@ -286,3 +291,12 @@ void WebEnginePage::handleSelectClientCertificate( qDebug() << selection.host(); } #endif + +void WebEnginePage::javaScriptConsoleMessage( + WebEnginePage::JavaScriptConsoleMessageLevel level, const QString &message, + int lineId, const QString &sourceId) { + Q_UNUSED(level); + Q_UNUSED(message); + Q_UNUSED(lineId); + Q_UNUSED(sourceId); +} diff --git a/src/webenginepage.h b/src/webenginepage.h index a8241d0..e2684f3 100644 --- a/src/webenginepage.h +++ b/src/webenginepage.h @@ -1,53 +1,66 @@ #ifndef WEBENGINEPAGE_H #define WEBENGINEPAGE_H - #include #include #include #include -#include +#include #include -#include #include +#include #include -#include +#include -#include #include +#include #include #include "ui_certificateerrordialog.h" #include "ui_passworddialog.h" -class WebEnginePage : public QWebEnginePage -{ - Q_OBJECT +class WebEnginePage : public QWebEnginePage { + Q_OBJECT public: - WebEnginePage(QWebEngineProfile *profile, QObject *parent = nullptr); + WebEnginePage(QWebEngineProfile *profile, QObject *parent = nullptr); private: - QSettings settings; + QSettings settings; + protected: - bool acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame) override; - QWebEnginePage* createWindow(QWebEnginePage::WebWindowType type) override; - bool certificateError(const QWebEngineCertificateError &error) override; - QStringList chooseFiles(FileSelectionMode mode, const QStringList &oldFiles, const QStringList &acceptedMimeTypes); + bool acceptNavigationRequest(const QUrl &url, + QWebEnginePage::NavigationType type, + bool isMainFrame) override; + QWebEnginePage *createWindow(QWebEnginePage::WebWindowType type) override; + bool certificateError(const QWebEngineCertificateError &error) override; + QStringList chooseFiles(FileSelectionMode mode, const QStringList &oldFiles, + const QStringList &acceptedMimeTypes); public slots: - void handleFeaturePermissionRequested(const QUrl &securityOrigin, QWebEnginePage::Feature feature); - void handleLoadFinished(bool ok); + void handleFeaturePermissionRequested(const QUrl &securityOrigin, + QWebEnginePage::Feature feature); + void handleLoadFinished(bool ok); +protected slots: + void + javaScriptConsoleMessage(WebEnginePage::JavaScriptConsoleMessageLevel level, + const QString &message, int lineId, + const QString &sourceId); private slots: - void handleAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *auth); - void handleProxyAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *auth, const QString &proxyHost); - void handleRegisterProtocolHandlerRequested(QWebEngineRegisterProtocolHandlerRequest request); + void handleAuthenticationRequired(const QUrl &requestUrl, + QAuthenticator *auth); + void handleProxyAuthenticationRequired(const QUrl &requestUrl, + QAuthenticator *auth, + const QString &proxyHost); + void handleRegisterProtocolHandlerRequested( + QWebEngineRegisterProtocolHandlerRequest request); #if !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) - void handleSelectClientCertificate(QWebEngineClientCertificateSelection clientCertSelection); + void handleSelectClientCertificate( + QWebEngineClientCertificateSelection clientCertSelection); #endif - void fullScreenRequestedByPage(QWebEngineFullScreenRequest request); + void fullScreenRequestedByPage(QWebEngineFullScreenRequest request); }; #endif // WEBENGINEPAGE_H -- cgit v1.2.3 From 011db4495d98932cbffa5fc2268ee1a3e2984aa6 Mon Sep 17 00:00:00 2001 From: Keshav Bhatt Date: Fri, 27 Jan 2023 02:57:48 +0530 Subject: chore: cleanup - move methods to page --- src/SunClock.cpp | 276 -------------------------------- src/SunClock.hpp | 126 --------------- src/WhatsApp.pro | 10 +- src/automatictheme.cpp | 2 +- src/downloadwidget.h | 2 +- src/downloadwidget.ui | 3 +- src/elidedlabel.cpp | 52 ------ src/elidedlabel.h | 49 ------ src/mainwindow.cpp | 147 +++-------------- src/mainwindow.h | 5 - src/sunclock.cpp | 276 ++++++++++++++++++++++++++++++++ src/sunclock.hpp | 126 +++++++++++++++ src/webenginepage.cpp | 113 ++++++++++++- src/webenginepage.h | 5 + src/widgets/elidedlabel/elidedlabel.cpp | 52 ++++++ src/widgets/elidedlabel/elidedlabel.h | 49 ++++++ 16 files changed, 648 insertions(+), 645 deletions(-) delete mode 100644 src/SunClock.cpp delete mode 100644 src/SunClock.hpp delete mode 100644 src/elidedlabel.cpp delete mode 100644 src/elidedlabel.h create mode 100644 src/sunclock.cpp create mode 100644 src/sunclock.hpp create mode 100644 src/widgets/elidedlabel/elidedlabel.cpp create mode 100644 src/widgets/elidedlabel/elidedlabel.h (limited to 'src/webenginepage.h') diff --git a/src/SunClock.cpp b/src/SunClock.cpp deleted file mode 100644 index 132c0a6..0000000 --- a/src/SunClock.cpp +++ /dev/null @@ -1,276 +0,0 @@ -#include -#include -#include - -inline double rad(double degrees) { - static const double degToRad = 4.0 * atan(1.0) / 180.0; - return degrees * degToRad; -} - -inline double deg(double radians) { - static const double radToDeg = 180.0 / (4.0 * atan(1.0)); - return radians * radToDeg; -} - -Sunclock::Sunclock(double const &latitude_, double const &longitude_, - double const &tz_offset_) - : latitude(latitude_), longitude(longitude_), tz_offset(tz_offset_) {} - -double Sunclock::irradiance() { return irradiance(time(0)); } - -double Sunclock::irradiance(time_t when) { - when = when + (time_t)(tz_offset * 60 * 60); - struct tm *t = gmtime(&when); - double _time_of_day = time_of_day(when); - double _julian_day = julian_day(t, _time_of_day, tz_offset); - double _julian_century = julian_century(_julian_day); - double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); - double _mean_long_sun = mean_long_sun(_julian_century); - double _mean_anom_sun = mean_anom_sun(_julian_century); - double _sun_eq_of_centre = sun_eq_of_centre(_mean_anom_sun, _julian_century); - double _sun_true_long = sun_true_long(_mean_long_sun, _sun_eq_of_centre); - double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); - double _sun_app_long = sun_app_long(_sun_true_long, _julian_century); - double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); - double _var_y = var_y(_obliq_corr); - double _eq_of_time = - eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); - double _declination = declination(_obliq_corr, _sun_app_long); - double _true_solar_time = true_solar_time(_time_of_day, _eq_of_time); - double _hour_angle = hour_angle(_true_solar_time); - double _solar_zenith = solar_zenith(_declination, _hour_angle); - return std::cos(rad(_solar_zenith)); -} - -time_t Sunclock::sunrise() { return sunrise(time(0)); } - -time_t Sunclock::sunrise(time_t date) { - date = date + (time_t)(tz_offset * 60 * 60); - struct tm *t = gmtime(&date); - double _time_of_day = time_of_day(date); - double _julian_day = julian_day(t, _time_of_day, tz_offset); - double _julian_century = julian_century(_julian_day); - double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); - double _mean_long_sun = mean_long_sun(_julian_century); - double _mean_anom_sun = mean_anom_sun(_julian_century); - double _sun_eq_of_centre = sun_eq_of_centre(_mean_anom_sun, _julian_century); - double _sun_true_long = sun_true_long(_mean_long_sun, _sun_eq_of_centre); - double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); - double _sun_app_long = sun_app_long(_sun_true_long, _julian_century); - double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); - double _var_y = var_y(_obliq_corr); - double _eq_of_time = - eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); - double _declination = declination(_obliq_corr, _sun_app_long); - double _hour_angle_sunrise = hour_angle_sunrise(_declination); - - double noon_decimal_day = - (720 - 4 * longitude - _eq_of_time + tz_offset * 60) / 1440; - double decimal_day = noon_decimal_day - _hour_angle_sunrise * 4 / 1440; - return time_from_decimal_day(date, decimal_day) - - (time_t)(tz_offset * 60 * 60); -} - -time_t Sunclock::solar_noon() { return solar_noon(time(0)); } - -time_t Sunclock::solar_noon(time_t date) { - date = date + (time_t)(tz_offset * 60 * 60); - struct tm *t = gmtime(&date); - double _time_of_day = time_of_day(date); - double _julian_day = julian_day(t, _time_of_day, tz_offset); - double _julian_century = julian_century(_julian_day); - double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); - double _mean_long_sun = mean_long_sun(_julian_century); - double _mean_anom_sun = mean_anom_sun(_julian_century); - double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); - double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); - double _var_y = var_y(_obliq_corr); - double _eq_of_time = - eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); - - double decimal_day = - (720 - 4 * longitude - _eq_of_time + tz_offset * 60) / 1440; - return time_from_decimal_day(date, decimal_day) - - (time_t)(tz_offset * 60 * 60); -} - -time_t Sunclock::sunset() { return sunset(time(0)); } - -time_t Sunclock::sunset(time_t date) { - date = date + (time_t)(tz_offset * 60 * 60); - struct tm *t = gmtime(&date); - double _time_of_day = time_of_day(date); - double _julian_day = julian_day(t, _time_of_day, tz_offset); - double _julian_century = julian_century(_julian_day); - double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); - double _mean_long_sun = mean_long_sun(_julian_century); - double _mean_anom_sun = mean_anom_sun(_julian_century); - double _sun_eq_of_centre = sun_eq_of_centre(_mean_anom_sun, _julian_century); - double _sun_true_long = sun_true_long(_mean_long_sun, _sun_eq_of_centre); - double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); - double _sun_app_long = sun_app_long(_sun_true_long, _julian_century); - double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); - double _var_y = var_y(_obliq_corr); - double _eq_of_time = - eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); - double _declination = declination(_obliq_corr, _sun_app_long); - double _hour_angle_sunrise = hour_angle_sunrise(_declination); - - double noon_decimal_day = - (720 - 4 * longitude - _eq_of_time + tz_offset * 60) / 1440; - double decimal_day = noon_decimal_day + _hour_angle_sunrise * 4 / 1440; - return time_from_decimal_day(date, decimal_day) - - (time_t)(tz_offset * 60 * 60); -} - -double Sunclock::time_of_day(time_t date) { - struct tm *t = gmtime(&date); - return (t->tm_hour + t->tm_min / 60.0 + t->tm_sec / 3600.0) / 24.0; -} - -time_t Sunclock::time_from_decimal_day(time_t date, double decimal_day) { - struct std::tm epoch; - epoch.tm_isdst = 0; - epoch.tm_sec = epoch.tm_min = epoch.tm_hour = epoch.tm_mon = 0; - epoch.tm_mday = 1; - epoch.tm_year = 70; - time_t local_tz_offset = mktime(&epoch); - - struct tm *dt = gmtime(&date); - struct tm t = {}; - t.tm_year = dt->tm_year; - t.tm_mon = dt->tm_mon; - t.tm_mday = dt->tm_mday; - double hours = 24.0 * decimal_day; - t.tm_hour = int(hours); - double minutes = (hours - t.tm_hour) * 60; - t.tm_min = int(minutes); - double seconds = (minutes - t.tm_sec) * 60; - t.tm_sec = int(seconds) % 60; - return mktime(&t) - local_tz_offset; -} - -int Sunclock::days_since_1900(struct tm *t) { - int year = t->tm_year; - if (year < 0 || year > 199) { - throw std::invalid_argument( - "days_since_1900 - Date must be between 1900 and 2099"); - } - int month = t->tm_mon + 1; - int days = t->tm_mday; - - if (month < 3) { - month += 12; - year--; - } - int yearDays = (int)(year * 365.25); - int monthDays = (int)((month + 1) * 30.61); - - return (yearDays + monthDays + days - 63); -} - -double Sunclock::julian_day(struct tm *t, double const &time_of_day, - double const &tz_offset) { - return days_since_1900(t) + 2415018.5 + time_of_day - tz_offset / 24; -} - -double Sunclock::julian_century(double _julian_day) { - return (_julian_day - 2451545.0) / 36525.0; -} - -double Sunclock::mean_long_sun(double _julian_century) { - return ( - 280.46646 + - fmod(_julian_century * (36000.76983 + _julian_century * 0.0003032), 360)); -} - -double Sunclock::mean_anom_sun(double _julian_century) { - return 357.52911 + - _julian_century * (35999.05029 - 0.0001537 * _julian_century); -} - -double Sunclock::sun_eq_of_centre(double _mean_anom_sun, - double _julian_century) { - return sin(rad(_mean_anom_sun)) * - (1.914602 - - _julian_century * (0.004817 + 0.000014 * _julian_century)) + - sin(rad(2 * _mean_anom_sun)) * - (0.019993 - 0.000101 * _julian_century) + - sin(rad(3 * _mean_anom_sun)) * 0.000289; -} - -double Sunclock::sun_true_long(double _mean_long_sun, - double _sun_eq_of_centre) { - return _mean_long_sun + _sun_eq_of_centre; -} - -double Sunclock::eccent_earth_orbit(double _julian_century) { - return 0.016708634 - - _julian_century * (0.000042037 + 0.0001537 * _julian_century); -} - -double Sunclock::var_y(double _obliq_corr) { - return tan(rad(_obliq_corr / 2)) * tan(rad(_obliq_corr / 2)); -} - -double Sunclock::mean_obliq_ecliptic(double _julian_century) { - return (23 + (26 + ((21.448 - _julian_century * - (46.815 + _julian_century * - (0.00059 - _julian_century * - 0.001813)))) / - 60) / - 60); -} - -double Sunclock::obliq_corr(double _mean_obliq_ecliptic, - double _julian_century) { - return _mean_obliq_ecliptic + - 0.00256 * cos(deg(125.04 - 1934.136 * _julian_century)); -} - -double Sunclock::sun_app_long(double _sun_true_long, double _julian_century) { - return (_sun_true_long - 0.00569 - - 0.00478 * sin(deg(125.04 - 1934.136 * _julian_century))); -} - -double Sunclock::declination(double _obliq_corr, double _sun_app_long) { - return deg(asin(sin(rad(_obliq_corr)) * sin(rad(_sun_app_long)))); -} - -double Sunclock::eq_of_time(double _var_y, double _mean_long_sun, - double _eccent_earth_orbit, double _mean_anom_sun) { - return 4 * deg(_var_y * sin(2 * rad(_mean_long_sun)) - - 2 * _eccent_earth_orbit * sin(rad(_mean_anom_sun)) + - 4 * _eccent_earth_orbit * _var_y * sin(rad(_mean_anom_sun)) * - cos(2 * rad(_mean_long_sun)) - - 0.5 * _var_y * _var_y * sin(4 * rad(_mean_long_sun)) - - 1.25 * _eccent_earth_orbit * _eccent_earth_orbit * - sin(2 * rad(_mean_anom_sun))); -} - -double Sunclock::true_solar_time(double _time_of_day, double _eq_of_time) { - return fmod( - (_time_of_day * 1440 + _eq_of_time + 4 * longitude - 60 * tz_offset), - 1440); -} - -double Sunclock::hour_angle(double _true_solar_time) { - return (_true_solar_time / 4 < 0 ? _true_solar_time / 4 + 180 - : _true_solar_time / 4 - 180); -} - -double Sunclock::hour_angle_sunrise(double _declination) { - return deg( - acos(cos(rad(90.833)) / (cos(rad(latitude)) * cos(rad(_declination))) - - tan(rad(latitude)) * tan(rad(_declination)))); -} - -double Sunclock::solar_zenith(double _declination, double _hour_angle) { - return deg(acos(sin(rad(latitude)) * sin(rad(_declination)) + - cos(rad(latitude)) * cos(rad(_declination)) * - cos(rad(_hour_angle)))); -} - -double Sunclock::solar_elevation(double _solar_zenith) { - return 90 - _solar_zenith; -} diff --git a/src/SunClock.hpp b/src/SunClock.hpp deleted file mode 100644 index 4cfad57..0000000 --- a/src/SunClock.hpp +++ /dev/null @@ -1,126 +0,0 @@ -#ifndef DAYLIGHT_SUNCLOCK_HPP -#define DAYLIGHT_SUNCLOCK_HPP - -#include - -class Sunclock { -public: - Sunclock(double const &latitude_, double const &longitude_, double const &tz_offset_ = 0); - - /** - * \overload double Sunclock::irradiance(time_t when) - */ - double irradiance(); - - /** - * Specifically, we calculate Direct Normal Irradiance - * That is we do not consider atmospheric components like cloud cover, - * moisture content etc. - * - * @param when - * @return a value representing irradiance (power per unit area) - */ - double irradiance(time_t when); - - /** - * \overload time_t Sunclock::sunrise(time_t date) - */ - time_t sunrise(); - - /** - * Returns sunrise time for given date - * - * @param date only date is considered - * @return sunrise time - */ - time_t sunrise(time_t date); - - /** - * \overload time_t Sunclock::solar_noon(time_t date) - */ - time_t solar_noon(); - - /** - * Returns solar_noon time for given date - * - * @param date only date is considered - * @return solar_noon time - */ - time_t solar_noon(time_t date); - - /** - * \overload time_t Sunclock::sunset(time_t date) - */ - time_t sunset(); - - /** - * Returns sunset time for given date - * - * @param date only date is considered - * @return sunset time - */ - time_t sunset(time_t date); - -private: - // in decimal degrees, east is positive - double const latitude; - - // in decimal degrees, north is positive - double const longitude; - - // in hours, east is positive, i.e. IST (+05:30) is 5.5 - double const tz_offset; - - /** - * @param date - * @return percentage past midnight, i.e. noon is 0.5 - */ - double time_of_day(time_t date); - - static int days_since_1900(struct tm *t); - - /** - * @param date - * @param decimal_day decimal between 0.0 and 1.0, e.g. noon = 0.5 - * @return time_t with date and time set accordingly - */ - static time_t time_from_decimal_day(time_t date, double decimal_day); - - /** - * Get day count since Monday, January 1, 4713 BC - * https://en.wikipedia.org/wiki/Julian_day - * - * @param t - * @param time_of_day percentage past midnight, i.e. noon is 0.5 - * @param tz_offset in hours, east is positive, i.e. IST (+05:30) is 5.5 - * @return julian day - */ - static double julian_day(struct tm *t, double const &time_of_day, double const &tz_offset); - - /** - * Extract information in a suitable format from a time_t object. - */ - void prepare_time(time_t const &when, struct tm *ptm); - - double julian_century(double _julian_day); - double mean_long_sun(double _julian_century); - double mean_anom_sun(double _julian_century); - double sun_eq_of_centre(double _mean_anom_sun, double _julian_century); - double eccent_earth_orbit(double _julian_century); - double var_y(double _obliq_corr); - double mean_obliq_ecliptic(double _julian_century); - double sun_true_long(double _mean_long_sun, double _sun_eq_of_centre); - double obliq_corr(double _mean_obliq_ecliptic, double _julian_century); - double sun_app_long(double _sun_true_long, double _julian_century); - double declination(double _obliq_corr, double _sun_app_long); - double eq_of_time(double _var_y, double _mean_long_sun, double _eccent_earth_orbit, - double _mean_anom_sun); - double true_solar_time(double _time_of_day, double _eq_of_time); - double hour_angle(double _true_solar_time); - double hour_angle_sunrise(double _declination); - double solar_zenith(double _declination, double _hour_angle); - double solar_elevation(double _solar_zenith); -}; - -#endif - diff --git a/src/WhatsApp.pro b/src/WhatsApp.pro index 36b1ca2..844c000 100644 --- a/src/WhatsApp.pro +++ b/src/WhatsApp.pro @@ -59,29 +59,27 @@ DEFINES += VERSIONSTR=\\\"$${VERSION}\\\" # DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ - SunClock.cpp \ about.cpp \ automatictheme.cpp \ dictionaries.cpp \ downloadmanagerwidget.cpp \ downloadwidget.cpp \ - elidedlabel.cpp \ lock.cpp \ main.cpp \ mainwindow.cpp \ permissiondialog.cpp \ rateapp.cpp \ settingswidget.cpp \ + sunclock.cpp \ utils.cpp \ webenginepage.cpp \ webview.cpp \ + widgets/elidedlabel/elidedlabel.cpp \ widgets/scrolltext/scrolltext.cpp - RESOURCES += \ icons.qrc HEADERS += \ - SunClock.hpp \ about.h \ autolockeventfilter.h \ automatictheme.h \ @@ -90,7 +88,6 @@ HEADERS += \ dictionaries.h \ downloadmanagerwidget.h \ downloadwidget.h \ - elidedlabel.h \ lock.h \ mainwindow.h \ notificationpopup.h \ @@ -98,11 +95,12 @@ HEADERS += \ rateapp.h \ requestinterceptor.h \ settingswidget.h \ + sunclock.hpp \ utils.h \ webenginepage.h \ webview.h \ + widgets/elidedlabel/elidedlabel.h \ widgets/scrolltext/scrolltext.h - FORMS += \ about.ui \ automatictheme.ui \ diff --git a/src/automatictheme.cpp b/src/automatictheme.cpp index 6e14623..3cf33c8 100644 --- a/src/automatictheme.cpp +++ b/src/automatictheme.cpp @@ -1,7 +1,7 @@ #include "automatictheme.h" #include "ui_automatictheme.h" -#include "SunClock.hpp" +#include "sunclock.hpp" #include AutomaticTheme::AutomaticTheme(QWidget *parent) diff --git a/src/downloadwidget.h b/src/downloadwidget.h index ff9e488..074a979 100644 --- a/src/downloadwidget.h +++ b/src/downloadwidget.h @@ -52,7 +52,7 @@ #define DOWNLOADWIDGET_H #include "ui_downloadwidget.h" -#include "elidedlabel.h" +#include "widgets/elidedlabel/elidedlabel.h" #include diff --git a/src/downloadwidget.ui b/src/downloadwidget.ui index d405b8f..45d16e9 100644 --- a/src/downloadwidget.ui +++ b/src/downloadwidget.ui @@ -47,7 +47,6 @@ - 75 true @@ -72,7 +71,7 @@ ElidedLabel QLabel -
elidedlabel.h
+
widgets/elidedlabel/elidedlabel.h
diff --git a/src/elidedlabel.cpp b/src/elidedlabel.cpp deleted file mode 100644 index e870959..0000000 --- a/src/elidedlabel.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include "elidedlabel.h" - -#include -#include -#include -#include - -ElidedLabel::ElidedLabel(QWidget *parent) - : QLabel(parent), m_elide_mode(Qt::ElideRight) { - setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); -} - -ElidedLabel::ElidedLabel(const QString &txt, QWidget *parent) - : QLabel(txt, parent), m_elide_mode(Qt::ElideRight) { - setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); -} - -ElidedLabel::ElidedLabel(const QString &txt, Qt::TextElideMode elideMode, - QWidget *parent) - : QLabel(txt, parent), m_elide_mode(elideMode) { - setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); -} - -void ElidedLabel::setText(const QString &txt) { - QLabel::setText(txt); - cacheElidedText(geometry().width()); - setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); -} - -void ElidedLabel::cacheElidedText(int w) { - m_cached_elided_text = fontMetrics().elidedText( - text(), m_elide_mode, w, (buddy() == nullptr) ? 0 : Qt::TextShowMnemonic); -} - -void ElidedLabel::resizeEvent(QResizeEvent *e) { - QLabel::resizeEvent(e); - cacheElidedText(e->size().width()); -} - -void ElidedLabel::paintEvent(QPaintEvent *e) { - if (m_elide_mode == Qt::ElideNone) { - QLabel::paintEvent(e); - } else { - QPainter p(this); - p.drawText(0, 0, geometry().width(), geometry().height(), - QStyle::visualAlignment(text().isRightToLeft() ? Qt::RightToLeft - : Qt::LeftToRight, - alignment()) | - ((buddy() == nullptr) ? 0 : Qt::TextShowMnemonic), - m_cached_elided_text); - } -} diff --git a/src/elidedlabel.h b/src/elidedlabel.h deleted file mode 100644 index 7dc610a..0000000 --- a/src/elidedlabel.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -// A label that elides its text when not enough geometry is available to show all of the text. -// Currently only capable of one-line. -class ElidedLabel : public QLabel { - Q_OBJECT - -private: - Qt::TextElideMode m_elide_mode; - QString m_cached_elided_text; - - -public: - ElidedLabel(QWidget* parent = NULL); - ElidedLabel(const QString& txt, QWidget* parent = NULL); - ElidedLabel(const QString& txt, Qt::TextElideMode elideMode = Qt::ElideRight, QWidget* parent = NULL); - -public: - // Set the elide mode used for displaying text. - inline void setElideMode(Qt::TextElideMode elideMode) { - m_elide_mode = elideMode; - updateGeometry(); - } - - // Get the elide mode currently used to display text. - inline Qt::TextElideMode elideMode() const { - return m_elide_mode; - } - - - -public: // QLabel overrides - void setText(const QString&); // note: not virtual so no polymorphism ... - - -protected: // QLabel overrides - virtual void paintEvent(QPaintEvent*) override; - virtual void resizeEvent(QResizeEvent*) override; - -protected: - // Cache the elided text so as to not recompute it every paint event - void cacheElidedText(int w); - -}; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3d01ba0..ae8fdbe 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -205,11 +205,11 @@ void MainWindow::updateWindowTheme() { settings.value("widgetStyle", "Fusion").toString())); if (settings.value("windowTheme", "light").toString() == "dark") { qApp->setPalette(darkPalette); - this->webEngine->setStyleSheet( + webEngine->setStyleSheet( "QWebEngineView{background:rgb(17, 27, 33);}"); // whatsapp dark color } else { qApp->setPalette(lightPalette); - this->webEngine->setStyleSheet( + webEngine->setStyleSheet( "QWebEngineView{background:#F0F0F0;}"); // whatsapp light color } @@ -316,7 +316,7 @@ void MainWindow::initSettingWidget() { webSettings->setAttribute( QWebEngineSettings::PlaybackRequiresUserGesture, checked); - this->webEngine->page()->profile()->settings()->setAttribute( + webEngine->page()->profile()->settings()->setAttribute( QWebEngineSettings::PlaybackRequiresUserGesture, checked); }); @@ -357,7 +357,7 @@ void MainWindow::initSettingWidget() { connect(settingsWidget, &SettingsWidget::notificationPopupTimeOutChanged, settingsWidget, [=]() { - setNotificationPresenter(this->webEngine->page()->profile()); + setNotificationPresenter(webEngine->page()->profile()); }); connect(settingsWidget, &SettingsWidget::notify, settingsWidget, @@ -479,7 +479,7 @@ void MainWindow::showSettings(bool isAskedByCLI) { void MainWindow::updateSettingsUserAgentWidget() { settingsWidget->updateDefaultUAButton( - this->webEngine->page()->profile()->httpUserAgent()); + webEngine->page()->profile()->httpUserAgent()); } void MainWindow::askToReloadPage() { @@ -806,16 +806,16 @@ void MainWindow::createWebEngine() { m_dictionaries = Dictionaries::GetDictionaries(); - WebView *webEngine = new WebView(this, m_dictionaries); - setCentralWidget(webEngine); - webEngine->setSizePolicy(widgetSize); - webEngine->show(); + WebView *webEngineView = new WebView(this, m_dictionaries); + setCentralWidget(webEngineView); + webEngineView->setSizePolicy(widgetSize); + webEngineView->show(); - this->webEngine = webEngine; + this->webEngine = webEngineView; - webEngine->addAction(minimizeAction); - webEngine->addAction(lockAction); - webEngine->addAction(quitAction); + webEngineView->addAction(minimizeAction); + webEngineView->addAction(lockAction); + webEngineView->addAction(quitAction); createWebPage(false); } @@ -964,119 +964,14 @@ void MainWindow::handleLoadFinished(bool loaded) { checkLoadedCorrectly(); updatePageTheme(); handleZoom(); - injectMutationObserver(); - injectPreventScrollWheelZoomHelper(); - injectFullWidthJavaScript(); - injectClassChangeObserver(); - injectNewChatJavaScript(); + if (settingsWidget != nullptr) { settingsWidget->refresh(); } } } -void MainWindow::injectPreventScrollWheelZoomHelper() { - QString js = R"( - (function () { - const SSWZ = function () { - this.keyScrollHandler = function (e) { - if (e.ctrlKey) { - e.preventDefault(); - return false; - } - } - }; - if (window === top) { - const sswz = new SSWZ(); - window.addEventListener('wheel', sswz.keyScrollHandler, { - passive: false - }); - } - })(); - )"; - webEngine->page()->runJavaScript(js); -} - -void MainWindow::injectClassChangeObserver() { - QString js = R"( - const observer = new MutationObserver(() => { - var haveFullView = document.body.classList.contains('whatsie-full-view'); - var container = document.querySelector('#app > .app-wrapper-web > div'); - if(container){ - if(haveFullView){ - container.style.width = '100%'; - container.style.height = '100%'; - container.style.top = '0'; - container.style.maxWidth = 'unset'; - }else{ - container.style.width = null; - container.style.height = null; - container.style.top = null; - container.style.maxWidth = null; - } - } - }); - observer.observe(document.body, { - attributes: true, - attributeFilter: ['class'], - childList: false, - characterData: false - });)"; - webEngine->page()->runJavaScript(js); -} -void MainWindow::injectMutationObserver() { - QString js = - R"(function waitForElement(selector) { - return new Promise(resolve => { - if (document.querySelector(selector)) { - return resolve(document.querySelector(selector)); - } - const observer = new MutationObserver(mutations => { - if (document.querySelector(selector)) { - resolve(document.querySelector(selector)); - observer.disconnect(); - } - }); - observer.observe(document.body, { - childList: true, - subtree: true - }); - }); - };)"; - webEngine->page()->runJavaScript(js); -} - -void MainWindow::injectFullWidthJavaScript() { - if (!settings.value("fullWidthView", true).toBool()) - return; - QString js = - R"(waitForElement('#pane-side').then( () => { - var container = document.querySelector('#app > .app-wrapper-web > div'); - container.style.width = '100%'; - container.style.height = '100%'; - container.style.top = '0'; - container.style.maxWidth = 'unset'; - }); - )"; - webEngine->page()->runJavaScript(js); -} - -void MainWindow::injectNewChatJavaScript() { - QString js = R"(const openNewChatWhatsie = (phone,text) => { - const link = document.createElement('a'); - link.setAttribute('href', - `whatsapp://send/?phone=${phone}&text=${text}`); - document.body.append(link); - link.click(); - document.body.removeChild(link); - }; - function openNewChatWhatsieDefined() - { - return (openNewChatWhatsie != 'undefined'); - })"; - webEngine->page()->runJavaScript(js); -} void MainWindow::checkLoadedCorrectly() { if (webEngine && webEngine->page()) { @@ -1172,8 +1067,8 @@ void MainWindow::messageClicked() { void MainWindow::doAppReload() { - if (this->webEngine->page()) { - this->webEngine->page()->disconnect(); + if (webEngine->page()) { + webEngine->page()->disconnect(); } createWebPage(false); } @@ -1195,7 +1090,7 @@ void MainWindow::triggerNewChat(QString phone, QString text) { "openNewChatWhatsieDefined()", [this, phone, text](const QVariant &result) { if (result.toString().contains("true")) { - this->webEngine->page()->runJavaScript( + webEngine->page()->runJavaScript( QString("openNewChatWhatsie(\"%1\",\"%2\")").arg(phone, text)); } else { // create send url equivalent @@ -1203,7 +1098,7 @@ void MainWindow::triggerNewChat(QString phone, QString text) { textStr = text.isEmpty() ? "" : "text=" + text; QString urlStr = "https://web.whatsapp.com/send?" + phoneStr + "&" + textStr; - this->webEngine->page()->load(QUrl(urlStr)); + webEngine->page()->load(QUrl(urlStr)); } this->alreadyRunning(); }); @@ -1212,7 +1107,7 @@ void MainWindow::triggerNewChat(QString phone, QString text) { void MainWindow::doReload(bool byPassCache, bool isAskedByCLI, bool byLoadingQuirk) { if (byLoadingQuirk) { - this->webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, + webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, byPassCache); } else { if (lockWidget && !lockWidget->getIsLocked()) { @@ -1229,13 +1124,13 @@ void MainWindow::doReload(bool byPassCache, bool isAskedByCLI, this->show(); return; } - this->webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, + webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, byPassCache); } } void MainWindow::toggleMute(const bool &checked) { - this->webEngine->page()->setAudioMuted(checked); + webEngine->page()->setAudioMuted(checked); } // get value of page theme when page is loaded diff --git a/src/mainwindow.h b/src/mainwindow.h index 98dbf8b..f6346ad 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -129,13 +129,8 @@ private slots: bool isLoggedIn(); void initAutoLock(); void appAutoLockChanged(); - void injectNewChatJavaScript(); void triggerNewChat(QString phone, QString text); void restoreMainWindow(); - void injectFullWidthJavaScript(); - void injectMutationObserver(); - void injectClassChangeObserver(); - void injectPreventScrollWheelZoomHelper(); }; #endif // MAINWINDOW_H diff --git a/src/sunclock.cpp b/src/sunclock.cpp new file mode 100644 index 0000000..29400f1 --- /dev/null +++ b/src/sunclock.cpp @@ -0,0 +1,276 @@ +#include +#include +#include + +inline double rad(double degrees) { + static const double degToRad = 4.0 * atan(1.0) / 180.0; + return degrees * degToRad; +} + +inline double deg(double radians) { + static const double radToDeg = 180.0 / (4.0 * atan(1.0)); + return radians * radToDeg; +} + +Sunclock::Sunclock(double const &latitude_, double const &longitude_, + double const &tz_offset_) + : latitude(latitude_), longitude(longitude_), tz_offset(tz_offset_) {} + +double Sunclock::irradiance() { return irradiance(time(0)); } + +double Sunclock::irradiance(time_t when) { + when = when + (time_t)(tz_offset * 60 * 60); + struct tm *t = gmtime(&when); + double _time_of_day = time_of_day(when); + double _julian_day = julian_day(t, _time_of_day, tz_offset); + double _julian_century = julian_century(_julian_day); + double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); + double _mean_long_sun = mean_long_sun(_julian_century); + double _mean_anom_sun = mean_anom_sun(_julian_century); + double _sun_eq_of_centre = sun_eq_of_centre(_mean_anom_sun, _julian_century); + double _sun_true_long = sun_true_long(_mean_long_sun, _sun_eq_of_centre); + double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); + double _sun_app_long = sun_app_long(_sun_true_long, _julian_century); + double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); + double _var_y = var_y(_obliq_corr); + double _eq_of_time = + eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); + double _declination = declination(_obliq_corr, _sun_app_long); + double _true_solar_time = true_solar_time(_time_of_day, _eq_of_time); + double _hour_angle = hour_angle(_true_solar_time); + double _solar_zenith = solar_zenith(_declination, _hour_angle); + return std::cos(rad(_solar_zenith)); +} + +time_t Sunclock::sunrise() { return sunrise(time(0)); } + +time_t Sunclock::sunrise(time_t date) { + date = date + (time_t)(tz_offset * 60 * 60); + struct tm *t = gmtime(&date); + double _time_of_day = time_of_day(date); + double _julian_day = julian_day(t, _time_of_day, tz_offset); + double _julian_century = julian_century(_julian_day); + double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); + double _mean_long_sun = mean_long_sun(_julian_century); + double _mean_anom_sun = mean_anom_sun(_julian_century); + double _sun_eq_of_centre = sun_eq_of_centre(_mean_anom_sun, _julian_century); + double _sun_true_long = sun_true_long(_mean_long_sun, _sun_eq_of_centre); + double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); + double _sun_app_long = sun_app_long(_sun_true_long, _julian_century); + double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); + double _var_y = var_y(_obliq_corr); + double _eq_of_time = + eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); + double _declination = declination(_obliq_corr, _sun_app_long); + double _hour_angle_sunrise = hour_angle_sunrise(_declination); + + double noon_decimal_day = + (720 - 4 * longitude - _eq_of_time + tz_offset * 60) / 1440; + double decimal_day = noon_decimal_day - _hour_angle_sunrise * 4 / 1440; + return time_from_decimal_day(date, decimal_day) - + (time_t)(tz_offset * 60 * 60); +} + +time_t Sunclock::solar_noon() { return solar_noon(time(0)); } + +time_t Sunclock::solar_noon(time_t date) { + date = date + (time_t)(tz_offset * 60 * 60); + struct tm *t = gmtime(&date); + double _time_of_day = time_of_day(date); + double _julian_day = julian_day(t, _time_of_day, tz_offset); + double _julian_century = julian_century(_julian_day); + double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); + double _mean_long_sun = mean_long_sun(_julian_century); + double _mean_anom_sun = mean_anom_sun(_julian_century); + double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); + double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); + double _var_y = var_y(_obliq_corr); + double _eq_of_time = + eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); + + double decimal_day = + (720 - 4 * longitude - _eq_of_time + tz_offset * 60) / 1440; + return time_from_decimal_day(date, decimal_day) - + (time_t)(tz_offset * 60 * 60); +} + +time_t Sunclock::sunset() { return sunset(time(0)); } + +time_t Sunclock::sunset(time_t date) { + date = date + (time_t)(tz_offset * 60 * 60); + struct tm *t = gmtime(&date); + double _time_of_day = time_of_day(date); + double _julian_day = julian_day(t, _time_of_day, tz_offset); + double _julian_century = julian_century(_julian_day); + double _mean_obliq_ecliptic = mean_obliq_ecliptic(_julian_century); + double _mean_long_sun = mean_long_sun(_julian_century); + double _mean_anom_sun = mean_anom_sun(_julian_century); + double _sun_eq_of_centre = sun_eq_of_centre(_mean_anom_sun, _julian_century); + double _sun_true_long = sun_true_long(_mean_long_sun, _sun_eq_of_centre); + double _obliq_corr = obliq_corr(_mean_obliq_ecliptic, _julian_century); + double _sun_app_long = sun_app_long(_sun_true_long, _julian_century); + double _eccent_earth_orbit = eccent_earth_orbit(_julian_century); + double _var_y = var_y(_obliq_corr); + double _eq_of_time = + eq_of_time(_var_y, _mean_long_sun, _eccent_earth_orbit, _mean_anom_sun); + double _declination = declination(_obliq_corr, _sun_app_long); + double _hour_angle_sunrise = hour_angle_sunrise(_declination); + + double noon_decimal_day = + (720 - 4 * longitude - _eq_of_time + tz_offset * 60) / 1440; + double decimal_day = noon_decimal_day + _hour_angle_sunrise * 4 / 1440; + return time_from_decimal_day(date, decimal_day) - + (time_t)(tz_offset * 60 * 60); +} + +double Sunclock::time_of_day(time_t date) { + struct tm *t = gmtime(&date); + return (t->tm_hour + t->tm_min / 60.0 + t->tm_sec / 3600.0) / 24.0; +} + +time_t Sunclock::time_from_decimal_day(time_t date, double decimal_day) { + struct std::tm epoch; + epoch.tm_isdst = 0; + epoch.tm_sec = epoch.tm_min = epoch.tm_hour = epoch.tm_mon = 0; + epoch.tm_mday = 1; + epoch.tm_year = 70; + time_t local_tz_offset = mktime(&epoch); + + struct tm *dt = gmtime(&date); + struct tm t = {}; + t.tm_year = dt->tm_year; + t.tm_mon = dt->tm_mon; + t.tm_mday = dt->tm_mday; + double hours = 24.0 * decimal_day; + t.tm_hour = int(hours); + double minutes = (hours - t.tm_hour) * 60; + t.tm_min = int(minutes); + double seconds = (minutes - t.tm_sec) * 60; + t.tm_sec = int(seconds) % 60; + return mktime(&t) - local_tz_offset; +} + +int Sunclock::days_since_1900(struct tm *t) { + int year = t->tm_year; + if (year < 0 || year > 199) { + throw std::invalid_argument( + "days_since_1900 - Date must be between 1900 and 2099"); + } + int month = t->tm_mon + 1; + int days = t->tm_mday; + + if (month < 3) { + month += 12; + year--; + } + int yearDays = (int)(year * 365.25); + int monthDays = (int)((month + 1) * 30.61); + + return (yearDays + monthDays + days - 63); +} + +double Sunclock::julian_day(struct tm *t, double const &time_of_day, + double const &tz_offset) { + return days_since_1900(t) + 2415018.5 + time_of_day - tz_offset / 24; +} + +double Sunclock::julian_century(double _julian_day) { + return (_julian_day - 2451545.0) / 36525.0; +} + +double Sunclock::mean_long_sun(double _julian_century) { + return ( + 280.46646 + + fmod(_julian_century * (36000.76983 + _julian_century * 0.0003032), 360)); +} + +double Sunclock::mean_anom_sun(double _julian_century) { + return 357.52911 + + _julian_century * (35999.05029 - 0.0001537 * _julian_century); +} + +double Sunclock::sun_eq_of_centre(double _mean_anom_sun, + double _julian_century) { + return sin(rad(_mean_anom_sun)) * + (1.914602 - + _julian_century * (0.004817 + 0.000014 * _julian_century)) + + sin(rad(2 * _mean_anom_sun)) * + (0.019993 - 0.000101 * _julian_century) + + sin(rad(3 * _mean_anom_sun)) * 0.000289; +} + +double Sunclock::sun_true_long(double _mean_long_sun, + double _sun_eq_of_centre) { + return _mean_long_sun + _sun_eq_of_centre; +} + +double Sunclock::eccent_earth_orbit(double _julian_century) { + return 0.016708634 - + _julian_century * (0.000042037 + 0.0001537 * _julian_century); +} + +double Sunclock::var_y(double _obliq_corr) { + return tan(rad(_obliq_corr / 2)) * tan(rad(_obliq_corr / 2)); +} + +double Sunclock::mean_obliq_ecliptic(double _julian_century) { + return (23 + (26 + ((21.448 - _julian_century * + (46.815 + _julian_century * + (0.00059 - _julian_century * + 0.001813)))) / + 60) / + 60); +} + +double Sunclock::obliq_corr(double _mean_obliq_ecliptic, + double _julian_century) { + return _mean_obliq_ecliptic + + 0.00256 * cos(deg(125.04 - 1934.136 * _julian_century)); +} + +double Sunclock::sun_app_long(double _sun_true_long, double _julian_century) { + return (_sun_true_long - 0.00569 - + 0.00478 * sin(deg(125.04 - 1934.136 * _julian_century))); +} + +double Sunclock::declination(double _obliq_corr, double _sun_app_long) { + return deg(asin(sin(rad(_obliq_corr)) * sin(rad(_sun_app_long)))); +} + +double Sunclock::eq_of_time(double _var_y, double _mean_long_sun, + double _eccent_earth_orbit, double _mean_anom_sun) { + return 4 * deg(_var_y * sin(2 * rad(_mean_long_sun)) - + 2 * _eccent_earth_orbit * sin(rad(_mean_anom_sun)) + + 4 * _eccent_earth_orbit * _var_y * sin(rad(_mean_anom_sun)) * + cos(2 * rad(_mean_long_sun)) - + 0.5 * _var_y * _var_y * sin(4 * rad(_mean_long_sun)) - + 1.25 * _eccent_earth_orbit * _eccent_earth_orbit * + sin(2 * rad(_mean_anom_sun))); +} + +double Sunclock::true_solar_time(double _time_of_day, double _eq_of_time) { + return fmod( + (_time_of_day * 1440 + _eq_of_time + 4 * longitude - 60 * tz_offset), + 1440); +} + +double Sunclock::hour_angle(double _true_solar_time) { + return (_true_solar_time / 4 < 0 ? _true_solar_time / 4 + 180 + : _true_solar_time / 4 - 180); +} + +double Sunclock::hour_angle_sunrise(double _declination) { + return deg( + acos(cos(rad(90.833)) / (cos(rad(latitude)) * cos(rad(_declination))) - + tan(rad(latitude)) * tan(rad(_declination)))); +} + +double Sunclock::solar_zenith(double _declination, double _hour_angle) { + return deg(acos(sin(rad(latitude)) * sin(rad(_declination)) + + cos(rad(latitude)) * cos(rad(_declination)) * + cos(rad(_hour_angle)))); +} + +double Sunclock::solar_elevation(double _solar_zenith) { + return 90 - _solar_zenith; +} diff --git a/src/sunclock.hpp b/src/sunclock.hpp new file mode 100644 index 0000000..4cfad57 --- /dev/null +++ b/src/sunclock.hpp @@ -0,0 +1,126 @@ +#ifndef DAYLIGHT_SUNCLOCK_HPP +#define DAYLIGHT_SUNCLOCK_HPP + +#include + +class Sunclock { +public: + Sunclock(double const &latitude_, double const &longitude_, double const &tz_offset_ = 0); + + /** + * \overload double Sunclock::irradiance(time_t when) + */ + double irradiance(); + + /** + * Specifically, we calculate Direct Normal Irradiance + * That is we do not consider atmospheric components like cloud cover, + * moisture content etc. + * + * @param when + * @return a value representing irradiance (power per unit area) + */ + double irradiance(time_t when); + + /** + * \overload time_t Sunclock::sunrise(time_t date) + */ + time_t sunrise(); + + /** + * Returns sunrise time for given date + * + * @param date only date is considered + * @return sunrise time + */ + time_t sunrise(time_t date); + + /** + * \overload time_t Sunclock::solar_noon(time_t date) + */ + time_t solar_noon(); + + /** + * Returns solar_noon time for given date + * + * @param date only date is considered + * @return solar_noon time + */ + time_t solar_noon(time_t date); + + /** + * \overload time_t Sunclock::sunset(time_t date) + */ + time_t sunset(); + + /** + * Returns sunset time for given date + * + * @param date only date is considered + * @return sunset time + */ + time_t sunset(time_t date); + +private: + // in decimal degrees, east is positive + double const latitude; + + // in decimal degrees, north is positive + double const longitude; + + // in hours, east is positive, i.e. IST (+05:30) is 5.5 + double const tz_offset; + + /** + * @param date + * @return percentage past midnight, i.e. noon is 0.5 + */ + double time_of_day(time_t date); + + static int days_since_1900(struct tm *t); + + /** + * @param date + * @param decimal_day decimal between 0.0 and 1.0, e.g. noon = 0.5 + * @return time_t with date and time set accordingly + */ + static time_t time_from_decimal_day(time_t date, double decimal_day); + + /** + * Get day count since Monday, January 1, 4713 BC + * https://en.wikipedia.org/wiki/Julian_day + * + * @param t + * @param time_of_day percentage past midnight, i.e. noon is 0.5 + * @param tz_offset in hours, east is positive, i.e. IST (+05:30) is 5.5 + * @return julian day + */ + static double julian_day(struct tm *t, double const &time_of_day, double const &tz_offset); + + /** + * Extract information in a suitable format from a time_t object. + */ + void prepare_time(time_t const &when, struct tm *ptm); + + double julian_century(double _julian_day); + double mean_long_sun(double _julian_century); + double mean_anom_sun(double _julian_century); + double sun_eq_of_centre(double _mean_anom_sun, double _julian_century); + double eccent_earth_orbit(double _julian_century); + double var_y(double _obliq_corr); + double mean_obliq_ecliptic(double _julian_century); + double sun_true_long(double _mean_long_sun, double _sun_eq_of_centre); + double obliq_corr(double _mean_obliq_ecliptic, double _julian_century); + double sun_app_long(double _sun_true_long, double _julian_century); + double declination(double _obliq_corr, double _sun_app_long); + double eq_of_time(double _var_y, double _mean_long_sun, double _eccent_earth_orbit, + double _mean_anom_sun); + double true_solar_time(double _time_of_day, double _eq_of_time); + double hour_angle(double _true_solar_time); + double hour_angle_sunrise(double _declination); + double solar_zenith(double _declination, double _hour_angle); + double solar_elevation(double _solar_zenith); +}; + +#endif + diff --git a/src/webenginepage.cpp b/src/webenginepage.cpp index 6cd5f44..e27d928 100644 --- a/src/webenginepage.cpp +++ b/src/webenginepage.cpp @@ -116,7 +116,7 @@ void WebEnginePage::handleFeaturePermissionRequested(const QUrl &securityOrigin, } void WebEnginePage::handleLoadFinished(bool ok) { - Q_UNUSED(ok); + // turn on Notification settings by default if (settings.value("permissions/Notifications").isValid() == false) { settings.beginGroup("permissions"); @@ -132,6 +132,14 @@ void WebEnginePage::handleLoadFinished(bool ok) { QWebEnginePage::Feature::Notifications, QWebEnginePage::PermissionPolicy::PermissionGrantedByUser); } + + if(ok){ + injectMutationObserver(); + injectPreventScrollWheelZoomHelper(); + injectFullWidthJavaScript(); + injectClassChangeObserver(); + injectNewChatJavaScript(); + } } void WebEnginePage::fullScreenRequestedByPage( @@ -301,3 +309,106 @@ void WebEnginePage::javaScriptConsoleMessage( Q_UNUSED(lineId); Q_UNUSED(sourceId); } + +void WebEnginePage::injectPreventScrollWheelZoomHelper() { + QString js = R"( + (function () { + const SSWZ = function () { + this.keyScrollHandler = function (e) { + if (e.ctrlKey) { + e.preventDefault(); + return false; + } + } + }; + if (window === top) { + const sswz = new SSWZ(); + window.addEventListener('wheel', sswz.keyScrollHandler, { + passive: false + }); + } + })(); + )"; + this->runJavaScript(js); +} + +void WebEnginePage::injectClassChangeObserver() { + QString js = R"( + const observer = new MutationObserver(() => { + var haveFullView = document.body.classList.contains('whatsie-full-view'); + var container = document.querySelector('#app > .app-wrapper-web > div'); + if(container){ + if(haveFullView){ + container.style.width = '100%'; + container.style.height = '100%'; + container.style.top = '0'; + container.style.maxWidth = 'unset'; + }else{ + container.style.width = null; + container.style.height = null; + container.style.top = null; + container.style.maxWidth = null; + } + } + }); + observer.observe(document.body, { + attributes: true, + attributeFilter: ['class'], + childList: false, + characterData: false + });)"; + this->runJavaScript(js); +} + +void WebEnginePage::injectMutationObserver() { + QString js = + R"(function waitForElement(selector) { + return new Promise(resolve => { + if (document.querySelector(selector)) { + return resolve(document.querySelector(selector)); + } + const observer = new MutationObserver(mutations => { + if (document.querySelector(selector)) { + resolve(document.querySelector(selector)); + observer.disconnect(); + } + }); + observer.observe(document.body, { + childList: true, + subtree: true + }); + }); + };)"; + this->runJavaScript(js); +} + +void WebEnginePage::injectFullWidthJavaScript() { + if (!settings.value("fullWidthView", true).toBool()) + return; + QString js = + R"(waitForElement('#pane-side').then( () => { + var container = document.querySelector('#app > .app-wrapper-web > div'); + container.style.width = '100%'; + container.style.height = '100%'; + container.style.top = '0'; + container.style.maxWidth = 'unset'; + }); + )"; + this->runJavaScript(js); +} + +void WebEnginePage::injectNewChatJavaScript() { + QString js = R"(const openNewChatWhatsie = (phone,text) => { + const link = document.createElement('a'); + link.setAttribute('href', + `whatsapp://send/?phone=${phone}&text=${text}`); + document.body.append(link); + link.click(); + document.body.removeChild(link); + }; + function openNewChatWhatsieDefined() + { + return (openNewChatWhatsie != 'undefined'); + })"; + this->runJavaScript(js); +} diff --git a/src/webenginepage.h b/src/webenginepage.h index e2684f3..d039288 100644 --- a/src/webenginepage.h +++ b/src/webenginepage.h @@ -61,6 +61,11 @@ private slots: QWebEngineClientCertificateSelection clientCertSelection); #endif void fullScreenRequestedByPage(QWebEngineFullScreenRequest request); + void injectPreventScrollWheelZoomHelper(); + void injectClassChangeObserver(); + void injectMutationObserver(); + void injectFullWidthJavaScript(); + void injectNewChatJavaScript(); }; #endif // WEBENGINEPAGE_H diff --git a/src/widgets/elidedlabel/elidedlabel.cpp b/src/widgets/elidedlabel/elidedlabel.cpp new file mode 100644 index 0000000..e870959 --- /dev/null +++ b/src/widgets/elidedlabel/elidedlabel.cpp @@ -0,0 +1,52 @@ +#include "elidedlabel.h" + +#include +#include +#include +#include + +ElidedLabel::ElidedLabel(QWidget *parent) + : QLabel(parent), m_elide_mode(Qt::ElideRight) { + setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); +} + +ElidedLabel::ElidedLabel(const QString &txt, QWidget *parent) + : QLabel(txt, parent), m_elide_mode(Qt::ElideRight) { + setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); +} + +ElidedLabel::ElidedLabel(const QString &txt, Qt::TextElideMode elideMode, + QWidget *parent) + : QLabel(txt, parent), m_elide_mode(elideMode) { + setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); +} + +void ElidedLabel::setText(const QString &txt) { + QLabel::setText(txt); + cacheElidedText(geometry().width()); + setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); +} + +void ElidedLabel::cacheElidedText(int w) { + m_cached_elided_text = fontMetrics().elidedText( + text(), m_elide_mode, w, (buddy() == nullptr) ? 0 : Qt::TextShowMnemonic); +} + +void ElidedLabel::resizeEvent(QResizeEvent *e) { + QLabel::resizeEvent(e); + cacheElidedText(e->size().width()); +} + +void ElidedLabel::paintEvent(QPaintEvent *e) { + if (m_elide_mode == Qt::ElideNone) { + QLabel::paintEvent(e); + } else { + QPainter p(this); + p.drawText(0, 0, geometry().width(), geometry().height(), + QStyle::visualAlignment(text().isRightToLeft() ? Qt::RightToLeft + : Qt::LeftToRight, + alignment()) | + ((buddy() == nullptr) ? 0 : Qt::TextShowMnemonic), + m_cached_elided_text); + } +} diff --git a/src/widgets/elidedlabel/elidedlabel.h b/src/widgets/elidedlabel/elidedlabel.h new file mode 100644 index 0000000..7dc610a --- /dev/null +++ b/src/widgets/elidedlabel/elidedlabel.h @@ -0,0 +1,49 @@ +#pragma once +#include +#include +#include +#include +#include + +// A label that elides its text when not enough geometry is available to show all of the text. +// Currently only capable of one-line. +class ElidedLabel : public QLabel { + Q_OBJECT + +private: + Qt::TextElideMode m_elide_mode; + QString m_cached_elided_text; + + +public: + ElidedLabel(QWidget* parent = NULL); + ElidedLabel(const QString& txt, QWidget* parent = NULL); + ElidedLabel(const QString& txt, Qt::TextElideMode elideMode = Qt::ElideRight, QWidget* parent = NULL); + +public: + // Set the elide mode used for displaying text. + inline void setElideMode(Qt::TextElideMode elideMode) { + m_elide_mode = elideMode; + updateGeometry(); + } + + // Get the elide mode currently used to display text. + inline Qt::TextElideMode elideMode() const { + return m_elide_mode; + } + + + +public: // QLabel overrides + void setText(const QString&); // note: not virtual so no polymorphism ... + + +protected: // QLabel overrides + virtual void paintEvent(QPaintEvent*) override; + virtual void resizeEvent(QResizeEvent*) override; + +protected: + // Cache the elided text so as to not recompute it every paint event + void cacheElidedText(int w); + +}; -- cgit v1.2.3 From 5f10a0f9657358fcd86c55ec065f3855bad0c160 Mon Sep 17 00:00:00 2001 From: Keshav Bhatt Date: Wed, 17 May 2023 21:59:43 +0530 Subject: feat: minor fixes + code cleanup --- src/about.cpp | 17 +- src/about.h | 29 +- src/about.ui | 9 +- src/autolockeventfilter.h | 21 +- src/automatictheme.cpp | 85 ++-- src/automatictheme.h | 42 +- src/common.h | 3 +- src/dictionaries.cpp | 2 +- src/downloadmanagerwidget.cpp | 13 +- src/downloadmanagerwidget.h | 8 +- src/lock.cpp | 51 +- src/lock.h | 9 +- src/main.cpp | 44 +- src/mainwindow.cpp | 905 ++++++++++++++++++---------------- src/mainwindow.h | 105 ++-- src/notificationpopup.h | 16 +- src/permissiondialog.cpp | 11 +- src/permissiondialog.h | 9 +- src/rateapp.cpp | 56 ++- src/rateapp.h | 52 +- src/requestinterceptor.h | 50 +- src/settingsmanager.h | 21 + src/settingswidget.cpp | 327 ++++++++---- src/settingswidget.h | 7 +- src/theme.cpp | 69 +++ src/theme.h | 27 + src/utils.cpp | 214 ++++++-- src/utils.h | 13 +- src/webenginepage.cpp | 51 +- src/webenginepage.h | 23 +- src/webview.cpp | 19 +- src/webview.h | 12 +- src/widgets/MoreApps/moreapps.cpp | 14 +- src/widgets/scrolltext/scrolltext.cpp | 2 +- 34 files changed, 1384 insertions(+), 952 deletions(-) create mode 100644 src/settingsmanager.h create mode 100644 src/theme.cpp create mode 100644 src/theme.h (limited to 'src/webenginepage.h') 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 #include +#include 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 @@ 0 0 522 - 486 + 487 @@ -172,13 +172,6 @@ p, li { white-space: pre-wrap; }
- - - - Donate OpenCollective - - - 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 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 -#include #include +#include +#include #include -#include +#include + +#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 // 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 -#include -#include - 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 + +#include +#include +#include #include 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 -#include -#include -#include #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; } diff --git a/src/lock.h b/src/lock.h index 23af8e0..809ca3c 100644 --- a/src/lock.h +++ b/src/lock.h @@ -2,9 +2,15 @@ #define LOCK_H #include -#include +#include +#include +#include +#include #include +#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 #include -#include #include #include #include @@ -9,6 +8,7 @@ #include "common.h" #include "def.h" #include "mainwindow.h" +#include "settingsmanager.h" #include 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("engineNotifier"); + auto *op = m_webEngine->findChild("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 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 #include #include -#include -#include #include #include #include @@ -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 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 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 #include #include @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include @@ -27,7 +26,6 @@ class NotificationPopup : public QWidget { QLabel m_icon, m_title; ScrollText m_message; std::unique_ptr 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 -#include -#include 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 +#include +#include +#include #include #include -#include + +#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 -#include #include -#include #include #include +#include +#include + +#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 + +#include #include #include -#include -#include +#include #include #include -#include +#include + +#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 - "< + +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 + #include "permissiondialog.h" +#include "settingsmanager.h" #include "utils.h" -#include -#include - 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 +#include +#include + +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 -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 = + "
  • " + QObject::tr("Install mode") + ": " + + QString(installType.trimmed().isEmpty() ? "Unknown" : installType) + + "
  • "; + + 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 << "

    " + QApplication::applicationName() + "

    " + debugInfo << "

    " + applicationName + "

    " << "
      " << "
    • " + QObject::tr("Version") + ": " + - QString(VERSIONSTR) + "
    • " + version + "" << "
    • " + QObject::tr("Source Branch") + ": " + - QString(GIT_BRANCH) + "
    • " + sourceBranch + "" << "
    • " + QObject::tr("Commit Hash") + ": " + - QString(GIT_HASH) + "
    • " + commitHash + "" << "
    • " + QObject::tr("Build Datetime") + ": " + - QString::fromLatin1(BUILD_TIMESTAMP) + "
    • " + buildDatetime + "" << "
    • " + QObject::tr("Qt Runtime Version") + ": " + - QString(qVersion()) + "
    • " + qtRuntimeVersion + "" << "
    • " + QObject::tr("Qt Compiled Version") + ": " + - QString(QT_VERSION_STR) + "
    • " + qtCompiledVersion + "" << "
    • " + QObject::tr("System") + ": " + - QSysInfo::prettyProductName() + "
    • " + systemInfo + "" << "
    • " + QObject::tr("Architecture") + ": " + - QSysInfo::currentCpuArchitecture() + "
    • "; - debugInfo << "
    "; + architecture + "" + << "
  • " + QObject::tr("Install mode") + ": " + + QString(installMode.trimmed().isEmpty() ? "Unknown" + : installMode) + + "
  • " + << ""; + 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 #include -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 -#include -#include - 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 -#include -#include -#include - #include #include +#include +#include #include #include +#include #include -#include - #include +#include +#include +#include #include +#include -#include +#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 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 -#include #include +#include + +#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 #include #include +#include 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); } -- cgit v1.2.3