aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLibravatar Keshav Bhatt <keshavnrj@gmail.com>2022-02-28 18:08:28 +0530
committerLibravatar Keshav Bhatt <keshavnrj@gmail.com>2022-02-28 18:08:28 +0530
commit9867a6b6279229d53fe59854a511c9eea9888427 (patch)
treecefdf3aa78e35741100a554f0fc25d75c4ef3065 /src
parent020ac6daeac226da90bc0c884a9b22a7da9baa99 (diff)
downloadwhatsie-9867a6b6279229d53fe59854a511c9eea9888427.tar.gz
whatsie-9867a6b6279229d53fe59854a511c9eea9888427.zip
build: migrate to qt 5.15
Diffstat (limited to 'src')
-rw-r--r--src/SunClock.cpp133
-rw-r--r--src/about.cpp172
-rw-r--r--src/automatictheme.cpp171
-rw-r--r--src/dictionaries.cpp97
-rw-r--r--src/downloadmanagerwidget.cpp72
-rw-r--r--src/downloadwidget.cpp171
-rw-r--r--src/downloadwidget.h3
-rw-r--r--src/elidedlabel.cpp53
-rw-r--r--src/lock.cpp350
-rw-r--r--src/main.cpp96
-rw-r--r--src/mainwindow.cpp1743
-rw-r--r--src/mainwindow.h147
-rw-r--r--src/permissiondialog.cpp114
-rw-r--r--src/rateapp.cpp204
-rw-r--r--src/rungaurd.cpp104
-rw-r--r--src/settingswidget.cpp785
-rw-r--r--src/utils.cpp417
-rw-r--r--src/webenginepage.cpp479
-rw-r--r--src/webview.cpp152
-rw-r--r--src/widgets/scrolltext/scrolltext.cpp263
20 files changed, 2818 insertions, 2908 deletions
diff --git a/src/SunClock.cpp b/src/SunClock.cpp
index ead4d54..132c0a6 100644
--- a/src/SunClock.cpp
+++ b/src/SunClock.cpp
@@ -1,5 +1,5 @@
-#include <cmath>
#include <SunClock.hpp>
+#include <cmath>
#include <stdexcept>
inline double rad(double degrees) {
@@ -12,7 +12,8 @@ inline double deg(double radians) {
return radians * radToDeg;
}
-Sunclock::Sunclock(double const &latitude_, double const &longitude_, double const &tz_offset_)
+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)); }
@@ -32,7 +33,8 @@ double Sunclock::irradiance(time_t when) {
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 _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);
@@ -57,13 +59,16 @@ time_t Sunclock::sunrise(time_t date) {
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 _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 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);
+ return time_from_decimal_day(date, decimal_day) -
+ (time_t)(tz_offset * 60 * 60);
}
time_t Sunclock::solar_noon() { return solar_noon(time(0)); }
@@ -80,10 +85,13 @@ time_t Sunclock::solar_noon(time_t date) {
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 _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);
+ 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)); }
@@ -103,13 +111,16 @@ time_t Sunclock::sunset(time_t date) {
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 _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 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);
+ return time_from_decimal_day(date, decimal_day) -
+ (time_t)(tz_offset * 60 * 60);
}
double Sunclock::time_of_day(time_t date) {
@@ -142,7 +153,8 @@ time_t Sunclock::time_from_decimal_day(time_t date, double decimal_day) {
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");
+ 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;
@@ -157,33 +169,44 @@ int Sunclock::days_since_1900(struct tm *t) {
return (yearDays + monthDays + days - 63);
}
-double Sunclock::julian_day(struct tm *t, double const &time_of_day, double const &tz_offset) {
+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::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));
+ 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);
+ 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_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) {
+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);
+ return 0.016708634 -
+ _julian_century * (0.000042037 + 0.0001537 * _julian_century);
}
double Sunclock::var_y(double _obliq_corr) {
@@ -191,55 +214,63 @@ double Sunclock::var_y(double _obliq_corr) {
}
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);
+ 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::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)));
+ 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::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);
+ 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);
+ 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))));
+ 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))));
+ 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; }
-
+double Sunclock::solar_elevation(double _solar_zenith) {
+ return 90 - _solar_zenith;
+}
diff --git a/src/about.cpp b/src/about.cpp
index 2212700..9038f20 100644
--- a/src/about.cpp
+++ b/src/about.cpp
@@ -6,102 +6,92 @@
#include <QUrl>
#include <utils.h>
-About::About(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::About)
-{
- ui->setupUi(this);
-
- //init
- appName = QApplication::applicationName();
- appDescription = "WhatsApp Web clinet for Linux Desktop";
- isOpenSource = true;
- appAuthorName = "Keshav Bhatt";
- appAuthorEmail = "keshavnrj@gmail.com";
- appAuthorLink = "http://ktechpit.com";
- donateLink = "https://paypal.me/keshavnrj/5";
- moreAppsLink = "https://snapcraft.io/search?q=keshavnrj";
-
- appSourceCodeLink = "https://github.com/keshavbhatt/whatsie";
- appRateLink = "snap://whatsie";
-
-
- ui->appNameDesc->setText(QString("<p style=' margin-top:12px; margin-bottom:12px; margin-left:0px;"
- " margin-right:0px; -qt-block-indent:0; text-indent:0px;'>"
- "<span style=' font-size:18pt;'>%1</span></p>"
- "<p style=' margin-top:12px; margin-bottom:12px; margin-left:0px;"
- " margin-right:0px; -qt-block-indent:0; text-indent:0px;'>"
- "%2</p>").arg(appName,appDescription));
-
- ui->desc2->setText(QString("<p><span style=' font-weight:600;'>Designed &amp; Developed by:</span>"
- " %1 </p><p><span style=' font-weight:600;'>"
- "Developer Email address: </span>%2</p>"
- "<p><span style=' font-weight:600;'>Developer Website:</span>"
- " %3</p>").arg(appAuthorName,appAuthorEmail,appAuthorLink));
-
-
- ui->version->setText("Version: "+QApplication::applicationVersion());
+About::About(QWidget *parent) : QWidget(parent), ui(new Ui::About) {
+ ui->setupUi(this);
+
+ // init
+ appName = QApplication::applicationName();
+ appDescription = "WhatsApp Web clinet for Linux Desktop";
+ isOpenSource = true;
+ appAuthorName = "Keshav Bhatt";
+ appAuthorEmail = "keshavnrj@gmail.com";
+ appAuthorLink = "http://ktechpit.com";
+ donateLink = "https://paypal.me/keshavnrj/5";
+ moreAppsLink = "https://snapcraft.io/search?q=keshavnrj";
+
+ appSourceCodeLink = "https://github.com/keshavbhatt/whatsie";
+ appRateLink = "snap://whatsie";
+
+ ui->appNameDesc->setText(
+ QString("<p style=' margin-top:12px; margin-bottom:12px; margin-left:0px;"
+ " margin-right:0px; -qt-block-indent:0; text-indent:0px;'>"
+ "<span style=' font-size:18pt;'>%1</span></p>"
+ "<p style=' margin-top:12px; margin-bottom:12px; margin-left:0px;"
+ " margin-right:0px; -qt-block-indent:0; text-indent:0px;'>"
+ "%2</p>")
+ .arg(appName, appDescription));
+
+ ui->desc2->setText(
+ QString("<p><span style=' font-weight:600;'>Designed &amp; Developed "
+ "by:</span>"
+ " %1 </p><p><span style=' font-weight:600;'>"
+ "Developer Email address: </span>%2</p>"
+ "<p><span style=' font-weight:600;'>Developer Website:</span>"
+ " %3</p>")
+ .arg(appAuthorName, appAuthorEmail, appAuthorLink));
+
+ ui->version->setText("Version: " + QApplication::applicationVersion());
+
+ ui->debugInfoText->setHtml(utils::appDebugInfo());
+
+ ui->debugInfoText->hide();
+
+ ui->debugInfoButton->setText(QObject::tr("Show Debug Info"));
+
+ if (isOpenSource == false) {
+ ui->source_code->hide();
+ }
+
+ connect(ui->donate, &QPushButton::clicked,
+ [=]() { QDesktopServices::openUrl(QUrl(donateLink)); });
+
+ connect(ui->rate, &QPushButton::clicked,
+ [=]() { QDesktopServices::openUrl(QUrl(appRateLink)); });
+ connect(ui->more_apps, &QPushButton::clicked,
+ [=]() { QDesktopServices::openUrl(QUrl(moreAppsLink)); });
+ connect(ui->source_code, &QPushButton::clicked,
+ [=]() { QDesktopServices::openUrl(QUrl(appSourceCodeLink)); });
+
+ setWindowTitle(QApplication::applicationName() + " | About");
+
+ ui->centerWidget->hide();
+
+ QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
+ ui->centerWidget->setGraphicsEffect(eff);
+ QPropertyAnimation *a = new QPropertyAnimation(eff, "opacity");
+ a->setDuration(1000);
+ a->setStartValue(0);
+ a->setEndValue(1);
+ a->setEasingCurve(QEasingCurve::InCurve);
+ a->start(QPropertyAnimation::DeleteWhenStopped);
+ ui->centerWidget->show();
+}
- ui->debugInfoText->setHtml(utils::appDebugInfo());
+About::~About() { delete ui; }
+void About::on_debugInfoButton_clicked() {
+ if (ui->debugInfoText->isVisible()) {
ui->debugInfoText->hide();
-
ui->debugInfoButton->setText(QObject::tr("Show Debug Info"));
- if(isOpenSource == false){
- ui->source_code->hide();
- }
-
- connect(ui->donate,&QPushButton::clicked,[=](){
- QDesktopServices::openUrl(QUrl(donateLink));
- });
-
- connect(ui->rate,&QPushButton::clicked,[=](){
- QDesktopServices::openUrl(QUrl(appRateLink));
- });
- connect(ui->more_apps,&QPushButton::clicked,[=](){
- QDesktopServices::openUrl(QUrl(moreAppsLink));
- });
- connect(ui->source_code,&QPushButton::clicked,[=](){
- QDesktopServices::openUrl(QUrl(appSourceCodeLink));
- });
-
- setWindowTitle(QApplication::applicationName() +" | About");
-
- ui->centerWidget->hide();
-
- QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
- ui->centerWidget->setGraphicsEffect(eff);
- QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity");
- a->setDuration(1000);
- a->setStartValue(0);
- a->setEndValue(1);
- a->setEasingCurve(QEasingCurve::InCurve);
- a->start(QPropertyAnimation::DeleteWhenStopped);
- ui->centerWidget->show();
-}
-
-About::~About()
-{
- delete ui;
-}
-
-void About::on_debugInfoButton_clicked()
-{
- if(ui->debugInfoText->isVisible()){
- ui->debugInfoText->hide();
- ui->debugInfoButton->setText(QObject::tr("Show Debug Info"));
-
- this->resize(this->width(),this->minimumHeight());
- }else{
- ui->debugInfoText->show();
- ui->debugInfoButton->setText(QObject::tr("Hide Debug Info"));
- this->adjustSize();
- }
-
+ this->resize(this->width(), this->minimumHeight());
+ } else {
+ ui->debugInfoText->show();
+ ui->debugInfoButton->setText(QObject::tr("Hide Debug Info"));
+ this->adjustSize();
+ }
}
-void About::on_donate_2_clicked()
-{
- QDesktopServices::openUrl(QUrl("https://opencollective.com/whatsie"));
+void About::on_donate_2_clicked() {
+ QDesktopServices::openUrl(QUrl("https://opencollective.com/whatsie"));
}
diff --git a/src/automatictheme.cpp b/src/automatictheme.cpp
index b538244..6e14623 100644
--- a/src/automatictheme.cpp
+++ b/src/automatictheme.cpp
@@ -4,113 +4,114 @@
#include "SunClock.hpp"
#include <QMessageBox>
-AutomaticTheme::AutomaticTheme(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::AutomaticTheme)
-{
- ui->setupUi(this);
- ui->refresh->setEnabled(false);
+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());
+ sunrise.setSecsSinceEpoch(settings.value("sunrise").toLongLong());
+ sunset.setSecsSinceEpoch(settings.value("sunset").toLongLong());
- ui->sunrise->setTime(sunrise.time());
- ui->sunset->setTime(sunset.time());
+ ui->sunrise->setTime(sunrise.time());
+ ui->sunset->setTime(sunset.time());
- QTimeZone zone = QTimeZone::systemTimeZone();
- QDateTime dt = QDateTime::currentDateTime();
+ QTimeZone zone = QTimeZone::systemTimeZone();
+ QDateTime dt = QDateTime::currentDateTime();
- if(zone.isValid()){
- hour_offset = (double)zone.standardTimeOffset(dt)/(double)3600;
- }else{
- settings.setValue("automaticTheme",false);
- QMessageBox::critical(this,"Error","Unable to get system TimeZone information.\n\nAutomatic theme switcher will not work.");
- return;
- }
+ if (zone.isValid()) {
+ hour_offset = (double)zone.standardTimeOffset(dt) / (double)3600;
+ } else {
+ settings.setValue("automaticTheme", false);
+ QMessageBox::critical(
+ this, "Error",
+ "Unable to get system TimeZone information.\n\nAutomatic theme "
+ "switcher will not work.");
+ return;
+ }
- gPosInfoSrc = QGeoPositionInfoSource::createDefaultSource(this);
+ gPosInfoSrc = QGeoPositionInfoSource::createDefaultSource(this);
- if (gPosInfoSrc) // sudo apt install geoclue-2.0
- {
- ui->refresh->setEnabled(true);
- connect(gPosInfoSrc,&QGeoPositionInfoSource::positionUpdated,[=](const QGeoPositionInfo &update){
- QGeoCoordinate cor = update.coordinate();
- if(cor.isValid())
- {
+ if (gPosInfoSrc) // sudo apt install geoclue-2.0
+ {
+ ui->refresh->setEnabled(true);
+ connect(gPosInfoSrc, &QGeoPositionInfoSource::positionUpdated,
+ [=](const QGeoPositionInfo &update) {
+ QGeoCoordinate cor = update.coordinate();
+ if (cor.isValid()) {
this->lon = cor.longitude();
this->lat = cor.latitude();
ui->refresh->setEnabled(true);
gPosInfoSrc->stopUpdates();
- }else{
+ } else {
ui->refresh->setEnabled(false);
- }
- });
- connect(gPosInfoSrc,&QGeoPositionInfoSource::updateTimeout,[=](){
- if(!settings.value("sunrise").isValid() || !settings.value("sunset").isValid())
- {
- if(ui->refresh->isEnabled())
- ui->refresh->click();
- }
- });
- gPosInfoSrc->startUpdates();
- }else{
- ui->refresh->setEnabled(false);
- settings.setValue("automaticTheme",false);
- QMessageBox::critical(this,"Error","Unable to initialize QGeoPositionInfoSource.\n\nAutomatic theme switcher will not work."
- "\n\nPlease fill the sunset and sunrise time manually.");
- }
+ }
+ });
+ connect(gPosInfoSrc, &QGeoPositionInfoSource::updateTimeout, [=]() {
+ if (!settings.value("sunrise").isValid() ||
+ !settings.value("sunset").isValid()) {
+ if (ui->refresh->isEnabled())
+ ui->refresh->click();
+ }
+ });
+ gPosInfoSrc->startUpdates();
+ } else {
+ ui->refresh->setEnabled(false);
+ settings.setValue("automaticTheme", false);
+ QMessageBox::critical(
+ this, "Error",
+ "Unable to initialize QGeoPositionInfoSource.\n\nAutomatic theme "
+ "switcher will not work."
+ "\n\nPlease fill the sunset and sunrise time manually.");
+ }
}
-AutomaticTheme::~AutomaticTheme()
-{
- gPosInfoSrc->disconnect();
- gPosInfoSrc->deleteLater();
- delete ui;
+AutomaticTheme::~AutomaticTheme() {
+ gPosInfoSrc->disconnect();
+ gPosInfoSrc->deleteLater();
+ delete ui;
}
-void AutomaticTheme::on_refresh_clicked()
-{
- QGeoCoordinate geoCor = QGeoCoordinate(this->lat,this->lon);
- 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()));
+void AutomaticTheme::on_refresh_clicked() {
+ QGeoCoordinate geoCor = QGeoCoordinate(this->lat, this->lon);
+ 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()));
- ui->sunrise->setTime(sunrise.time());
- ui->sunset->setTime(sunset.time());
- }else{
- settings.setValue("automaticTheme",false);
- QMessageBox::critical(this,"Error","Invalid Geo-Coordinates.\n\nPlease try again.");
- }
+ ui->sunrise->setTime(sunrise.time());
+ ui->sunset->setTime(sunset.time());
+ } else {
+ 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.");
- //this->close();
- }else{
- settings.setValue("sunrise",sunrise.toSecsSinceEpoch());
- settings.setValue("sunset",sunset.toSecsSinceEpoch());
- settings.setValue("automaticTheme",true);
- this->close();
- }
+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.");
+ } else {
+ settings.setValue("sunrise", sunrise.toSecsSinceEpoch());
+ settings.setValue("sunset", sunset.toSecsSinceEpoch());
+ settings.setValue("automaticTheme", true);
+ this->close();
+ }
}
-void AutomaticTheme::on_cancel_clicked()
-{
- settings.setValue("automaticTheme",false);
- this->close();
+void AutomaticTheme::on_cancel_clicked() {
+ settings.setValue("automaticTheme", false);
+ this->close();
}
-void AutomaticTheme::on_sunrise_timeChanged(const QTime &time)
-{
- sunrise.setTime(QTime(time.hour(),time.minute(),0));
+void AutomaticTheme::on_sunrise_timeChanged(const QTime &time) {
+ sunrise.setTime(QTime(time.hour(), time.minute(), 0));
}
-void AutomaticTheme::on_sunset_timeChanged(const QTime &time)
-{
- sunset.setTime(QTime(time.hour(),time.minute(),0));
+void AutomaticTheme::on_sunset_timeChanged(const QTime &time) {
+ sunset.setTime(QTime(time.hour(), time.minute(), 0));
}
diff --git a/src/dictionaries.cpp b/src/dictionaries.cpp
index 5ae6cc3..9538582 100644
--- a/src/dictionaries.cpp
+++ b/src/dictionaries.cpp
@@ -1,73 +1,66 @@
#include "dictionaries.h"
-#include <QDir>
+#include "utils.h"
#include <QCoreApplication>
+#include <QDir>
#include <QLibraryInfo>
#include <QString>
#include <QStringList>
-#include "utils.h"
-static QString DICTIONARY_FILE_SUFFIX = ".bdic";
-Dictionaries::Dictionaries(QObject *parent) : QObject(parent)
-{
- setParent(parent);
-}
+QString DICTIONARY_FILE_SUFFIX = ".bdic";
-Dictionaries::~Dictionaries()
-{
- this->deleteLater();
+Dictionaries::Dictionaries(QObject *parent) : QObject(parent) {
+ setParent(parent);
}
+Dictionaries::~Dictionaries() { this->deleteLater(); }
-QString Dictionaries::GetDictionaryPath()
-{
- QString dict_path;
-
- // the environment variable takes precedence on all platforms
- if (qEnvironmentVariableIsSet("QTWEBENGINE_DICTIONARIES_PATH")) {
- dict_path = utils::GetEnvironmentVar("QTWEBENGINE_DICTIONARIES_PATH");
- return dict_path;
- }
-
- // next look relative to the executable
- dict_path = QCoreApplication::applicationDirPath() + "/qtwebengine_dictionaries";
+QString Dictionaries::GetDictionaryPath() {
+ QString dict_path;
+ // the environment variable takes precedence on all platforms
+ if (qEnvironmentVariableIsSet("QTWEBENGINE_DICTIONARIES_PATH")) {
+ dict_path = utils::GetEnvironmentVar("QTWEBENGINE_DICTIONARIES_PATH");
+ return dict_path;
+ }
- if (QDir(dict_path).exists()) {
- return dict_path;
- }
+ // next look relative to the executable
+ dict_path =
+ QCoreApplication::applicationDirPath() + "/qtwebengine_dictionaries";
- //inside the installed Qt directories
- dict_path = QLibraryInfo::location(QLibraryInfo::DataPath) + "/qtwebengine_dictionaries";
+ if (QDir(dict_path).exists()) {
+ return dict_path;
+ }
+ // inside the installed Qt directories
+ dict_path = QLibraryInfo::location(QLibraryInfo::DataPath) +
+ "/qtwebengine_dictionaries";
- if (QDir(dict_path).exists()) {
- return dict_path;
- }
+ if (QDir(dict_path).exists()) {
+ return dict_path;
+ }
- return QString();
+ return QString();
}
-
-QStringList Dictionaries::GetDictionaries()
-{
- QStringList dictionaries;
- QString dict_path = GetDictionaryPath();
- if (dict_path.isEmpty()) {
- return dictionaries;
- }
- QDir dictDir(dict_path);
- if (dictDir.exists()) {
- QStringList filters;
- // Look for all *.bdic files.
- filters << "*" + DICTIONARY_FILE_SUFFIX;
- dictDir.setNameFilters(filters);
- QStringList dictionary_files = dictDir.entryList();
- foreach(QString file, dictionary_files) {
- QFileInfo fileInfo(file);
- QString dname = fileInfo.baseName();
- dictionaries.append(dname);
- }
- }
+QStringList Dictionaries::GetDictionaries() {
+ QStringList dictionaries;
+ QString dict_path = GetDictionaryPath();
+ if (dict_path.isEmpty()) {
return dictionaries;
+ }
+ QDir dictDir(dict_path);
+ if (dictDir.exists()) {
+ QStringList filters;
+ // Look for all *.bdic files.
+ filters << "*" + DICTIONARY_FILE_SUFFIX;
+ dictDir.setNameFilters(filters);
+ QStringList dictionary_files = dictDir.entryList();
+ foreach (QString file, dictionary_files) {
+ QFileInfo fileInfo(file);
+ QString dname = fileInfo.baseName();
+ dictionaries.append(dname);
+ }
+ }
+ return dictionaries;
}
diff --git a/src/downloadmanagerwidget.cpp b/src/downloadmanagerwidget.cpp
index d013b1c..ac44efe 100644
--- a/src/downloadmanagerwidget.cpp
+++ b/src/downloadmanagerwidget.cpp
@@ -6,45 +6,47 @@
#include <QWebEngineDownloadItem>
DownloadManagerWidget::DownloadManagerWidget(QWidget *parent)
- : QWidget(parent)
- , m_numDownloads(0)
-{
- setupUi(this);
+ : QWidget(parent), m_numDownloads(0) {
+ setupUi(this);
}
-void DownloadManagerWidget::downloadRequested(QWebEngineDownloadItem *download)
-{
- Q_ASSERT(download && download->state() == QWebEngineDownloadItem::DownloadRequested);
- QString path;
-
- bool usenativeFileDialog = settings.value("useNativeFileDialog",false).toBool();
- if(usenativeFileDialog == false){
- path = QFileDialog::getSaveFileName(this, tr("Save as"), download->path(),tr("Any file (*)"),nullptr,QFileDialog::DontUseNativeDialog);
- }else{
- path = QFileDialog::getSaveFileName(this, tr("Save as"), download->path(),tr("Any file (*)"),nullptr);
- }
-
- if (path.isEmpty())
- return;
-
- download->setPath(path);
- download->accept();
- add(new DownloadWidget(download));
- show();
+void DownloadManagerWidget::downloadRequested(
+ QWebEngineDownloadItem *download) {
+ Q_ASSERT(download &&
+ download->state() == QWebEngineDownloadItem::DownloadRequested);
+ QString path;
+
+ bool usenativeFileDialog =
+ settings.value("useNativeFileDialog", false).toBool();
+ if (usenativeFileDialog == false) {
+ path = QFileDialog::getSaveFileName(this, tr("Save as"), download->downloadDirectory(),
+ tr("Any file (*)"), nullptr,
+ QFileDialog::DontUseNativeDialog);
+ } else {
+ path = QFileDialog::getSaveFileName(this, tr("Save as"), download->downloadDirectory(),
+ tr("Any file (*)"), nullptr);
+ }
+
+ if (path.isEmpty())
+ return;
+
+ download->setDownloadDirectory(path);
+ download->accept();
+ add(new DownloadWidget(download));
+ show();
}
-void DownloadManagerWidget::add(DownloadWidget *downloadWidget)
-{
- connect(downloadWidget, &DownloadWidget::removeClicked, this, &DownloadManagerWidget::remove);
- m_itemsLayout->insertWidget(0, downloadWidget, 0, Qt::AlignTop);
- if (m_numDownloads++ == 0)
- m_zeroItemsLabel->hide();
+void DownloadManagerWidget::add(DownloadWidget *downloadWidget) {
+ connect(downloadWidget, &DownloadWidget::removeClicked, this,
+ &DownloadManagerWidget::remove);
+ m_itemsLayout->insertWidget(0, downloadWidget, 0, Qt::AlignTop);
+ if (m_numDownloads++ == 0)
+ m_zeroItemsLabel->hide();
}
-void DownloadManagerWidget::remove(DownloadWidget *downloadWidget)
-{
- m_itemsLayout->removeWidget(downloadWidget);
- downloadWidget->deleteLater();
- if (--m_numDownloads == 0)
- m_zeroItemsLabel->show();
+void DownloadManagerWidget::remove(DownloadWidget *downloadWidget) {
+ m_itemsLayout->removeWidget(downloadWidget);
+ downloadWidget->deleteLater();
+ if (--m_numDownloads == 0)
+ m_zeroItemsLabel->show();
}
diff --git a/src/downloadwidget.cpp b/src/downloadwidget.cpp
index 005ea1e..acfe732 100644
--- a/src/downloadwidget.cpp
+++ b/src/downloadwidget.cpp
@@ -4,105 +4,96 @@
#include <QUrl>
#include <QWebEngineDownloadItem>
-DownloadWidget::DownloadWidget(QWebEngineDownloadItem *download, QWidget *parent)
- : QFrame(parent)
- , m_download(download)
- , m_timeAdded(QTime::currentTime())
-{
- setupUi(this);
- m_dstName->setText(QFileInfo(m_download->path()).fileName());
- m_srcUrl->setText(m_download->url().toDisplayString());
+DownloadWidget::DownloadWidget(QWebEngineDownloadItem *download,
+ QWidget *parent)
+ : QFrame(parent), m_download(download) {
+ setupUi(this);
+ //m_timeAdded(QTime::currentTime());
+ m_dstName->setText(QFileInfo(m_download->downloadDirectory()).fileName());
+ m_srcUrl->setText(m_download->url().toDisplayString());
- connect(m_cancelButton, &QPushButton::clicked,
- [this](bool) {
- if (m_download->state() == QWebEngineDownloadItem::DownloadInProgress)
- m_download->cancel();
- else
- emit removeClicked(this);
- });
+ connect(m_cancelButton, &QPushButton::clicked, [this](bool) {
+ if (m_download->state() == QWebEngineDownloadItem::DownloadInProgress)
+ m_download->cancel();
+ else
+ emit removeClicked(this);
+ });
- connect(m_download, &QWebEngineDownloadItem::downloadProgress,
- this, &DownloadWidget::updateWidget);
+ connect(m_download, &QWebEngineDownloadItem::downloadProgress, this,
+ &DownloadWidget::updateWidget);
- connect(m_download, &QWebEngineDownloadItem::stateChanged,
- this, &DownloadWidget::updateWidget);
+ connect(m_download, &QWebEngineDownloadItem::stateChanged, this,
+ &DownloadWidget::updateWidget);
- updateWidget();
+ updateWidget();
}
-inline QString DownloadWidget::withUnit(qreal bytes)
-{
- if (bytes < (1 << 10))
- return tr("%L1 B").arg(bytes);
- else if (bytes < (1 << 20))
- return tr("%L1 KiB").arg(bytes / (1 << 10), 0, 'f', 2);
- else if (bytes < (1 << 30))
- return tr("%L1 MiB").arg(bytes / (1 << 20), 0, 'f', 2);
- else
- return tr("%L1 GiB").arg(bytes / (1 << 30), 0, 'f', 2);
+inline QString DownloadWidget::withUnit(qreal bytes) {
+ if (bytes < (1 << 10))
+ return tr("%L1 B").arg(bytes);
+ else if (bytes < (1 << 20))
+ return tr("%L1 KiB").arg(bytes / (1 << 10), 0, 'f', 2);
+ else if (bytes < (1 << 30))
+ return tr("%L1 MiB").arg(bytes / (1 << 20), 0, 'f', 2);
+ else
+ return tr("%L1 GiB").arg(bytes / (1 << 30), 0, 'f', 2);
}
-void DownloadWidget::updateWidget()
-{
- qreal totalBytes = m_download->totalBytes();
- qreal receivedBytes = m_download->receivedBytes();
- qreal bytesPerSecond = receivedBytes / m_timeAdded.elapsed() * 1000;
+void DownloadWidget::updateWidget() {
+ qreal totalBytes = m_download->totalBytes();
+ qreal receivedBytes = m_download->receivedBytes();
+ qreal bytesPerSecond = receivedBytes / m_timeAdded.elapsed() * 1000;
- auto state = m_download->state();
- switch (state) {
- case QWebEngineDownloadItem::DownloadRequested:
- Q_UNREACHABLE();
- break;
- case QWebEngineDownloadItem::DownloadInProgress:
- if (totalBytes >= 0) {
- m_progressBar->setValue(qRound(100 * receivedBytes / totalBytes));
- m_progressBar->setDisabled(false);
- m_progressBar->setFormat(
- tr("%p% - %1 of %2 downloaded - %3/s")
- .arg(withUnit(receivedBytes))
- .arg(withUnit(totalBytes))
- .arg(withUnit(bytesPerSecond)));
- } else {
- m_progressBar->setValue(0);
- m_progressBar->setDisabled(false);
- m_progressBar->setFormat(
- tr("unknown size - %1 downloaded - %2/s")
- .arg(withUnit(receivedBytes))
- .arg(withUnit(bytesPerSecond)));
- }
- break;
- case QWebEngineDownloadItem::DownloadCompleted:
- m_progressBar->setValue(100);
- m_progressBar->setDisabled(true);
- m_progressBar->setFormat(
- tr("completed - %1 downloaded - %2/s")
- .arg(withUnit(receivedBytes))
- .arg(withUnit(bytesPerSecond)));
- break;
- case QWebEngineDownloadItem::DownloadCancelled:
- m_progressBar->setValue(0);
- m_progressBar->setDisabled(true);
- m_progressBar->setFormat(
- tr("cancelled - %1 downloaded - %2/s")
- .arg(withUnit(receivedBytes))
- .arg(withUnit(bytesPerSecond)));
- break;
- case QWebEngineDownloadItem::DownloadInterrupted:
- m_progressBar->setValue(0);
- m_progressBar->setDisabled(true);
- m_progressBar->setFormat(
- tr("interrupted: %1")
- .arg(m_download->interruptReasonString()));
- break;
- }
-
- if (state == QWebEngineDownloadItem::DownloadInProgress) {
- static QIcon cancelIcon(QStringLiteral(":/icons/stop-line.png"));
- m_cancelButton->setIcon(cancelIcon);
- m_cancelButton->setToolTip(tr("Stop downloading"));
+ auto state = m_download->state();
+ switch (state) {
+ case QWebEngineDownloadItem::DownloadRequested:
+ Q_UNREACHABLE();
+ break;
+ case QWebEngineDownloadItem::DownloadInProgress:
+ if (totalBytes >= 0) {
+ m_progressBar->setValue(qRound(100 * receivedBytes / totalBytes));
+ m_progressBar->setDisabled(false);
+ m_progressBar->setFormat(tr("%p% - %1 of %2 downloaded - %3/s")
+ .arg(withUnit(receivedBytes))
+ .arg(withUnit(totalBytes))
+ .arg(withUnit(bytesPerSecond)));
} else {
- static QIcon removeIcon(QStringLiteral(":/icons/close-fill.png"));
- m_cancelButton->setIcon(removeIcon);
- m_cancelButton->setToolTip(tr("Remove from list"));
+ m_progressBar->setValue(0);
+ m_progressBar->setDisabled(false);
+ m_progressBar->setFormat(tr("unknown size - %1 downloaded - %2/s")
+ .arg(withUnit(receivedBytes))
+ .arg(withUnit(bytesPerSecond)));
}
+ break;
+ case QWebEngineDownloadItem::DownloadCompleted:
+ m_progressBar->setValue(100);
+ m_progressBar->setDisabled(true);
+ m_progressBar->setFormat(tr("completed - %1 downloaded - %2/s")
+ .arg(withUnit(receivedBytes))
+ .arg(withUnit(bytesPerSecond)));
+ break;
+ case QWebEngineDownloadItem::DownloadCancelled:
+ m_progressBar->setValue(0);
+ m_progressBar->setDisabled(true);
+ m_progressBar->setFormat(tr("cancelled - %1 downloaded - %2/s")
+ .arg(withUnit(receivedBytes))
+ .arg(withUnit(bytesPerSecond)));
+ break;
+ case QWebEngineDownloadItem::DownloadInterrupted:
+ m_progressBar->setValue(0);
+ m_progressBar->setDisabled(true);
+ m_progressBar->setFormat(
+ tr("interrupted: %1").arg(m_download->interruptReasonString()));
+ break;
+ }
+
+ if (state == QWebEngineDownloadItem::DownloadInProgress) {
+ static QIcon cancelIcon(QStringLiteral(":/icons/stop-line.png"));
+ m_cancelButton->setIcon(cancelIcon);
+ m_cancelButton->setToolTip(tr("Stop downloading"));
+ } else {
+ static QIcon removeIcon(QStringLiteral(":/icons/close-fill.png"));
+ m_cancelButton->setIcon(removeIcon);
+ m_cancelButton->setToolTip(tr("Remove from list"));
+ }
}
diff --git a/src/downloadwidget.h b/src/downloadwidget.h
index 521d996..ff9e488 100644
--- a/src/downloadwidget.h
+++ b/src/downloadwidget.h
@@ -57,6 +57,7 @@
#include <QFrame>
#include <QTime>
+#include <QElapsedTimer>
QT_BEGIN_NAMESPACE
class QWebEngineDownloadItem;
@@ -82,7 +83,7 @@ private:
QString withUnit(qreal bytes);
QWebEngineDownloadItem *m_download;
- QTime m_timeAdded;
+ QElapsedTimer m_timeAdded;
};
#endif // DOWNLOADWIDGET_H
diff --git a/src/elidedlabel.cpp b/src/elidedlabel.cpp
index 6c14af4..b88ed4f 100644
--- a/src/elidedlabel.cpp
+++ b/src/elidedlabel.cpp
@@ -5,45 +5,48 @@
#include <QResizeEvent>
#include <QStyle>
-ElidedLabel::ElidedLabel(QWidget* parent, Qt::WindowFlags f)
+ElidedLabel::ElidedLabel(QWidget *parent, Qt::WindowFlags f)
: QLabel(parent, f), m_elide_mode(Qt::ElideRight) {
- setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
+ setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
}
-ElidedLabel::ElidedLabel(const QString& txt, QWidget* parent, Qt::WindowFlags f)
+ElidedLabel::ElidedLabel(const QString &txt, QWidget *parent, Qt::WindowFlags f)
: QLabel(txt, parent, f), m_elide_mode(Qt::ElideRight) {
- setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
+ setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
}
-ElidedLabel::ElidedLabel(const QString& txt, Qt::TextElideMode elideMode, QWidget* parent, Qt::WindowFlags f)
+ElidedLabel::ElidedLabel(const QString &txt, Qt::TextElideMode elideMode,
+ QWidget *parent, Qt::WindowFlags f)
: QLabel(txt, parent, f), m_elide_mode(elideMode) {
- setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
-
+ setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
}
-void ElidedLabel::setText(const QString& txt) {
- QLabel::setText(txt);
- cacheElidedText(geometry().width());
- 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);
+ 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::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);
- }
+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/lock.cpp b/src/lock.cpp
index e5c65d1..4eb65d1 100644
--- a/src/lock.cpp
+++ b/src/lock.cpp
@@ -5,214 +5,196 @@
#ifdef Q_OS_WIN32
#include <Windows.h>
#else
-#include <X11/XKBlib.h> // sudo apt install libx11-dev
+#include <X11/XKBlib.h> // apt install libx11-dev
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>
#endif
-Lock::Lock(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::Lock)
-{
- ui->setupUi(this);
- ui->unlock->setEnabled(false);
- ui->setPass->setEnabled(false);
- ui->wrong->hide();
+Lock::Lock(QWidget *parent) : QWidget(parent), ui(new Ui::Lock) {
+ ui->setupUi(this);
+ ui->unlock->setEnabled(false);
+ ui->setPass->setEnabled(false);
+ ui->wrong->hide();
- QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
- ui->centerWidget->setGraphicsEffect(eff);
+ QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
+ ui->centerWidget->setGraphicsEffect(eff);
- animate();
+ animate();
- if(settings.value("asdfg").isValid() == false)
- {
- isLocked = false;
- ui->signup->show();
- ui->login->hide();
- animate();
- ui->passcode1->setFocus();
- }else
- {
- lock_app();
- }
+ if (settings.value("asdfg").isValid() == false) {
+ isLocked = false;
+ ui->signup->show();
+ ui->login->hide();
+ animate();
+ ui->passcode1->setFocus();
+ } else {
+ lock_app();
+ }
+ checkCaps();
+ QString capsStyle = QString("background-color: palette(window);"
+ "padding:4px;"
+ "border:0px solid palette(highlight);"
+ "border-radius: 2px;"
+ "color:palette(window-text);");
+ ui->caps1->setStyleSheet(capsStyle);
+ ui->caps2->setStyleSheet(capsStyle);
+ ui->signup_warning->setStyleSheet(capsStyle);
+ ui->wrong->setStyleSheet(capsStyle);
+}
+
+void Lock::animate() {
+ ui->centerWidget->hide();
+ QPropertyAnimation *a =
+ new QPropertyAnimation(ui->centerWidget->graphicsEffect(), "opacity");
+ a->setDuration(400);
+ a->setStartValue(0);
+ a->setEndValue(1);
+ a->setEasingCurve(QEasingCurve::InCurve);
+ a->start(QPropertyAnimation::DeleteWhenStopped);
+ ui->centerWidget->show();
+}
+
+void Lock::applyThemeQuirks() {
+ // little quirks
+
+ ui->label_4->setStyleSheet(
+ "color:#c2c5d1;padding: 0px 8px 0px 8px;background:transparent;");
+ ui->label_3->setStyleSheet(
+ "color:#c2c5d1;padding: 0px 8px 0px 8px;background:transparent;");
+
+ ui->login->setStyleSheet("QWidget#login{background-color:palette(window);"
+ "background-image:url(:/icons/wa_bg.png)};");
+ ui->signup->setStyleSheet("QWidget#signup{background-color:palette(window);"
+ "background-image:url(:/icons/wa_bg.png)};");
+
+ ui->widget_2->setStyleSheet(
+ "QWidget#widget_2{\nborder-radius: "
+ "5px;\nbackground-image:url(:/icons/"
+ "texture.png);\nbackground-color:palette(shadow);\n}");
+ ui->widget->setStyleSheet(
+ "QWidget#widget{\nborder-radius: "
+ "5px;\nbackground-image:url(:/icons/"
+ "texture.png);\nbackground-color:palette(shadow);\n}");
+
+ ui->centerWidget->setStyleSheet(
+ "QWidget#centerWidget{background-image:url(:/icons/wa_bg.png)}");
+ if (settings.value("windowTheme", "light").toString() == "dark") {
+
+ } else {
+ }
+}
+
+Lock::~Lock() { delete ui; }
+
+void Lock::checkCaps() {
+ if (getCapsLockOn()) {
+ ui->caps1->show();
+ ui->caps2->show();
+ } else {
+ ui->caps1->hide();
+ ui->caps2->hide();
+ }
+}
+
+void Lock::keyReleaseEvent(QKeyEvent *event) {
+ if (event->key() == Qt::Key_CapsLock) {
checkCaps();
- QString capsStyle = QString("background-color: palette(window);"
- "padding:4px;"
- "border:0px solid palette(highlight);"
- "border-radius: 2px;"
- "color:palette(window-text);");
- ui->caps1->setStyleSheet(capsStyle);
- ui->caps2->setStyleSheet(capsStyle);
- ui->signup_warning->setStyleSheet(capsStyle);
- ui->wrong->setStyleSheet(capsStyle);
-
-}
-
-void Lock::animate()
-{
- ui->centerWidget->hide();
- QPropertyAnimation *a = new QPropertyAnimation(ui->centerWidget->graphicsEffect(),"opacity");
- a->setDuration(400);
- a->setStartValue(0);
- a->setEndValue(1);
- a->setEasingCurve(QEasingCurve::InCurve);
- a->start(QPropertyAnimation::DeleteWhenStopped);
- ui->centerWidget->show();
-}
-
-void Lock::applyThemeQuirks(){
- //little quirks
-
- ui->label_4->setStyleSheet("color:#c2c5d1;padding: 0px 8px 0px 8px;background:transparent;");
- ui->label_3->setStyleSheet("color:#c2c5d1;padding: 0px 8px 0px 8px;background:transparent;");
-
- ui->login->setStyleSheet("QWidget#login{background-color:palette(window);background-image:url(:/icons/wa_bg.png)};");
- ui->signup->setStyleSheet("QWidget#signup{background-color:palette(window);background-image:url(:/icons/wa_bg.png)};");
-
- ui->widget_2->setStyleSheet("QWidget#widget_2{\nborder-radius: 5px;\nbackground-image:url(:/icons/texture.png);\nbackground-color:palette(shadow);\n}");
- ui->widget->setStyleSheet("QWidget#widget{\nborder-radius: 5px;\nbackground-image:url(:/icons/texture.png);\nbackground-color:palette(shadow);\n}");
-
- ui->centerWidget->setStyleSheet("QWidget#centerWidget{background-image:url(:/icons/wa_bg.png)}");
- if(settings.value("windowTheme","light").toString() == "dark")
- {
-
- }else{
-
- }
-}
-
-Lock::~Lock()
-{
- delete ui;
-}
-
-void Lock::checkCaps()
-{
- if(getCapsLockOn()){
- ui->caps1->show();
- ui->caps2->show();
- }else{
- ui->caps1->hide();
- ui->caps2->hide();
- }
-}
-
-void Lock::keyReleaseEvent(QKeyEvent *event){
- if(event->key() == Qt::Key_CapsLock){
- checkCaps();
+ }
+}
+
+bool Lock::event(QEvent *e) { return QWidget::event(e); }
+
+void Lock::on_passcode1_textChanged(const QString &arg1) {
+ if (arg1.contains(" ")) {
+ ui->passcode1->setText(arg1.simplified());
+ }
+ ui->setPass->setEnabled(arg1.length() > 4 && arg1 == ui->passcode2->text());
+}
+
+void Lock::on_passcode2_textChanged(const QString &arg1) {
+ if (arg1.contains(" ")) {
+ ui->passcode2->setText(arg1.simplified());
+ }
+ ui->setPass->setEnabled(arg1.length() > 4 && arg1 == ui->passcode1->text());
+}
+
+void Lock::on_setPass_clicked() {
+ QString pass1, pass2;
+ pass1 = ui->passcode1->text().trimmed();
+ pass2 = ui->passcode2->text().trimmed();
+ if (pass1 == pass2) {
+ settings.setValue("asdfg", QByteArray(pass1.toUtf8()).toBase64());
+ settings.setValue("lockscreen", true);
+ ui->passcode1->clear();
+ ui->passcode2->clear();
+ emit passwordSet();
+ if (check_password_set()) {
+ ui->signup->hide();
+ ui->login->show();
+ ui->passcodeLogin->setFocus();
}
+ } else {
+ return;
+ }
}
-bool Lock::event(QEvent* e)
-{
- return QWidget::event(e);
-}
+bool Lock::check_password_set() { return settings.value("asdfg").isValid(); }
-void Lock::on_passcode1_textChanged(const QString &arg1)
-{
- if(arg1.contains(" ")){
- ui->passcode1->setText(arg1.simplified());
- }
- ui->setPass->setEnabled(arg1.length()>4 && arg1== ui->passcode2->text());
-}
-
-void Lock::on_passcode2_textChanged(const QString &arg1)
-{
- if(arg1.contains(" ")){
- ui->passcode2->setText(arg1.simplified());
- }
- ui->setPass->setEnabled(arg1.length()>4 && arg1== ui->passcode1->text());
-}
-
-void Lock::on_setPass_clicked()
-{
- QString pass1,pass2;
- pass1 = ui->passcode1->text().trimmed();
- pass2 = ui->passcode2->text().trimmed();
- if(pass1==pass2)
- {
- settings.setValue("asdfg",QByteArray(pass1.toUtf8()).toBase64());
- settings.setValue("lockscreen",true);
- ui->passcode1->clear();
- ui->passcode2->clear();
- emit passwordSet();
- if(check_password_set()){
- ui->signup->hide();
- ui->login->show();
- ui->passcodeLogin->setFocus();
- }
- }else {
- return;
- }
-}
-
-bool Lock::check_password_set(){
- return settings.value("asdfg").isValid();
-}
-
-void Lock::on_unlock_clicked()
-{
- QString password = QByteArray::fromBase64(settings.value("asdfg").toByteArray());
- if(ui->passcodeLogin->text() == password && check_password_set())
- {
- ui->login->hide();
- ui->signup->hide();
- ui->passcodeLogin->clear();
- isLocked = false;
- this->hide();
- emit unLocked();
- }else{
- ui->wrong->show();
- }
+void Lock::on_unlock_clicked() {
+ QString password =
+ QByteArray::fromBase64(settings.value("asdfg").toByteArray());
+ if (ui->passcodeLogin->text() == password && check_password_set()) {
+ ui->login->hide();
+ ui->signup->hide();
+ ui->passcodeLogin->clear();
+ isLocked = false;
+ this->hide();
+ emit unLocked();
+ } else {
+ ui->wrong->show();
+ }
}
-void Lock::on_passcodeLogin_textChanged(const QString &arg1)
-{
- if(arg1.contains(" ")){
- ui->passcodeLogin->setText(arg1.simplified());
- }
- ui->wrong->hide();
- ui->unlock->setEnabled(arg1.length()>4);
+void Lock::on_passcodeLogin_textChanged(const QString &arg1) {
+ if (arg1.contains(" ")) {
+ ui->passcodeLogin->setText(arg1.simplified());
+ }
+ ui->wrong->hide();
+ ui->unlock->setEnabled(arg1.length() > 4);
}
-void Lock::lock_app()
-{
- checkCaps();
- ui->wrong->hide();
- ui->signup->hide();
- ui->login->show();
- isLocked = true;
- this->show();
- animate();
- ui->passcodeLogin->setFocus();
+void Lock::lock_app() {
+ checkCaps();
+ ui->wrong->hide();
+ ui->signup->hide();
+ ui->login->show();
+ isLocked = true;
+ this->show();
+ animate();
+ ui->passcodeLogin->setFocus();
}
-void Lock::on_passcodeLogin_returnPressed()
-{
- on_unlock_clicked();
-}
+void Lock::on_passcodeLogin_returnPressed() { on_unlock_clicked(); }
-bool Lock::getCapsLockOn()
-{
+bool Lock::getCapsLockOn() {
// platform dependent method of determining if CAPS LOCK is on
#ifdef Q_OS_WIN32 // MS Windows version
- return GetKeyState(VK_CAPITAL) == 1;
+ return GetKeyState(VK_CAPITAL) == 1;
#else // X11 version (Linux/Unix/Mac OS X/etc...)
- Display* d = XOpenDisplay((char*)0);
- bool caps_state = false;
- if (d) {
- unsigned n;
- XkbGetIndicatorState(d, XkbUseCoreKbd, &n);
- caps_state = (n & 0x01) == 1;
- }
- return caps_state;
+ Display *d = XOpenDisplay((char *)0);
+ bool caps_state = false;
+ if (d) {
+ unsigned n;
+ XkbGetIndicatorState(d, XkbUseCoreKbd, &n);
+ caps_state = (n & 0x01) == 1;
+ }
+ return caps_state;
#endif
}
-void Lock::on_cancelSetting_clicked()
-{
- isLocked = false;
- emit passwordNotSet();
- this->hide();
+void Lock::on_cancelSetting_clicked() {
+ isLocked = false;
+ emit passwordNotSet();
+ this->hide();
}
diff --git a/src/main.cpp b/src/main.cpp
index 1b3881e..7f94a3d 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -1,67 +1,71 @@
#include <QApplication>
-#include <QtWidgets>
-#include <QtWebEngine>
+#include <QDebug>
+#include <QSettings>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
-#include <QSettings>
-#include <QDebug>
+#include <QtWebEngine>
+#include <QtWidgets>
#include "mainwindow.h"
-#include "rungaurd.h"
#include "common.h"
+#include "rungaurd.h"
+int main(int argc, char *argv[]) {
+ QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
+ static const char ENV_VAR_QT_DEVICE_PIXEL_RATIO[] = "QT_DEVICE_PIXEL_RATIO";
+ if (!qEnvironmentVariableIsSet(ENV_VAR_QT_DEVICE_PIXEL_RATIO) &&
+ !qEnvironmentVariableIsSet("QT_AUTO_SCREEN_SCALE_FACTOR") &&
+ !qEnvironmentVariableIsSet("QT_SCALE_FACTOR") &&
+ !qEnvironmentVariableIsSet("QT_SCREEN_SCALE_FACTORS")) {
+ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
+ }
-int main(int argc, char *argv[])
-{
- QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
- static const char ENV_VAR_QT_DEVICE_PIXEL_RATIO[] = "QT_DEVICE_PIXEL_RATIO";
- if (!qEnvironmentVariableIsSet(ENV_VAR_QT_DEVICE_PIXEL_RATIO)
- && !qEnvironmentVariableIsSet("QT_AUTO_SCREEN_SCALE_FACTOR")
- && !qEnvironmentVariableIsSet("QT_SCALE_FACTOR")
- && !qEnvironmentVariableIsSet("QT_SCREEN_SCALE_FACTORS")) {
- QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
- }
-
- QApplication app(argc, argv);
- app.setWindowIcon(QIcon(":/icons/app/icon-256.png"));
+ QApplication app(argc, argv);
+ app.setWindowIcon(QIcon(":/icons/app/icon-256.png"));
- QApplication::setApplicationName("WhatSie");
- QApplication::setOrganizationName("org.keshavnrj.ubuntu");
- QApplication::setApplicationVersion(VERSIONSTR);
+ QApplication::setApplicationName("WhatSie");
+ QApplication::setOrganizationName("org.keshavnrj.ubuntu");
+ QApplication::setApplicationVersion(VERSIONSTR);
- QString appname = QApplication::applicationName();
+ QString appname = QApplication::applicationName();
- //allow multiple instances in debug builds
- #ifndef QT_DEBUG
- RunGuard guard("org.keshavnrj.ubuntu."+appname);
- if ( !guard.tryToRun() ){
- QMessageBox::critical(0, appname,"An instance of "+appname+" is already running.");
- return 0;
- }
- #endif
+// allow multiple instances in debug builds
+#ifndef QT_DEBUG
+ RunGuard guard("org.keshavnrj.ubuntu." + appname);
+ if (!guard.tryToRun()) {
+ QMessageBox::critical(0, appname,
+ "An instance of " + appname + " is already running.");
+ return 0;
+ }
+#endif
- qputenv("QTWEBENGINE_CHROMIUM_FLAGS","--single-process");
+ qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--single-process");
#ifdef QT_DEBUG
- qputenv("QTWEBENGINE_CHROMIUM_FLAGS","--remote-debugging-port=9421");
+ qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--remote-debugging-port=9421");
#endif
- qputenv("QTWEBENGINE_CHROMIUM_FLAGS","--disable-logging");
+ qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-logging");
- QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
- QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::DnsPrefetchEnabled, true);
- QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
+ QWebEngineSettings::defaultSettings()->setAttribute(
+ QWebEngineSettings::PluginsEnabled, true);
+ QWebEngineSettings::defaultSettings()->setAttribute(
+ QWebEngineSettings::DnsPrefetchEnabled, true);
+ QWebEngineSettings::defaultSettings()->setAttribute(
+ QWebEngineSettings::FullScreenSupportEnabled, true);
+ QWebEngineSettings::defaultSettings()->setAttribute(
+ QWebEngineSettings::JavascriptCanAccessClipboard, true);
- MainWindow window;
+ MainWindow window;
- QStringList argsList = app.arguments();
- qWarning()<<"Launching with argument"<<argsList;
- foreach (QString argStr, argsList) {
- if(argStr.contains("whatsapp://")){
- qWarning()<<"Link passed as argument"<<argStr;
- window.loadAppWithArgument(argStr);
- }
+ QStringList argsList = app.arguments();
+ qWarning() << "Launching with argument" << argsList;
+ foreach (QString argStr, argsList) {
+ if (argStr.contains("whatsapp://")) {
+ qWarning() << "Link passed as argument" << argStr;
+ window.loadAppWithArgument(argStr);
}
- window.show();
+ }
+ window.show();
- return app.exec();
+ return app.exec();
}
diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp
index e75166c..9f7e187 100644
--- a/src/mainwindow.cpp
+++ b/src/mainwindow.cpp
@@ -5,927 +5,908 @@
#include <QStyleHints>
#include <QUrlQuery>
#include <QWebEngineNotification>
+#include <QRandomGenerator>
extern QString defaultUserAgentStr;
MainWindow::MainWindow(QWidget *parent)
- : QMainWindow(parent),
- notificationsTitleRegExp("^\\([1-9]\\d*\\).*"),
+ : QMainWindow(parent), notificationsTitleRegExp("^\\([1-9]\\d*\\).*"),
trayIconRead(":/icons/app/whatsapp.svg"),
- trayIconUnread(":/icons/app/whatsapp-message.svg")
-{
- this->setObjectName("MainWindow");
-
- qApp->setQuitOnLastWindowClosed(false);
-
- lightPalette = qApp->palette();
- lightPalette.setColor(QPalette::Window,QColor("#F0F0F0"));//whatsapp light palette
-
-
- setWindowTitle(QApplication::applicationName());
- setWindowIcon(QIcon(":/icons/app/icon-256.png"));
- setMinimumWidth(500);
- setMinimumHeight(520);
-
- restoreGeometry(settings.value("geometry").toByteArray());
- restoreState(settings.value("windowState").toByteArray());
-
- createActions();
- createTrayIcon();
- createWebEngine();
-
- if(settings.value("lockscreen",false).toBool())
- {
- init_lock();
- }
- QTimer *timer = new QTimer(this);
- timer->setInterval(1000);
- connect(timer,&QTimer::timeout,[=](){
- if(settings.value("asdfg").isValid()){
- if(lockWidget && lockWidget->isLocked==false){
- timer->stop();
- //init_accountWidget();
- }
- }
- });
- timer->start();
-
- init_settingWidget();
-
- // quit application if the download manager window is the only remaining window
- m_downloadManagerWidget.setAttribute(Qt::WA_QuitOnClose, false);
-
- updateWindowTheme();
-
- RateApp *rateApp = new RateApp(this, "snap://whatsie", 5, 5, 1000 * 30);
- rateApp->setWindowTitle(QApplication::applicationName()+" | "+tr("Rate Application"));
- rateApp->setVisible(false);
- rateApp->setWindowFlags(Qt::Dialog);
- rateApp->setAttribute(Qt::WA_DeleteOnClose,true);
- QPoint centerPos = this->geometry().center()-rateApp->geometry().center();
- connect(rateApp,&RateApp::showRateDialog,[=]()
- {
- if(this->windowState() != Qt::WindowMinimized && this->isVisible() && isActiveWindow()){
- rateApp->move(centerPos);
- rateApp->show();
- }else{
- rateApp->delayShowEvent();
- }
- });
-}
-
-void MainWindow::loadAppWithArgument(const QString &arg)
-{
- //https://faq.whatsapp.com/iphone/how-to-link-to-whatsapp-from-a-different-app/?lang=en
-
- //The WhatsApp Messenger application
- if(arg.contains("://app")){
- qWarning()<<"WhatsApp Messenger application";
- this->show(); //restore app
- return;
- }
- //PASSED SCHEME whatsapp://send?text=Hello%2C%20World!&phone=919568388397"
- //CONVERTED URI https://web.whatsapp.com/send?phone=919568388397&text=Hello%2C%20World
- //New chat composer
- if(arg.contains("send?") || arg.contains("send/?"))
- {
- QString newArg = arg;
- qWarning()<<"New chat composer";
- newArg = newArg.replace("?","&");
- QUrlQuery query(newArg);
- qWarning()<<query.hasQueryItem("phone");
- QString phone, phoneStr, text, textStr, urlStr;
- //create send url equivalent
- phone = query.queryItemValue("phone");
- text = query.queryItemValue("text");
-
- phoneStr = phone.isEmpty() ? "" : "phone="+phone;
- textStr = text.isEmpty() ? "" : "text="+text;
-
- urlStr = "https://web.whatsapp.com/send?"+phoneStr+"&"+textStr;
- qWarning()<<"Loading"<<urlStr;
- this->webEngine->page()->load(QUrl(urlStr));
- return;
- }
-}
-
-void MainWindow::updatePageTheme()
-{
- QString webPageTheme = "web"; //implies light
- QString windowTheme = settings.value("windowTheme","light").toString();
- if(windowTheme == "dark"){
- webPageTheme = "web dark";
- }
- if(webEngine && webEngine->page()){
- webEngine->page()->runJavaScript(
- "document.querySelector('body').className='"+webPageTheme+"';",
- [](const QVariant &result){
- qDebug() << "Value is: " << result.toString() << endl;
- }
- );
- }
-}
-
-void MainWindow::resizeEvent(QResizeEvent *event)
-{
- if(lockWidget != nullptr){
- lockWidget->resize(event->size());
- }
-}
-
-void MainWindow::updateWindowTheme()
-{
- if(settings.value("windowTheme","light").toString() == "dark")
- {
- qApp->setStyle(QStyleFactory::create("fusion"));
- QPalette palette;
- palette.setColor(QPalette::Window, QColor("#262D31"));
- palette.setColor(QPalette::Text, Qt::white);
- palette.setColor(QPalette::WindowText, Qt::white);
- palette.setColor(QPalette::Base, QColor("#323739"));
- palette.setColor(QPalette::AlternateBase, QColor("#5f6c73"));
- palette.setColor(QPalette::ToolTipBase, QColor(66, 66, 66));
- palette.setColor(QPalette::Disabled, QPalette::Window,QColor("#3f4143"));
- palette.setColor(QPalette::ToolTipText, QColor("silver"));
- palette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127));
- palette.setColor(QPalette::Dark, QColor(35, 35, 35));
- palette.setColor(QPalette::Shadow, QColor(20, 20, 20));
- palette.setColor(QPalette::Button, QColor("#262D31"));
- palette.setColor(QPalette::ButtonText, Qt::white);
- palette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(127, 127, 127));
- palette.setColor(QPalette::BrightText, Qt::red);
- palette.setColor(QPalette::Link, QColor(42, 130, 218));
- palette.setColor(QPalette::Highlight, QColor(38, 140, 196));
- palette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(80, 80, 80));
- palette.setColor(QPalette::HighlightedText, Qt::white);
- palette.setColor(QPalette::Disabled, QPalette::HighlightedText,QColor(127, 127, 127));
- qApp->setPalette(palette);
- this->webEngine->setStyleSheet("QWebEngineView{background:#131C21;}"); //whatsapp dark color
- //this->webEngine->page()->setBackgroundColor(QColor("#131C21;")); //whatsapp dark color
- }
- else{
- qApp->setPalette(lightPalette);
- this->webEngine->setStyleSheet("QWebEngineView{background:#F0F0F0;}"); //whatsapp light color
- //this->webEngine->page()->setBackgroundColor(QColor("#F0F0F0;")); //whatsapp light color
- }
-
- QList<QWidget*> widgets = this->findChildren<QWidget*>();
-
- foreach (QWidget* w, widgets)
- {
- w->setPalette(qApp->palette());
- }
-
- setNotificationPresenter(webEngine->page()->profile());
-
- if(lockWidget!=nullptr)
- {
- lockWidget->setStyleSheet("QWidget#login{background-color:palette(window)};"
- "QWidget#signup{background-color:palette(window)};");
- lockWidget->applyThemeQuirks();
- }
- this->update();
-}
-
-void MainWindow::handleCookieAdded(const QNetworkCookie &cookie)
-{
+ trayIconUnread(":/icons/app/whatsapp-message.svg") {
+ this->setObjectName("MainWindow");
+
+ qApp->setQuitOnLastWindowClosed(false);
+
+ lightPalette = qApp->palette();
+ lightPalette.setColor(QPalette::Window,
+ QColor(240, 240, 240)); // whatsapp light palette
+
+ setWindowTitle(QApplication::applicationName());
+ setWindowIcon(QIcon(":/icons/app/icon-256.png"));
+ setMinimumWidth(750);
+ setMinimumHeight(640);
+
+ restoreGeometry(settings.value("geometry").toByteArray());
+ restoreState(settings.value("windowState").toByteArray());
+
+ createActions();
+ createTrayIcon();
+ createWebEngine();
+
+ if (settings.value("lockscreen", false).toBool()) {
+ init_lock();
+ }
+ QTimer *timer = new QTimer(this);
+ timer->setInterval(1000);
+ connect(timer, &QTimer::timeout, lockWidget, [=]() {
+ if (settings.value("asdfg").isValid()) {
+ if (lockWidget && lockWidget->isLocked == false) {
+ timer->stop();
+ }
+ }
+ });
+ timer->start();
+
+ init_settingWidget();
+
+ // quit application if the download manager window is the only remaining
+ // window
+ m_downloadManagerWidget.setAttribute(Qt::WA_QuitOnClose, false);
+
+ updateWindowTheme();
+
+ RateApp *rateApp = new RateApp(this, "snap://whatsie", 5, 5, 1000 * 30);
+ rateApp->setWindowTitle(QApplication::applicationName() + " | " +
+ tr("Rate Application"));
+ rateApp->setVisible(false);
+ rateApp->setWindowFlags(Qt::Dialog);
+ rateApp->setAttribute(Qt::WA_DeleteOnClose, true);
+ QPoint centerPos = this->geometry().center() - rateApp->geometry().center();
+ connect(rateApp, &RateApp::showRateDialog, rateApp, [=]() {
+ if (this->windowState() != Qt::WindowMinimized && this->isVisible() &&
+ isActiveWindow()) {
+ rateApp->move(centerPos);
+ rateApp->show();
+ } else {
+ rateApp->delayShowEvent();
+ }
+ });
+}
+
+void MainWindow::loadAppWithArgument(const QString &arg) {
+ // https://faq.whatsapp.com/iphone/how-to-link-to-whatsapp-from-a-different-app/?lang=en
+
+ // The WhatsApp Messenger application
+ if (arg.contains("://app")) {
+ qWarning() << "WhatsApp Messenger application";
+ this->show(); // restore app
+ return;
+ }
+ // PASSED SCHEME whatsapp://send?text=Hello%2C%20World!&phone=919568388397"
+ // CONVERTED URI
+ // https://web.whatsapp.com/send?phone=919568388397&text=Hello%2C%20World New
+ // chat composer
+ if (arg.contains("send?") || arg.contains("send/?")) {
+ QString newArg = arg;
+ qWarning() << "New chat composer";
+ newArg = newArg.replace("?", "&");
+ QUrlQuery query(newArg);
+ qWarning() << query.hasQueryItem("phone");
+ QString phone, phoneStr, text, textStr, urlStr;
+ // create send url equivalent
+ phone = query.queryItemValue("phone");
+ text = query.queryItemValue("text");
+
+ phoneStr = phone.isEmpty() ? "" : "phone=" + phone;
+ textStr = text.isEmpty() ? "" : "text=" + text;
+
+ urlStr = "https://web.whatsapp.com/send?" + phoneStr + "&" + textStr;
+ qWarning() << "Loading" << urlStr;
+ this->webEngine->page()->load(QUrl(urlStr));
+ return;
+ }
+}
+
+void MainWindow::updatePageTheme() {
+ QString webPageTheme = "web"; // implies light
+ QString windowTheme = settings.value("windowTheme", "light").toString();
+ if (windowTheme == "dark") {
+ webPageTheme = "web dark";
+ }
+ if (webEngine && webEngine->page()) {
+ webEngine->page()->runJavaScript(
+ "document.querySelector('body').className='" + webPageTheme + "';",
+ [](const QVariant &result) {
+ qDebug() << "Value is: " << result.toString() << Qt::endl;
+ });
+ }
+}
+
+void MainWindow::resizeEvent(QResizeEvent *event) {
+ if (lockWidget != nullptr) {
+ lockWidget->resize(event->size());
+ }
+}
+
+void MainWindow::updateWindowTheme() {
+ if (settings.value("windowTheme", "light").toString() == "dark") {
+ qApp->setStyle(QStyleFactory::create("fusion"));
+ QPalette palette;
+ palette.setColor(QPalette::Window, QColor(38, 45, 49));
+ palette.setColor(QPalette::Text, Qt::white);
+ palette.setColor(QPalette::WindowText, Qt::white);
+ palette.setColor(QPalette::Base, QColor(50, 55, 57));
+ palette.setColor(QPalette::AlternateBase, QColor(95, 108, 115));
+ palette.setColor(QPalette::ToolTipBase, QColor(66, 66, 66));
+ palette.setColor(QPalette::Disabled, QPalette::Window, QColor(65, 65, 67));
+ palette.setColor(QPalette::ToolTipText, QColor("silver"));
+ palette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127));
+ palette.setColor(QPalette::Dark, QColor(35, 35, 35));
+ palette.setColor(QPalette::Shadow, QColor(20, 20, 20));
+ palette.setColor(QPalette::Button, QColor(38, 45, 49));
+ palette.setColor(QPalette::ButtonText, Qt::white);
+ palette.setColor(QPalette::Disabled, QPalette::ButtonText,
+ QColor(127, 127, 127));
+ palette.setColor(QPalette::BrightText, Qt::red);
+ palette.setColor(QPalette::Link, QColor(42, 130, 218));
+ palette.setColor(QPalette::Highlight, QColor(38, 140, 196));
+ palette.setColor(QPalette::Disabled, QPalette::Highlight,
+ QColor(80, 80, 80));
+ palette.setColor(QPalette::HighlightedText, Qt::white);
+ palette.setColor(QPalette::Disabled, QPalette::HighlightedText,
+ QColor(127, 127, 127));
+ qApp->setPalette(palette);
+ this->webEngine->setStyleSheet(
+ "QWebEngineView{background:#131C21;}"); // whatsapp dark color
+ } else {
+ qApp->setPalette(lightPalette);
+ this->webEngine->setStyleSheet(
+ "QWebEngineView{background:#F0F0F0;}"); // whatsapp light color
+ }
+
+ QList<QWidget *> widgets = this->findChildren<QWidget *>();
+
+ foreach (QWidget *w, widgets) { w->setPalette(qApp->palette()); }
+
+ setNotificationPresenter(webEngine->page()->profile());
+
+ if (lockWidget != nullptr) {
+ lockWidget->setStyleSheet(
+ "QWidget#login{background-color:palette(window)};"
+ "QWidget#signup{background-color:palette(window)};");
+ lockWidget->applyThemeQuirks();
+ }
+ this->update();
+}
+
+void MainWindow::handleCookieAdded(const QNetworkCookie &cookie) {
qDebug() << cookie.toRawForm() << "\n\n\n";
}
-
-void MainWindow::init_settingWidget()
-{
- if(settingsWidget == nullptr)
- {
- settingsWidget = new SettingsWidget(this,webEngine->page()->profile()->cachePath()
- ,webEngine->page()->profile()->persistentStoragePath());
- settingsWidget->setWindowTitle(QApplication::applicationName()+" | Settings");
- settingsWidget->setWindowFlags(Qt::Dialog);
-
- connect(settingsWidget,SIGNAL(init_lock()),this,SLOT(init_lock()));
- connect(settingsWidget,SIGNAL(updateWindowTheme()),this,SLOT(updateWindowTheme()));
- connect(settingsWidget,SIGNAL(updatePageTheme()),this,SLOT(updatePageTheme()));
-
- connect(settingsWidget,&SettingsWidget::muteToggled,[=](const bool checked)
- {
- this->toggleMute(checked);
- });
- connect(settingsWidget,&SettingsWidget::userAgentChanged,[=](QString userAgentStr)
- {
- if(webEngine->page()->profile()->httpUserAgent() != userAgentStr)
- {
- settings.setValue("useragent",userAgentStr);
+void MainWindow::init_settingWidget() {
+ if (settingsWidget == nullptr) {
+ settingsWidget = new SettingsWidget(
+ this, webEngine->page()->profile()->cachePath(),
+ webEngine->page()->profile()->persistentStoragePath());
+ settingsWidget->setWindowTitle(QApplication::applicationName() +
+ " | Settings");
+ settingsWidget->setWindowFlags(Qt::Dialog);
+
+ connect(settingsWidget, SIGNAL(init_lock()), this, SLOT(init_lock()));
+ 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() !=
+ userAgentStr) {
+ settings.setValue("useragent", userAgentStr);
this->updateSettingsUserAgentWidget();
this->askToReloadPage();
- }
- });
- connect(settingsWidget,&SettingsWidget::autoPlayMediaToggled,[=](bool checked)
- {
- QWebEngineProfile *profile = QWebEngineProfile::defaultProfile();
- auto* webSettings = profile->settings();
- webSettings->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture,checked);
-
- this->webEngine->page()->profile()->settings()->setAttribute(
- QWebEngineSettings::PlaybackRequiresUserGesture,
- checked);
- });
+ }
+ });
+ connect(settingsWidget, &SettingsWidget::autoPlayMediaToggled,settingsWidget,
+ [=](bool checked) {
+ QWebEngineProfile *profile = QWebEngineProfile::defaultProfile();
+ auto *webSettings = profile->settings();
+ webSettings->setAttribute(
+ QWebEngineSettings::PlaybackRequiresUserGesture, checked);
+
+ this->webEngine->page()->profile()->settings()->setAttribute(
+ QWebEngineSettings::PlaybackRequiresUserGesture, checked);
+ });
- connect(settingsWidget,&SettingsWidget::dictChanged,[=](QString dictName)
- {
- if(webEngine && webEngine->page())
- {
- webEngine->page()->profile()->setSpellCheckLanguages(QStringList()<<dictName);
- }
- });
+ connect(settingsWidget, &SettingsWidget::dictChanged, settingsWidget,
+ [=](QString dictName) {
+ if (webEngine && webEngine->page()) {
+ webEngine->page()->profile()->setSpellCheckLanguages(
+ QStringList() << dictName);
+ }
+ });
- connect(settingsWidget,&SettingsWidget::spellCheckChanged,[=](bool checked){
- if(webEngine && webEngine->page())
- {
+ connect(settingsWidget, &SettingsWidget::spellCheckChanged,settingsWidget,
+ [=](bool checked) {
+ if (webEngine && webEngine->page()) {
webEngine->page()->profile()->setSpellCheckEnabled(checked);
- }
- });
-
- connect(settingsWidget,&SettingsWidget::zoomChanged,[=]()
- {
- double currentFactor = settings.value("zoomFactor",1.0).toDouble();
- webEngine->page()->setZoomFactor(currentFactor);
- });
+ }
+ });
- connect(settingsWidget,&SettingsWidget::notificationPopupTimeOutChanged,[=](){
- setNotificationPresenter(this->webEngine->page()->profile());
- });
+ connect(settingsWidget, &SettingsWidget::zoomChanged,settingsWidget, [=]() {
+ double currentFactor = settings.value("zoomFactor", 1.0).toDouble();
+ webEngine->page()->setZoomFactor(currentFactor);
+ });
- connect(settingsWidget,&SettingsWidget::notify,[=](QString message)
- {
- notify("",message);
- });
+ connect(settingsWidget, &SettingsWidget::notificationPopupTimeOutChanged,settingsWidget,
+ [=]() {
+ setNotificationPresenter(this->webEngine->page()->profile());
+ });
- settingsWidget->appLockSetChecked(settings.value("lockscreen",false).toBool());
+ connect(settingsWidget, &SettingsWidget::notify,settingsWidget,
+ [=](QString message) { notify("", message); });
- //spell checker
- settingsWidget->loadDictionaries(m_dictionaries);
+ settingsWidget->appLockSetChecked(
+ settings.value("lockscreen", false).toBool());
- settingsWidget->resize(settingsWidget->sizeHint().width(),settingsWidget->minimumSizeHint().height());
- }
-}
+ // spell checker
+ settingsWidget->loadDictionaries(m_dictionaries);
-void MainWindow::lockApp()
-{
- if(lockWidget != nullptr && lockWidget->isLocked)
- return;
-
-// if(settings.value("asdfg").isValid() && settings.value("lockscreen").toBool()==false){
-// QMessageBox::critical(this,QApplication::applicationName()+"| Error",
-// "Unable to lock App, Enable AppLock in settings First.");
-// this->show();
-// return;
-// }
-
- if(settings.value("asdfg").isValid()){
- init_lock();
- lockWidget->lock_app();
- }else{
- QMessageBox msgBox;
- msgBox.setText("App lock is not configured.");
- msgBox.setIconPixmap(QPixmap(":/icons/information-line.png").scaled(42,42,Qt::KeepAspectRatio,Qt::SmoothTransformation));
- msgBox.setInformativeText("Do you want to setup App lock now ?");
- msgBox.setStandardButtons(QMessageBox::Cancel );
- QPushButton *setAppLock = new QPushButton("Yes",nullptr);
- msgBox.addButton(setAppLock,QMessageBox::NoRole);
- connect(setAppLock,&QPushButton::clicked,[=](){
- init_lock();
- });
- msgBox.exec();
- }
+ settingsWidget->resize(settingsWidget->sizeHint().width(),
+ settingsWidget->minimumSizeHint().height());
+ }
}
-void MainWindow::showSettings()
-{
- if(lockWidget && lockWidget->isLocked){
- QMessageBox::critical(this,QApplication::applicationName()+"| Error",
- "UnLock Application to access Settings.");
- this->show();
- return;
- }
+void MainWindow::lockApp() {
+ if (lockWidget != nullptr && lockWidget->isLocked)
+ return;
- if(webEngine == nullptr){
- QMessageBox::critical(this,QApplication::applicationName()+"| Error",
- "Unable to initialize settings module.\nIs webengine initialized?");
- return;
- }
- if(!settingsWidget->isVisible())
- {
- this->updateSettingsUserAgentWidget();
- settingsWidget->refresh();
- settingsWidget->showNormal();
- }
-}
-
-void MainWindow::updateSettingsUserAgentWidget()
-{
- settingsWidget->updateDefaultUAButton(this->webEngine->page()->profile()->httpUserAgent());
-}
-
-void MainWindow::askToReloadPage()
-{
+ if (settings.value("asdfg").isValid()) {
+ init_lock();
+ lockWidget->lock_app();
+ } else {
QMessageBox msgBox;
- msgBox.setWindowTitle(QApplication::applicationName()+" | Action required");
- msgBox.setInformativeText("Page needs to be reloaded to continue.");
- msgBox.setStandardButtons(QMessageBox::Ok);
+ msgBox.setText("App lock is not configured.");
+ msgBox.setIconPixmap(
+ QPixmap(":/icons/information-line.png")
+ .scaled(42, 42, Qt::KeepAspectRatio, Qt::SmoothTransformation));
+ msgBox.setInformativeText("Do you want to setup App lock now ?");
+ msgBox.setStandardButtons(QMessageBox::Cancel);
+ QPushButton *setAppLock = new QPushButton("Yes", nullptr);
+ msgBox.addButton(setAppLock, QMessageBox::NoRole);
+ connect(setAppLock, &QPushButton::clicked,setAppLock, [=]() { init_lock(); });
msgBox.exec();
- this->doAppReload();
-}
-
-void MainWindow::showAbout()
-{
- About *about = new About(this);
- about->setWindowFlag(Qt::Dialog);
- about->setMinimumSize(about->sizeHint());
- about->adjustSize();
- about->setAttribute(Qt::WA_DeleteOnClose);
- about->show();
-}
-
-
-void MainWindow::closeEvent(QCloseEvent *event)
-{
- settings.setValue("geometry", saveGeometry());
- settings.setValue("windowState", saveState());
- getPageTheme();
- QTimer::singleShot(500,[=](){
- settingsWidget->refresh();
- });
-
- if(QSystemTrayIcon::isSystemTrayAvailable() && settings.value("closeButtonActionCombo",0).toInt() == 0){
- this->hide();
- event->ignore();
- if(settings.value("firstrun_tray",true).toBool()){
- notify(QApplication::applicationName(),"Application is minimized to system tray.");
- settings.setValue("firstrun_tray", false);
- }
- return;
- }
- event->accept();
- qApp->quit();
- settings.setValue("firstrun_tray", true);
- QMainWindow::closeEvent(event);
-}
-
-void MainWindow::notify(QString title, QString message)
-{
-
- if(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/icon-64.png"),settings.value("notificationTimeOut",9000).toInt());
- trayIcon->disconnect(trayIcon,SIGNAL(messageClicked()));
- connect(trayIcon,&QSystemTrayIcon::messageClicked,[=](){
- if(windowState()==Qt::WindowMinimized || windowState()!=Qt::WindowActive){
- activateWindow();
- raise();
- showNormal();
- }
- });
- }
- else{
- auto popup = new NotificationPopup(webEngine);
- connect(popup,&NotificationPopup::notification_clicked,[=](){
- if(windowState() == Qt::WindowMinimized || windowState() != Qt::WindowActive){
- activateWindow();
- raise();
- showNormal();
- }
- });
- popup->style()->polish(qApp);
- popup->setMinimumWidth(300);
- popup->adjustSize();
- popup->present(title,message,QPixmap(":/icons/app/icon-64.png"));
- }
-}
-
-void MainWindow::createActions()
-{
-
- openUrlAction = new QAction("New Chat",this);
- this->addAction(openUrlAction);
- openUrlAction->setShortcut(QKeySequence(Qt::Modifier::CTRL+Qt::Key_N));
- connect(openUrlAction,&QAction::triggered,this,&MainWindow::newChat);
-
- fullscreenAction = new QAction(tr("Fullscreen"),this);
- fullscreenAction->setShortcut(Qt::Key_F11);
- connect(fullscreenAction, &QAction::triggered,[=](){
- setWindowState(windowState() ^ Qt::WindowFullScreen);
- });
- this->addAction(fullscreenAction);
-
-
- minimizeAction = new QAction(tr("Mi&nimize to tray"), this);
- minimizeAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_H));
- connect(minimizeAction, &QAction::triggered, this, &QWidget::hide);
- addAction(minimizeAction);
- this->addAction(minimizeAction);
-
- restoreAction = new QAction(tr("&Restore"), this);
- connect(restoreAction, &QAction::triggered, this, &QWidget::show);
- addAction(restoreAction);
-
- reloadAction = new QAction(tr("Re&load"), this);
- reloadAction->setShortcut(Qt::Key_F5);
- connect(reloadAction, &QAction::triggered, this, &MainWindow::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);
- this->addAction(lockAction);
-
- settingsAction = new QAction(tr("&Settings"), this);
- connect(settingsAction, &QAction::triggered, this, &MainWindow::showSettings);
-
-
- aboutAction = new QAction(tr("&About"), this);
- connect(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);
- this->addAction(quitAction);
-}
-
-void MainWindow::quitApp()
-{
- getPageTheme();
- QTimer::singleShot(500,[=](){
- qWarning()<<"THEME"<<settings.value("windowTheme").toString();
- settings.setValue("firstrun_tray", true);
- qApp->quit();
+ }
+}
+
+void MainWindow::showSettings() {
+ if (lockWidget && lockWidget->isLocked) {
+ QMessageBox::critical(this, QApplication::applicationName() + "| Error",
+ "UnLock Application to access Settings.");
+ this->show();
+ return;
+ }
+
+ if (webEngine == nullptr) {
+ QMessageBox::critical(
+ this, QApplication::applicationName() + "| Error",
+ "Unable to initialize settings module.\nIs webengine initialized?");
+ return;
+ }
+ if (!settingsWidget->isVisible()) {
+ this->updateSettingsUserAgentWidget();
+ settingsWidget->refresh();
+ settingsWidget->showNormal();
+ }
+}
+
+void MainWindow::updateSettingsUserAgentWidget() {
+ settingsWidget->updateDefaultUAButton(
+ this->webEngine->page()->profile()->httpUserAgent());
+}
+
+void MainWindow::askToReloadPage() {
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(QApplication::applicationName() + " | Action required");
+ msgBox.setInformativeText("Page needs to be reloaded to continue.");
+ msgBox.setStandardButtons(QMessageBox::Ok);
+ msgBox.exec();
+ this->doAppReload();
+}
+
+void MainWindow::showAbout() {
+ About *about = new About(this);
+ about->setWindowFlag(Qt::Dialog);
+ about->setMinimumSize(about->sizeHint());
+ about->adjustSize();
+ about->setAttribute(Qt::WA_DeleteOnClose);
+ about->show();
+}
+
+void MainWindow::closeEvent(QCloseEvent *event) {
+ settings.setValue("geometry", saveGeometry());
+ settings.setValue("windowState", saveState());
+ getPageTheme();
+ QTimer::singleShot(500,settingsWidget, [=]() { settingsWidget->refresh(); });
+
+ if (QSystemTrayIcon::isSystemTrayAvailable() &&
+ settings.value("closeButtonActionCombo", 0).toInt() == 0) {
+ this->hide();
+ event->ignore();
+ if (settings.value("firstrun_tray", true).toBool()) {
+ notify(QApplication::applicationName(),
+ "Application is minimized to system tray.");
+ settings.setValue("firstrun_tray", false);
+ }
+ return;
+ }
+ event->accept();
+ qApp->quit();
+ settings.setValue("firstrun_tray", true);
+ QMainWindow::closeEvent(event);
+}
+
+void MainWindow::notify(QString title, QString message) {
+
+ if (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/icon-64.png"),
+ settings.value("notificationTimeOut", 9000).toInt());
+ trayIcon->disconnect(trayIcon, SIGNAL(messageClicked()));
+ connect(trayIcon, &QSystemTrayIcon::messageClicked,trayIcon, [=]() {
+ if (windowState() == Qt::WindowMinimized ||
+ windowState() != Qt::WindowActive) {
+ activateWindow();
+ raise();
+ showNormal();
+ }
});
-}
-
-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(settingsAction);
- trayIconMenu->addAction(aboutAction);
- trayIconMenu->addSeparator();
- trayIconMenu->addAction(quitAction);
-
- trayIcon = new QSystemTrayIcon(trayIconRead, this);
- trayIcon->setContextMenu(trayIconMenu);
- connect(trayIconMenu,SIGNAL(aboutToShow()),this,SLOT(check_window_state()));
-
- trayIcon->show();
-
- connect(trayIcon, &QSystemTrayIcon::messageClicked,
- this, &MainWindow::messageClicked);
- connect(trayIcon, &QSystemTrayIcon::activated,
- this, &MainWindow::iconActivated);
-
-
- //enable show shortcuts in menu
- if(qApp->styleHints()->showShortcutsInContextMenus())
- {
- foreach(QAction *action, trayIconMenu->actions()){
- action->setShortcutVisibleInContextMenu(true);
- }
- }
-}
-
-
-void MainWindow::init_lock()
-{
- if(lockWidget==nullptr){
- lockWidget = new Lock(this);
- lockWidget->setObjectName("lockWidget");
- }
- lockWidget->setWindowFlags(Qt::Widget);
- lockWidget->setStyleSheet("QWidget#login{background-color:palette(window)};"
- "QWidget#signup{background-color:palette(window)}");
- lockWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
- lockWidget->setGeometry(this->rect());
-
- connect(lockWidget,&Lock::passwordNotSet,[=]()
- {
- settings.setValue("lockscreen",false);
- settingsWidget->appLockSetChecked(false);
- });
-
- connect(lockWidget,&Lock::unLocked,[=]()
- {
- //unlock event
- });
-
- connect(lockWidget,&Lock::passwordSet,[=](){
- //enable disable lock screen
- if(settings.value("asdfg").isValid()){
- settingsWidget->setCurrentPasswordText("Current Password: <i>"
- +QByteArray::fromBase64(settings.value("asdfg").toString().toUtf8())+"</i>");
- }else{
- settingsWidget->setCurrentPasswordText("Current Password: <i>Require setup</i>");
- }
- settingsWidget->appLockSetChecked(settings.value("lockscreen",false).toBool());
- });
- lockWidget->applyThemeQuirks();
- lockWidget->show();
- if(settings.value("asdfg").isValid() && settings.value("lockscreen").toBool()==true){
- lockWidget->lock_app();
- }
- updateWindowTheme();
-}
-
-//check window state and set tray menus
-void MainWindow::check_window_state()
-{
- QObject *tray_icon_menu = this->findChild<QObject*>("trayIconMenu");
- if(tray_icon_menu != nullptr){
- if(this->isVisible()){
- ((QMenu*)(tray_icon_menu))->actions().at(0)->setDisabled(false);
- ((QMenu*)(tray_icon_menu))->actions().at(1)->setDisabled(true);
- }else{
- ((QMenu*)(tray_icon_menu))->actions().at(0)->setDisabled(true);
- ((QMenu*)(tray_icon_menu))->actions().at(1)->setDisabled(false);
- }
- if(lockWidget && lockWidget->isLocked){
- ((QMenu*)(tray_icon_menu))->actions().at(4)->setDisabled(true);
- }else{
- ((QMenu*)(tray_icon_menu))->actions().at(4)->setDisabled(false);
- }
- }
-}
-
-void MainWindow::init_globalWebProfile()
-{
-
- QWebEngineProfile *profile = QWebEngineProfile::defaultProfile();
- profile->setHttpUserAgent(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());
- profile->setSpellCheckLanguages(dict_names);
-
- auto* webSettings = profile->settings();
- webSettings->setAttribute(QWebEngineSettings::AutoLoadImages, true);
- webSettings->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
- webSettings->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
- webSettings->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
- webSettings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
- webSettings->setAttribute(QWebEngineSettings::XSSAuditingEnabled, true);
- webSettings->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls, true);
- webSettings->setAttribute(QWebEngineSettings::ScrollAnimatorEnabled, false);
- webSettings->setAttribute(QWebEngineSettings::DnsPrefetchEnabled,true);
- webSettings->setAttribute(QWebEngineSettings::FullScreenSupportEnabled ,true);
- webSettings->setAttribute(QWebEngineSettings::LinksIncludedInFocusChain, false);
- webSettings->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, false);
- webSettings->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture,
- settings.value("autoPlayMedia",false).toBool());
-
-}
-
-void MainWindow::createWebEngine()
-{
- init_globalWebProfile();
-
- QSizePolicy widgetSize;
- widgetSize.setHorizontalPolicy(QSizePolicy::Expanding);
- widgetSize.setVerticalPolicy(QSizePolicy::Expanding);
- widgetSize.setHorizontalStretch(1);
- widgetSize.setVerticalStretch(1);
-
- m_dictionaries = Dictionaries::GetDictionaries();
-
- WebView *webEngine = new WebView(this,m_dictionaries);
- setCentralWidget(webEngine);
- webEngine->setSizePolicy(widgetSize);
- webEngine->show();
-
- this->webEngine = webEngine;
-
- webEngine->addAction(minimizeAction);
- webEngine->addAction(lockAction);
- webEngine->addAction(quitAction);
-
- createWebPage(false);
-
-// QWebEngineCookieStore *browser_cookie_store = this->webEngine->page()->profile()->cookieStore();
-// connect( browser_cookie_store, &QWebEngineCookieStore::cookieAdded, this, &MainWindow::handleCookieAdded );
-
-}
-
-void MainWindow::createWebPage(bool offTheRecord)
-{
- if (offTheRecord && !m_otrProfile)
- {
- m_otrProfile.reset(new QWebEngineProfile);
- }
- auto profile = 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());
- profile->setSpellCheckLanguages(dict_names);
- profile->setHttpUserAgent(settings.value("useragent",defaultUserAgentStr).toString());
-
- setNotificationPresenter(profile);
-
- QWebEnginePage *page = new WebEnginePage(profile,webEngine);
- if(settings.value("windowTheme","light").toString() == "dark"){
- page->setBackgroundColor(QColor("#131C21")); //whatsapp dark bg color
- }else{
- page->setBackgroundColor(QColor("#F0F0F0")); //whatsapp light bg color
- }
- 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);
-
-// RequestInterceptor *interceptor = new RequestInterceptor(profile);
-// profile->setUrlRequestInterceptor(interceptor);
- qsrand(time(NULL));
- auto randomValue = qrand() % 300;
- page->setUrl(QUrl("https://web.whatsapp.com?v="+QString::number(randomValue)));
- connect(profile, &QWebEngineProfile::downloadRequested,
- &m_downloadManagerWidget, &DownloadManagerWidget::downloadRequested);
-
- connect(webEngine->page(), SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)),
- this, SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
-
- double currentFactor = settings.value("zoomFactor",1.0).toDouble();
- webEngine->page()->setZoomFactor(currentFactor);
-}
-
-void MainWindow::setNotificationPresenter(QWebEngineProfile* profile)
-{
- auto *op = webEngine->findChild<NotificationPopup*>("engineNotifier");
- if( op != nullptr){
- op->close();
- op->deleteLater();
- }
-
+ } else {
auto popup = new NotificationPopup(webEngine);
- popup->setObjectName("engineNotifier");
- connect(popup,&NotificationPopup::notification_clicked,[=](){
- if(windowState()==Qt::WindowMinimized || windowState()!=Qt::WindowActive){
- activateWindow();
- raise();
- showNormal();
- }
- });
-
- profile->setNotificationPresenter([=] (std::unique_ptr<QWebEngineNotification> notification)
- {
- if(settings.value("disableNotificationPopups",false).toBool() == true){
- return;
- }
- if(settings.value("notificationCombo",1).toInt() == 0 && trayIcon != 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,[=](){
- if(windowState() == Qt::WindowMinimized || windowState() != Qt::WindowActive){
- activateWindow();
- raise();
- showNormal();
- }
- });
-
- }else{
- popup->setMinimumWidth(300);
- popup->present(notification);
- }
-
+ connect(popup, &NotificationPopup::notification_clicked, popup,[=]() {
+ if (windowState() == Qt::WindowMinimized ||
+ windowState() != Qt::WindowActive) {
+ activateWindow();
+ raise();
+ showNormal();
+ }
});
-}
-
-void MainWindow::fullScreenRequested(QWebEngineFullScreenRequest request)
-{
- if (request.toggleOn())
- {
- webEngine->showFullScreen();
- this->showFullScreen();
- request.accept();
+ popup->style()->polish(qApp);
+ popup->setMinimumWidth(300);
+ popup->adjustSize();
+ popup->present(title, message, QPixmap(":/icons/app/icon-64.png"));
+ }
+}
+
+void MainWindow::createActions() {
+
+ openUrlAction = new QAction("New Chat", this);
+ this->addAction(openUrlAction);
+ openUrlAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_N));
+ connect(openUrlAction, &QAction::triggered, this, &MainWindow::newChat);
+
+ fullscreenAction = new QAction(tr("Fullscreen"), this);
+ fullscreenAction->setShortcut(Qt::Key_F11);
+ connect(fullscreenAction, &QAction::triggered,fullscreenAction,
+ [=]() { setWindowState(windowState() ^ Qt::WindowFullScreen); });
+ this->addAction(fullscreenAction);
+
+ minimizeAction = new QAction(tr("Mi&nimize to tray"), this);
+ minimizeAction->setShortcut(QKeySequence(Qt::Modifier::CTRL + Qt::Key_H));
+ connect(minimizeAction, &QAction::triggered, this, &QWidget::hide);
+ addAction(minimizeAction);
+ this->addAction(minimizeAction);
+
+ restoreAction = new QAction(tr("&Restore"), this);
+ connect(restoreAction, &QAction::triggered, this, &QWidget::show);
+ addAction(restoreAction);
+
+ reloadAction = new QAction(tr("Re&load"), this);
+ reloadAction->setShortcut(Qt::Key_F5);
+ connect(reloadAction, &QAction::triggered, this, &MainWindow::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);
+ this->addAction(lockAction);
+
+ settingsAction = new QAction(tr("&Settings"), this);
+ connect(settingsAction, &QAction::triggered, this, &MainWindow::showSettings);
+
+ aboutAction = new QAction(tr("&About"), this);
+ connect(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);
+ this->addAction(quitAction);
+}
+
+void MainWindow::quitApp() {
+ getPageTheme();
+ QTimer::singleShot(500, &settings,[=]() {
+ qWarning() << "THEME" << settings.value("windowTheme").toString();
+ 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(settingsAction);
+ trayIconMenu->addAction(aboutAction);
+ trayIconMenu->addSeparator();
+ trayIconMenu->addAction(quitAction);
+
+ trayIcon = new QSystemTrayIcon(trayIconRead, this);
+ trayIcon->setContextMenu(trayIconMenu);
+ connect(trayIconMenu, SIGNAL(aboutToShow()), this,
+ SLOT(check_window_state()));
+
+ trayIcon->show();
+
+ connect(trayIcon, &QSystemTrayIcon::messageClicked, this,
+ &MainWindow::messageClicked);
+ connect(trayIcon, &QSystemTrayIcon::activated, this,
+ &MainWindow::iconActivated);
+
+ // enable show shortcuts in menu
+ if (qApp->styleHints()->showShortcutsInContextMenus()) {
+ foreach (QAction *action, trayIconMenu->actions()) {
+ action->setShortcutVisibleInContextMenu(true);
+ }
+ }
+}
+
+void MainWindow::init_lock() {
+ if (lockWidget == nullptr) {
+ lockWidget = new Lock(this);
+ lockWidget->setObjectName("lockWidget");
+ }
+ lockWidget->setWindowFlags(Qt::Widget);
+ lockWidget->setStyleSheet("QWidget#login{background-color:palette(window)};"
+ "QWidget#signup{background-color:palette(window)}");
+ lockWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
+ lockWidget->setGeometry(this->rect());
+
+ connect(lockWidget, &Lock::passwordNotSet,settingsWidget, [=]() {
+ settings.setValue("lockscreen", false);
+ settingsWidget->appLockSetChecked(false);
+ });
+
+ connect(lockWidget, &Lock::unLocked, [=]() {
+ // unlock event
+ });
+
+ connect(lockWidget, &Lock::passwordSet,settingsWidget, [=]() {
+ // enable disable lock screen
+ if (settings.value("asdfg").isValid()) {
+ settingsWidget->setCurrentPasswordText(
+ "Current Password: <i>" +
+ QByteArray::fromBase64(settings.value("asdfg").toString().toUtf8()) +
+ "</i>");
} else {
- webEngine->showNormal();
- this->showNormal();
- request.accept();
- }
-}
-
-void MainWindow::handleWebViewTitleChanged(QString title)
-{
- setWindowTitle(title);
-
- if (notificationsTitleRegExp.exactMatch(title))
- {
- if(notificationsTitleRegExp.isEmpty() == false){
- QString capturedTitle = notificationsTitleRegExp.capturedTexts().first();
- QRegExp rgex("\\([^\\d]*(\\d+)[^\\d]*\\)");
- rgex.setMinimal(true);
- if(rgex.indexIn(capturedTitle) != -1){
- qDebug()<<rgex.capturedTexts();
- QString unreadMessageCount = rgex.capturedTexts().last();
- QString suffix = unreadMessageCount.toInt() > 1 ? tr("messages"): tr("message");
- restoreAction->setText(tr("Restore")+" | "+unreadMessageCount+" "+suffix);
- }
- }
- trayIcon->setIcon(trayIconUnread);
- setWindowIcon(trayIconUnread);
- }
- else
- {
- trayIcon->setIcon(trayIconRead);
- setWindowIcon(trayIconRead);
- }
-}
-
-void MainWindow::handleLoadFinished(bool loaded)
-{
- if(loaded){
- //check if page has loaded correctly
- checkLoadedCorrectly();
- updatePageTheme();
- }
-}
-
-void MainWindow::checkLoadedCorrectly()
-{
- if(webEngine && webEngine->page())
- {
- //test 1 based on the class name of body of the page
- webEngine->page()->runJavaScript("document.querySelector('body').className",[this](const QVariant &result)
- {
- if(result.toString().contains("page-version",Qt::CaseInsensitive))
- {
- qWarning()<<"Test 1 found"<<result.toString();
- 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 * util = new utils(this);
- util->DisplayExceptionErrorDialog("test1 handleWebViewTitleChanged(title) title: Error, Resetting UA, Quiting!\nUA: "+settings.value("useragent","DefaultUA").toString());
-
- quitAction->trigger();
- }else{
- qWarning()<<"Test 1 Loaded correctly value:"<<result.toString();
- }
- });
-
-// //test #2 based on the content of landing-title class of page
-// webEngine->page()->runJavaScript(
-// "document.getElementsByClassName('landing-title')[0].innerText",
-// [this](const QVariant &result){
-// qWarning()<<"Test #1 Loaded correctly value:"<<result.toString();
-// if(result.toString().contains("WhatsApp works with",Qt::CaseInsensitive)){
-// loadingQuirk("test2");
-// }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 * util = new utils(this);
-// util->DisplayExceptionErrorDialog("handleWebViewTitleChanged(title) title: Error, Resetting UA, Quiting!\nUA: "+settings.value("useragent","DefaultUA").toString());
-
-// quitAction->trigger();
-// }
-// }
-// );
- }
-}
-
-void MainWindow::loadingQuirk(QString test)
-{
- //contains ug message apply quirk
- if(correctlyLoaderRetries > -1){
- qWarning()<<test<<"checkLoadedCorrectly()/loadingQuirk()/doReload()"<<correctlyLoaderRetries;
- doReload();
- correctlyLoaderRetries--;
- }else{
- utils::delete_cache(webEngine->page()->profile()->cachePath());
- utils::delete_cache(webEngine->page()->profile()->persistentStoragePath());
- settings.setValue("useragent",defaultUserAgentStr);
- utils * util = new utils(this);
- util->DisplayExceptionErrorDialog(test+" checkLoadedCorrectly()/loadingQuirk() reload retries 0, Resetting UA, Quiting!\nUA: "+settings.value("useragent","DefaultUA").toString());
-
- quitAction->trigger();
- }
-}
-
-//unused direct method to download file without having entry in download manager
-void MainWindow::handleDownloadRequested(QWebEngineDownloadItem *download)
-{
- QFileDialog dialog(this);
- bool usenativeFileDialog = settings.value("useNativeFileDialog",false).toBool();
-
- if(usenativeFileDialog == false){
- dialog.setOption(QFileDialog::DontUseNativeDialog,true);
- }
-
- dialog.setAcceptMode(QFileDialog::AcceptMode::AcceptSave);
- dialog.setFileMode(QFileDialog::FileMode::AnyFile);
- QString suggestedFileName = QUrl(download->path()).fileName();
- dialog.selectFile(suggestedFileName);
-
- if (dialog.exec() && dialog.selectedFiles().size() > 0)
- {
- download->setPath(dialog.selectedFiles().at(0));
- download->accept();
- }
-}
-
-void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
-{
- Q_UNUSED(reason);
- if (isVisible()) {
- hide();
+ settingsWidget->setCurrentPasswordText(
+ "Current Password: <i>Require setup</i>");
+ }
+ settingsWidget->appLockSetChecked(
+ settings.value("lockscreen", false).toBool());
+ });
+ lockWidget->applyThemeQuirks();
+ lockWidget->show();
+ if (settings.value("asdfg").isValid() &&
+ settings.value("lockscreen").toBool() == true) {
+ lockWidget->lock_app();
+ }
+ updateWindowTheme();
+}
+
+// check window state and set tray menus
+void MainWindow::check_window_state() {
+ QObject *tray_icon_menu = this->findChild<QObject *>("trayIconMenu");
+ if (tray_icon_menu != nullptr) {
+ if (this->isVisible()) {
+ ((QMenu *)(tray_icon_menu))->actions().at(0)->setDisabled(false);
+ ((QMenu *)(tray_icon_menu))->actions().at(1)->setDisabled(true);
} else {
- showNormal();
+ ((QMenu *)(tray_icon_menu))->actions().at(0)->setDisabled(true);
+ ((QMenu *)(tray_icon_menu))->actions().at(1)->setDisabled(false);
}
-}
-
-void MainWindow::messageClicked()
-{
- if (isVisible()) {
- hide();
+ if (lockWidget && lockWidget->isLocked) {
+ ((QMenu *)(tray_icon_menu))->actions().at(4)->setDisabled(true);
} else {
- showNormal();
- }
-}
+ ((QMenu *)(tray_icon_menu))->actions().at(4)->setDisabled(false);
+ }
+ }
+}
+
+void MainWindow::init_globalWebProfile() {
+
+ QWebEngineProfile *profile = QWebEngineProfile::defaultProfile();
+ profile->setHttpUserAgent(
+ 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());
+ profile->setSpellCheckLanguages(dict_names);
+
+ auto *webSettings = profile->settings();
+ webSettings->setAttribute(QWebEngineSettings::AutoLoadImages, true);
+ webSettings->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
+ webSettings->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows, true);
+ webSettings->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
+ webSettings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls,
+ true);
+ webSettings->setAttribute(QWebEngineSettings::XSSAuditingEnabled, true);
+ webSettings->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls,
+ true);
+ webSettings->setAttribute(QWebEngineSettings::ScrollAnimatorEnabled, false);
+ webSettings->setAttribute(QWebEngineSettings::DnsPrefetchEnabled, true);
+ webSettings->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true);
+ webSettings->setAttribute(QWebEngineSettings::LinksIncludedInFocusChain,
+ false);
+ webSettings->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled,
+ false);
+ webSettings->setAttribute(QWebEngineSettings::PlaybackRequiresUserGesture,
+ settings.value("autoPlayMedia", false).toBool());
+}
+
+void MainWindow::createWebEngine() {
+ init_globalWebProfile();
+
+ QSizePolicy widgetSize;
+ widgetSize.setHorizontalPolicy(QSizePolicy::Expanding);
+ widgetSize.setVerticalPolicy(QSizePolicy::Expanding);
+ widgetSize.setHorizontalStretch(1);
+ widgetSize.setVerticalStretch(1);
+
+ m_dictionaries = Dictionaries::GetDictionaries();
+
+ WebView *webEngine = new WebView(this, m_dictionaries);
+ setCentralWidget(webEngine);
+ webEngine->setSizePolicy(widgetSize);
+ webEngine->show();
+
+ this->webEngine = webEngine;
+
+ webEngine->addAction(minimizeAction);
+ webEngine->addAction(lockAction);
+ webEngine->addAction(quitAction);
+
+ createWebPage(false);
+
+ // QWebEngineCookieStore *browser_cookie_store =
+ // this->webEngine->page()->profile()->cookieStore(); connect(
+ // browser_cookie_store, &QWebEngineCookieStore::cookieAdded, this,
+ // &MainWindow::handleCookieAdded );
+}
+
+void MainWindow::createWebPage(bool offTheRecord) {
+ if (offTheRecord && !m_otrProfile) {
+ m_otrProfile.reset(new QWebEngineProfile);
+ }
+ auto profile =
+ 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());
+ profile->setSpellCheckLanguages(dict_names);
+ profile->setHttpUserAgent(
+ settings.value("useragent", defaultUserAgentStr).toString());
+
+ setNotificationPresenter(profile);
+
+ QWebEnginePage *page = new WebEnginePage(profile, webEngine);
+ if (settings.value("windowTheme", "light").toString() == "dark") {
+ page->setBackgroundColor(QColor(19, 28, 33)); // whatsapp dark bg color
+ } else {
+ page->setBackgroundColor(QColor(240, 240, 240)); // whatsapp light bg color
+ }
+ 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);
+ // RequestInterceptor *interceptor = new RequestInterceptor(profile);
+ // profile->setUrlRequestInterceptor(interceptor);
+ auto randomValue = QRandomGenerator::global()->generateDouble() * 300;
+ page->setUrl(
+ QUrl("https://web.whatsapp.com?v=" + QString::number(randomValue)));
+ connect(profile, &QWebEngineProfile::downloadRequested,
+ &m_downloadManagerWidget, &DownloadManagerWidget::downloadRequested);
+
+ connect(webEngine->page(),
+ SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this,
+ SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
+
+ double currentFactor = settings.value("zoomFactor", 1.0).toDouble();
+ webEngine->page()->setZoomFactor(currentFactor);
+}
+
+void MainWindow::setNotificationPresenter(QWebEngineProfile *profile) {
+ auto *op = webEngine->findChild<NotificationPopup *>("engineNotifier");
+ if (op != nullptr) {
+ op->close();
+ op->deleteLater();
+ }
+
+ auto popup = new NotificationPopup(webEngine);
+ popup->setObjectName("engineNotifier");
+ connect(popup, &NotificationPopup::notification_clicked,popup,[=]() {
+ if (windowState() == Qt::WindowMinimized ||
+ windowState() != Qt::WindowActive) {
+ activateWindow();
+ raise();
+ showNormal();
+ }
+ });
+
+ profile->setNotificationPresenter(
+ [=](std::unique_ptr<QWebEngineNotification> notification) {
+ if (settings.value("disableNotificationPopups", false).toBool() ==
+ true) {
+ return;
+ }
+ if (settings.value("notificationCombo", 1).toInt() == 0 &&
+ trayIcon != 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() == Qt::WindowMinimized ||
+ windowState() != Qt::WindowActive) {
+ activateWindow();
+ raise();
+ showNormal();
+ }
+ });
-void MainWindow::doAppReload()
-{
+ } else {
+ popup->setMinimumWidth(300);
+ popup->present(notification);
+ }
+ });
+}
+
+void MainWindow::fullScreenRequested(QWebEngineFullScreenRequest request) {
+ if (request.toggleOn()) {
+ webEngine->showFullScreen();
+ this->showFullScreen();
+ request.accept();
+ } else {
+ webEngine->showNormal();
+ this->showNormal();
+ request.accept();
+ }
+}
+
+void MainWindow::handleWebViewTitleChanged(QString title) {
+ setWindowTitle(title);
+
+ if (notificationsTitleRegExp.exactMatch(title)) {
+ if (notificationsTitleRegExp.isEmpty() == false) {
+ QString capturedTitle = notificationsTitleRegExp.capturedTexts().first();
+ QRegExp rgex("\\([^\\d]*(\\d+)[^\\d]*\\)");
+ rgex.setMinimal(true);
+ if (rgex.indexIn(capturedTitle) != -1) {
+ qDebug() << rgex.capturedTexts();
+ QString unreadMessageCount = rgex.capturedTexts().last();
+ QString suffix =
+ unreadMessageCount.toInt() > 1 ? tr("messages") : tr("message");
+ restoreAction->setText(tr("Restore") + " | " + unreadMessageCount +
+ " " + suffix);
+ }
+ }
+ trayIcon->setIcon(trayIconUnread);
+ setWindowIcon(trayIconUnread);
+ } else {
+ trayIcon->setIcon(trayIconRead);
+ setWindowIcon(trayIconRead);
+ }
+}
+
+void MainWindow::handleLoadFinished(bool loaded) {
+ if (loaded) {
+ // check if page has loaded correctly
+ checkLoadedCorrectly();
+ updatePageTheme();
+ }
+}
+
+void MainWindow::checkLoadedCorrectly() {
+ if (webEngine && webEngine->page()) {
+ // test 1 based on the class name of body of the page
+ webEngine->page()->runJavaScript(
+ "document.querySelector('body').className",
+ [this](const QVariant &result) {
+ if (result.toString().contains("page-version", Qt::CaseInsensitive)) {
+ qWarning() << "Test 1 found" << result.toString();
+ 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 *util = new utils(this);
+ util->DisplayExceptionErrorDialog(
+ "test1 handleWebViewTitleChanged(title) title: Error, "
+ "Resetting UA, Quiting!\nUA: " +
+ settings.value("useragent", "DefaultUA").toString());
+
+ quitAction->trigger();
+ } else {
+ qWarning() << "Test 1 Loaded correctly value:" << result.toString();
+ }
+ });
- if(this->webEngine->page()){
- this->webEngine->page()->disconnect();
- }
- createWebPage(false);
-}
-
-void MainWindow::newChat()
-{
- bool ok;
- QString text = QInputDialog::getText(this, tr("New Chat"),
- tr("Enter a valid WhatsApp number with country code (ex- +91XXXXXXXXXX)"), QLineEdit::Normal,
- "",&ok);
- if (ok){
- if(isPhoneNumber(text))
- this->webEngine->page()->load(QUrl("https://web.whatsapp.com/send?phone="+text));
- else
- QMessageBox::information(this,QApplication::applicationName()+"| Error",
- "Invalid Phone Number");
- }
+ // //test #2 based on the content of landing-title class of page
+ // webEngine->page()->runJavaScript(
+ // "document.getElementsByClassName('landing-title')[0].innerText",
+ // [this](const QVariant &result){
+ // qWarning()<<"Test #1 Loaded correctly
+ // value:"<<result.toString();
+ // if(result.toString().contains("WhatsApp works
+ // with",Qt::CaseInsensitive)){
+ // loadingQuirk("test2");
+ // }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 * util = new utils(this);
+ // util->DisplayExceptionErrorDialog("handleWebViewTitleChanged(title)
+ // title: Error, Resetting UA, Quiting!\nUA:
+ // "+settings.value("useragent","DefaultUA").toString());
+
+ // quitAction->trigger();
+ // }
+ // }
+ // );
+ }
+}
+
+void MainWindow::loadingQuirk(QString test) {
+ // contains ug message apply quirk
+ if (correctlyLoaderRetries > -1) {
+ qWarning() << test << "checkLoadedCorrectly()/loadingQuirk()/doReload()"
+ << correctlyLoaderRetries;
+ doReload();
+ correctlyLoaderRetries--;
+ } else {
+ utils::delete_cache(webEngine->page()->profile()->cachePath());
+ utils::delete_cache(webEngine->page()->profile()->persistentStoragePath());
+ settings.setValue("useragent", defaultUserAgentStr);
+ utils *util = new utils(this);
+ util->DisplayExceptionErrorDialog(
+ test +
+ " checkLoadedCorrectly()/loadingQuirk() reload retries 0, Resetting "
+ "UA, Quiting!\nUA: " +
+ settings.value("useragent", "DefaultUA").toString());
+
+ quitAction->trigger();
+ }
+}
+
+// unused direct method to download file without having entry in download
+// manager
+void MainWindow::handleDownloadRequested(QWebEngineDownloadItem *download) {
+ QFileDialog dialog(this);
+ bool usenativeFileDialog =
+ settings.value("useNativeFileDialog", false).toBool();
+
+ if (usenativeFileDialog == false) {
+ dialog.setOption(QFileDialog::DontUseNativeDialog, true);
+ }
+
+ dialog.setAcceptMode(QFileDialog::AcceptMode::AcceptSave);
+ dialog.setFileMode(QFileDialog::FileMode::AnyFile);
+ QString suggestedFileName = QUrl(download->downloadDirectory()).fileName();
+ dialog.selectFile(suggestedFileName);
+
+ if (dialog.exec() && dialog.selectedFiles().size() > 0) {
+ download->setDownloadDirectory(dialog.selectedFiles().at(0));
+ download->accept();
+ }
+}
+
+void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) {
+ Q_UNUSED(reason);
+ if (isVisible()) {
+ hide();
+ } else {
+ showNormal();
+ }
+}
+
+void MainWindow::messageClicked() {
+ if (isVisible()) {
+ hide();
+ } else {
+ showNormal();
+ }
+}
+
+void MainWindow::doAppReload() {
+
+ if (this->webEngine->page()) {
+ this->webEngine->page()->disconnect();
+ }
+ createWebPage(false);
+}
+
+void MainWindow::newChat() {
+ bool ok;
+ QString text = QInputDialog::getText(
+ this, tr("New Chat"),
+ tr("Enter a valid WhatsApp number with country code (ex- +91XXXXXXXXXX)"),
+ QLineEdit::Normal, "", &ok);
+ if (ok) {
+ if (isPhoneNumber(text))
+ this->webEngine->page()->load(
+ QUrl("https://web.whatsapp.com/send?phone=" + text));
+ else
+ QMessageBox::information(this,
+ QApplication::applicationName() + "| Error",
+ "Invalid Phone Number");
+ }
}
-bool MainWindow::isPhoneNumber(const QString &phoneNumber)
-{
- const QString phone = "^\\+(((\\d{2}))\\s?)?((\\d{2})|(\\((\\d{2})\\))\\s?)?(\\d{3,15})(\\-(\\d{3,15}))?$";
- QRegularExpression reg(phone);
- return reg.match(phoneNumber).hasMatch();
+bool MainWindow::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);
+ return reg.match(phoneNumber).hasMatch();
}
-void MainWindow::doReload()
-{
- this->webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache, false);
+void MainWindow::doReload() {
+ this->webEngine->triggerPageAction(QWebEnginePage::ReloadAndBypassCache,
+ false);
}
-void MainWindow::toggleMute(const bool &checked)
-{
- this->webEngine->page()->setAudioMuted(checked);
+void MainWindow::toggleMute(const bool &checked) {
+ this->webEngine->page()->setAudioMuted(checked);
}
// get value of page theme when page is loaded
-QString MainWindow::getPageTheme()
-{
- static QString theme = "web"; //implies light
- if(webEngine && webEngine->page())
- {
- webEngine->page()->runJavaScript(
- "document.querySelector('body').className;",
- [this](const QVariant &result){
- theme = result.toString();
- theme.contains("dark") ? theme = "dark" : theme = "light";
- settings.setValue("windowTheme",theme);
- }
- );
- }
- return theme;
+QString MainWindow::getPageTheme() {
+ static QString theme = "web"; // implies light
+ if (webEngine && webEngine->page()) {
+ webEngine->page()->runJavaScript(
+ "document.querySelector('body').className;",
+ [this](const QVariant &result) {
+ theme = result.toString();
+ theme.contains("dark") ? theme = "dark" : theme = "light";
+ settings.setValue("windowTheme", theme);
+ });
+ }
+ return theme;
}
diff --git a/src/mainwindow.h b/src/mainwindow.h
index 98da302..dbc59e7 100644
--- a/src/mainwindow.h
+++ b/src/mainwindow.h
@@ -19,116 +19,109 @@
#include <QWebEngineCookieStore>
#include <QWebEngineFullScreenRequest>
#include <QWebEngineProfile>
-#include <QWebEngineView>
#include <QWebEngineSettings>
+#include <QWebEngineView>
#include <QRadioButton>
#include <QWebEngineContextMenuData>
+#include "lock.h"
#include "notificationpopup.h"
#include "requestinterceptor.h"
#include "settingswidget.h"
#include "webenginepage.h"
-#include "lock.h"
-#include "downloadmanagerwidget.h"
#include "about.h"
#include "dictionaries.h"
-#include "webview.h"
+#include "downloadmanagerwidget.h"
#include "rateapp.h"
+#include "webview.h"
-
-class MainWindow : public QMainWindow
-{
- Q_OBJECT
+class MainWindow : public QMainWindow {
+ Q_OBJECT
public:
- explicit MainWindow(QWidget *parent = nullptr);
+ explicit MainWindow(QWidget *parent = nullptr);
public slots:
- void updateWindowTheme();
- void updatePageTheme();
-
- void handleWebViewTitleChanged(QString title);
- void handleLoadFinished(bool loaded);
- void handleDownloadRequested(QWebEngineDownloadItem *download);
- void loadAppWithArgument(const QString &arg);
+ void updateWindowTheme();
+ void updatePageTheme();
+ void handleWebViewTitleChanged(QString title);
+ void handleLoadFinished(bool loaded);
+ void handleDownloadRequested(QWebEngineDownloadItem *download);
+ void loadAppWithArgument(const QString &arg);
protected slots:
- void closeEvent(QCloseEvent *event) override;
- void resizeEvent(QResizeEvent *event);
-private:
- QPalette lightPalette;
- void createActions();
- void createTrayIcon();
- void createWebEngine();
-
- QSettings settings;
+ void closeEvent(QCloseEvent *event) override;
+ void resizeEvent(QResizeEvent *event) override;
- QRegExp notificationsTitleRegExp;
- QIcon trayIconRead;
- QIcon trayIconUnread;
+private:
+ QPalette lightPalette;
+ void createActions();
+ void createTrayIcon();
+ void createWebEngine();
- QAction *reloadAction;
- QAction *minimizeAction;
- QAction *restoreAction;
- QAction *aboutAction;
- QAction *settingsAction;
- QAction *quitAction;
- QAction *lockAction;
- QAction *fullscreenAction;
- QAction *openUrlAction;
+ QSettings settings;
- QMenu *trayIconMenu;
- QSystemTrayIcon *trayIcon;
+ QRegExp notificationsTitleRegExp;
+ QIcon trayIconRead;
+ QIcon trayIconUnread;
- QWebEngineView *webEngine;
- //QStatusBar *statusBar;
+ QAction *reloadAction;
+ QAction *minimizeAction;
+ QAction *restoreAction;
+ QAction *aboutAction;
+ QAction *settingsAction;
+ QAction *quitAction;
+ QAction *lockAction;
+ QAction *fullscreenAction;
+ QAction *openUrlAction;
+ QMenu *trayIconMenu;
+ QSystemTrayIcon *trayIcon;
- SettingsWidget * settingsWidget = nullptr;
+ QWebEngineView *webEngine;
- //void reload();
+ SettingsWidget *settingsWidget = nullptr;
- DownloadManagerWidget m_downloadManagerWidget;
- QScopedPointer<QWebEngineProfile> m_otrProfile;
+ DownloadManagerWidget m_downloadManagerWidget;
+ QScopedPointer<QWebEngineProfile> m_otrProfile;
- Lock *lockWidget = nullptr;
+ Lock *lockWidget = nullptr;
- int correctlyLoaderRetries = 4;
+ int correctlyLoaderRetries = 4;
- QStringList m_dictionaries;
+ QStringList m_dictionaries;
private slots:
- void iconActivated(QSystemTrayIcon::ActivationReason reason);
- void messageClicked();
- void doReload();
- void showAbout();
- void notify(QString title, QString message);
- void showSettings();
- void handleCookieAdded(const QNetworkCookie &cookie);
-
- QString getPageTheme();
- void toggleMute(const bool &checked);
- void doAppReload();
- void askToReloadPage();
- void updateSettingsUserAgentWidget();
- void fullScreenRequested(QWebEngineFullScreenRequest request);
-
- void createWebPage(bool offTheRecord =false);
- void init_settingWidget();
- void init_globalWebProfile();
- void check_window_state();
- void init_lock();
- void lockApp();
-
-
- void checkLoadedCorrectly();
- void loadingQuirk(QString test);
- void setNotificationPresenter(QWebEngineProfile *profile);
- void newChat();
- bool isPhoneNumber(const QString &phoneNumber);
- void quitApp();
+ void iconActivated(QSystemTrayIcon::ActivationReason reason);
+ void messageClicked();
+ void doReload();
+ void showAbout();
+ void notify(QString title, QString message);
+ void showSettings();
+ void handleCookieAdded(const QNetworkCookie &cookie);
+
+ QString getPageTheme();
+ void toggleMute(const bool &checked);
+ void doAppReload();
+ void askToReloadPage();
+ void updateSettingsUserAgentWidget();
+ void fullScreenRequested(QWebEngineFullScreenRequest request);
+
+ void createWebPage(bool offTheRecord = false);
+ void init_settingWidget();
+ void init_globalWebProfile();
+ void check_window_state();
+ void init_lock();
+ void lockApp();
+
+ void checkLoadedCorrectly();
+ void loadingQuirk(QString test);
+ void setNotificationPresenter(QWebEngineProfile *profile);
+ void newChat();
+ bool isPhoneNumber(const QString &phoneNumber);
+ void quitApp();
};
#endif // MAINWINDOW_H
diff --git a/src/permissiondialog.cpp b/src/permissiondialog.cpp
index 4cd77c8..2f181b6 100644
--- a/src/permissiondialog.cpp
+++ b/src/permissiondialog.cpp
@@ -5,72 +5,68 @@
#include <QMetaEnum>
#include <QWebEnginePage>
+PermissionDialog::PermissionDialog(QWidget *parent)
+ : QWidget(parent), ui(new Ui::PermissionDialog) {
+ ui->setupUi(this);
-PermissionDialog::PermissionDialog(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::PermissionDialog)
-{
- ui->setupUi(this);
+ ui->featuresTableWidget->horizontalHeader()->setSectionResizeMode(
+ QHeaderView::Stretch);
+ ui->featuresTableWidget->verticalHeader()->setVisible(true);
+ ui->featuresTableWidget->horizontalHeader()->setVisible(true);
+ ui->featuresTableWidget->setSelectionMode(QAbstractItemView::NoSelection);
+ ui->featuresTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ ui->featuresTableWidget->setFocusPolicy(Qt::NoFocus);
- ui->featuresTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
- ui->featuresTableWidget->verticalHeader()->setVisible(true);
- ui->featuresTableWidget->horizontalHeader()->setVisible(true);
- ui->featuresTableWidget->setSelectionMode(QAbstractItemView::NoSelection);
- ui->featuresTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
- ui->featuresTableWidget->setFocusPolicy(Qt::NoFocus);
-
- QMetaEnum en = QMetaEnum::fromType<QWebEnginePage::Feature>();
- for (int i = 0; i < en.keyCount(); i++ ) {
- QWebEnginePage::Feature feature = (QWebEnginePage::Feature) en.value(i);
- QString featureName = QVariant::fromValue(feature).toString();
- addToFeaturesTable(feature,featureName);
- }
+ QMetaEnum en = QMetaEnum::fromType<QWebEnginePage::Feature>();
+ for (int i = 0; i < en.keyCount(); i++) {
+ QWebEnginePage::Feature feature = (QWebEnginePage::Feature)en.value(i);
+ QString featureName = QVariant::fromValue(feature).toString();
+ addToFeaturesTable(feature, featureName);
+ }
}
-void PermissionDialog::addToFeaturesTable(QWebEnginePage::Feature feature, QString & featureName)
-{
- if(featureName.isEmpty()== false){
- int nextRow;
- int row = ui->featuresTableWidget->rowCount();
- if(row==0){
- nextRow = 0;
- }else{
- nextRow = row++;
- }
+void PermissionDialog::addToFeaturesTable(QWebEnginePage::Feature feature,
+ QString &featureName) {
+ if (featureName.isEmpty() == false) {
+ int nextRow;
+ int row = ui->featuresTableWidget->rowCount();
+ if (row == 0) {
+ nextRow = 0;
+ } else {
+ nextRow = row++;
+ }
- QStringList columnData;
- columnData<<featureName<<"status";
+ QStringList columnData;
+ columnData << featureName << "status";
- //insertRow
- ui->featuresTableWidget->insertRow(nextRow);
- settings.beginGroup("permissions");
- //add column
- for (int i = 0; i < columnData.count(); i++) {
+ // insertRow
+ ui->featuresTableWidget->insertRow(nextRow);
+ settings.beginGroup("permissions");
+ // add column
+ for (int i = 0; i < columnData.count(); i++) {
- if(columnData.at(i)=="status"){
- QCheckBox *featureCheckBox = new QCheckBox(0);
- featureCheckBox->setStyleSheet("border:0px;margin-left:50%; margin-right:50%;");
- featureCheckBox->setChecked(settings.value(featureName,false).toBool());
- connect(featureCheckBox,&QCheckBox::toggled,[=](bool checked){
- //save permission
- settings.setValue("permissions/"+featureName,checked);
- emit webPageFeatureChanged(feature);
- });
- ui->featuresTableWidget->setCellWidget(nextRow,i,featureCheckBox);
- }else{
- QTableWidgetItem *item = new QTableWidgetItem();
- item->setText(columnData.at(i));
- item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
- ui->featuresTableWidget->setItem(nextRow, i,item);
- }
- this->update();
- }
- settings.endGroup();
+ if (columnData.at(i) == "status") {
+ QCheckBox *featureCheckBox = new QCheckBox(0);
+ featureCheckBox->setStyleSheet(
+ "border:0px;margin-left:50%; margin-right:50%;");
+ featureCheckBox->setChecked(
+ settings.value(featureName, false).toBool());
+ connect(featureCheckBox, &QCheckBox::toggled, [=](bool checked) {
+ // save permission
+ settings.setValue("permissions/" + featureName, checked);
+ emit webPageFeatureChanged(feature);
+ });
+ ui->featuresTableWidget->setCellWidget(nextRow, i, featureCheckBox);
+ } else {
+ QTableWidgetItem *item = new QTableWidgetItem();
+ item->setText(columnData.at(i));
+ item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
+ ui->featuresTableWidget->setItem(nextRow, i, item);
+ }
+ this->update();
}
+ settings.endGroup();
+ }
}
-
-PermissionDialog::~PermissionDialog()
-{
- delete ui;
-}
+PermissionDialog::~PermissionDialog() { delete ui; }
diff --git a/src/rateapp.cpp b/src/rateapp.cpp
index 47382f5..f69080e 100644
--- a/src/rateapp.cpp
+++ b/src/rateapp.cpp
@@ -3,137 +3,131 @@
#include <QDebug>
#include <QMetaEnum>
-RateApp::RateApp(QWidget *parent, QString app_rating_url, int app_launch_count, int app_install_days, int present_delay) :
- QWidget(parent),
- ui(new Ui::RateApp)
-{
- ui->setupUi(this);
-
- this->app_rating_url= app_rating_url; // Url to open when rating button clicked
- this->app_launch_count = app_launch_count; // How many time the app must be launched by user to show this dialog
- this->app_install_days = app_install_days; // How many days the app must be installed by user to show this dialog
- this->present_delay = present_delay; // Delay after which this dialog should be shown to use if all conditions matched
-
- showTimer = new QTimer(this);
- showTimer->setInterval(this->present_delay);
- connect(showTimer,&QTimer::timeout,[=](){
- qDebug()<<"Rate timer timeout";
- emit showRateDialog();
- if(this->isVisible())
- showTimer->stop();
- });
-
- //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);
-
- //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(shouldShow()){
- showTimer->start();
- }else {
- //if shouldshow is false, delete this obj to free resources
- this->deleteLater();
- }
+RateApp::RateApp(QWidget *parent, QString app_rating_url, int app_launch_count,
+ int app_install_days, int present_delay)
+ : QWidget(parent), ui(new Ui::RateApp) {
+ ui->setupUi(this);
+
+ this->app_rating_url =
+ app_rating_url; // Url to open when rating button clicked
+ this->app_launch_count =
+ app_launch_count; // How many time the app must be launched by user to
+ // show this dialog
+ this->app_install_days =
+ app_install_days; // How many days the app must be installed by user to
+ // show this dialog
+ this->present_delay =
+ present_delay; // Delay after which this dialog should be shown to use if
+ // all conditions matched
+
+ showTimer = new QTimer(this);
+ showTimer->setInterval(this->present_delay);
+ connect(showTimer, &QTimer::timeout, [=]() {
+ qDebug() << "Rate timer timeout";
+ emit showRateDialog();
+ if (this->isVisible())
+ showTimer->stop();
+ });
+
+ // 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);
+
+ // 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 (shouldShow()) {
+ showTimer->start();
+ } else {
+ // if shouldshow is false, delete this obj to free resources
+ this->deleteLater();
}
+ }
- //if already reated delete this obj to free resources
- if(settings.value("rated_already",false).toBool())
- {
- this->deleteLater();
- }
+ // if already reated delete this obj to free resources
+ if (settings.value("rated_already", false).toBool()) {
+ this->deleteLater();
+ }
}
-void RateApp::delayShowEvent()
-{
- showTimer->start();
+void RateApp::delayShowEvent() {
+ showTimer->start();
- qDebug()<<"Timer running"<<showTimer->isActive()<<showTimer->interval()<<
- showTimer->isSingleShot();
- qDebug()<<"App was minimized and was not visible, "
+ qDebug() << "Timer running" << showTimer->isActive() << showTimer->interval()
+ << showTimer->isSingleShot();
+ qDebug() << "App was minimized and was not visible, "
"hence delaying the showevent of RateApp dialog by "
- <<this->showTimer->interval()/1000<<"seconds";
+ << this->showTimer->interval() / 1000 << "seconds";
}
/**
* @brief RateApp::shouldShow
* @return true, if the dialog should be shown to user
*/
-bool RateApp::shouldShow()
-{
- bool shouldShow = false;
- int app_launched_count = 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();
-
- if(ratedAlready) //return false if already reated;
- return false;
-
- shouldShow = (((currentDateTime - installed_date_time > app_install_days * 86400) ||
- app_launched_count >= this->app_launch_count)
- && ratedAlready == false);
-
- return shouldShow;
+bool RateApp::shouldShow() {
+ bool shouldShow = false;
+ int app_launched_count = 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();
+
+ if (ratedAlready) // return false if already reated;
+ return false;
+
+ shouldShow =
+ (((currentDateTime - installed_date_time > app_install_days * 86400) ||
+ app_launched_count >= this->app_launch_count) &&
+ ratedAlready == false);
+
+ return shouldShow;
}
-RateApp::~RateApp()
-{
- qDebug()<<"RateApp Obj deleted";
- showTimer->disconnect();
- showTimer->deleteLater();
- delete ui;
+RateApp::~RateApp() {
+ qDebug() << "RateApp Obj deleted";
+ showTimer->disconnect();
+ showTimer->deleteLater();
+ delete ui;
}
-void RateApp::on_rateNowBtn_clicked()
-{
- QDesktopServices::openUrl(QUrl(app_rating_url));
- this->reset();
- this->close();
+void RateApp::on_rateNowBtn_clicked() {
+ QDesktopServices::openUrl(QUrl(app_rating_url));
+ this->reset();
+ this->close();
}
-void RateApp::on_alreadyDoneBtn_clicked()
-{
- settings.setValue("rated_already",true);
- this->close();
+void RateApp::on_alreadyDoneBtn_clicked() {
+ settings.setValue("rated_already", true);
+ this->close();
}
-void RateApp::on_laterBtn_clicked()
-{
- this->reset();
- this->close();
+void RateApp::on_laterBtn_clicked() {
+ this->reset();
+ this->close();
}
-void RateApp::reset()
-{
- settings.setValue("rated_already",false);
- settings.setValue("app_launched_count",0);
- settings.setValue("app_install_time",QDateTime::currentSecsSinceEpoch());
+void RateApp::reset() {
+ settings.setValue("rated_already", false);
+ settings.setValue("app_launched_count", 0);
+ settings.setValue("app_install_time", QDateTime::currentSecsSinceEpoch());
}
-void RateApp::on_rateOnGithub_clicked()
-{
- QDesktopServices::openUrl(QUrl("https://github.com/keshavbhatt/whatsie"));
- this->reset();
- this->close();
+void RateApp::on_rateOnGithub_clicked() {
+ QDesktopServices::openUrl(QUrl("https://github.com/keshavbhatt/whatsie"));
+ this->reset();
+ this->close();
}
-void RateApp::on_donate_clicked()
-{
- QDesktopServices::openUrl(QUrl("https://paypal.me/keshavnrj/5.00"));
- this->reset();
- this->close();
+void RateApp::on_donate_clicked() {
+ QDesktopServices::openUrl(QUrl("https://paypal.me/keshavnrj/5.00"));
+ this->reset();
+ this->close();
}
-void RateApp::on_donate_2_clicked()
-{
- QDesktopServices::openUrl(QUrl("https://opencollective.com/whatsie"));
- this->reset();
- this->close();
+void RateApp::on_donate_2_clicked() {
+ QDesktopServices::openUrl(QUrl("https://opencollective.com/whatsie"));
+ this->reset();
+ this->close();
}
diff --git a/src/rungaurd.cpp b/src/rungaurd.cpp
index 7136e7b..887eaf0 100644
--- a/src/rungaurd.cpp
+++ b/src/rungaurd.cpp
@@ -2,78 +2,66 @@
#include <QCryptographicHash>
-namespace
-{
+namespace {
- QString generateKeyHash( const QString& key, const QString& salt )
- {
- QByteArray data;
+QString generateKeyHash(const QString &key, const QString &salt) {
+ QByteArray data;
- data.append( key.toUtf8() );
- data.append( salt.toUtf8() );
- data = QCryptographicHash::hash( data, QCryptographicHash::Sha1 ).toHex();
-
- return data;
- }
+ data.append(key.toUtf8());
+ data.append(salt.toUtf8());
+ data = QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex();
+ return data;
}
-
-RunGuard::RunGuard( const QString& key )
- : key( key )
- , memLockKey( generateKeyHash( key, "_memLockKey" ) )
- , sharedmemKey( generateKeyHash( key, "_sharedmemKey" ) )
- , sharedMem( sharedmemKey )
- , memLock( memLockKey, 1 )
-{
- memLock.acquire();
- {
- QSharedMemory fix( sharedmemKey ); // Fix for *nix: http://habrahabr.ru/post/173281/
- fix.attach();
- }
- memLock.release();
+} // namespace
+
+RunGuard::RunGuard(const QString &key)
+ : key(key), memLockKey(generateKeyHash(key, "_memLockKey")),
+ sharedmemKey(generateKeyHash(key, "_sharedmemKey")),
+ sharedMem(sharedmemKey), memLock(memLockKey, 1) {
+ memLock.acquire();
+ {
+ QSharedMemory fix(
+ sharedmemKey); // Fix for *nix: http://habrahabr.ru/post/173281/
+ fix.attach();
+ }
+ memLock.release();
}
-RunGuard::~RunGuard()
-{
- release();
-}
+RunGuard::~RunGuard() { release(); }
-bool RunGuard::isAnotherRunning()
-{
- if ( sharedMem.isAttached() )
- return false;
+bool RunGuard::isAnotherRunning() {
+ if (sharedMem.isAttached())
+ return false;
- memLock.acquire();
- const bool isRunning = sharedMem.attach();
- if ( isRunning )
- sharedMem.detach();
- memLock.release();
+ memLock.acquire();
+ const bool isRunning = sharedMem.attach();
+ if (isRunning)
+ sharedMem.detach();
+ memLock.release();
- return isRunning;
+ return isRunning;
}
-bool RunGuard::tryToRun()
-{
- if ( isAnotherRunning() ) // Extra check
- return false;
+bool RunGuard::tryToRun() {
+ if (isAnotherRunning()) // Extra check
+ return false;
- memLock.acquire();
- const bool result = sharedMem.create( sizeof( quint64 ) );
- memLock.release();
- if ( !result )
- {
- release();
- return false;
- }
+ memLock.acquire();
+ const bool result = sharedMem.create(sizeof(quint64));
+ memLock.release();
+ if (!result) {
+ release();
+ return false;
+ }
- return true;
+ return true;
}
-void RunGuard::release()
-{
- memLock.acquire();
- if ( sharedMem.isAttached() )
- sharedMem.detach();
- memLock.release();
+void RunGuard::release() {
+ memLock.acquire();
+ if (sharedMem.isAttached())
+ sharedMem.detach();
+ memLock.release();
}
diff --git a/src/settingswidget.cpp b/src/settingswidget.cpp
index 2750e4d..5903491 100644
--- a/src/settingswidget.cpp
+++ b/src/settingswidget.cpp
@@ -1,460 +1,443 @@
#include "settingswidget.h"
#include "ui_settingswidget.h"
+#include "mainwindow.h"
#include <QDateTime>
#include <QMessageBox>
-#include "mainwindow.h"
#include "automatictheme.h"
-
extern QString defaultUserAgentStr;
-SettingsWidget::SettingsWidget(QWidget *parent, QString engineCachePath, QString enginePersistentStoragePath) :
- QWidget(parent),
- ui(new Ui::SettingsWidget)
-{
- ui->setupUi(this);
-
- this->engineCachePath = engineCachePath;
- this->enginePersistentStoragePath = enginePersistentStoragePath;
-
- ui->zoomFactorSpinBox->setRange(0.25,5.0);
- ui->zoomFactorSpinBox->setValue(settings.value("zoomFactor",1.0).toDouble());
- //emit zoomChanged();
-
- ui->closeButtonActionComboBox->setCurrentIndex(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());
- ui->themeComboBox->setCurrentText(utils::toCamelCase(settings.value("windowTheme","light").toString()));
- ui->userAgentLineEdit->setText(settings.value("useragent",defaultUserAgentStr).toString());
- ui->enableSpellCheck->setChecked(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->automaticThemeCheckBox->blockSignals(true);
- bool automaticThemeSwitching = 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,[=](){
- themeSwitchTimerTimeout();
- });
-
- //instantly call the timeout slot if automatic theme switching enabled
- if(automaticThemeSwitching)
- themeSwitchTimerTimeout();
- //start regular timer to update theme
- updateAutomaticTheme();
-
- this->setCurrentPasswordText("Current Password: <i>"
- +QByteArray::fromBase64(settings.value("asdfg").toString().toUtf8())+"</i>");
-
- applyThemeQuirks();
-
- ui->setUserAgent->setEnabled(false);
-}
-
-inline bool inRange(unsigned low, unsigned high, unsigned x)
-{
- return ((x-low) <= (high-low));
-}
-
-void SettingsWidget::themeSwitchTimerTimeout()
-{
- if(settings.value("automaticTheme",false).toBool())
- {
- //start time
- QDateTime sunrise; sunrise.setSecsSinceEpoch(settings.value("sunrise").toLongLong());
- //end time
- QDateTime sunset; sunset.setSecsSinceEpoch(settings.value("sunset").toLongLong());
- QDateTime currentTime = QDateTime::currentDateTime();
-
- int sunsetSeconds = QTime(0,0).secsTo(sunset.time());
- int sunriseSeconds = QTime(0,0).secsTo(sunrise.time());
- int currentSeconds = QTime(0,0).secsTo(currentTime.time());
-
- if(inRange(sunsetSeconds,sunriseSeconds,currentSeconds))
- {
- qDebug()<<"is night: ";
- ui->themeComboBox->setCurrentText("Dark");
- }else{
- qDebug()<<"is morn: ";
- ui->themeComboBox->setCurrentText("Light");
- }
+SettingsWidget::SettingsWidget(QWidget *parent, QString engineCachePath,
+ QString enginePersistentStoragePath)
+ : QWidget(parent), ui(new Ui::SettingsWidget) {
+ ui->setupUi(this);
+
+ this->engineCachePath = engineCachePath;
+ this->enginePersistentStoragePath = enginePersistentStoragePath;
+
+ ui->zoomFactorSpinBox->setRange(0.25, 5.0);
+ ui->zoomFactorSpinBox->setValue(settings.value("zoomFactor", 1.0).toDouble());
+ // emit zoomChanged();
+
+ ui->closeButtonActionComboBox->setCurrentIndex(
+ 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());
+ ui->themeComboBox->setCurrentText(
+ utils::toCamelCase(settings.value("windowTheme", "light").toString()));
+ ui->userAgentLineEdit->setText(
+ settings.value("useragent", defaultUserAgentStr).toString());
+ ui->enableSpellCheck->setChecked(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->automaticThemeCheckBox->blockSignals(true);
+ bool automaticThemeSwitching =
+ 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,
+ [=]() { themeSwitchTimerTimeout(); });
+
+ // instantly call the timeout slot if automatic theme switching enabled
+ if (automaticThemeSwitching)
+ themeSwitchTimerTimeout();
+ // start regular timer to update theme
+ updateAutomaticTheme();
+
+ this->setCurrentPasswordText(
+ "Current Password: <i>" +
+ QByteArray::fromBase64(settings.value("asdfg").toString().toUtf8()) +
+ "</i>");
+
+ applyThemeQuirks();
+
+ ui->setUserAgent->setEnabled(false);
+}
+
+inline bool inRange(unsigned low, unsigned high, unsigned x) {
+ return ((x - low) <= (high - low));
+}
+
+void SettingsWidget::themeSwitchTimerTimeout() {
+ if (settings.value("automaticTheme", false).toBool()) {
+ // start time
+ QDateTime sunrise;
+ sunrise.setSecsSinceEpoch(settings.value("sunrise").toLongLong());
+ // end time
+ QDateTime sunset;
+ sunset.setSecsSinceEpoch(settings.value("sunset").toLongLong());
+ QDateTime currentTime = QDateTime::currentDateTime();
+
+ int sunsetSeconds = QTime(0, 0).secsTo(sunset.time());
+ int sunriseSeconds = QTime(0, 0).secsTo(sunrise.time());
+ int currentSeconds = QTime(0, 0).secsTo(currentTime.time());
+
+ if (inRange(sunsetSeconds, sunriseSeconds, currentSeconds)) {
+ qDebug() << "is night: ";
+ ui->themeComboBox->setCurrentText("Dark");
+ } else {
+ qDebug() << "is morn: ";
+ ui->themeComboBox->setCurrentText("Light");
}
-}
-
-
-
-void SettingsWidget::updateAutomaticTheme()
-{
- bool automaticThemeSwitching = settings.value("automaticTheme",false).toBool();
- if(automaticThemeSwitching && !themeSwitchTimer->isActive()){
- themeSwitchTimer->start();
- }else if(!automaticThemeSwitching){
- themeSwitchTimer->stop();
- }
-}
-
-SettingsWidget::~SettingsWidget()
-{
- delete ui;
-}
-
-void SettingsWidget::loadDictionaries(QStringList dictionaries)
-{
- // set up supported spellcheck dictionaries
- QStringList ui_dictionary_names;
- foreach(QString dictionary_name, dictionaries) {
- ui_dictionary_names.append(dictionary_name);
- }
-
- ui_dictionary_names.removeDuplicates();
- ui_dictionary_names.sort();
-
- //add to ui
- ui->dictComboBox->blockSignals(true);
- foreach(const QString dict_name, ui_dictionary_names)
- {
- QString short_name = QString(dict_name).split("_").last();
- short_name = (short_name.isEmpty() || short_name.contains("-")) ? QString(dict_name).split("-").last() : short_name;
- short_name = short_name.isEmpty() ? "XX" : short_name;
- short_name = short_name.length() > 2 ? short_name.left(2) : short_name;
- QIcon icon(QString(":/icons/flags/%1.png").arg(short_name.toLower()));
- if(icon.isNull() == false)
- ui->dictComboBox->addItem(icon,dict_name);
- else
- ui->dictComboBox->addItem(QIcon(":/icons/flags/xx.png"),dict_name);
- }
- ui->dictComboBox->blockSignals(false);
-
- // load settings for spellcheck dictionary
- QString dictionary_name = settings.value("sc_dict","en-US").toString();
- int pos = ui->dictComboBox->findText(dictionary_name);
- if (pos == -1) {
- pos = ui->dictComboBox->findText("en-US");
- if (pos == -1) {
- pos = 0;
- }
- }
- ui->dictComboBox->setCurrentIndex(pos);
-}
-
-void SettingsWidget::refresh()
-{
- ui->themeComboBox->setCurrentText(utils::toCamelCase(settings.value("windowTheme","light").toString()));
-
- ui->cacheSize->setText(utils::refreshCacheSize(cachePath()));
- 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();
- int pos = ui->dictComboBox->findText(dictionary_name);
+ }
+}
+
+void SettingsWidget::updateAutomaticTheme() {
+ bool automaticThemeSwitching =
+ settings.value("automaticTheme", false).toBool();
+ if (automaticThemeSwitching && !themeSwitchTimer->isActive()) {
+ themeSwitchTimer->start();
+ } else if (!automaticThemeSwitching) {
+ themeSwitchTimer->stop();
+ }
+}
+
+SettingsWidget::~SettingsWidget() { delete ui; }
+
+void SettingsWidget::loadDictionaries(QStringList dictionaries) {
+ // set up supported spellcheck dictionaries
+ QStringList ui_dictionary_names;
+ foreach (QString dictionary_name, dictionaries) {
+ ui_dictionary_names.append(dictionary_name);
+ }
+
+ ui_dictionary_names.removeDuplicates();
+ ui_dictionary_names.sort();
+
+ // add to ui
+ ui->dictComboBox->blockSignals(true);
+ foreach (const QString dict_name, ui_dictionary_names) {
+ QString short_name = QString(dict_name).split("_").last();
+ short_name = (short_name.isEmpty() || short_name.contains("-"))
+ ? QString(dict_name).split("-").last()
+ : short_name;
+ short_name = short_name.isEmpty() ? "XX" : short_name;
+ short_name = short_name.length() > 2 ? short_name.left(2) : short_name;
+ QIcon icon(QString(":/icons/flags/%1.png").arg(short_name.toLower()));
+ if (icon.isNull() == false)
+ ui->dictComboBox->addItem(icon, dict_name);
+ else
+ ui->dictComboBox->addItem(QIcon(":/icons/flags/xx.png"), dict_name);
+ }
+ ui->dictComboBox->blockSignals(false);
+
+ // load settings for spellcheck dictionary
+ QString dictionary_name = settings.value("sc_dict", "en-US").toString();
+ int pos = ui->dictComboBox->findText(dictionary_name);
+ if (pos == -1) {
+ pos = ui->dictComboBox->findText("en-US");
if (pos == -1) {
- pos = ui->dictComboBox->findText("en-US");
- if (pos == -1) {
- pos = 0;
- }
- }
- ui->dictComboBox->setCurrentIndex(pos);
-
- //enable disable spell check
- ui->enableSpellCheck->setChecked(settings.value("sc_enabled",true).toBool());
-
-
-}
-
-void SettingsWidget::updateDefaultUAButton(const QString engineUA)
-{
- bool isDefault = QString::compare(engineUA,defaultUserAgentStr,Qt::CaseInsensitive) == 0;
- ui->defaultUserAgentButton->setEnabled(!isDefault);
-
- if(ui->userAgentLineEdit->text().trimmed().isEmpty()){
- ui->userAgentLineEdit->setText(engineUA);
+ pos = 0;
}
+ }
+ ui->dictComboBox->setCurrentIndex(pos);
}
+void SettingsWidget::refresh() {
+ ui->themeComboBox->setCurrentText(
+ utils::toCamelCase(settings.value("windowTheme", "light").toString()));
-QString SettingsWidget::cachePath()
-{
- return engineCachePath;
-}
+ ui->cacheSize->setText(utils::refreshCacheSize(cachePath()));
+ ui->cookieSize->setText(utils::refreshCacheSize(persistentStoragePath()));
-QString SettingsWidget::persistentStoragePath()
-{
- return enginePersistentStoragePath;
-}
-
-void SettingsWidget::on_deleteCache_clicked()
-{
- QMessageBox msgBox;
- msgBox.setText("This will delete app cache! Application cache makes application load faster.");
- msgBox.setIconPixmap(QPixmap(":/icons/information-line.png").scaled(42,42,Qt::KeepAspectRatio,Qt::SmoothTransformation));
-
- msgBox.setInformativeText("Delete Application cache ?");
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::No);
- int ret = msgBox.exec();
- switch (ret) {
- case QMessageBox::Yes:{
- utils::delete_cache(this->cachePath());
- refresh();
- break;
- }
- case QMessageBox::No:
- break;
+ // update dict settings at runtime
+ // load settings for spellcheck dictionary
+ QString dictionary_name = settings.value("sc_dict", "en-US").toString();
+ int pos = ui->dictComboBox->findText(dictionary_name);
+ if (pos == -1) {
+ pos = ui->dictComboBox->findText("en-US");
+ if (pos == -1) {
+ pos = 0;
}
+ }
+ ui->dictComboBox->setCurrentIndex(pos);
+
+ // enable disable spell check
+ ui->enableSpellCheck->setChecked(settings.value("sc_enabled", true).toBool());
+}
+
+void SettingsWidget::updateDefaultUAButton(const QString engineUA) {
+ bool isDefault =
+ QString::compare(engineUA, defaultUserAgentStr, Qt::CaseInsensitive) == 0;
+ ui->defaultUserAgentButton->setEnabled(!isDefault);
+
+ if (ui->userAgentLineEdit->text().trimmed().isEmpty()) {
+ ui->userAgentLineEdit->setText(engineUA);
+ }
+}
+
+QString SettingsWidget::cachePath() { return engineCachePath; }
+
+QString SettingsWidget::persistentStoragePath() {
+ return enginePersistentStoragePath;
+}
+
+void SettingsWidget::on_deleteCache_clicked() {
+ QMessageBox msgBox;
+ msgBox.setText("This will delete app cache! Application cache makes "
+ "application load faster.");
+ msgBox.setIconPixmap(
+ QPixmap(":/icons/information-line.png")
+ .scaled(42, 42, Qt::KeepAspectRatio, Qt::SmoothTransformation));
+
+ msgBox.setInformativeText("Delete Application cache ?");
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::No);
+ int ret = msgBox.exec();
+ switch (ret) {
+ case QMessageBox::Yes: {
+ utils::delete_cache(this->cachePath());
+ refresh();
+ break;
+ }
+ case QMessageBox::No:
+ break;
+ }
+}
+
+void SettingsWidget::on_deletePersistentData_clicked() {
+ QMessageBox msgBox;
+ msgBox.setText(
+ "This will delete app Persistent Data ! Persistent data includes "
+ "persistent cookies, HTML5 local storage, and visited links.");
+ msgBox.setIconPixmap(
+ QPixmap(":/icons/information-line.png")
+ .scaled(42, 42, Qt::KeepAspectRatio, Qt::SmoothTransformation));
+ msgBox.setInformativeText("Delete Application Cookies ?");
+ msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ msgBox.setDefaultButton(QMessageBox::No);
+ int ret = msgBox.exec();
+ switch (ret) {
+ case QMessageBox::Yes: {
+ utils::delete_cache(this->persistentStoragePath());
+ refresh();
+ break;
+ }
+ case QMessageBox::No:
+ break;
+ }
+}
+
+void SettingsWidget::on_notificationCheckBox_toggled(bool checked) {
+ settings.setValue("disableNotificationPopups", checked);
+}
+
+void SettingsWidget::on_themeComboBox_currentTextChanged(const QString &arg1) {
+ applyThemeQuirks();
+ settings.setValue("windowTheme", QString(arg1).toLower());
+ emit updateWindowTheme();
+ emit updatePageTheme();
+}
+
+void SettingsWidget::applyThemeQuirks() {
+ // little quirks
+ if (QString::compare(ui->themeComboBox->currentText(), "dark",
+ Qt::CaseInsensitive) == 0) {
+ ui->bottomLine->setStyleSheet("background-color: rgb(5, 97, 98);");
+ ui->label_7->setStyleSheet(
+ "color:#c2c5d1;padding: 0px 8px 0px 8px;background:transparent;");
+ } else {
+ ui->bottomLine->setStyleSheet("background-color: rgb(74, 223, 131);");
+ ui->label_7->setStyleSheet(
+ "color:#1e1f21;padding: 0px 8px 0px 8px;background:transparent;");
+ }
+}
+
+void SettingsWidget::on_muteAudioCheckBox_toggled(bool checked) {
+ settings.setValue("muteAudio", checked);
+ emit muteToggled(checked);
+}
+
+void SettingsWidget::on_autoPlayMediaCheckBox_toggled(bool checked) {
+ settings.setValue("autoPlayMedia", checked);
+ emit autoPlayMediaToggled(checked);
+}
+
+void SettingsWidget::on_defaultUserAgentButton_clicked() {
+ ui->userAgentLineEdit->setText(defaultUserAgentStr);
+ emit userAgentChanged(ui->userAgentLineEdit->text());
+}
+
+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;
+
+ if (isDefault == false && arg1.trimmed().isEmpty() == false) {
+ ui->defaultUserAgentButton->setEnabled(false);
+ ui->setUserAgent->setEnabled(false);
+ }
+ if (isPrevious == false && arg1.trimmed().isEmpty() == false) {
+ ui->setUserAgent->setEnabled(true);
+ ui->defaultUserAgentButton->setEnabled(true);
+ }
+ if (isPrevious) {
+ ui->defaultUserAgentButton->setEnabled(true);
+ ui->setUserAgent->setEnabled(false);
+ }
}
-void SettingsWidget::on_deletePersistentData_clicked()
-{
- QMessageBox msgBox;
- msgBox.setText("This will delete app Persistent Data ! Persistent data includes persistent cookies, HTML5 local storage, and visited links.");
- msgBox.setIconPixmap(QPixmap(":/icons/information-line.png").scaled(42,42,Qt::KeepAspectRatio,Qt::SmoothTransformation));
- msgBox.setInformativeText("Delete Application Cookies ?");
- msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- msgBox.setDefaultButton(QMessageBox::No);
- int ret = msgBox.exec();
- switch (ret) {
- case QMessageBox::Yes:{
- utils::delete_cache(this->persistentStoragePath());
- refresh();
- break;
- }
- case QMessageBox::No:
- break;
- }
+void SettingsWidget::on_setUserAgent_clicked() {
+ if (ui->userAgentLineEdit->text().trimmed().isEmpty()) {
+ QMessageBox::information(this, QApplication::applicationName() + "| Error",
+ "Cannot set an empty UserAgent String.");
+ return;
+ }
+ emit userAgentChanged(ui->userAgentLineEdit->text());
}
-void SettingsWidget::on_notificationCheckBox_toggled(bool checked)
-{
- settings.setValue("disableNotificationPopups",checked);
+void SettingsWidget::on_closeButtonActionComboBox_currentIndexChanged(
+ int index) {
+ settings.setValue("closeButtonActionCombo", index);
}
-void SettingsWidget::on_themeComboBox_currentTextChanged(const QString &arg1)
-{
- applyThemeQuirks();
- settings.setValue("windowTheme",QString(arg1).toLower());
- emit updateWindowTheme();
- emit updatePageTheme();
+void SettingsWidget::appLockSetChecked(bool checked) {
+ ui->applock_checkbox->setChecked(checked);
}
-
-void SettingsWidget::applyThemeQuirks()
-{
- //little quirks
- if(QString::compare(ui->themeComboBox->currentText(),"dark",Qt::CaseInsensitive)==0)
- {
- ui->bottomLine->setStyleSheet("background-color: rgb(5, 97, 98);");
- ui->label_7->setStyleSheet("color:#c2c5d1;padding: 0px 8px 0px 8px;background:transparent;");
- }else{
- ui->bottomLine->setStyleSheet("background-color: rgb(74, 223, 131);");
- ui->label_7->setStyleSheet("color:#1e1f21;padding: 0px 8px 0px 8px;background:transparent;");
- }
+void SettingsWidget::setCurrentPasswordText(QString str) {
+ ui->current_password->setText(str);
}
-
-void SettingsWidget::on_muteAudioCheckBox_toggled(bool checked)
-{
- settings.setValue("muteAudio",checked);
- emit muteToggled(checked);
+void SettingsWidget::on_applock_checkbox_toggled(bool checked) {
+ if (settings.value("asdfg").isValid()) {
+ settings.setValue("lockscreen", checked);
+ } else {
+ settings.setValue("lockscreen", false);
+ }
+ if (checked) {
+ emit init_lock();
+ }
}
-void SettingsWidget::on_autoPlayMediaCheckBox_toggled(bool checked)
-{
- settings.setValue("autoPlayMedia",checked);
- emit autoPlayMediaToggled(checked);
+void SettingsWidget::on_dictComboBox_currentIndexChanged(const QString &arg1) {
+ settings.setValue("sc_dict", arg1);
+ emit dictChanged(arg1);
}
-void SettingsWidget::on_defaultUserAgentButton_clicked()
-{
- ui->userAgentLineEdit->setText(defaultUserAgentStr);
- emit userAgentChanged(ui->userAgentLineEdit->text());
+void SettingsWidget::on_enableSpellCheck_toggled(bool checked) {
+ settings.setValue("sc_enabled", checked);
+ emit spellCheckChanged(checked);
}
-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;
+void SettingsWidget::on_showShortcutsButton_clicked() {
+ QWidget *sheet = new QWidget(this);
+ sheet->setWindowTitle(QApplication::applicationName() +
+ " | Global shortcuts");
- if(isDefault == false && arg1.trimmed().isEmpty()==false)
- {
- ui->defaultUserAgentButton->setEnabled(false);
- ui->setUserAgent->setEnabled(false);
- }
- if(isPrevious == false && arg1.trimmed().isEmpty() == false)
- {
- ui->setUserAgent->setEnabled(true);
- ui->defaultUserAgentButton->setEnabled(true);
- }
- if(isPrevious){
- ui->defaultUserAgentButton->setEnabled(true);
- ui->setUserAgent->setEnabled(false);
- }
-}
+ sheet->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint);
+ sheet->move(this->geometry().center() - sheet->geometry().center());
-void SettingsWidget::on_setUserAgent_clicked()
-{
- if(ui->userAgentLineEdit->text().trimmed().isEmpty()){
- QMessageBox::information(this,QApplication::applicationName()+"| Error",
- "Cannot set an empty UserAgent String.");
- return;
+ QVBoxLayout *layout = new QVBoxLayout(sheet);
+ sheet->setLayout(layout);
+ auto *w = qobject_cast<MainWindow *>(parent());
+ if (w != 0) {
+ foreach (QAction *action, w->actions()) {
+ QString shortcutStr = action->shortcut().toString();
+ if (shortcutStr.isEmpty() == false) {
+ QLabel *label = new QLabel(
+ action->text().remove("&") + " | " + shortcutStr, sheet);
+ label->setAlignment(Qt::AlignHCenter);
+ layout->addWidget(label);
+ }
}
- emit userAgentChanged(ui->userAgentLineEdit->text());
+ }
+ sheet->setAttribute(Qt::WA_DeleteOnClose);
+ sheet->show();
}
-
-void SettingsWidget::on_closeButtonActionComboBox_currentIndexChanged(int index)
-{
- settings.setValue("closeButtonActionCombo",index);
-}
-
-void SettingsWidget::appLockSetChecked(bool checked)
-{
- ui->applock_checkbox->setChecked(checked);
+void SettingsWidget::on_showPermissionsButton_clicked() {
+ PermissionDialog *permissionDialog = new PermissionDialog(this);
+ permissionDialog->setWindowTitle(QApplication::applicationName() + " | " +
+ tr("Feature permissions"));
+ permissionDialog->setWindowFlag(Qt::Dialog);
+ permissionDialog->setAttribute(Qt::WA_DeleteOnClose, true);
+ permissionDialog->move(this->geometry().center() -
+ permissionDialog->geometry().center());
+ permissionDialog->setMinimumSize(485, 310);
+ permissionDialog->adjustSize();
+ permissionDialog->show();
}
-void SettingsWidget::setCurrentPasswordText(QString str)
-{
- ui->current_password->setText(str);
-}
-
-void SettingsWidget::on_applock_checkbox_toggled(bool checked)
-{
- if(settings.value("asdfg").isValid()){
- settings.setValue("lockscreen",checked);
- }else{
- settings.setValue("lockscreen",false);
- }
- if(checked){
- emit init_lock();
- }
+void SettingsWidget::on_notificationTimeOutspinBox_valueChanged(int arg1) {
+ settings.setValue("notificationTimeOut", arg1 * 1000);
+ emit notificationPopupTimeOutChanged();
}
-void SettingsWidget::on_dictComboBox_currentIndexChanged(const QString &arg1)
-{
- settings.setValue("sc_dict",arg1);
- emit dictChanged(arg1);
+void SettingsWidget::on_notificationCombo_currentIndexChanged(int index) {
+ settings.setValue("notificationCombo", index);
}
-void SettingsWidget::on_enableSpellCheck_toggled(bool checked)
-{
- settings.setValue("sc_enabled",checked);
- emit spellCheckChanged(checked);
+void SettingsWidget::on_tryNotification_clicked() {
+ emit notify("Test Notification");
}
-void SettingsWidget::on_showShortcutsButton_clicked()
-{
- QWidget *sheet = new QWidget(this);
- sheet->setWindowTitle(QApplication::applicationName()+" | Global shortcuts");
-
- sheet->setWindowFlags(Qt::Popup |Qt::FramelessWindowHint);
- sheet->move(this->geometry().center()-sheet->geometry().center());
-
- QVBoxLayout *layout = new QVBoxLayout(sheet);
- sheet->setLayout(layout);
- auto *w = qobject_cast<MainWindow*>(parent());
- if(w != 0){
- foreach (QAction *action, w->actions()) {
- QString shortcutStr = action->shortcut().toString();
- if(shortcutStr.isEmpty()==false){
- QLabel *label = new QLabel(action->text().remove("&")+" | "+shortcutStr,sheet);
- label->setAlignment(Qt::AlignHCenter);
- layout->addWidget(label);
- }
- }
- }
- sheet->setAttribute(Qt::WA_DeleteOnClose);
- sheet->show();
-}
-
-void SettingsWidget::on_showPermissionsButton_clicked()
-{
- PermissionDialog *permissionDialog = new PermissionDialog(this);
- permissionDialog->setWindowTitle(QApplication::applicationName()+" | "+tr("Feature permissions"));
- permissionDialog->setWindowFlag(Qt::Dialog);
- permissionDialog->setAttribute(Qt::WA_DeleteOnClose,true);
- permissionDialog->move(this->geometry().center()-permissionDialog->geometry().center());
- permissionDialog->setMinimumSize(485,310);
- permissionDialog->adjustSize();
- permissionDialog->show();
-}
-
-
-void SettingsWidget::on_notificationTimeOutspinBox_valueChanged(int arg1)
-{
- settings.setValue("notificationTimeOut",arg1*1000);
- emit notificationPopupTimeOutChanged();
-}
-
-void SettingsWidget::on_notificationCombo_currentIndexChanged(int index)
-{
- settings.setValue("notificationCombo",index);
-}
-
-void SettingsWidget::on_tryNotification_clicked()
-{
- emit notify("Test Notification");
-}
-
-void SettingsWidget::on_automaticThemeCheckBox_toggled(bool checked)
-{
- if(checked)
- {
- AutomaticTheme *automaticTheme = new AutomaticTheme(this);
- automaticTheme->setWindowTitle(QApplication::applicationName()+" | Automatic theme switcher setup");
- automaticTheme->setWindowFlag(Qt::Dialog);
- automaticTheme->setAttribute(Qt::WA_DeleteOnClose,true);
- connect(automaticTheme,&AutomaticTheme::destroyed,[=](){
- bool automaticThemeSwitching = settings.value("automaticTheme",false).toBool();
- ui->automaticThemeCheckBox->setChecked(automaticThemeSwitching);
- if(automaticThemeSwitching)
- themeSwitchTimerTimeout();
- updateAutomaticTheme();
- });
- automaticTheme->show();
- }else{
- settings.setValue("automaticTheme",false);
- updateAutomaticTheme();
- }
+void SettingsWidget::on_automaticThemeCheckBox_toggled(bool checked) {
+ if (checked) {
+ AutomaticTheme *automaticTheme = new AutomaticTheme(this);
+ automaticTheme->setWindowTitle(QApplication::applicationName() +
+ " | Automatic theme switcher setup");
+ automaticTheme->setWindowFlag(Qt::Dialog);
+ automaticTheme->setAttribute(Qt::WA_DeleteOnClose, true);
+ connect(automaticTheme, &AutomaticTheme::destroyed, [=]() {
+ bool automaticThemeSwitching =
+ settings.value("automaticTheme", false).toBool();
+ ui->automaticThemeCheckBox->setChecked(automaticThemeSwitching);
+ if (automaticThemeSwitching)
+ themeSwitchTimerTimeout();
+ updateAutomaticTheme();
+ });
+ automaticTheme->show();
+ } else {
+ settings.setValue("automaticTheme", false);
+ updateAutomaticTheme();
+ }
}
-void SettingsWidget::on_useNativeFileDialog_toggled(bool checked)
-{
- settings.setValue("useNativeFileDialog",checked);
+void SettingsWidget::on_useNativeFileDialog_toggled(bool checked) {
+ settings.setValue("useNativeFileDialog", checked);
}
-void SettingsWidget::on_zoomPlus_clicked()
-{
- double currentFactor = settings.value("zoomFactor",1.0).toDouble();
- double newFactor = currentFactor + 0.25;
- ui->zoomFactorSpinBox->setValue(newFactor);
+void SettingsWidget::on_zoomPlus_clicked() {
+ double currentFactor = settings.value("zoomFactor", 1.0).toDouble();
+ double newFactor = currentFactor + 0.25;
+ ui->zoomFactorSpinBox->setValue(newFactor);
- settings.setValue("zoomFactor",ui->zoomFactorSpinBox->value());
- emit zoomChanged();
+ settings.setValue("zoomFactor", ui->zoomFactorSpinBox->value());
+ emit zoomChanged();
}
-void SettingsWidget::on_zoomMinus_clicked()
-{
- double currentFactor = settings.value("zoomFactor",1.0).toDouble();
- double newFactor = currentFactor - 0.25;
- ui->zoomFactorSpinBox->setValue(newFactor);
+void SettingsWidget::on_zoomMinus_clicked() {
+ double currentFactor = settings.value("zoomFactor", 1.0).toDouble();
+ double newFactor = currentFactor - 0.25;
+ ui->zoomFactorSpinBox->setValue(newFactor);
- settings.setValue("zoomFactor",ui->zoomFactorSpinBox->value());
- emit zoomChanged();
+ settings.setValue("zoomFactor", ui->zoomFactorSpinBox->value());
+ emit zoomChanged();
}
-void SettingsWidget::on_zoomReset_clicked()
-{
- double newFactor = 1.0;
- ui->zoomFactorSpinBox->setValue(newFactor);
+void SettingsWidget::on_zoomReset_clicked() {
+ double newFactor = 1.0;
+ ui->zoomFactorSpinBox->setValue(newFactor);
- settings.setValue("zoomFactor",ui->zoomFactorSpinBox->value());
- emit zoomChanged();
+ settings.setValue("zoomFactor", ui->zoomFactorSpinBox->value());
+ emit zoomChanged();
}
diff --git a/src/utils.cpp b/src/utils.cpp
index d810997..e248081 100644
--- a/src/utils.cpp
+++ b/src/utils.cpp
@@ -6,274 +6,261 @@
#include <QRegularExpression>
#include <time.h>
-utils::utils(QObject *parent) : QObject(parent)
-{
- setParent(parent);
-}
-
-utils::~utils()
-{
- this->deleteLater();
-}
-
-//calculate dir size
-quint64 utils::dir_size(const QString & directory)
-{
- quint64 sizex = 0;
- QFileInfo str_info(directory);
- if (str_info.isDir())
- {
- QDir dir(directory);
- QFileInfoList list = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot);
- for (int i = 0; i < list.size(); ++i)
- {
- QFileInfo fileInfo = list.at(i);
- if(fileInfo.isDir())
- {
- sizex += dir_size(fileInfo.absoluteFilePath());
- }
- else{
- sizex += fileInfo.size();
- }
- }
+utils::utils(QObject *parent) : QObject(parent) { setParent(parent); }
+
+utils::~utils() { this->deleteLater(); }
+
+// calculate dir size
+quint64 utils::dir_size(const QString &directory) {
+ quint64 sizex = 0;
+ QFileInfo str_info(directory);
+ if (str_info.isDir()) {
+ QDir dir(directory);
+ QFileInfoList list =
+ dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::Hidden |
+ QDir::NoSymLinks | QDir::NoDotAndDotDot);
+ for (int i = 0; i < list.size(); ++i) {
+ QFileInfo fileInfo = list.at(i);
+ if (fileInfo.isDir()) {
+ sizex += dir_size(fileInfo.absoluteFilePath());
+ } else {
+ sizex += fileInfo.size();
+ }
}
- return sizex;
+ }
+ return sizex;
}
-//get the size of cache folder in human readble format
-QString utils::refreshCacheSize(const QString cache_dir)
-{
- qint64 cache_size = dir_size(cache_dir);
- QString cache_unit;
- if(cache_size > 1024*1024*1024)
- {
- cache_size = cache_size/(1024*1024*1024);
- cache_unit = " GB";
- }
- if(cache_size > 1024*1024)
- {
- cache_size = cache_size/(1024*1024);
- cache_unit = " MB";
- }
- else if(cache_size > 1024)
- {
- cache_size = cache_size/(1024);
- cache_unit = " kB";
- }
- else
- {
- cache_unit = " B";
- }
- return QString::number(cache_size) + cache_unit;
+// get the size of cache folder in human readble format
+QString utils::refreshCacheSize(const QString cache_dir) {
+ qint64 cache_size = dir_size(cache_dir);
+ QString cache_unit;
+ if (cache_size > 1024 * 1024 * 1024) {
+ cache_size = cache_size / (1024 * 1024 * 1024);
+ cache_unit = " GB";
+ }
+ if (cache_size > 1024 * 1024) {
+ cache_size = cache_size / (1024 * 1024);
+ cache_unit = " MB";
+ } else if (cache_size > 1024) {
+ cache_size = cache_size / (1024);
+ cache_unit = " kB";
+ } else {
+ cache_unit = " B";
+ }
+ return QString::number(cache_size) + cache_unit;
}
-bool utils::delete_cache(const QString cache_dir)
-{
- bool deleted = QDir(cache_dir).removeRecursively();
- QDir(cache_dir).mkpath(cache_dir);
- return deleted;
+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)
-{
- QStringList parts = s.split(' ', QString::SkipEmptyParts);
- for (int i = 0; i < parts.size(); ++i)
- parts[i].replace(0, 1, parts[i][0].toUpper());
- return parts.join(" ");
+// returns string with first letter capitalized
+QString utils::toCamelCase(const QString &s) {
+ QStringList parts = s.split(' ', QString::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) {
- QString str = QUuid::createUuid().toString();
- str.remove(QRegularExpression("{|}|-"));
- if(str.length()<length){
- while(str.length() != length){
- int required_char = length - str.length();
- str = str + str.append(genRand(required_char));
- }
+ QString str = QUuid::createUuid().toString();
+ str.remove(QRegularExpression("{|}|-"));
+ if (str.length() < length) {
+ while (str.length() != length) {
+ int required_char = length - str.length();
+ str = str + str.append(genRand(required_char));
}
- if(str.length()>length){
- while(str.length() != length){
- str = str.remove(str.length()-1,1);
- }
+ }
+ if (str.length() > length) {
+ while (str.length() != length) {
+ str = str.remove(str.length() - 1, 1);
}
- return str;
+ }
+ return str;
}
-QString utils::genRand(int length)
-{
- QDateTime cd = QDateTime::currentDateTime();
- const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+QString::number(cd.currentMSecsSinceEpoch()).remove(QRegExp("[^a-zA-Z\\d\\s]")));
-
- const int randomStringLength = length;
- QString randomString;
- qsrand(cd.toTime_t());
- for(int i=0; i<randomStringLength; ++i)
- {
- int index = qrand() % possibleCharacters.length();
- QChar nextChar = possibleCharacters.at(index);
- randomString.append(nextChar);
- }
- randomString = randomString.trimmed().simplified().remove(" ");
- return randomString;
+QString utils::genRand(int length) {
+ QDateTime cd = QDateTime::currentDateTime();
+ const QString possibleCharacters(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" +
+ QString::number(cd.currentMSecsSinceEpoch())
+ .remove(QRegExp("[^a-zA-Z\\d\\s]")));
+
+ const int randomStringLength = length;
+ QString randomString;
+ qsrand(cd.toTime_t());
+ for (int i = 0; i < randomStringLength; ++i) {
+ int index = qrand() % possibleCharacters.length();
+ QChar nextChar = possibleCharacters.at(index);
+ randomString.append(nextChar);
+ }
+ randomString = randomString.trimmed().simplified().remove(" ");
+ return randomString;
}
-QString utils::convertSectoDay(qint64 secs)
-{
- int day = secs / (24 * 3600);
+QString utils::convertSectoDay(qint64 secs) {
+ int day = secs / (24 * 3600);
- secs = secs % (24 * 3600);
- int hour = secs / 3600;
+ secs = secs % (24 * 3600);
+ int hour = secs / 3600;
- secs %= 3600;
- int minutes = secs / 60 ;
+ secs %= 3600;
+ int minutes = secs / 60;
- secs %= 60;
- int seconds = secs;
+ secs %= 60;
+ int seconds = secs;
- QString days = QString::number(day) + " " + "days " + QString::number(hour)
- + " " + "hours " + QString::number(minutes) + " "
- + "minutes " + QString::number(seconds) + " "
- + "seconds ";
- return days;
+ QString days = QString::number(day) + " " + "days " + QString::number(hour) +
+ " " + "hours " + QString::number(minutes) + " " + "minutes " +
+ QString::number(seconds) + " " + "seconds ";
+ return days;
}
-//static on demand path maker
-QString utils::returnPath(QString pathname)
-{
- QString _data_path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
- if(!QDir(_data_path+"/"+pathname).exists()){
- QDir d(_data_path+"/"+pathname);
- d.mkpath(_data_path+"/"+pathname);
- }
- return _data_path+"/"+pathname+"/";
+// static on demand path maker
+QString utils::returnPath(QString pathname) {
+ QString _data_path =
+ QStandardPaths::writableLocation(QStandardPaths::DataLocation);
+ if (!QDir(_data_path + "/" + pathname).exists()) {
+ QDir d(_data_path + "/" + pathname);
+ d.mkpath(_data_path + "/" + pathname);
+ }
+ return _data_path + "/" + pathname + "/";
}
-QString utils::EncodeXML(const QString &encodeMe){
+QString utils::EncodeXML(const QString &encodeMe) {
- QString temp;
- int length = encodeMe.size();
- for (int index = 0; index < length; index++)
- {
- QChar character(encodeMe.at(index));
+ QString temp;
+ int length = encodeMe.size();
+ for (int index = 0; index < length; index++) {
+ QChar character(encodeMe.at(index));
- switch (character.unicode())
- {
- case '&':
- temp += "&amp;"; break;
+ switch (character.unicode()) {
+ case '&':
+ temp += "&amp;";
+ break;
- case '\'':
- temp += "&apos;"; break;
+ case '\'':
+ temp += "&apos;";
+ break;
- case '"':
- temp += "&quot;"; break;
+ case '"':
+ temp += "&quot;";
+ break;
- case '<':
- temp += "&lt;"; break;
+ case '<':
+ temp += "&lt;";
+ break;
- case '>':
- temp += "&gt;"; break;
+ case '>':
+ temp += "&gt;";
+ break;
- default:
- temp += character;
- break;
- }
+ default:
+ temp += character;
+ break;
}
+ }
- return temp;
+ return temp;
}
QString utils::DecodeXML(const QString &decodeMe) {
- QString temp(decodeMe);
+ QString temp(decodeMe);
- temp.replace("&amp;", "&");
- temp.replace("&apos;", "'");
- temp.replace("&quot;", "\"");
- temp.replace("&lt;", "<");
- temp.replace("&gt;", ">");
+ temp.replace("&amp;", "&");
+ temp.replace("&apos;", "'");
+ temp.replace("&quot;", "\"");
+ temp.replace("&lt;", "<");
+ temp.replace("&gt;", ">");
- return temp;
+ return temp;
}
-
-QString utils::htmlToPlainText(QString str){
- QString out;
- QTextDocument text;
- text.setHtml(str);
- out = text.toPlainText();
- text.deleteLater();
- return out .replace("\\\"","'")
- .replace("&amp;","&")
- .replace("&gt;",">")
- .replace("&lt;","<")
- .replace("&#39;","'");
+QString utils::htmlToPlainText(QString str) {
+ QString out;
+ QTextDocument text;
+ text.setHtml(str);
+ out = text.toPlainText();
+ text.deleteLater();
+ return out.replace("\\\"", "'")
+ .replace("&amp;", "&")
+ .replace("&gt;", ">")
+ .replace("&lt;", "<")
+ .replace("&#39;", "'");
}
-
-QString utils::appDebugInfo()
-{
-
- QStringList debugInfo;
- debugInfo << "<h3>"+QApplication::applicationName()+"</h3>"
- << "<ul>"
- << "<li><b>" + QObject::tr("Version") + ":</b> " + QString(VERSIONSTR) + "</li>"
- << "<li><b>" + QObject::tr("Build Date") + ":</b> " + QString::fromLatin1(__DATE__) + "</li>"
- << "<li><b>" + QObject::tr("Build Time") + ":</b> " + QString::fromLatin1(__TIME__) + "</li>"
- << "<li><b>" + QObject::tr("Qt Runtime Version")+ ":</b> " + QString(qVersion()) + "</li>"
- << "<li><b>" + QObject::tr("Qt Compiled Version") + ":</b> " + QString(QT_VERSION_STR) + "</li>"
- << "<li><b>" + QObject::tr("System") + ":</b> " + QSysInfo::prettyProductName() + "</li>"
- << "<li><b>" + QObject::tr("Architecture") + ":</b> " + QSysInfo::currentCpuArchitecture() + "</li>";
- debugInfo << "</ul>";
- return debugInfo.join("\n");
-
+QString utils::appDebugInfo() {
+
+ QStringList debugInfo;
+ debugInfo << "<h3>" + QApplication::applicationName() + "</h3>"
+ << "<ul>"
+ << "<li><b>" + QObject::tr("Version") + ":</b> " +
+ QString(VERSIONSTR) + "</li>"
+ << "<li><b>" + QObject::tr("Build Date") + ":</b> " +
+ QString::fromLatin1(__DATE__) + "</li>"
+ << "<li><b>" + QObject::tr("Build Time") + ":</b> " +
+ QString::fromLatin1(__TIME__) + "</li>"
+ << "<li><b>" + QObject::tr("Qt Runtime Version") + ":</b> " +
+ QString(qVersion()) + "</li>"
+ << "<li><b>" + QObject::tr("Qt Compiled Version") + ":</b> " +
+ QString(QT_VERSION_STR) + "</li>"
+ << "<li><b>" + QObject::tr("System") + ":</b> " +
+ QSysInfo::prettyProductName() + "</li>"
+ << "<li><b>" + QObject::tr("Architecture") + ":</b> " +
+ QSysInfo::currentCpuArchitecture() + "</li>";
+ debugInfo << "</ul>";
+ return debugInfo.join("\n");
}
-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);
- message_box.setModal(true);
- message_box.setIcon(QMessageBox::Critical);
- message_box.setWindowTitle(QApplication::applicationName()+QObject::tr("Exception"));
- //spaces are added to the end because otherwise the dialog is too small
- message_box.setText(QApplication::applicationName()+QObject::tr(" has encountered a problem."));
- message_box.setInformativeText(QApplication::applicationName()+QObject::tr(" may need to Restart. Please report the error to developer."));
- message_box.setStandardButtons(QMessageBox::Close);
- QStringList detailed_text;
- detailed_text << "Error info: " + error_info
- << "\nApp version: " + QString(VERSIONSTR)
- << "\nQt Runtime Version: " + QString(qVersion())
- << "\nQt Compiled Version: " + QString(QT_VERSION_STR)
- << "\nSystem: " + QSysInfo::prettyProductName()
- << "\nArchitecture: " + QSysInfo::currentCpuArchitecture();
- message_box.setDetailedText(detailed_text.join("\n"));
- message_box.exec();
+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);
+ message_box.setModal(true);
+ message_box.setIcon(QMessageBox::Critical);
+ message_box.setWindowTitle(QApplication::applicationName() +
+ QObject::tr("Exception"));
+ // spaces are added to the end because otherwise the dialog is too small
+ message_box.setText(QApplication::applicationName() +
+ QObject::tr(" has encountered a problem."));
+ message_box.setInformativeText(
+ QApplication::applicationName() +
+ QObject::tr(
+ " may need to Restart. Please report the error to developer."));
+ message_box.setStandardButtons(QMessageBox::Close);
+ QStringList detailed_text;
+ detailed_text << "Error info: " + error_info
+ << "\nApp version: " + QString(VERSIONSTR)
+ << "\nQt Runtime Version: " + QString(qVersion())
+ << "\nQt Compiled Version: " + QString(QT_VERSION_STR)
+ << "\nSystem: " + QSysInfo::prettyProductName()
+ << "\nArchitecture: " + QSysInfo::currentCpuArchitecture();
+ 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)
-{
- return QString::number(number, 'f', 1).toFloat();
+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)
-{
+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
- // utility function for retrieval if that's the case.
- return qEnvironmentVariable(variable_name.toUtf8().constData(), "").trimmed();
+ // The only time this might fall down is on Linux when an
+ // environment variable holds bytedata. Don't use this
+ // utility function for retrieval if that's the case.
+ return qEnvironmentVariable(variable_name.toUtf8().constData(), "").trimmed();
#else
- // This will typically only be used on older Qts on Linux
- return QProcessEnvironment::systemEnvironment().value(variable_name, "").trimmed();
+ // This will typically only be used on older Qts on Linux
+ return QProcessEnvironment::systemEnvironment()
+ .value(variable_name, "")
+ .trimmed();
#endif
}
-
-
-
-
diff --git a/src/webenginepage.cpp b/src/webenginepage.cpp
index f0155bc..d5ecfff 100644
--- a/src/webenginepage.cpp
+++ b/src/webenginepage.cpp
@@ -4,275 +4,290 @@
#include <QStyle>
#include <QWebEngineSettings>
-
WebEnginePage::WebEnginePage(QWebEngineProfile *profile, QObject *parent)
- : QWebEnginePage(profile, parent)
-{
- // Connect signals and slots
- 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);
- connect(this, &QWebEnginePage::registerProtocolHandlerRequested, this, &WebEnginePage::handleRegisterProtocolHandlerRequested);
+ : QWebEnginePage(profile, parent) {
+ // Connect signals and slots
+ 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);
+ connect(this, &QWebEnginePage::registerProtocolHandlerRequested, this,
+ &WebEnginePage::handleRegisterProtocolHandlerRequested);
#if !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
- connect(this, &QWebEnginePage::selectClientCertificate, this, &WebEnginePage::handleSelectClientCertificate);
+ connect(this, &QWebEnginePage::selectClientCertificate, this,
+ &WebEnginePage::handleSelectClientCertificate);
#endif
}
-bool WebEnginePage::acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame)
-{
- qDebug() << "Navigation request: [" + url.toDisplayString() + "] " + type;
+bool WebEnginePage::acceptNavigationRequest(const QUrl &url,
+ QWebEnginePage::NavigationType type,
+ bool isMainFrame) {
+ qDebug() << "Navigation request: [" + url.toDisplayString() + "] " + type;
- if (QWebEnginePage::NavigationType::NavigationTypeLinkClicked == type)
- {
- QDesktopServices::openUrl(url);
- return false;
- }
+ if (QWebEnginePage::NavigationType::NavigationTypeLinkClicked == type) {
+ QDesktopServices::openUrl(url);
+ return false;
+ }
- return QWebEnginePage::acceptNavigationRequest(url, type, isMainFrame);
+ return QWebEnginePage::acceptNavigationRequest(url, type, isMainFrame);
}
-QWebEnginePage *WebEnginePage::createWindow(QWebEnginePage::WebWindowType type)
-{
- Q_UNUSED(type);
- return new WebEnginePage(this->profile());
+QWebEnginePage *
+WebEnginePage::createWindow(QWebEnginePage::WebWindowType type) {
+ Q_UNUSED(type);
+ return new WebEnginePage(this->profile());
}
-
-inline QString questionForFeature(QWebEnginePage::Feature feature)
-{
- switch (feature) {
- case QWebEnginePage::Geolocation:
- return WebEnginePage::tr("Allow %1 to access your location information?");
- case QWebEnginePage::MediaAudioCapture:
- return WebEnginePage::tr("Allow %1 to access your microphone?");
- case QWebEnginePage::MediaVideoCapture:
- return WebEnginePage::tr("Allow %1 to access your webcam?");
- case QWebEnginePage::MediaAudioVideoCapture:
- return WebEnginePage::tr("Allow %1 to access your microphone and webcam?");
- case QWebEnginePage::MouseLock:
- return WebEnginePage::tr("Allow %1 to lock your mouse cursor?");
- case QWebEnginePage::DesktopVideoCapture:
- return WebEnginePage::tr("Allow %1 to capture video of your desktop?");
- case QWebEnginePage::DesktopAudioVideoCapture:
- return WebEnginePage::tr("Allow %1 to capture audio and video of your desktop?");
- case QWebEnginePage::Notifications:
- return WebEnginePage::tr("Allow %1 to show notification on your desktop?");
- }
- return QString();
+inline QString questionForFeature(QWebEnginePage::Feature feature) {
+ switch (feature) {
+ case QWebEnginePage::Geolocation:
+ return WebEnginePage::tr("Allow %1 to access your location information?");
+ case QWebEnginePage::MediaAudioCapture:
+ return WebEnginePage::tr("Allow %1 to access your microphone?");
+ case QWebEnginePage::MediaVideoCapture:
+ return WebEnginePage::tr("Allow %1 to access your webcam?");
+ case QWebEnginePage::MediaAudioVideoCapture:
+ return WebEnginePage::tr("Allow %1 to access your microphone and webcam?");
+ case QWebEnginePage::MouseLock:
+ return WebEnginePage::tr("Allow %1 to lock your mouse cursor?");
+ case QWebEnginePage::DesktopVideoCapture:
+ return WebEnginePage::tr("Allow %1 to capture video of your desktop?");
+ case QWebEnginePage::DesktopAudioVideoCapture:
+ return WebEnginePage::tr(
+ "Allow %1 to capture audio and video of your desktop?");
+ case QWebEnginePage::Notifications:
+ return WebEnginePage::tr("Allow %1 to show notification on your desktop?");
+ }
+ return QString();
}
-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);
+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());
+
+ 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();
+}
- QString title = tr("Permission Request");
- QString question = questionForFeature(feature).arg(securityOrigin.host());
-
- QString featureStr = QVariant::fromValue(feature).toString();
+void WebEnginePage::handleLoadFinished(bool ok) {
+ Q_UNUSED(ok);
+ // turn on Notification settings by default
+ if (settings.value("permissions/Notifications").isValid() == false) {
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.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::handleLoadFinished(bool ok)
-{
- Q_UNUSED(ok);
- //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)
-{
- //qDebug()<<"Fullscreen";
- request.accept();
+void WebEnginePage::fullScreenRequestedByPage(
+ QWebEngineFullScreenRequest request) {
+ // qDebug()<<"Fullscreen";
+ request.accept();
}
-QStringList WebEnginePage::chooseFiles(QWebEnginePage::FileSelectionMode mode, const QStringList &oldFiles, const QStringList &acceptedMimeTypes)
-{
- qDebug()<<mode<<oldFiles<<acceptedMimeTypes;
- QFileDialog::FileMode dialogMode;
- if(mode == QWebEnginePage::FileSelectOpen) {
- dialogMode = QFileDialog::ExistingFile;
- } else {
- dialogMode = QFileDialog::ExistingFiles;
- }
-
- QFileDialog* dialog = new QFileDialog();
- bool usenativeFileDialog = settings.value("useNativeFileDialog",false).toBool();
-
- if(usenativeFileDialog == false){
- dialog->setOption(QFileDialog::DontUseNativeDialog,true);
- }
-
- dialog->setFileMode(dialogMode);
-
- QStringList mimeFilters;
- mimeFilters.append("application/octet-stream"); // to show All files(*)
- mimeFilters.append(acceptedMimeTypes);
-
- if(acceptedMimeTypes.contains("image/*")){
- foreach(QByteArray mime,QImageReader::supportedImageFormats()){
- mimeFilters.append("image/"+mime);
- }
- }
-
- mimeFilters.sort(Qt::CaseSensitive);
- dialog->setMimeTypeFilters(mimeFilters);
-
- QStringList selectedFiles;
- if(dialog->exec()) {
- selectedFiles = dialog->selectedFiles();
- }
- return selectedFiles;
-}
-
-bool WebEnginePage::certificateError(const QWebEngineCertificateError &error)
-{
- QWidget *mainWindow = view()->window();
- if (error.isOverridable()) {
- QDialog dialog(mainWindow);
- dialog.setModal(true);
- dialog.setWindowFlags(dialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
- Ui::CertificateErrorDialog certificateDialog;
- certificateDialog.setupUi(&dialog);
- certificateDialog.m_iconLabel->setText(QString());
- QIcon icon(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxWarning, nullptr, mainWindow));
- certificateDialog.m_iconLabel->setPixmap(icon.pixmap(32, 32));
- certificateDialog.m_errorLabel->setText(error.errorDescription());
- dialog.setWindowTitle(tr("Certificate Error"));
- return dialog.exec() == QDialog::Accepted;
+QStringList WebEnginePage::chooseFiles(QWebEnginePage::FileSelectionMode mode,
+ const QStringList &oldFiles,
+ const QStringList &acceptedMimeTypes) {
+ qDebug() << mode << oldFiles << acceptedMimeTypes;
+ QFileDialog::FileMode dialogMode;
+ if (mode == QWebEnginePage::FileSelectOpen) {
+ dialogMode = QFileDialog::ExistingFile;
+ } else {
+ dialogMode = QFileDialog::ExistingFiles;
+ }
+
+ QFileDialog *dialog = new QFileDialog();
+ bool usenativeFileDialog =
+ settings.value("useNativeFileDialog", false).toBool();
+
+ if (usenativeFileDialog == false) {
+ dialog->setOption(QFileDialog::DontUseNativeDialog, true);
+ }
+
+ dialog->setFileMode(dialogMode);
+
+ QStringList mimeFilters;
+ mimeFilters.append("application/octet-stream"); // to show All files(*)
+ mimeFilters.append(acceptedMimeTypes);
+
+ if (acceptedMimeTypes.contains("image/*")) {
+ foreach (QByteArray mime, QImageReader::supportedImageFormats()) {
+ mimeFilters.append("image/" + mime);
}
+ }
- QMessageBox::critical(mainWindow, tr("Certificate Error"), error.errorDescription());
- return false;
-}
-
-void WebEnginePage::handleAuthenticationRequired(const QUrl &requestUrl, QAuthenticator *auth)
-{
- QWidget *mainWindow = view()->window();
- QDialog dialog(mainWindow);
- dialog.setModal(true);
- dialog.setWindowFlags(dialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
-
- Ui::PasswordDialog passwordDialog;
- passwordDialog.setupUi(&dialog);
-
- passwordDialog.m_iconLabel->setText(QString());
- QIcon icon(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxQuestion, nullptr, mainWindow));
- passwordDialog.m_iconLabel->setPixmap(icon.pixmap(32, 32));
+ mimeFilters.sort(Qt::CaseSensitive);
+ dialog->setMimeTypeFilters(mimeFilters);
- QString introMessage(tr("Enter username and password for \"%1\" at %2")
- .arg(auth->realm()).arg(requestUrl.toString().toHtmlEscaped()));
- passwordDialog.m_infoLabel->setText(introMessage);
- passwordDialog.m_infoLabel->setWordWrap(true);
-
- if (dialog.exec() == QDialog::Accepted) {
- auth->setUser(passwordDialog.m_userNameLineEdit->text());
- auth->setPassword(passwordDialog.m_passwordLineEdit->text());
- } else {
- // Set authenticator null if dialog is cancelled
- *auth = QAuthenticator();
- }
+ QStringList selectedFiles;
+ if (dialog->exec()) {
+ selectedFiles = dialog->selectedFiles();
+ }
+ return selectedFiles;
}
-void WebEnginePage::handleProxyAuthenticationRequired(const QUrl &, QAuthenticator *auth, const QString &proxyHost)
-{
- QWidget *mainWindow = view()->window();
+bool WebEnginePage::certificateError(const QWebEngineCertificateError &error) {
+ QWidget *mainWindow = view()->window();
+ if (error.isOverridable()) {
QDialog dialog(mainWindow);
dialog.setModal(true);
- dialog.setWindowFlags(dialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
-
- Ui::PasswordDialog passwordDialog;
- passwordDialog.setupUi(&dialog);
-
- passwordDialog.m_iconLabel->setText(QString());
- QIcon icon(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxQuestion, nullptr, mainWindow));
- passwordDialog.m_iconLabel->setPixmap(icon.pixmap(32, 32));
+ dialog.setWindowFlags(dialog.windowFlags() &
+ ~Qt::WindowContextHelpButtonHint);
+ Ui::CertificateErrorDialog certificateDialog;
+ certificateDialog.setupUi(&dialog);
+ certificateDialog.m_iconLabel->setText(QString());
+ QIcon icon(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxWarning,
+ nullptr, mainWindow));
+ certificateDialog.m_iconLabel->setPixmap(icon.pixmap(32, 32));
+ certificateDialog.m_errorLabel->setText(error.errorDescription());
+ dialog.setWindowTitle(tr("Certificate Error"));
+ return dialog.exec() == QDialog::Accepted;
+ }
+
+ QMessageBox::critical(mainWindow, tr("Certificate Error"),
+ error.errorDescription());
+ return false;
+}
- QString introMessage = tr("Connect to proxy \"%1\" using:");
- introMessage = introMessage.arg(proxyHost.toHtmlEscaped());
- passwordDialog.m_infoLabel->setText(introMessage);
- passwordDialog.m_infoLabel->setWordWrap(true);
+void WebEnginePage::handleAuthenticationRequired(const QUrl &requestUrl,
+ QAuthenticator *auth) {
+ QWidget *mainWindow = view()->window();
+ QDialog dialog(mainWindow);
+ dialog.setModal(true);
+ dialog.setWindowFlags(dialog.windowFlags() &
+ ~Qt::WindowContextHelpButtonHint);
+
+ Ui::PasswordDialog passwordDialog;
+ passwordDialog.setupUi(&dialog);
+
+ passwordDialog.m_iconLabel->setText(QString());
+ QIcon icon(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxQuestion,
+ nullptr, mainWindow));
+ passwordDialog.m_iconLabel->setPixmap(icon.pixmap(32, 32));
+
+ QString introMessage(tr("Enter username and password for \"%1\" at %2")
+ .arg(auth->realm())
+ .arg(requestUrl.toString().toHtmlEscaped()));
+ passwordDialog.m_infoLabel->setText(introMessage);
+ passwordDialog.m_infoLabel->setWordWrap(true);
+
+ if (dialog.exec() == QDialog::Accepted) {
+ auth->setUser(passwordDialog.m_userNameLineEdit->text());
+ auth->setPassword(passwordDialog.m_passwordLineEdit->text());
+ } else {
+ // Set authenticator null if dialog is cancelled
+ *auth = QAuthenticator();
+ }
+}
- if (dialog.exec() == QDialog::Accepted) {
- auth->setUser(passwordDialog.m_userNameLineEdit->text());
- auth->setPassword(passwordDialog.m_passwordLineEdit->text());
- } else {
- // Set authenticator null if dialog is cancelled
- *auth = QAuthenticator();
- }
+void WebEnginePage::handleProxyAuthenticationRequired(
+ const QUrl &, QAuthenticator *auth, const QString &proxyHost) {
+ QWidget *mainWindow = view()->window();
+ QDialog dialog(mainWindow);
+ dialog.setModal(true);
+ dialog.setWindowFlags(dialog.windowFlags() &
+ ~Qt::WindowContextHelpButtonHint);
+
+ Ui::PasswordDialog passwordDialog;
+ passwordDialog.setupUi(&dialog);
+
+ passwordDialog.m_iconLabel->setText(QString());
+ QIcon icon(mainWindow->style()->standardIcon(QStyle::SP_MessageBoxQuestion,
+ nullptr, mainWindow));
+ passwordDialog.m_iconLabel->setPixmap(icon.pixmap(32, 32));
+
+ QString introMessage = tr("Connect to proxy \"%1\" using:");
+ introMessage = introMessage.arg(proxyHost.toHtmlEscaped());
+ passwordDialog.m_infoLabel->setText(introMessage);
+ passwordDialog.m_infoLabel->setWordWrap(true);
+
+ if (dialog.exec() == QDialog::Accepted) {
+ auth->setUser(passwordDialog.m_userNameLineEdit->text());
+ auth->setPassword(passwordDialog.m_passwordLineEdit->text());
+ } else {
+ // Set authenticator null if dialog is cancelled
+ *auth = QAuthenticator();
+ }
}
//! [registerProtocolHandlerRequested]
-void WebEnginePage::handleRegisterProtocolHandlerRequested(QWebEngineRegisterProtocolHandlerRequest request)
-{
- auto answer = QMessageBox::question(
- view()->window(),
- tr("Permission Request"),
- tr("Allow %1 to open all %2 links?")
- .arg(request.origin().host())
- .arg(request.scheme()));
- if (answer == QMessageBox::Yes)
- request.accept();
- else
- request.reject();
+void WebEnginePage::handleRegisterProtocolHandlerRequested(
+ QWebEngineRegisterProtocolHandlerRequest request) {
+ auto answer =
+ QMessageBox::question(view()->window(), tr("Permission Request"),
+ tr("Allow %1 to open all %2 links?")
+ .arg(request.origin().host())
+ .arg(request.scheme()));
+ if (answer == QMessageBox::Yes)
+ request.accept();
+ else
+ request.reject();
}
//! [registerProtocolHandlerRequested]
#if !defined(QT_NO_SSL) || QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
-void WebEnginePage::handleSelectClientCertificate(QWebEngineClientCertificateSelection selection)
-{
- // Just select one.
- selection.select(selection.certificates().at(0));
-
- qDebug() << __FUNCTION__;
- for(QSslCertificate cert : selection.certificates()) {
- qDebug() << cert;
- selection.select(cert); // select the first available cert
- break;
- }
- qDebug() << selection.host();
+void WebEnginePage::handleSelectClientCertificate(
+ QWebEngineClientCertificateSelection selection) {
+ // Just select one.
+ selection.select(selection.certificates().at(0));
+
+ qDebug() << __FUNCTION__;
+ for (QSslCertificate cert : selection.certificates()) {
+ qDebug() << cert;
+ selection.select(cert); // select the first available cert
+ break;
+ }
+ qDebug() << selection.host();
}
#endif
-
-
diff --git a/src/webview.cpp b/src/webview.cpp
index 5fc00f4..39273eb 100644
--- a/src/webview.cpp
+++ b/src/webview.cpp
@@ -2,92 +2,94 @@
#include <QContextMenuEvent>
#include <QMenu>
-#include <QWebEngineProfile>
#include <QWebEngineContextMenuData>
+#include <QWebEngineProfile>
#include <mainwindow.h>
WebView::WebView(QWidget *parent, QStringList dictionaries)
- : QWebEngineView(parent)
-{
- m_dictionaries = dictionaries;
+ : QWebEngineView(parent) {
+ m_dictionaries = dictionaries;
- QObject *parentMainWindow = this->parent();
- while (!parentMainWindow -> objectName().contains("MainWindow")){
- parentMainWindow = parentMainWindow -> parent();
- }
- MainWindow *mainWindow = dynamic_cast<MainWindow *>(parentMainWindow);
+ QObject *parentMainWindow = this->parent();
+ while (!parentMainWindow->objectName().contains("MainWindow")) {
+ parentMainWindow = parentMainWindow->parent();
+ }
+ MainWindow *mainWindow = dynamic_cast<MainWindow *>(parentMainWindow);
- connect(this, &WebView::titleChanged,
- mainWindow, &MainWindow::handleWebViewTitleChanged);
- connect(this, &WebView::loadFinished,
- mainWindow, &MainWindow::handleLoadFinished);
- connect(this, &WebView::renderProcessTerminated,
- [this](QWebEnginePage::RenderProcessTerminationStatus termStatus, int statusCode) {
- QString status;
- switch (termStatus) {
- case QWebEnginePage::NormalTerminationStatus:
- status = tr("Render process normal exit");
- break;
- case QWebEnginePage::AbnormalTerminationStatus:
- status = tr("Render process abnormal exit");
- break;
- case QWebEnginePage::CrashedTerminationStatus:
- status = tr("Render process crashed");
- break;
- case QWebEnginePage::KilledTerminationStatus:
- status = tr("Render process killed");
- break;
- }
- QMessageBox::StandardButton btn = QMessageBox::question(window(), status,
- tr("Render process exited with code: %1\n" "Do you want to reload the page ?").arg(statusCode));
- if (btn == QMessageBox::Yes)
- QTimer::singleShot(0, [this] { this->reload(); });
- });
+ connect(this, &WebView::titleChanged, mainWindow,
+ &MainWindow::handleWebViewTitleChanged);
+ connect(this, &WebView::loadFinished, mainWindow,
+ &MainWindow::handleLoadFinished);
+ connect(this, &WebView::renderProcessTerminated,
+ [this](QWebEnginePage::RenderProcessTerminationStatus termStatus,
+ int statusCode) {
+ QString status;
+ switch (termStatus) {
+ case QWebEnginePage::NormalTerminationStatus:
+ status = tr("Render process normal exit");
+ break;
+ case QWebEnginePage::AbnormalTerminationStatus:
+ status = tr("Render process abnormal exit");
+ break;
+ case QWebEnginePage::CrashedTerminationStatus:
+ status = tr("Render process crashed");
+ break;
+ case QWebEnginePage::KilledTerminationStatus:
+ status = tr("Render process killed");
+ break;
+ }
+ QMessageBox::StandardButton btn =
+ QMessageBox::question(window(), status,
+ tr("Render process exited with code: %1\n"
+ "Do you want to reload the page ?")
+ .arg(statusCode));
+ if (btn == QMessageBox::Yes)
+ QTimer::singleShot(0, [this] { this->reload(); });
+ });
}
+void WebView::contextMenuEvent(QContextMenuEvent *event) {
+ const QWebEngineContextMenuData &data = page()->contextMenuData();
+ Q_ASSERT(data.isValid());
-void WebView::contextMenuEvent(QContextMenuEvent *event)
-{
- const QWebEngineContextMenuData &data = page()->contextMenuData();
- Q_ASSERT(data.isValid());
-
- //allow context menu on image
- if (data.mediaType() == QWebEngineContextMenuData::MediaTypeImage) {
- QWebEngineView::contextMenuEvent(event);
- return;
- }
- // if content is not editable
- if (!data.isContentEditable()) {
- event->ignore();
- return;
- }
+ // allow context menu on image
+ if (data.mediaType() == QWebEngineContextMenuData::MediaTypeImage) {
+ QWebEngineView::contextMenuEvent(event);
+ return;
+ }
+ // if content is not editable
+ if (!data.isContentEditable()) {
+ event->ignore();
+ return;
+ }
- QWebEngineProfile *profile = page()->profile();
- const QStringList &languages = profile->spellCheckLanguages();
- QMenu *menu = page()->createStandardContextMenu();
- menu->addSeparator();
+ QWebEngineProfile *profile = page()->profile();
+ const QStringList &languages = profile->spellCheckLanguages();
+ QMenu *menu = page()->createStandardContextMenu();
+ menu->addSeparator();
- QAction *spellcheckAction = new QAction(tr("Check Spelling"), nullptr);
- spellcheckAction->setCheckable(true);
- spellcheckAction->setChecked(profile->isSpellCheckEnabled());
- connect(spellcheckAction, &QAction::toggled, this, [profile,this](bool toogled) {
- profile->setSpellCheckEnabled(toogled);
- settings.setValue("sc_enabled",toogled);
- });
- menu->addAction(spellcheckAction);
+ QAction *spellcheckAction = new QAction(tr("Check Spelling"), nullptr);
+ spellcheckAction->setCheckable(true);
+ spellcheckAction->setChecked(profile->isSpellCheckEnabled());
+ connect(spellcheckAction, &QAction::toggled, this,
+ [profile, this](bool toogled) {
+ profile->setSpellCheckEnabled(toogled);
+ settings.setValue("sc_enabled", toogled);
+ });
+ menu->addAction(spellcheckAction);
- if (profile->isSpellCheckEnabled()) {
- QMenu *subMenu = menu->addMenu(tr("Select Language"));
- for (const QString &dict : m_dictionaries) {
- QAction *action = subMenu->addAction(dict);
- action->setCheckable(true);
- action->setChecked(languages.contains(dict));
- connect(action, &QAction::triggered, this, [profile, dict,this](){
- profile->setSpellCheckLanguages(QStringList()<<dict);
- settings.setValue("sc_dict",dict);
- });
- }
+ if (profile->isSpellCheckEnabled()) {
+ QMenu *subMenu = menu->addMenu(tr("Select Language"));
+ for (const QString &dict : m_dictionaries) {
+ QAction *action = subMenu->addAction(dict);
+ action->setCheckable(true);
+ action->setChecked(languages.contains(dict));
+ connect(action, &QAction::triggered, this, [profile, dict, this]() {
+ profile->setSpellCheckLanguages(QStringList() << dict);
+ settings.setValue("sc_dict", dict);
+ });
}
- connect(menu, &QMenu::aboutToHide, menu, &QObject::deleteLater);
- menu->popup(event->globalPos());
+ }
+ connect(menu, &QMenu::aboutToHide, menu, &QObject::deleteLater);
+ menu->popup(event->globalPos());
}
diff --git a/src/widgets/scrolltext/scrolltext.cpp b/src/widgets/scrolltext/scrolltext.cpp
index 00696af..b03b761 100644
--- a/src/widgets/scrolltext/scrolltext.cpp
+++ b/src/widgets/scrolltext/scrolltext.cpp
@@ -1,179 +1,152 @@
#include "scrolltext.h"
-#include <QPainter>
#include <QHoverEvent>
+#include <QPainter>
-ScrollText::ScrollText(QWidget *parent) :
- QWidget(parent), scrollPos(0)
-{
+ScrollText::ScrollText(QWidget *parent) : QWidget(parent), scrollPos(0) {
- staticText.setTextFormat(Qt::PlainText);
+ staticText.setTextFormat(Qt::PlainText);
- setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
+ setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- setMinimumHeight(fontMetrics().height()+10);
- setMaximumHeight(this->minimumHeight()+6);
+ setMinimumHeight(fontMetrics().height() + 10);
+ setMaximumHeight(this->minimumHeight() + 6);
- leftMargin = 0; //height() / 3;
+ leftMargin = 0; // height() / 3;
- setSeparator(" ");
+ setSeparator(" ");
- connect(&timer, SIGNAL(timeout()), this, SLOT(timer_timeout()));
- timer.setInterval(50);
+ connect(&timer, SIGNAL(timeout()), this, SLOT(timer_timeout()));
+ timer.setInterval(50);
}
-QString ScrollText::text() const
-{
- return _text;
-}
+QString ScrollText::text() const { return _text; }
-void ScrollText::setText(QString text)
-{
- _text = text;
- updateText();
- update();
+void ScrollText::setText(QString text) {
+ _text = text;
+ updateText();
+ update();
}
-QString ScrollText::separator() const
-{
- return _separator;
-}
-
-void ScrollText::setSeparator(QString separator)
-{
- _separator = separator;
- updateText();
- update();
-}
+QString ScrollText::separator() const { return _separator; }
-void ScrollText::setLeftMargin(int pixels)
-{
- leftMargin = pixels;
- update();
+void ScrollText::setSeparator(QString separator) {
+ _separator = separator;
+ updateText();
+ update();
}
-void ScrollText::pause()
-{
- if(scrollEnabled){
- timer.stop();
- }
+void ScrollText::setLeftMargin(int pixels) {
+ leftMargin = pixels;
+ update();
}
-void ScrollText::resume()
-{
- if(scrollEnabled){
- timer.start();
- scrolledOnce = false;
- }
+void ScrollText::pause() {
+ if (scrollEnabled) {
+ timer.stop();
+ }
}
-void ScrollText::updateText()
-{
+void ScrollText::resume() {
+ if (scrollEnabled) {
+ timer.start();
scrolledOnce = false;
- timer.stop();
-
- singleTextWidth = fontMetrics().horizontalAdvance(_text);
-// scrollEnabled = true;
- scrollEnabled = (singleTextWidth > width() - leftMargin);
-
- if(scrollEnabled)
- {
- scrollPos = -64;
- staticText.setText(_text + _separator);
- timer.start();
- }
- else{
- staticText.setText(_text);
- }
- staticText.prepare(QTransform(), font());
- //wholeTextSize = QSize(fontMetrics().width(staticText.text()), fontMetrics().height());
- wholeTextSize = QSize(fontMetrics().horizontalAdvance(staticText.text()), fontMetrics().height());
-
+ }
}
-void ScrollText::paintEvent(QPaintEvent*)
-{
- QPainter p(this);
-
- if(scrollEnabled)
- {
- buffer.fill(qRgba(0, 0, 0, 0));
- QPainter pb(&buffer);
- pb.setPen(p.pen());
- pb.setFont(p.font());
-
- int x = qMin(-scrollPos, 0) + leftMargin;
- while(x < width())
- {
- pb.drawStaticText(QPointF(x, (height() - wholeTextSize.height()) / 2) + QPoint(2, 2), staticText);
- x += wholeTextSize.width();
- }
-
- //Apply Alpha Channel
- pb.setCompositionMode(QPainter::CompositionMode_DestinationIn);
- pb.setClipRect(width() - 15, 0, 15, height());
- pb.drawImage(0, 0, alphaChannel);
- pb.setClipRect(0, 0, 15, height());
- //initial situation: don't apply alpha channel in the left half of the image at all; apply it more and more until scrollPos gets positive
- if(scrollPos < 0)
- pb.setOpacity((qreal)(qMax(-8, scrollPos) + 8) / 8.0);
- pb.drawImage(0, 0, alphaChannel);
- p.drawImage(0, 0, buffer);
- }
- else
- {
- p.drawText(QRectF(0, 0, width(), height()), Qt::AlignCenter, text());
-// p.drawStaticText(QPointF(leftMargin, (height() - wholeTextSize.height()) / 2), staticText);
- }
+void ScrollText::updateText() {
+ scrolledOnce = false;
+ timer.stop();
+
+ singleTextWidth = fontMetrics().horizontalAdvance(_text);
+ // scrollEnabled = true;
+ scrollEnabled = (singleTextWidth > width() - leftMargin);
+
+ if (scrollEnabled) {
+ scrollPos = -64;
+ staticText.setText(_text + _separator);
+ timer.start();
+ } else {
+ staticText.setText(_text);
+ }
+ staticText.prepare(QTransform(), font());
+ // wholeTextSize = QSize(fontMetrics().width(staticText.text()),
+ // fontMetrics().height());
+ wholeTextSize = QSize(fontMetrics().horizontalAdvance(staticText.text()),
+ fontMetrics().height());
}
-void ScrollText::resizeEvent(QResizeEvent*)
-{
- //When the widget is resized, we need to update the alpha channel.
-
- alphaChannel = QImage(size(), QImage::Format_ARGB32_Premultiplied);
- buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied);
-
- //Create Alpha Channel:
- if(width() > 64)
- {
- //create first scanline
- QRgb* scanline1 = (QRgb*)alphaChannel.scanLine(0);
- for(int x = 1; x < 16; ++x)
- scanline1[x - 1] = scanline1[width() - x] = qRgba(0, 0, 0, x << 4);
- for(int x = 15; x < width() - 15; ++x)
- scanline1[x] = qRgb(0, 0, 0);
- //copy scanline to the other ones
- for(int y = 1; y < height(); ++y)
- memcpy(alphaChannel.scanLine(y), (uchar*)scanline1, width() * 4);
+void ScrollText::paintEvent(QPaintEvent *) {
+ QPainter p(this);
+
+ if (scrollEnabled) {
+ buffer.fill(qRgba(0, 0, 0, 0));
+ QPainter pb(&buffer);
+ pb.setPen(p.pen());
+ pb.setFont(p.font());
+
+ int x = qMin(-scrollPos, 0) + leftMargin;
+ while (x < width()) {
+ pb.drawStaticText(QPointF(x, (height() - wholeTextSize.height()) / 2) +
+ QPoint(2, 2),
+ staticText);
+ x += wholeTextSize.width();
}
- else
- alphaChannel.fill(qRgb(0, 0, 0));
-
- //Update scrolling state
- bool newScrollEnabled = (singleTextWidth > width() - leftMargin);
- if(newScrollEnabled != scrollEnabled)
- updateText();
+ // Apply Alpha Channel
+ pb.setCompositionMode(QPainter::CompositionMode_DestinationIn);
+ pb.setClipRect(width() - 15, 0, 15, height());
+ pb.drawImage(0, 0, alphaChannel);
+ pb.setClipRect(0, 0, 15, height());
+ // initial situation: don't apply alpha channel in the left half of the
+ // image at all; apply it more and more until scrollPos gets positive
+ if (scrollPos < 0)
+ pb.setOpacity((qreal)(qMax(-8, scrollPos) + 8) / 8.0);
+ pb.drawImage(0, 0, alphaChannel);
+ p.drawImage(0, 0, buffer);
+ } else {
+ p.drawText(QRectF(0, 0, width(), height()), Qt::AlignCenter, text());
+ // p.drawStaticText(QPointF(leftMargin, (height() -
+ // wholeTextSize.height()) / 2), staticText);
+ }
}
-void ScrollText::timer_timeout()
-{
- scrollPos = (scrollPos + 2)
- % wholeTextSize.width();
- pauseAfterOneRotation(scrollPos);
- update();
+void ScrollText::resizeEvent(QResizeEvent *) {
+ // When the widget is resized, we need to update the alpha channel.
+
+ alphaChannel = QImage(size(), QImage::Format_ARGB32_Premultiplied);
+ buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied);
+
+ // Create Alpha Channel:
+ if (width() > 64) {
+ // create first scanline
+ QRgb *scanline1 = (QRgb *)alphaChannel.scanLine(0);
+ for (int x = 1; x < 16; ++x)
+ scanline1[x - 1] = scanline1[width() - x] = qRgba(0, 0, 0, x << 4);
+ for (int x = 15; x < width() - 15; ++x)
+ scanline1[x] = qRgb(0, 0, 0);
+ // copy scanline to the other ones
+ for (int y = 1; y < height(); ++y)
+ memcpy(alphaChannel.scanLine(y), (uchar *)scanline1, width() * 4);
+ } else
+ alphaChannel.fill(qRgb(0, 0, 0));
+
+ // Update scrolling state
+ bool newScrollEnabled = (singleTextWidth > width() - leftMargin);
+ if (newScrollEnabled != scrollEnabled)
+ updateText();
}
-void ScrollText::pauseAfterOneRotation(int scrollPos)
-{
- if(scrolledOnce == false && scrollPos+2==wholeTextSize.width()){
- scrolledOnce = true;
- }
- if(scrolledOnce){
- pause();
- }
+void ScrollText::timer_timeout() {
+ scrollPos = (scrollPos + 2) % wholeTextSize.width();
+ pauseAfterOneRotation(scrollPos);
+ update();
}
-
-
-
+void ScrollText::pauseAfterOneRotation(int scrollPos) {
+ if (scrolledOnce == false && scrollPos + 2 == wholeTextSize.width()) {
+ scrolledOnce = true;
+ }
+ if (scrolledOnce) {
+ pause();
+ }
+}