Files
RRJClient/mainwindow.cpp
2024-10-03 10:13:14 +03:00

578 lines
16 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "updatenotifywidget.h"
#include "updatenotifywidget.h"
#include <QFontDatabase>
#include <QMessageBox>
#include <QMovie>
#include <QPaintEvent>
#include <QPainter>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowFlag(Qt::FramelessWindowHint);
painting();
initialize();
}
void MainWindow::initialize()
{
ui->loadingProgressBar->setValue(0);
ui->settingsWidget->hide();
ui->notificationLabel->hide();
ui->loadingProgressBar->hide();
ui->updateButton->hide();
ui->offlineWidget->hide();
ui->offlineStartButton->show();
ui->offlineStartButton->setEnabled(false);
ui->offlineStartButton->setGeometry(570,552,220,35);
ui->startButton->hide();
ui->startButton->setEnabled(false);
ui->displayGroupWidget->show();
ui->autostartCheckBox->hide();
ui->startButton->setEnabled(false);
ui->loginWidget->hide();
ui->updateWidget->hide();
ui->updateButtonGroup_2->hide();
createObjects();
bindConnection();
emit sigCalculateHash();
emit sigInitializeClient(recognizeSystem,externalExecuter,sendSystem,connectionThread);
recognizeSystem->initialize(updateController,dataParser,this);
screenChecker->check();
loadStaticData();
emit sigSetConnect(dataParser->getServerSettings(),connectionThread);
checkAppAvailable();
}
void MainWindow::createObjects()
{
connectionThread = new QThread;
animationThread = new QThread;
client = new TCPClient;
client->moveToThread(connectionThread);
dataParser = new DataParser;
sendSystem = new SendSystem;
sendSystem->moveToThread(connectionThread);
updateController = new UpdateController(dataParser,sendSystem);
updateController->moveToThread(connectionThread);
recognizeSystem = new RecognizeSystem;
recognizeSystem->moveToThread(connectionThread);
screenChecker = new ScreenChecker(dataParser,ui->displayLayout);
externalExecuter = new ExternalExecuter;
hashComparer = new HashComparer(dataParser);
connectionThread->start();
connectionThread->setPriority(QThread::HighestPriority);
timer = new QTimer;
}
void MainWindow::bindConnection()
{
connect(timer,&QTimer::timeout,this,&MainWindow::slotDisableNotify);
connect(recognizeSystem,&RecognizeSystem::sigStartCompare,hashComparer,&HashComparer::CompareDeltas);
connect(recognizeSystem,&RecognizeSystem::sigUpdateBytesAvailable,this,&MainWindow::updateProgress,Qt::QueuedConnection);
connect(recognizeSystem,&RecognizeSystem::sigLoadComplete,this,&MainWindow::loadComplete);
connect(recognizeSystem,&RecognizeSystem::sigNeedUpdate,this,&MainWindow::setNeedUpdate);
connect(recognizeSystem,&RecognizeSystem::sigSocketDisabled,this,&MainWindow::lostConnection);
connect(recognizeSystem,&RecognizeSystem::sigSaveLoginData,this,&MainWindow::checkLoginResult);
connect(recognizeSystem,&RecognizeSystem::sigSocketWaitForReadyRead,client,&TCPClient::waitRead,Qt::AutoConnection);
connect(recognizeSystem,&RecognizeSystem::sigServerBlocked,this,&MainWindow::serverBlocked);
connect(updateController,&UpdateController::sigUpdateComplete,this,&MainWindow::showCompleteDialogBox);
connect(hashComparer,&HashComparer::sigCallCheck,this,&MainWindow::checkUpdate);
connect(hashComparer,&HashComparer::sigHaveDelta,this,&MainWindow::showUpdateInfo);
connect(sendSystem,&SendSystem::sigSend,this,&MainWindow::updateProgress);
connect(sendSystem,&SendSystem::sigGetXmlAnswer,dataParser,&DataParser::slotGetXmlAnswer);
connect(this,&MainWindow::sigUpdateFilesOnServer,updateController,&UpdateController::updateFilesOnServer);
connect(this,&MainWindow::sigInitializeClient,client,&TCPClient::initialize,Qt::AutoConnection);
connect(this,&MainWindow::sigSetConnect,client,&TCPClient::setConnect,Qt::AutoConnection);
connect(this,&MainWindow::sigSendCommand,client,&TCPClient::slotSendCommand,Qt::AutoConnection);
connect(client,&TCPClient::sigConnectionState,this,&MainWindow::slotConnectionState,Qt::AutoConnection);
connect(client,&TCPClient::sigServerDisconnect,this,&MainWindow::slotServerDisconnect);
connect(this,&MainWindow::sigGetConnected,client,&TCPClient::getIsConnected);
connect(this,&MainWindow::sigCalculateHash,updateController,&UpdateController::calculateCommonHash);
connect(this,&MainWindow::sigSendAutorization,sendSystem,&SendSystem::sendClientAutorization);
}
void MainWindow::updateProgress()
{
filesLoaded++;
float value = 100 / ((float)fileCountForUpdate / filesLoaded);
ui->loadingProgressBar->setValue(value);
}
void MainWindow::loadComplete()
{
externalExecuter->findApp();
ui->updateButton->setEnabled(false);
ui->startButton->setEnabled(true);
autoStart();
ui->inlineTextDebug->setText(tr("Обновление завершено"));
ui->loadingProgressBar->setValue(100);
ui->startButton->show();
ui->offlineStartButton->setEnabled(true);
ui->autostartCheckBox->hide();
ui->offlineStartButton->show();
}
void MainWindow::setNeedUpdate(bool flag,quint64 size, quint64 fileCount)
{
fileCountForUpdate = 0;
filesLoaded = 0;
fileCountForUpdate = fileCount;
QString availableSizeText;
if (flag){
QString result = tr("Доступно обновление: ") + Tools::convertFileSize(size);
result += tr("Количество файлов: ") + QString::number(fileCount);
ui->inlineTextDebug->setText(result);
ui->updateButton->show();
ui->autostartCheckBox->show();
}
else
{
ui->inlineTextDebug->setText(tr("Установлена последняя версия"));
ui->loadingProgressBar->setMaximum(100);
ui->loadingProgressBar->setValue(100);
autoStart();
ui->startButton->show();
ui->offlineStartButton->setGeometry(570,510,220,35);
ui->offlineStartButton->show();
}
ui->updateButton->setEnabled(flag);
ui->startButton->setEnabled(!flag);
}
void MainWindow::lostConnection()
{
ui->loadingProgressBar->setValue(0);
slotConnectionState(false);
}
void MainWindow::serverBlocked()
{
ui->notificationLabel->show();
QPalette palette = ui->notificationLabel->palette();
QColor orangeColor(255,165,0);
palette.setColor(ui->notificationLabel->foregroundRole(),orangeColor);
ui->notificationLabel->setText(tr("Сервер заблокирован"));
ui->notificationLabel->setPalette(palette);
timer->start(3000);
}
void MainWindow::checkLoginResult(ServerAuthorization *serverAuth)
{
if (serverAuth->Result)
{
if (serverAuth->AccessType != "instructor") //временно для отладки загрузки на сервер
{
checkUpdate();
}
dataParser->createAuthData(serverAuth);
ui->loginWidget->hide();
ui->LanguageWidget->hide();
ui->settingsButton->hide();
ui->offlineStartButton->setGeometry(570,510,220,35);
ui->offlineStartButton->show();
}
else
{
ui->notificationLabel->setText(tr("Неверный логин/пароль"));
timer->setInterval(3000);
timer->start();
QPalette palette = ui->notificationLabel->palette();
palette.setColor(ui->notificationLabel->foregroundRole(), Qt::red);
ui->notificationLabel->setPalette(palette);
ui->notificationLabel->show();
}
}
void MainWindow::checkAppAvailable()
{
bool isAvailable = externalExecuter->findApp();
ui->startButton->setEnabled(isAvailable);
ui->offlineStartButton->setEnabled(isAvailable);
}
void MainWindow::checkLanguage(QString language)
{
if (language == "RUS")
{
translator.load("QtLanguage_ru_RU",".");
}
else if(language == "ENG")
{
translator.load("QtLanguage_eng_EN",".");
}
qApp->installTranslator(&translator);
ui->retranslateUi(this);
}
void MainWindow::autoStart()
{
if(ui->autostartCheckBox->isChecked()){
on_startButton_clicked();
}
}
void MainWindow::loadStaticData()
{
ServerSettings *currentSettings = dataParser->getServerSettings();
ui->serverInputField->setText(currentSettings->Address);
ui->portInputField->setText(currentSettings->Port);
ui->languageComboBox->setCurrentText(currentSettings->Language);
ui->autostartCheckBox->setChecked(currentSettings->isAutoStart);
checkLanguage(currentSettings->Language);
}
void MainWindow::slotConnectionState(bool flag)
{
ui->notificationLabel->show();
QPalette palette = ui->notificationLabel->palette();
stopLoadingMovie();
if(flag)
{
palette.setColor(ui->notificationLabel->foregroundRole(),Qt::green);
ui->notificationLabel->setText(tr("Соединение установлено"));
ui->loginWidget->show();
ui->offlineStartButton->show();
ui->offlineStartButton->setGeometry(570,552,220,35);
}
else
{
palette.setColor(ui->notificationLabel->foregroundRole(),Qt::red);
ui->notificationLabel->setText(tr("Соединение отсутсвует"));
ui->offlineWidget->show();
ui->offlineStartButton->show();
ui->offlineStartButton->setGeometry(285,340,220,35);
ui->settingsButton->show();
ui->loginWidget->hide();
}
ui->notificationLabel->setPalette(palette);
timer->start(3000);
}
void MainWindow::slotServerDisconnect()
{
ui->loadingProgressBar->hide();
ui->updateButton->hide();
ui->autostartCheckBox->hide();
ui->inlineTextDebug->setText("");
ui->updateButton->setEnabled(false);
slotConnectionState(false);
}
void MainWindow::slotDisableNotify()
{
ui->notificationLabel->hide();
QPalette palette = ui->notificationLabel->palette();
palette.setColor(ui->notificationLabel->foregroundRole(), Qt::black);
ui->notificationLabel->setPalette(palette);
timer->stop();
}
void MainWindow::callUpdateList()
{
updateController->calculateStreamingHash();
hashComparer->setWidget(updateWidget);
QByteArray answer = dataParser->xmlAnswer_notify("GETSERVERDATALIST");
sendSystem->sendXMLAnswer(answer);
updateWidget->initialize(this);
}
void MainWindow::bindNotifyWidget(UpdateNotifyWidget *widget)
{
updateWidget = widget;
}
void MainWindow::on_loginButton_clicked()
{
if (!client->getIsConnected())
{
QPalette palette = ui->notificationLabel->palette();
palette.setColor(ui->notificationLabel->foregroundRole(),Qt::red);
ui->notificationLabel->setText(tr("Соединение отсутсвует"));
ui->notificationLabel->setPalette(palette);
ui->notificationLabel->show();
ui->offlineWidget->show();
ui->offlineStartButton->show();
ui->offlineStartButton->setGeometry(300,340,220,35);
return;
}
QString username = ui->loginInputField->text();
QString password = ui->passwordInputField->text();
ClientAutorization *autorization = new ClientAutorization;
autorization->Login = username;
autorization->Password = password;
dataParser->createAuthMessage(autorization);
emit sigSendAutorization();
}
void MainWindow::on_updateButton_clicked()
{
emit sigSendCommand("update");
ui->updateButton->hide();
ui->loadingProgressBar->setValue(0);
}
void MainWindow::on_startButton_clicked()
{
externalExecuter->callApp();
sendSystem->sendDisable();
}
void MainWindow::on_saveServerButton_clicked()
{
startLoadingAnim();
ui->settingsWidget->hide();
if(client->getIsConnected())
{
ui->loginWidget->show();
ui->offlineStartButton->show();
stopLoadingMovie();
return;
}
QString server = ui->serverInputField->text();
QString port = ui->portInputField->text();
dataParser->createServerSettings(server,port);
emit sigSetConnect(dataParser->getServerSettings(),connectionThread);
}
void MainWindow::on_settingsButton_clicked()
{
ui->settingsWidget->show();
ui->loginWidget->hide();
ui->offlineWidget->hide();
ui->offlineStartButton->hide();
}
void MainWindow::on_connectButton_clicked()
{
emit sigSetConnect(dataParser->getServerSettings(),connectionThread);
}
void MainWindow::on_languageComboBox_activated(const QString &arg1)
{
qDebug() << arg1;
dataParser->saveClientSettrings(arg1,ui->autostartCheckBox->isChecked());
checkLanguage(arg1);
ui->retranslateUi(this);
}
void MainWindow::on_loadToServerButton_clicked()
{
ui->inlineTextDebug->setText(tr("Отправка файлов..."));
ui->loadingProgressBar->show();
ui->updateButtonGroup_2->hide();
ui->offlineStartButton->hide();
ui->updateWidget->hide();
emit sigUpdateFilesOnServer(hashComparer->getFilesForUpdate());
}
void MainWindow::on_undoChangesButton_clicked()
{
ui->loadingProgressBar->show();
ui->offlineStartButton->hide();
ui->updateButtonGroup_2->hide();
ui->updateWidget->hide();
on_updateButton_clicked();
}
void MainWindow::on_startWithCurrentChangesButton_clicked()
{
on_startButton_clicked();
}
void MainWindow::on_updateListGuideLabel_linkActivated(const QString &link)
{
updateWidget->show();
}
void MainWindow::on_exitButton_clicked()
{
exit(0);
}
void MainWindow::checkUpdate()
{
ui->loadingProgressBar->setValue(0);
ui->loadingProgressBar->show();
emit sigSendCommand("check");
ui->inlineTextDebug->setText(tr("Проверка обновлений..."));
}
void MainWindow::showUpdateInfo()
{
QString text = tr("Есть изменения в локальных файлах <A HREF=\"LINK\">(список)</A> ");
QString list = tr("Возможные действия:\n"
" 1. Загрузить изменения на сервер\n"
" 2. Отменить изменения с загрузкой версии с сервера \n"
" 3. Запустить без отправки файлов, но с текущими изменениями");
ui->updateListGuideLabel->setText(text);
ui->updateActionListLabel->setText(list);
ui->updateWidget->show();
ui->updateButtonGroup_2->show();
ui->offlineStartButton->setGeometry(570,552,220,35);
fileCountForUpdate = hashComparer->getFilesForUpdate()->length();
filesLoaded = 0;
}
void MainWindow::showCompleteDialogBox(bool flag)
{
ui->inlineTextDebug->setText(tr("Загрузка завершена"));
movie->start();
QTime dieTime= QTime::currentTime().addSecs(10);
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
movie->stop();
checkUpdate();
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
{
if (ui->loginInputField->text().length() <= 0 || ui->passwordInputField->text() <= 0) return;
on_loginButton_clicked();
}
}
void MainWindow::painting()
{
QFontDatabase::addApplicationFont(":/resource/Fonts/Kanit Cyrillic.ttf");
QFontDatabase::addApplicationFont(":/resource/Fonts/HelveticaNeue-Medium.ttf");
//settings
QPixmap settingIcon(":resource/Icons/settingWhite.png");
QPainter painter;
QColor color(45,84,130);
painter.begin(&settingIcon);
painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
painter.fillRect(settingIcon.rect(),color);
painter.end();
QIcon icon;
icon.addPixmap(settingIcon,QIcon::Normal,QIcon::Off);
ui->settingsButton->setIcon(icon);
//exit
QPixmap crossPixmap(":resource/Icons/crossInCircle.png");
QPainter painterCross;
painter.begin(&crossPixmap);
painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
painter.fillRect(crossPixmap.rect(),color);
painter.end();
QIcon crossIcon;
crossIcon.addPixmap(crossPixmap,QIcon::Normal,QIcon::Off);
ui->exitButton->setIcon(crossIcon);
//loading
movie = new QMovie(":/resource/Icons/762.gif");
movieLabel = new QLabel("No movie");
movieLabel->setParent(this);
movieLabel->setGeometry(367,300,70,70);
movieLabel->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
movieLabel->setMovie(movie);
startLoadingAnim();
}
void MainWindow::startLoadingAnim()
{
movie->start();
movieLabel->show();
}
void MainWindow::stopLoadingMovie()
{
movie->stop();
movieLabel->hide();
}
MainWindow::~MainWindow()
{
connectionThread->quit();
connectionThread->wait();
sendSystem->sendDisable();
delete connectionThread;
delete ui;
}