Files
shutdown2/mainwindow.cpp
2019-10-03 20:03:05 +02:00

130 lines
3.0 KiB
C++

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTime>
#include <QStyle>
#include <QDebug>
#include <QKeyEvent>
class QNetworkReply;
namespace shutdown2 {
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
setFixedSize(size());
#if defined(Q_OS_WIN)
setWindowFlags(windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
#endif
mSettings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "RogoSoftware", "EasyShutdown2");
restoreGeometry(mSettings->value("geometry", saveGeometry()).toByteArray());
move(mSettings->value("pos", pos()).toPoint());
QFile css(":style.css");
if (css.open(QFile::ReadOnly | QFile::Text))
mCss = css.readAll();
setStyleSheet(mCss);
// init state machine
initStateMachine();
connect(&mTimer, &QTimer::timeout, this, &MainWindow::updateTime);
}
MainWindow::~MainWindow()
{
delete ui;
delete mSettings;
}
void MainWindow::initStateMachine()
{
// states
QState* on = new QState();
on->assignProperty(ui->btn_startstop, "on", false);
on->assignProperty(ui->lbl_timer, "on", false);
on->assignProperty(ui->btn_startstop, "text", "Stop");
QState* off = new QState();
off->assignProperty(ui->btn_startstop, "on", true);
off->assignProperty(ui->lbl_timer, "on", true);
off->assignProperty(ui->btn_startstop, "text", "Start");
// transistions
on->addTransition(ui->btn_startstop, SIGNAL(clicked()), off);
off->addTransition(ui->btn_startstop, SIGNAL(clicked()), on);
// init
mStateMachine.addState(on);
mStateMachine.addState(off);
mStateMachine.setInitialState(off);
mStateMachine.start();
}
void MainWindow::on_btn_startstop_clicked()
{
timerToggled();
setStyleSheet(mCss);
}
void MainWindow::shutdown()
{
// TODO: shutdown
}
void MainWindow::updateTime()
{
if (mTimeLeft == 0) {
shutdown();
mTimer.stop();
return;
}
QString m = QString::number(mTimeLeft / 60);
QString s = QString::number(mTimeLeft % 60);
if (s.length() == 1) s = "0" + s;
ui->lbl_timer->setText(m + ":" + s);
mTimeLeft--;
}
void MainWindow::timerToggled() {
if (ui->btn_startstop->property("on").toBool()) {
int time = 0;
foreach (QRadioButton* r, ui->groupBox->findChildren<QRadioButton*>()) {
if (r->isChecked()) {
time = r->property("value").toInt();
break;
}
}
if (time == -1)
time = ui->spinBox->value();
time *= 60; // convert to seconds
mTimeLeft = time;
updateTime();
mTimer.start(1000);
} else {
mTimeLeft = -2;
mTimer.stop();
ui->lbl_timer->setText("-- : --");
}
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
ui->btn_startstop->click(); // this is needed this way to trigger statemachine transition
event->accept();
}
}
}