Files
RRJClient/mainwindow.cpp
2025-07-24 14:59:25 +03:00

637 lines
18 KiB
C++

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFontDatabase>
#include <QMessageBox>
#include <QMovie>
#include <QPaintEvent>
#include <QPainter>
#include <QTimer>
#include <Widgets/updatenotifywidget.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
ui(new Ui::MainWindow),
bottomRightPosition(QRect(530,505,250,40))
{
ui->setupUi(this);
isRecovery = false;
setAttribute(Qt::WA_TranslucentBackground);
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
_background.load(":/resource/SSJ_backgroundDarkSM.png");
}
void MainWindow::createObjects()
{
qRegisterMetaType<PacketType>("PacketType");
updateWidget = new UpdateNotifyWidget;
updateWidget->setParent(this);
commonButtonGroupWidget = new CommonButtonGroupWidget;
entryWidget = new EntryWidget;
versionSelectWidget = new VersionSelectWidget;
waitAnimationWidget = new WaitAnimationWidget;
waitAnimationWidget->setParent(this);
ui->changButtonGroup->addWidget(commonButtonGroupWidget);
ui->interactiveGroup->addWidget(entryWidget);
workerThread = new QThread;
animationThread = new QThread;
client = new TCPClient;
client->moveToThread(workerThread);
notifyController = new NotifyController;
notifyController->setParent(this);
dataParser = new DataParser;
dataParser->moveToThread(workerThread);
sendSystem = new SendSystem;
sendSystem->moveToThread(workerThread);
updateController = new UpdateController(dataParser,sendSystem);
updateController->moveToThread(workerThread);
recognizeSystem = new RecognizeSystem;
recognizeSystem->moveToThread(workerThread);
screenChecker = new ScreenChecker(this,dataParser,ui->displayLayout);
externalExecuter = new ExternalExecuter;
hashComparer = new HashComparer(dataParser);
hashComparer->moveToThread(workerThread);
versionContainer = new VersionContainer;
resourceManager = new ResourceManager;
workerThread->start();
workerThread->setPriority(QThread::HighestPriority);
timer = new QTimer;
}
void MainWindow::paintEvent(QPaintEvent* event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
path.addRoundedRect(rect(), 8, 8);
painter.setClipPath(path);
if (!_background.isNull())
{
int x = (width() - _background.width()) / 2;
int y = (height() - _background.height()) / 2;
painter.drawPixmap(x, y, _background);
}
}
void MainWindow::initialize()
{
createObjects();
loadStaticData();
bindConnection();
updateWidget->initialize(this,versionContainer);
entryWidget->initialize(this);
versionSelectWidget->initialize(sendSystem,versionContainer,notifyController);
hashComparer->initialize(this,versionContainer);
updateController->initialize(this,versionContainer);
sendSystem->initialize(this,dataParser);
dataParser->initialize(recognizeSystem,notifyController,updateController,hashComparer);
recognizeSystem->initialize(updateController,dataParser,this,hashComparer,client,versionContainer);
resourceManager->painting();
commonButtonGroupWidget->initialize(this,externalExecuter,sendSystem,client);
commonButtonGroupWidget->show();
ui->LanguageWidget->hide();
setUpUi();
setInlineDebug(tr("Инициализация..."));
emit sigCalculateHash();
emit sigInitializeClient(this,recognizeSystem,externalExecuter,sendSystem,workerThread);
screenChecker->check();
emit sigSetConnect(dataParser->getClientSettings(),workerThread);
checkAppAvailable();
//post
QString title = tr("Тренажер процедур технического обслуживания самолета RRJ-95NEW-100");
ui->headerLabel->setText(title);
ui->versionLayoutWidget->hide();
}
void MainWindow::bindConnection()
{
connect(timer,&QTimer::timeout,this,&MainWindow::slotDisableNotify);
connect(this,&MainWindow::sigInitializeClient,client,&TCPClient::initialize,Qt::AutoConnection);
connect(this,&MainWindow::sigSetConnect,client,&TCPClient::setConnect,Qt::AutoConnection);
connect(this,&MainWindow::sigSendCommand,sendSystem,&SendSystem::sendPacketType,Qt::AutoConnection);
connect(this,&MainWindow::sigSendCheck,sendSystem,&SendSystem::sendCheckHash,Qt::AutoConnection);
connect(this,&MainWindow::sigSendXMLAnswer,sendSystem,&SendSystem::xmlAnswer,Qt::AutoConnection);
connect(this,&MainWindow::sigSendAutorization,sendSystem,&SendSystem::sendClientAutorization);
connect(this,&MainWindow::sigSendCheckUpdate,updateController,&UpdateController::checkCanUpdate,Qt::AutoConnection);
connect(this,&MainWindow::sigGetConnected,client,&TCPClient::getIsConnected);
connect(this,&MainWindow::sigCalculateHash,updateController,&UpdateController::calculateCommonHash);
connect(versionContainer,&VersionContainer::sigSetServerVersion,this,&MainWindow::setServerVersion);
}
void MainWindow::updateProgress()
{
filesLoaded++;
float value = 100 / ((float)fileCountForUpdate / filesLoaded);
commonButtonGroupWidget->updateProgressBar(value);
}
void MainWindow::loadComplete()
{
externalExecuter->findApp();
commonButtonGroupWidget->loadCompleteState();
autoStart();
ui->inlineTextDebug->setText(tr("Обновление завершено"));
ui->offlineStartButton->setEnabled(true);
ui->autostartCheckBox->hide();
ui->offlineStartButton->show();
dataParser->changeVersion(versionContainer->getServerVersionData());
setTitle();
}
void MainWindow::setNeedUpdate(bool flag,quint64 size, quint64 fileCount,quint64 deleteCount)
{
fileCountForUpdate = 0;
filesLoaded = 0;
fileCountForUpdate = fileCount;
QString availableSizeText;
if (flag && isRecovery)
{
ui->inlineTextDebug->setText(tr("Восстановление версии..."));
}
else if(flag)
{
QString result;
if(fileCount > 0)
{
result = tr("Доступно обновление: ") + Tools::convertFileSize(size);
//result += tr("Количество файлов: ") + QString::number(fileCount);
}
else
{
result = tr("Файлов к удалению: ") + QString::number(deleteCount);
}
ui->inlineTextDebug->setText(result);
commonButtonGroupWidget->needUpdateState(flag);
ui->autostartCheckBox->show();
activateLoadingAnimation(false);
setTitle();
}
else
{
ui->inlineTextDebug->setText(tr("Установлена последняя версия"));
autoStart();
commonButtonGroupWidget->lastVerInstalledState();
ui->unsafeChangingButton->hide();
ui->offlineStartButton->setEnabled(true);
dataParser->changeVersion(versionContainer->getServerVersionData());
activateLoadingAnimation(false);
setTitle();
}
}
void MainWindow:: showServerListWidget(QList<StreamingVersionData *> *serverData)
{
entryWidget->hide();
activateLoadingAnimation(false);
versionSelectWidget->fillView(serverData);
}
void MainWindow::lostConnection()
{
commonButtonGroupWidget->updateProgressBar(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();
}
else
{
emit sigSendXMLAnswer(cmd_CheckVersionList);
}
dataParser->createAuthData(serverAuth);
entryWidget->loginIsActive(false);
//ui->LanguageWidget->hide();
ui->settingsButton->hide();
ui->offlineStartButton->show();
activateLoadingAnimation(true);
setTitle();
}
else
{
entryWidget->loginIsActive(true);
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();
commonButtonGroupWidget->startButtonActive(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()){
startUnityClient();
}
}
void MainWindow::setTitle()
{
ui->versionLayoutWidget->show();
ServerSettings *currentSettings = dataParser->getClientSettings();
StreamingVersionData *versionData = new StreamingVersionData;
versionData->setName(currentSettings->LocalVersionName);
versionData->setIsChangeable(currentSettings->versionData.getIsChangeable());
versionContainer->setLocalVersionData(versionData);
ui->valueClientVersion->setText(versionContainer->getLocalVersion());
//title.append(" (" + currentSettings->LocalVersionName + ")");
}
void MainWindow::loadStaticData()
{
ServerSettings *currentSettings = dataParser->getClientSettings();
entryWidget->fillSettings(currentSettings);
ui->languageComboBox->setCurrentText(currentSettings->Language);
ui->autostartCheckBox->setChecked(currentSettings->isAutoStart);
checkLanguage(currentSettings->Language);
}
void MainWindow::showConnectionEmpty()
{
QPalette palette = ui->notificationLabel->palette();
palette.setColor(ui->notificationLabel->foregroundRole(),Qt::red);
ui->notificationLabel->setText(tr("Соединение отсутсвует"));
entryWidget->connectionEmptyState();
updateWidget->hide();
ui->offlineStartButton->show();
ui->offlineStartButton->setGeometry(280,340,250,40);
ui->offlineStartButton->raise();
ui->settingsButton->show();
ui->unsafeChangingButton->hide();
versionSelectWidget->hide();
}
void MainWindow::disableUnsaveButton(bool flag)
{
if(!flag) ui->unsafeChangingButton->show();
else ui->unsafeChangingButton->hide();
}
void MainWindow::slotConnectionState(bool flag)
{
ui->notificationLabel->show();
QPalette palette = ui->notificationLabel->palette();
ui->versionLayoutWidget->hide();
activateLoadingAnimation(false);
setInlineDebug("");
if(flag)
{
palette.setColor(ui->notificationLabel->foregroundRole(),Qt::green);
ui->notificationLabel->setText(tr("Соединение установлено"));
entryWidget->loginIsActive(true);
ui->offlineStartButton->show();
ui->offlineStartButton->setGeometry(bottomRightPosition);
}
else
{
showConnectionEmpty();
}
ui->notificationLabel->setPalette(palette);
timer->start(3000);
}
void MainWindow::slotServerDisconnect()
{
commonButtonGroupWidget->disconnectState();
ui->autostartCheckBox->hide();
ui->inlineTextDebug->setText("");
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()
{
hashComparer->setWidget(updateWidget);
emit sigSendXMLAnswer(cmd_GetServerHash);
}
void MainWindow::login()
{
if (!client->getIsConnected())
{
showConnectionEmpty();
return;
}
entryWidget->loginIsActive(false);
ClientAutorization *autorization = entryWidget->getAuthData();
dataParser->createAuthMessage(autorization);
emit sigSendAutorization();
}
void MainWindow::saveServerSettingsWithConnect()
{
activateLoadingAnimation(true);
entryWidget->isActive(false);
ServerSettings *settings = entryWidget->getServerSettings();
settings->LocalVersionName = dataParser->getClientSettings()->LocalVersionName;
dataParser->createServerSettings(settings);
if(client->getIsConnected())
{
entryWidget->loginIsActive(true);
ui->offlineStartButton->show();
activateLoadingAnimation(false);
}
else
{
emit sigSetConnect(settings,workerThread);
}
//TODO: не заполняется 2 поля (автостарт и язык)
}
void MainWindow::on_settingsButton_clicked()
{
entryWidget->settingsState();
entryWidget->isActive(true);
ui->offlineStartButton->hide();
}
void MainWindow::on_languageComboBox_activated(const QString &arg1)
{
qDebug() << arg1;
dataParser->saveClientSettrings(arg1,ui->autostartCheckBox->isChecked());
checkLanguage(arg1);
ui->retranslateUi(this);
}
void MainWindow::loadToServer()
{
ui->mainFrame->show();
ui->inlineTextDebug->setText(tr("Отправка файлов..."));
commonButtonGroupWidget->showProgressBar(true);
ui->offlineStartButton->setEnabled(false);
updateWidget->hide();
ui->unsafeChangingButton->hide();
emit sigSendCheckUpdate();
}
void MainWindow::undoCurrentChanges()
{
isRecovery = true;
emit sigSendCheck();
ui->mainFrame->show();
commonButtonGroupWidget->showProgressBar(true);
ui->offlineStartButton->setEnabled(false);
updateWidget->hide();
activateLoadingAnimation(true);
//delay
QTime dieTime= QTime::currentTime().addSecs(10);
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
activateLoadingAnimation(true);
emit sigSendCommand(PacketType::TYPE_UPDATE);
commonButtonGroupWidget->startUpdateState();
isRecovery = false;
activateLoadingAnimation(false);
}
void MainWindow::on_unsafeChangingButton_clicked()
{
//checkUpdate();
showUpdateInfo();
updateWidget->show();
}
void MainWindow::on_exitButton_clicked()
{
workerThread->quit();
workerThread->wait();
emit sigSendXMLAnswer(cmd_Disable);
delete workerThread;
delete ui;
exit(0);
}
void MainWindow::checkUpdate()
{
emit sigSendCheck();
ui->inlineTextDebug->setText(tr("Проверка обновлений..."));
}
void MainWindow::showUpdateInfo()
{
activateLoadingAnimation(false);
updateWidget->showWithFill();
showMainFrame(false);
ui->unsafeChangingButton->show();
entryWidget->hide();
commonButtonGroupWidget->show();
ui->offlineStartButton->setGeometry(bottomRightPosition);
fileCountForUpdate = hashComparer->getFileUpdateCount();
filesLoaded = 0;
}
void MainWindow::showCompleteDialogBox()
{
ui->inlineTextDebug->setText(tr("Загрузка завершена"));
activateLoadingAnimation(true);
}
void MainWindow::startUnityClient()
{
externalExecuter->callApp();
emit sigSendXMLAnswer("DISABLE");
}
void MainWindow::setCurrentVersionName(StreamingVersionData *version)
{
versionContainer->setLocalVersionData(version);
}
void MainWindow::setUpUi()
{
ui->notificationLabel->hide();
ui->unsafeChangingButton->hide();
ui->offlineStartButton->show();
ui->offlineStartButton->setEnabled(false);
ui->offlineStartButton->setGeometry(bottomRightPosition);
ui->settingsButton->setIcon(*resourceManager->getSettingsIcon());
QSize cautionIconSize(30,30);
ui->unsafeChangingButton->setIcon(*resourceManager->getUnsavedIcon());
ui->unsafeChangingButton->setIconSize(cautionIconSize);
waitAnimationWidget->setMovie(resourceManager->getMovie());
QSize iconSize(20,20);
ui->exitButton->setIcon(*resourceManager->getCloseIcon());
ui->exitButton->setIconSize(iconSize);
ui->displayGroupWidget->show();
ui->autostartCheckBox->hide();
activateLoadingAnimation(true);
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
{
if (entryWidget->isLoginFieldsFill()) return;
login();
}
}
void MainWindow::activateLoadingAnimation(bool flag)
{
if (flag)
{
waitAnimationWidget->showWithPlay();
}
else
{
waitAnimationWidget->hideWithStop();
}
}
void MainWindow::showMainFrame(bool flag)
{
if (flag) ui->mainFrame->show();
else ui->mainFrame->hide();
}
void MainWindow::setInlineDebug(QString value)
{
ui->inlineTextDebug->setText(value);
}
void MainWindow::setServerVersion(StreamingVersionData *version)
{
ui->valueServerVersion->setText(version->getViewName());
}
MainWindow::~MainWindow()
{
workerThread->quit();
workerThread->wait();
emit sigSendXMLAnswer(cmd_Disable);
delete workerThread;
delete ui;
}
void MainWindow::on_offlineStartButton_clicked()
{
QString username = "offlineUser";
QString password = "000000";
dataParser->createAuthDataOffline(username,password);
startUnityClient();
}