CetHub/CetHub/hubmainwidget.cpp

302 lines
12 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 "hubmainwidget.h"
#include "ui_hubmainwidget.h"
#include "QtNetwork/QNetworkReply"
HubMainWidget::HubMainWidget(QWidget *parent, QApplication *app)
: QWidget(parent)
, ui(new Ui::HubMainWidget)
{
ui->setupUi(this);
parentApp = app;
connect(&sysTimer, &QTimer::timeout, this, [this]()
{
ui->dateTimeEdit->setTime(QTime::currentTime());
ui->dateTimeEdit->setDate(QDate::currentDate());
});
sysTimer.start(1000);
setupTableHeaders();
getModules();
}
bool HubMainWidget::getModules()
{
QStringList appDep;
appInfo UnionCom;
UnionCom.appName = "Терминал CAN, RS, Modbus";
UnionCom.fileName = "UnionCom";
UnionCom.fileDir = QDir::currentPath() + "/UnionCom/";
UnionCom.sourceAdr = "https://git.arktika.cyou/Tenocha/UnionComDLL";
UnionCom.downloadAdr = "https://git.arktika.cyou/Tenocha/UnionComDLL/archive/Release.zip";
connectModule(UnionCom);
appInfo M3KTE_TERM;
M3KTE_TERM.appName = "МЗКТЕ Терминал";
M3KTE_TERM.fileName = "M3KTE_TERM";
M3KTE_TERM.fileDir = QDir::currentPath() + "/M3KTE_TERM/";
M3KTE_TERM.sourceAdr = "https://git.arktika.cyou/Tenocha/M3KTE_TERM";
M3KTE_TERM.downloadAdr = "https://git.arktika.cyou/Tenocha/M3KTE_TERM/releases/download/Pre-release/M3KTETERM.rar";
connectModule(M3KTE_TERM);
appInfo LineRingerLib;
LineRingerLib.appName = "Поиск modbus устройств";
LineRingerLib.fileName = "LineRinger";
LineRingerLib.fileDir = QDir::currentPath() + "/LineRinge/";
LineRingerLib.sourceAdr = "https://git.arktika.cyou/Tenocha/LineRingerDLL";
LineRingerLib.downloadAdr = "https://git.arktika.cyou/Tenocha/LineRingerDLL/archive/Release.zip";
connectModule(LineRingerLib);
appInfo CanGaroo;
CanGaroo.appName = "CanGaroo";
CanGaroo.fileName = "cangaroo";
CanGaroo.fileDir = QDir::currentPath() + "/CanGaroo/";
CanGaroo.sourceAdr = "https://git.arktika.cyou/Tenocha/LineRingerDLL";
CanGaroo.downloadAdr = "https://git.arktika.cyou/Tenocha/LineRingerDLL/archive/Release.zip";
connectModule(CanGaroo);
//LogsViewS
appInfo LogsViewS;
LogsViewS.appName = "LogsViewS";
LogsViewS.fileName = "LogsViewS";
LogsViewS.fileDir = QDir::currentPath() + "/LogsViewS/";
LogsViewS.sourceAdr = "http://git.arktika.cyou/Tenocha/LineRingerDLL";
LogsViewS.downloadAdr = "http://git.arktika.cyou/all_public/LogViewNovel/raw/branch/master/LogsView_64/LogsViewS_64.exe";
connectModule(LogsViewS);
ui->appTable->resizeColumnsToContents();
setupTableHeaders();
return true;
}
void HubMainWidget::setupTableHeaders()
{
// Устанавливаем заголовки для каждой колонки
QStringList headers;
headers << "Наличие файла" // колонка 0
<< "Название программы" // колонка 1
<< "Название файла" // колонка 2
<< "Источник"; // колонка 3
ui->appTable->setHorizontalHeaderLabels(headers);
}
void HubMainWidget::connectModule(appInfo &info)
{
// 1. Проверка наличия файла .exe в директории
QString dirPath = info.fileDir; // предполагается, что это уже полный путь
QString filePath = dirPath + "/" + info.fileName;
// Проверяем наличие файла с расширением .exe
QString exeFilePath = filePath + ".exe";
info.isFileExists = QFile::exists(exeFilePath);
// 2. Создаём новую строку таблицы
int row = ui->appTable->rowCount();
ui->appTable->insertRow(row);
// 3. Создаём виджеты и заполняем ячейки таблицы
// 1) Наличие файла (QCheckBox)
QCheckBox *fileCheckBox = new QCheckBox();
fileCheckBox->setChecked(info.isFileExists);
QWidget *fileCellWidget = new QWidget();
QHBoxLayout *fileLayout = new QHBoxLayout(fileCellWidget);
fileLayout->addWidget(fileCheckBox);
fileLayout->setAlignment(Qt::AlignCenter);
fileLayout->setContentsMargins(0,0,0,0);
fileCellWidget->setLayout(fileLayout);
ui->appTable->setCellWidget(row, 0, fileCellWidget);
// 2) Название программы (QString)
QTableWidgetItem *nameItem = new QTableWidgetItem(info.appName);
ui->appTable->setItem(row, 1, nameItem);
// 3) Название файла (QString)
QTableWidgetItem *fileNameItem = new QTableWidgetItem(info.fileName);
ui->appTable->setItem(row, 2, fileNameItem);
// 4) Источник файла (QString из sourceAdr)
QLabel *sourceLabel = new QLabel();
QString linkText = QString("<a href=\"%1\">Source</a>").arg(info.sourceAdr.toString());
sourceLabel->setText(linkText);
sourceLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
sourceLabel->setOpenExternalLinks(true);
ui->appTable->setCellWidget(row, 3, sourceLabel);
// 4. Добавляем структуру в QVector
connectedModules.append(info);
// 5. Добавляем название программы
ui->appBox->addItem(info.appName);
}
HubMainWidget::~HubMainWidget()
{
delete ui;
}
void HubMainWidget::on_openOrDownloadButton_clicked()
{
int index = ui->appBox->currentIndex();
if (index < 0 || index >= connectedModules.size())
return; // Защита
auto &module = connectedModules.at(index);
QString filePath = module.fileDir + "/" + module.fileName + ".exe";
if (QFile::exists(filePath))
{
// // Файл есть, запускаем
QProcess process;
process.setWorkingDirectory(module.fileDir);
process.setProgram(filePath);
process.startDetached();
}
else
{
// Получаем путь к директории
QDir dir(module.fileDir);
// Проверяем, существует ли директория
if (!dir.exists()) {
// Создаём директорию (включая все недостающие промежуточные папки)
if (!dir.mkpath(".")) {
QMessageBox::warning(this, "Ошибка", "Не удалось создать директорию: " + module.fileDir);
return; // Выходим из функции, т.к. сохранить файл невозможно
}
}
// Путь для сохранения файла (включая имя файла и расширение)
QString saveFilePath = filePath;
// Создаем объект Downloader
Downloader downloader;
// Создаем диалог прогресса
QProgressDialog progressDialog;
progressDialog.setWindowTitle("Downloading");
progressDialog.setLabelText("Downloading file:\n" + module.downloadAdr.toString() + "...");
progressDialog.setCancelButton(new QPushButton("Cancel"));
progressDialog.setMinimumDuration(200);
// Связываем прогресс скачивания с диалогом
QObject::connect(&downloader, &Downloader::downloadProgress, [&](qint64 bytesReceived, qint64 bytesTotal) {
progressDialog.setMaximum(bytesTotal);
progressDialog.setValue(bytesReceived);
});
// Обработка завершения скачивания
QObject::connect(&downloader, &Downloader::downloadFinished, [&](bool success) {
if (success) {
QMessageBox::information(nullptr, "Загрузка завершена", "Файл успешно скачан:\n" + saveFilePath);
QWidget *statusWidget = ui->appTable->cellWidget(index, 0);
if (statusWidget) {
QCheckBox *statusCheckBox = statusWidget->findChild<QCheckBox *>();
if (statusCheckBox) {
statusCheckBox->setChecked(true); // файл есть
}
on_appBox_currentIndexChanged(ui->appBox->currentIndex());
}
} else {
QMessageBox::warning(nullptr, "Ошибка", "Ошибка при скачивании файла");
QFile::remove(saveFilePath); // удаляем поврежденный или неполный файл
if (dir.exists()) {
if (!dir.removeRecursively()) {
QMessageBox::warning(this, "Ошибка", "Не удалось удалить созданную директорию: " + module.fileDir);
}
}
}
progressDialog.setValue(progressDialog.maximum());
progressDialog.close();
});
// Запускаем скачивание
qDebug() << "Start download:" << module.downloadAdr.toString() << " to " << saveFilePath;
downloader.downloadFile(module.downloadAdr, saveFilePath);
// Показываем диалог прогресса
progressDialog.exec();
// // Файл отсутствует, скачиваем
// QUrl downloadUrl(module.downloadAdr);
// QNetworkRequest request(downloadUrl);
// QNetworkReply *reply = networkManager->get(request);
// // Ожидаем завершения скачивания
// QEventLoop loop;
// connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
// loop.exec();
// if (reply->error() == QNetworkReply::NoError)
// {
// QByteArray data = reply->readAll();
// // Получаем путь к директории
// QDir dir(module.fileDir);
// // Проверяем, существует ли директория
// if (!dir.exists()) {
// // Создаём директорию (включая все недостающие промежуточные папки)
// if (!dir.mkpath(".")) {
// QMessageBox::warning(this, "Ошибка", "Не удалось создать директорию: " + module.fileDir);
// return; // Выходим из функции, т.к. сохранить файл невозможно
// }
// }
// // Записываем файл
// QFile file(filePath);
// if (file.open(QIODevice::WriteOnly))
// {
// file.write(data);
// file.close();
// QMessageBox::information(this, "Загрузка завершена", "Файл успешно скачан.");
// // После скачивания можно запустить файл
// //QProcess::startDetached(filePath);
// // Обновляем статус наличия файла (чекбокс)
// QWidget *statusWidget = ui->appTable->cellWidget(index, 0);
// if (statusWidget) {
// QCheckBox *statusCheckBox = statusWidget->findChild<QCheckBox *>();
// if (statusCheckBox) {
// statusCheckBox->setChecked(true); // файл есть
// }
// }
// connectedModules[index].isFileExists = true;
// on_appBox_currentIndexChanged(ui->appBox->currentIndex());
// }
// else
// {
// QMessageBox::warning(this, "Ошибка", "Не удалось сохранить файл.");
// }
// }
// else
// {
// QMessageBox::warning(this, "Ошибка загрузки", reply->errorString());
// }
// reply->deleteLater();
}
}
void HubMainWidget::on_appBox_currentIndexChanged(int index)
{
if (index < 0 || index >= connectedModules.size())
return; // Защита от выхода за границы
const appInfo &info = connectedModules.at(index);
if (info.isFileExists)
{
ui->openOrDownloadButton->setText("Открыть");
}
else
{
ui->openOrDownloadButton->setText("Скачать");
}
}