Добавлена реализация базовых профилей (Имя, путь до java)

This commit is contained in:
2025-10-26 20:00:25 +03:00
parent 0d18e48783
commit 3b3d9e7af0
7 changed files with 365 additions and 3 deletions

View File

@@ -1,6 +1,7 @@
#include "mainwindow.h"
#include "ui_mainwindow.h" // Подключаем сгенерированный заголовочный файл
#include "settingsdialog.h"
#include "profiledialog.h" // Подключаем новый диалог
#include <QMessageBox>
#include <QDesktopServices>
@@ -12,6 +13,8 @@
#include <QJsonObject> // Для работы с JSON
#include <QJsonArray> // Для работы с JSON
#include <QJsonValue> // Для работы с JSON
#include <QUuid> // Для генерации ID профиля
#include <QStandardPaths> // Для поиска папки с данными
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
@@ -32,6 +35,9 @@ MainWindow::MainWindow(QWidget *parent)
connect(process, &QProcess::readyReadStandardError, this, &MainWindow::readProcessOutput);
connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onProcessFinished(int, QProcess::ExitStatus)));
connect(process, SIGNAL(errorOccurred(QProcess::ProcessError)), this, SLOT(onProcessError(QProcess::ProcessError)));
// Загружаем профили при старте
profilesPath = "/launcher_profiles.json";
loadProfiles();
}
MainWindow::~MainWindow()
@@ -86,8 +92,146 @@ bool checkRules(const QJsonObject &item) {
return isAllowed;
}
void MainWindow::loadProfiles()
{
QFile profilesFile(profilesPath);
if (profilesFile.exists() && profilesFile.open(QIODevice::ReadOnly)) {
QJsonDocument doc = QJsonDocument::fromJson(profilesFile.readAll());
profilesData = doc.object();
profilesFile.close();
} else {
// Создаем базовую структуру, если файла нет
profilesData = QJsonObject({{"profiles", QJsonObject()}});
}
QJsonObject profiles = profilesData["profiles"].toObject();
ui->profileComboBox->clear();
if (profiles.isEmpty()) {
// Если профилей нет, принудительно открываем диалог создания
QMessageBox::information(this, "Настройка", "Не найдено ни одного профиля. Давайте создадим новый.");
createNewProfile();
return; // createNewProfile вызовет loadProfiles() повторно
}
// Заполняем ComboBox
for (const QString &key : profiles.keys()) {
QJsonObject profile = profiles[key].toObject();
ui->profileComboBox->addItem(profile["name"].toString(), key); // Имя и UUID
}
}
void MainWindow::saveProfiles()
{
QFile profilesFile(profilesPath);
if (profilesFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
QJsonDocument doc(profilesData);
profilesFile.write(doc.toJson(QJsonDocument::Indented));
profilesFile.close();
} else {
QMessageBox::critical(this, "Ошибка", "Не удалось сохранить файл профилей: " + profilesFile.errorString());
}
}
void MainWindow::on_editProfileButton_clicked()
{
// 1. Проверяем, выбран ли профиль
QString currentProfileId = ui->profileComboBox->currentData().toString();
if (currentProfileId.isEmpty()) {
QMessageBox::warning(this, "Нет профиля", "Пожалуйста, выберите профиль для редактирования.");
return;
}
// 2. Получаем данные текущего профиля
QJsonObject profiles = profilesData["profiles"].toObject();
QJsonObject currentProfile = profiles[currentProfileId].toObject();
// 3. Создаем диалог и заполняем его данными
ProfileDialog dialog(this);
dialog.setWindowTitle("Редактирование профиля");
dialog.setProfileName(currentProfile["name"].toString());
dialog.setJavaPath(currentProfile["javaDir"].toString());
// 4. Показываем диалог и обрабатываем результат
if (dialog.exec() == QDialog::Accepted) {
if (dialog.profileName().isEmpty() || dialog.javaPath().isEmpty()) {
QMessageBox::warning(this, "Ошибка", "Имя профиля и путь к Java не могут быть пустыми.");
return;
}
// 5. Обновляем данные в нашем JSON объекте
currentProfile["name"] = dialog.profileName();
currentProfile["javaDir"] = dialog.javaPath();
// 6. Записываем обновленный профиль обратно
profiles[currentProfileId] = currentProfile;
profilesData["profiles"] = profiles;
// 7. Сохраняем и перезагружаем список
saveProfiles();
// Сохраняем ID, чтобы восстановить выбор после перезагрузки
QString previouslySelectedId = currentProfileId;
loadProfiles();
int indexToSelect = ui->profileComboBox->findData(previouslySelectedId);
if (indexToSelect != -1) {
ui->profileComboBox->setCurrentIndex(indexToSelect);
}
}
}
void MainWindow::createNewProfile()
{
ProfileDialog dialog(this);
if (dialog.exec() == QDialog::Accepted) {
if (dialog.profileName().isEmpty() || dialog.javaPath().isEmpty()) {
QMessageBox::warning(this, "Ошибка", "Имя профиля и путь к Java не могут быть пустыми.");
return;
}
QString uuid = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject newProfile;
newProfile["name"] = dialog.profileName();
newProfile["javaDir"] = dialog.javaPath();
newProfile["lastVersionId"] = "";
newProfile["created"] = QDateTime::currentDateTime().toString(Qt::ISODate);
newProfile["lastUsed"] = QDateTime::currentDateTime().toString(Qt::ISODate);
newProfile["icon"] = "Bedrock";
newProfile["type"] = "custom";
QJsonObject profiles = profilesData["profiles"].toObject();
profiles[uuid] = newProfile;
profilesData["profiles"] = profiles;
saveProfiles();
loadProfiles(); // Перезагружаем список профилей
}
}
void MainWindow::on_addProfileButton_clicked()
{
createNewProfile();
}
void MainWindow::on_profileComboBox_currentIndexChanged(int index)
{
// Пока ничего не делаем, но слот полезен для будущего
Q_UNUSED(index);
}
void MainWindow::on_launchButton_clicked()
{
QString currentProfileId = ui->profileComboBox->currentData().toString();
if (currentProfileId.isEmpty()) {
QMessageBox::critical(this, "Ошибка", "Не выбран профиль для запуска!");
return;
}
QJsonObject profile = profilesData["profiles"].toObject()[currentProfileId].toObject();
QString javaPath = profile["javaDir"].toString();
if (!QFileInfo::exists(javaPath)) {
QMessageBox::critical(this, "Ошибка", "Не найден исполняемый файл Java, указанный в профиле:\n" + javaPath);
return;
}
// --- 1. Выбор версии (остается без изменений) ---
QString minecraftPath = getMinecraftPath();
if (minecraftPath.isEmpty()) {
@@ -229,7 +373,7 @@ void MainWindow::on_launchButton_clicked()
// --- 6. Финальная сборка и запуск ---
QString mainClass = rootObj["mainClass"].toString();
QString javaPath = "java";
//QString javaPath = "java";
QStringList finalArguments;
finalArguments << jvmArgs << mainClass << gameArgs;