cleanups
tests / package-smoke-linux (push) Skipped
tests / package-smoke-windows (push) Skipped
tests / package-smoke-macos (push) Skipped
tests / linux (push) Successful in 2m22s
tests / macos (push) Successful in 2m29s
tests / windows (push) Successful in 4m31s
tests / package-smoke-linux (push) Skipped
tests / package-smoke-windows (push) Skipped
tests / package-smoke-macos (push) Skipped
tests / linux (push) Successful in 2m22s
tests / macos (push) Successful in 2m29s
tests / windows (push) Successful in 4m31s
Signed-off-by: galeon <dertiellis@gmail.com>
This commit is contained in:
1 parent
5635dcc558
commit
98344a1870
15 files changed
+38
-480
No files matched your search
+5
-171
@@ -42,16 +42,10 @@ const QString kOffline = QStringLiteral("offline");
|
||||
const QString kElyBy = QStringLiteral("elyby");
|
||||
const QString kMicrosoft = QStringLiteral("microsoft");
|
||||
|
||||
// Токен Minecraft живёт около суток, но обновляем его чуть раньше срока: игра
|
||||
// проверяет сессию не в первую секунду после старта.
|
||||
const int kTokenRenewMarginSecs = 120;
|
||||
|
||||
// Сервер готовых сборок по умолчанию. Переопределяется ключом seasonalBaseUrl
|
||||
// в settings.json — это нужно, чтобы прогонять установку против локального
|
||||
// http-сервера, не трогая боевой.
|
||||
const QString kSeasonalBaseUrl = QStringLiteral("https://launcher-builds.galeonworx.com");
|
||||
|
||||
// Тип авторизации профиля: всё, что лаунчер не знает, считается офлайном.
|
||||
QString normalizedAuthType(const QString &value)
|
||||
{
|
||||
if (value == kElyBy)
|
||||
@@ -61,7 +55,6 @@ QString normalizedAuthType(const QString &value)
|
||||
return kOffline;
|
||||
}
|
||||
|
||||
// Дата сезона в таблице: год нужен, время — нет.
|
||||
QString formatSeasonDate(const QDate &date)
|
||||
{
|
||||
return date.isValid() ? date.toString(QStringLiteral("dd.MM.yyyy")) : QStringLiteral("—");
|
||||
@@ -92,32 +85,20 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
, m_seasonalMeta(new SeasonalBuildService(this))
|
||||
, m_packDownloader(new SeasonalPackDownloader(this))
|
||||
{
|
||||
// Папка лаунчера создаётся при первом запуске и проверяется при каждом
|
||||
// следующем — если её удалили, она появится снова.
|
||||
QString storageError;
|
||||
if (!LauncherPaths::ensureRootExists(&storageError))
|
||||
m_storageIssues << Loc::text("storage.error.launcherDirFailed").arg(storageError);
|
||||
|
||||
// Первый запуск — ни настроек, ни списка сборок, ни старого versions.json.
|
||||
// Смотреть надо до loadData(): битый файл она отводит в .bak, а
|
||||
// ensureDataFiles() создаёт пустые. Пустой customBuilds.json — это уже
|
||||
// решение пользователя «сборок нет», и сборку из папки игры мы не заводим.
|
||||
const bool firstRun = !QFile::exists(LauncherPaths::settingsFile())
|
||||
&& !QFile::exists(LauncherPaths::customBuildsFile())
|
||||
&& !QFile::exists(LauncherPaths::legacyCustomBuildsFile());
|
||||
|
||||
loadSettings();
|
||||
// Порядок важен: миграция должна успеть до того, как ensureDataFiles()
|
||||
// создаст пустой customBuilds.json поверх старых данных.
|
||||
migrateLegacyBuildsFile();
|
||||
loadData();
|
||||
const QString importedBuild = firstRun && m_builds.isEmpty() ? importGameDir() : QString();
|
||||
ensureDataFiles();
|
||||
|
||||
// Прошлое переключение оборвалось на середине. Доигрываем его сами, а не
|
||||
// предлагаем пользователю переключиться заново: архив прежней сборки уже
|
||||
// записан целиком, а вот повторное переключение сначала заархивировало бы
|
||||
// поверх него нынешнее — наполовину разобранное — содержимое .minecraft.
|
||||
const QString interrupted = m_switcher->interruptedSwitchWarning();
|
||||
if (!interrupted.isEmpty()) {
|
||||
m_storageIssues << interrupted;
|
||||
@@ -190,23 +171,17 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
});
|
||||
connect(m_installer, &VersionInstaller::progressChanged,
|
||||
this, &LauncherBackend::downloadChanged);
|
||||
// Порядок важен: на installedVersionsChanged интерфейс перечитывает каталог,
|
||||
// и устаревший кэш вернулся бы наружу.
|
||||
connect(m_installer, &VersionInstaller::finished, this, [this](const QString &id) {
|
||||
invalidateCatalog();
|
||||
emit installedVersionsChanged();
|
||||
emit downloadChanged();
|
||||
emit busyChanged();
|
||||
emit launchProgress(Loc::text("version.status.downloaded").arg(id));
|
||||
// У ванильной сезонной сборки этот установщик и есть весь шаг Loader.
|
||||
// Внутри установки модлоадера он тоже отчитывается — тогда ход
|
||||
// передаст ModLoaderInstaller, а не он.
|
||||
if (m_season.stage == SeasonStage::Loader && !m_loaderInstaller->isRunning())
|
||||
seasonAdvance();
|
||||
});
|
||||
connect(m_installer, &VersionInstaller::failed, this, [this](const QString &id,
|
||||
const QString &message) {
|
||||
// Часть файлов всё же появилась — список установленного мог измениться.
|
||||
invalidateCatalog();
|
||||
emit installedVersionsChanged();
|
||||
emit downloadChanged();
|
||||
@@ -220,8 +195,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
emit busyChanged();
|
||||
});
|
||||
connect(m_switcher, &BuildSwitcher::finished, this, [this](int toBuildId) {
|
||||
// Активной сборка становится только здесь: провалившееся переключение
|
||||
// оставляет активной прежнюю.
|
||||
m_settings.insert(QStringLiteral("activeBuildId"), toBuildId);
|
||||
saveSettings();
|
||||
invalidateCatalog();
|
||||
@@ -233,8 +206,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
emit launchProgress(Loc::text("build.status.active")
|
||||
.arg(index >= 0 ? m_builds[index].name : QString()));
|
||||
|
||||
// Раскатка пака могла быть и той, что доигралась после перезапуска —
|
||||
// тогда цепочки установки уже нет, а записать ревизию всё равно надо.
|
||||
const QJsonObject note = m_switcher->lastPackNote();
|
||||
if (!note.isEmpty())
|
||||
recordSeasonalPack(toBuildId, note, m_switcher->lastPackEntries());
|
||||
@@ -250,10 +221,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
emit installedVersionsChanged();
|
||||
emit switchChanged();
|
||||
emit busyChanged();
|
||||
// Раскатка пака и смена сборки приходят одним сигналом, а
|
||||
// сказать пользователю надо разное: после сорванного
|
||||
// переключения .minecraft лежит разобранной, а сорванная
|
||||
// раскатка означает лишь наполовину обновлённую сборку.
|
||||
if (m_season.stage == SeasonStage::Applying) {
|
||||
emit launchError(gameDirIntact
|
||||
? Loc::text("build.error.filesNotInstalled").arg(message)
|
||||
@@ -276,8 +243,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
connect(m_loaderMeta, &ModLoaderVersionService::refreshingChanged,
|
||||
this, &LauncherBackend::downloadChanged);
|
||||
|
||||
// Установщик лоадера делит панель прогресса и флаг занятости с обычным
|
||||
// установщиком версий — сигналы у них одни и те же.
|
||||
connect(m_loaderInstaller, &ModLoaderInstaller::started, this, [this](const QString &label) {
|
||||
emit busyChanged();
|
||||
emit downloadChanged();
|
||||
@@ -343,8 +308,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
this, &LauncherBackend::invalidateSeasonalCatalog);
|
||||
connect(m_seasonalMeta, &SeasonalBuildService::refreshingChanged,
|
||||
this, &LauncherBackend::seasonalCatalogLoadingChanged);
|
||||
// Статус строки («установлена», «доступно обновление») считается по
|
||||
// локальным записям — их изменение обновляет и таблицу.
|
||||
connect(this, &LauncherBackend::customBuildsChanged,
|
||||
this, &LauncherBackend::invalidateSeasonalCatalog);
|
||||
|
||||
@@ -379,8 +342,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
||||
seasonFail({});
|
||||
});
|
||||
|
||||
// Интерфейс подключается к сигналам уже после конструктора — сообщаем отложенно.
|
||||
// Ошибки хранилища идут следом: плашка одна, и важнее показать их.
|
||||
if (!importedBuild.isEmpty()) {
|
||||
QTimer::singleShot(0, this, [this, importedBuild] { emit gameDirImported(importedBuild); });
|
||||
}
|
||||
@@ -448,8 +409,6 @@ void LauncherBackend::addCustomBuild(const QString &name,
|
||||
m_builds.append(build);
|
||||
saveCustomBuilds();
|
||||
emit customBuildsChanged();
|
||||
// Без версии игры ставить нечего: launchVersionIdOf() вернул бы имя сборки,
|
||||
// и установщик пошёл бы искать в манифесте «Сборка 1».
|
||||
if (!minecraftVersion.trimmed().isEmpty())
|
||||
maybeInstall(minecraftVersion.trimmed());
|
||||
}
|
||||
@@ -466,15 +425,11 @@ void LauncherBackend::updateProfile(int index,
|
||||
Profile &profile = m_profiles[index];
|
||||
const QString type = normalizedAuthType(authType);
|
||||
|
||||
// Смена логина или пароля обесценивает сохранённый токен Ely.by. У аккаунта
|
||||
// Microsoft ни того ни другого нет, и переименование профиля не должно
|
||||
// выкидывать из аккаунта.
|
||||
if (profile.authType == kElyBy && (profile.login != login || profile.password != password)) {
|
||||
profile.accessToken.clear();
|
||||
profile.uuid.clear();
|
||||
profile.resolvedName.clear();
|
||||
}
|
||||
// Смена типа авторизации: чужие учётные данные к новому типу не подходят.
|
||||
if (profile.authType != type) {
|
||||
profile.accessToken.clear();
|
||||
profile.refreshToken.clear();
|
||||
@@ -509,8 +464,6 @@ void LauncherBackend::updateCustomBuild(int index, const QVariantMap &fields)
|
||||
return true;
|
||||
};
|
||||
|
||||
// Сменилась версия игры — выбранная сборка модлоадера к ней уже не подходит.
|
||||
// Сам лоадер оставляем: чекбокс не должен слетать, он просто перевыберет версию.
|
||||
const QString previousMinecraft = build.minecraftVersion;
|
||||
|
||||
take("name", build.name);
|
||||
@@ -531,10 +484,7 @@ void LauncherBackend::updateCustomBuild(int index, const QVariantMap &fields)
|
||||
|
||||
saveCustomBuilds();
|
||||
emit customBuildsChanged();
|
||||
emit activeBuildChanged(); // имя активной сборки могло измениться
|
||||
// maybeInstall() здесь намеренно нет: карточка сборки сохраняется по ходу
|
||||
// правки, и загрузка стартовала бы почти на каждое действие. Для этого есть
|
||||
// installCustomBuild().
|
||||
emit activeBuildChanged();
|
||||
}
|
||||
|
||||
QVariantMap LauncherBackend::profileAt(int index) const
|
||||
@@ -649,7 +599,6 @@ int LauncherBackend::activeBuildIndex() const
|
||||
if (m_builds.isEmpty())
|
||||
return -1;
|
||||
const int index = indexOfBuildId(m_settings.value(QStringLiteral("activeBuildId")).toInt());
|
||||
// Настройка могла указывать на удалённую сборку — тогда активна первая.
|
||||
return index >= 0 ? index : 0;
|
||||
}
|
||||
|
||||
@@ -672,8 +621,6 @@ void LauncherBackend::setActiveBuildIndex(int index)
|
||||
return;
|
||||
}
|
||||
|
||||
// Содержимое .minecraft принадлежит прежней сборке: сначала оно уезжает в
|
||||
// её архив, и только потом на его место разворачивается выбранная.
|
||||
const CustomBuild &target = m_builds[index];
|
||||
emit launchProgress(Loc::text("build.progress.switchingTo").arg(target.name));
|
||||
m_switcher->switchTo(current >= 0 ? m_builds[current].id : -1,
|
||||
@@ -693,16 +640,11 @@ QString LauncherBackend::activeBuildName() const
|
||||
|
||||
void LauncherBackend::installCustomBuild(int index)
|
||||
{
|
||||
// Установка сборки — это установка её версии игры и, если выбран,
|
||||
// модлоадера: они ставятся одной цепочкой.
|
||||
installLoaderForBuild(index);
|
||||
}
|
||||
|
||||
QString LauncherBackend::launchVersionIdOf(const CustomBuild &build) const
|
||||
{
|
||||
// resolvedVersionId появляется после установки модлоадера. Пользователь мог
|
||||
// назвать сборку как угодно — тогда версией считаем само имя: так работали
|
||||
// записи, созданные до появления каталога версий.
|
||||
if (!build.resolvedVersionId.isEmpty())
|
||||
return build.resolvedVersionId;
|
||||
return build.minecraftVersion.isEmpty() ? build.name : build.minecraftVersion;
|
||||
@@ -751,7 +693,6 @@ bool LauncherBackend::catalogLoading() const
|
||||
|
||||
void LauncherBackend::refreshVersionCatalog(bool force)
|
||||
{
|
||||
// Список установленного мог поменяться и без нас (папку добавили руками).
|
||||
invalidateCatalog();
|
||||
m_manifest->ensureLoaded([this](bool ok, const QString &warning) {
|
||||
if (!ok && !warning.isEmpty())
|
||||
@@ -773,8 +714,6 @@ QVariantMap LauncherBackend::versionRemovalInfo(const QString &versionId) const
|
||||
return {};
|
||||
|
||||
const qint64 bytes = VersionLoader::installedSize(gameDir(), id);
|
||||
// Сборки не правим при удалении — ссылка на неустановленную версию это
|
||||
// рабочее состояние. Но перечислить, кого заденет, надо.
|
||||
QStringList builds;
|
||||
for (const CustomBuild &build : m_builds) {
|
||||
if (build.minecraftVersion == id || build.resolvedVersionId == id
|
||||
@@ -805,8 +744,6 @@ void LauncherBackend::removeVersion(const QString &versionId)
|
||||
emit launchError(Loc::text("common.error.busyOperation"));
|
||||
return;
|
||||
}
|
||||
// Какой версией сейчас играют, GameLauncher наружу не отдаёт, поэтому на
|
||||
// время игры удаление запрещено целиком.
|
||||
if (m_launcher->isRunning()) {
|
||||
emit launchError(Loc::text("common.error.closeGameFirst"));
|
||||
return;
|
||||
@@ -836,9 +773,6 @@ void LauncherBackend::rebuildCatalog() const
|
||||
{
|
||||
m_catalog.clear();
|
||||
|
||||
// Плоский список в порядке манифеста — новые версии сверху. Раскладку по
|
||||
// категориям и отбор делает окно выбора версии: ему нужен один список,
|
||||
// который можно фильтровать, а не готовая структура с разделителями.
|
||||
const QList<RemoteVersionEntry> remote = m_manifest->versions();
|
||||
const QStringList installed = VersionLoader::installedVersions(gameDir());
|
||||
const QSet<QString> installedSet(installed.cbegin(), installed.cend());
|
||||
@@ -867,7 +801,6 @@ void LauncherBackend::rebuildCatalog() const
|
||||
m_catalog.append(makeVersionRow(entry.id, entry.type, installedSet.contains(entry.id)));
|
||||
}
|
||||
|
||||
// Сборки модлоадеров манифест не знает — они попадают в «Прочие».
|
||||
QStringList unknown;
|
||||
for (const QString &id : installed) {
|
||||
if (!known.contains(id))
|
||||
@@ -887,8 +820,6 @@ void LauncherBackend::maybeInstall(const QString &versionId)
|
||||
return;
|
||||
if (m_installer->versionId() == id || m_installer->isQueued(id))
|
||||
return;
|
||||
// Манифест здесь не спрашиваем: установщик сам скажет, что версии в нём нет,
|
||||
// и это правильный ответ на вручную вписанный id сборки.
|
||||
m_installer->install(gameDir(), id);
|
||||
}
|
||||
|
||||
@@ -904,7 +835,6 @@ void LauncherBackend::installVersion(const QString &versionId)
|
||||
|
||||
void LauncherBackend::cancelDownload()
|
||||
{
|
||||
// Установщик лоадера сам остановит вложенную установку версии.
|
||||
if (m_loaderInstaller->isRunning())
|
||||
m_loaderInstaller->cancel();
|
||||
else if (m_installer->isRunning())
|
||||
@@ -915,24 +845,18 @@ void LauncherBackend::cancelDownload()
|
||||
m_packDownloader->cancel();
|
||||
}
|
||||
|
||||
// Панель загрузки одна на три установщика: пока идёт установка модлоадера, она
|
||||
// показывает его стадии, включая вложенную загрузку файлов версии. Установка
|
||||
// Java начинается только когда остальные не заняты, поэтому за панель они не спорят.
|
||||
bool LauncherBackend::downloading() const
|
||||
{
|
||||
return m_loaderInstaller->isRunning() || m_installer->isRunning()
|
||||
|| m_javaInstaller->isRunning() || m_packDownloader->isRunning();
|
||||
}
|
||||
|
||||
// Java качается сама по себе, а версия и лоадер — вместе; отсюда и порядок проверок.
|
||||
bool LauncherBackend::javaDownloadShown() const
|
||||
{
|
||||
return m_javaInstaller->isRunning() && !m_installer->isRunning()
|
||||
&& !m_loaderInstaller->isRunning();
|
||||
}
|
||||
|
||||
// Пак качается отдельным шагом цепочки, когда остальные установщики уже
|
||||
// отработали, — за панель они не спорят.
|
||||
bool LauncherBackend::packDownloadShown() const
|
||||
{
|
||||
return m_packDownloader->isRunning() && !m_installer->isRunning()
|
||||
@@ -947,7 +871,6 @@ double LauncherBackend::downloadProgress() const
|
||||
return m_javaInstaller->fraction();
|
||||
if (!m_loaderInstaller->isRunning())
|
||||
return m_installer->fraction();
|
||||
// Внутри установки лоадера файлы качает VersionInstaller — его доля точнее.
|
||||
return m_installer->isRunning() ? m_installer->fraction() : m_loaderInstaller->fraction();
|
||||
}
|
||||
|
||||
@@ -1042,7 +965,6 @@ void LauncherBackend::refreshLoaderVersions(const QString &loaderKey,
|
||||
bool ok, const QString &warning) {
|
||||
if (!ok && !warning.isEmpty())
|
||||
emit launchError(warning);
|
||||
// Кэш мог ответить сразу, без сигнала versionsChanged.
|
||||
emit loaderVersionsChanged(loaderKey, gameVersion);
|
||||
}, force);
|
||||
}
|
||||
@@ -1069,7 +991,6 @@ void LauncherBackend::installLoaderForBuild(int index)
|
||||
return;
|
||||
}
|
||||
|
||||
// Лоадер не выбран — сборка ванильная, ставим саму версию игры.
|
||||
const auto loader = loaderFromKey(build.loader);
|
||||
if (!loader) {
|
||||
if (build.resolvedVersionId != build.minecraftVersion)
|
||||
@@ -1105,8 +1026,6 @@ void LauncherBackend::launchGame(int profileIndex, int buildIndex)
|
||||
.arg(m_installer->versionId()));
|
||||
return;
|
||||
}
|
||||
// Игра ищет java при запуске: стартовать посреди её установки — значит
|
||||
// найти половину распакованного дерева.
|
||||
if (m_javaInstaller->isRunning()) {
|
||||
emit launchError(Loc::text("java.error.installBusy")
|
||||
.arg(m_javaInstaller->label()));
|
||||
@@ -1185,8 +1104,6 @@ void LauncherBackend::launchGame(int profileIndex, int buildIndex)
|
||||
}
|
||||
|
||||
m_pendingProfile = profileIndex;
|
||||
// Держим id, а не индекс: пока идёт авторизация, сборку могли удалить из
|
||||
// модального окна, и индекс уехал бы на чужую запись.
|
||||
m_pendingBuild = entry.id;
|
||||
m_pendingInjectorPath.clear();
|
||||
beginAuthentication();
|
||||
@@ -1198,8 +1115,6 @@ void LauncherBackend::startMicrosoftLogin(int profileIndex)
|
||||
emit microsoftLoginFailed(Loc::text("auth.msa.error.noWebEngine"));
|
||||
return;
|
||||
}
|
||||
// -1 из QML означает «профиля ещё нет»; внутри держим -2, чтобы отличать
|
||||
// это состояние от закрытого окна.
|
||||
if (profileIndex >= m_profiles.size()) {
|
||||
emit microsoftLoginFailed(Loc::text("profile.error.notFound"));
|
||||
return;
|
||||
@@ -1236,7 +1151,7 @@ void LauncherBackend::finishMicrosoftLogin(const QString &code)
|
||||
const int target = m_msaLoginProfile;
|
||||
m_msaLoginProfile = -1;
|
||||
if (target == -1)
|
||||
return; // окно закрыли, пока шла авторизация
|
||||
return;
|
||||
|
||||
if (!result.ok) {
|
||||
emit microsoftLoginFailed(result.error);
|
||||
@@ -1244,7 +1159,6 @@ void LauncherBackend::finishMicrosoftLogin(const QString &code)
|
||||
}
|
||||
|
||||
if (target == -2) {
|
||||
// Профиля ещё нет — заводим его на ник из аккаунта.
|
||||
Profile profile;
|
||||
profile.id = m_nextProfileId++;
|
||||
profile.name = result.playerName;
|
||||
@@ -1270,8 +1184,6 @@ void LauncherBackend::finishMicrosoftLogin(const QString &code)
|
||||
void LauncherBackend::applyMicrosoftResult(Profile &profile, const AuthResult &auth)
|
||||
{
|
||||
profile.accessToken = auth.accessToken;
|
||||
// Microsoft выдаёт новый refresh-токен и при продлении, но если в ответе
|
||||
// его не было — прежний остаётся рабочим.
|
||||
if (!auth.refreshToken.isEmpty())
|
||||
profile.refreshToken = auth.refreshToken;
|
||||
if (!auth.uuid.isEmpty())
|
||||
@@ -1297,7 +1209,6 @@ void LauncherBackend::beginMicrosoftAuthentication()
|
||||
return;
|
||||
}
|
||||
|
||||
// Сохранённый токен ещё жив — идём в игру, не дёргая Microsoft.
|
||||
const QDateTime expiry = QDateTime::fromString(profile.tokenExpiry, Qt::ISODate);
|
||||
if (!profile.accessToken.isEmpty() && expiry.isValid()
|
||||
&& QDateTime::currentDateTimeUtc().addSecs(kTokenRenewMarginSecs) < expiry) {
|
||||
@@ -1317,7 +1228,7 @@ void LauncherBackend::beginMicrosoftAuthentication()
|
||||
|
||||
m_msa->loginWithRefreshToken(profile.refreshToken, [this](const AuthResult &result) {
|
||||
if (m_pendingProfile < 0)
|
||||
return; // запуск отменили, пока шло продление
|
||||
return;
|
||||
if (result.licenseMissing) {
|
||||
failLaunch(result.error);
|
||||
return;
|
||||
@@ -1353,12 +1264,10 @@ void LauncherBackend::beginAuthentication()
|
||||
return;
|
||||
}
|
||||
|
||||
// Ely.by работает только вместе с authlib-injector — без него игра пойдёт
|
||||
// в сессионный сервер Mojang и токен окажется недействительным.
|
||||
m_auth->ensureAuthlibInjector(LauncherPaths::runtimeDir(),
|
||||
[this](const QString &path, const QString &error) {
|
||||
if (m_pendingProfile < 0)
|
||||
return; // запуск отменили, пока качался инжектор
|
||||
return;
|
||||
if (!error.isEmpty()) {
|
||||
failLaunch(error);
|
||||
return;
|
||||
@@ -1439,8 +1348,6 @@ void LauncherBackend::continueLaunch(const AuthResult &auth)
|
||||
Profile &profile = m_profiles[m_pendingProfile];
|
||||
const CustomBuild &build = m_builds[buildIndex];
|
||||
|
||||
// Ely.by возвращает игровой ник и UUID аккаунта — их и запоминаем,
|
||||
// чтобы в следующий раз обойтись без пароля.
|
||||
if (profile.authType == kMicrosoft && auth.ok) {
|
||||
applyMicrosoftResult(profile, auth);
|
||||
saveProfiles();
|
||||
@@ -1467,8 +1374,6 @@ void LauncherBackend::continueLaunch(const AuthResult &auth)
|
||||
options.userType = auth.userType;
|
||||
options.xuid = auth.xuid;
|
||||
|
||||
// Скачанная лаунчером сборка важнее пути из настроек: её выбрали явно в
|
||||
// окне выбора версии Java.
|
||||
options.javaPath = managedJavaPath();
|
||||
if (options.javaPath.isEmpty()) {
|
||||
if (!m_settings.value(QStringLiteral("javaRuntime")).toString().trimmed().isEmpty())
|
||||
@@ -1587,9 +1492,6 @@ void LauncherBackend::updateSettings(const QVariantMap &values)
|
||||
saveSettings();
|
||||
emit settingsChanged();
|
||||
|
||||
// Язык переключается после записи: порядок «сохранили → переключили»
|
||||
// гарантирует, что выбор переживёт падение сразу после переключения.
|
||||
// Сам Localization в settings.json не пишет — файл ведёт только бэкенд.
|
||||
const QString language = m_settings.value(QStringLiteral("language")).toString();
|
||||
if (language != previousLanguage)
|
||||
Localization::instance().setLanguage(language);
|
||||
@@ -1629,7 +1531,6 @@ bool LauncherBackend::javaCatalogLoading() const
|
||||
|
||||
void LauncherBackend::refreshJavaCatalog(bool force)
|
||||
{
|
||||
// Список установленного мог поменяться и без нас (папку удалили руками).
|
||||
invalidateJavaCatalog();
|
||||
m_javaMeta->ensureLoaded([this](bool ok, const QString &warning) {
|
||||
if (!ok && !warning.isEmpty())
|
||||
@@ -1684,7 +1585,6 @@ void LauncherBackend::rebuildJavaCatalog() const
|
||||
QStringLiteral("%1 %2 %3 %4").arg(version, QString::number(major), kind, detail).toLower()}};
|
||||
};
|
||||
|
||||
// Скачанное — сверху: этим уже можно пользоваться прямо сейчас.
|
||||
QSet<QString> listed;
|
||||
for (const InstalledJavaRuntime &runtime : installed) {
|
||||
listed.insert(runtime.id);
|
||||
@@ -1760,7 +1660,6 @@ void LauncherBackend::removeJavaRuntime(const QString &runtimeId)
|
||||
return;
|
||||
}
|
||||
|
||||
// Удалили выбранную — настройка указывала бы в пустоту.
|
||||
if (m_settings.value(QStringLiteral("javaRuntime")).toString() == runtimeId) {
|
||||
m_settings.insert(QStringLiteral("javaRuntime"), QString());
|
||||
saveSettings();
|
||||
@@ -1786,7 +1685,6 @@ QVariantMap LauncherBackend::javaRuntimeInfo(const QString &runtimeId) const
|
||||
{QStringLiteral("installed"), true}};
|
||||
}
|
||||
|
||||
// Выбрана, но ещё не скачана: подпись всё равно нужна.
|
||||
const auto entry = m_javaMeta->find(runtimeId);
|
||||
if (!entry)
|
||||
return QVariantMap{{QStringLiteral("id"), runtimeId},
|
||||
@@ -1825,7 +1723,6 @@ QUrl LauncherBackend::seasonalBaseUrl() const
|
||||
const QString configured =
|
||||
m_settings.value(QStringLiteral("seasonalBaseUrl")).toString().trimmed();
|
||||
QUrl url(configured.isEmpty() ? kSeasonalBaseUrl : configured);
|
||||
// Хвостовой слэш превратил бы адрес каталога в «…//index.json».
|
||||
while (url.path().endsWith(u'/'))
|
||||
url.setPath(url.path().chopped(1));
|
||||
return url;
|
||||
@@ -1921,7 +1818,6 @@ bool LauncherBackend::seasonalInstalling() const
|
||||
|
||||
void LauncherBackend::refreshSeasonalCatalog(bool force)
|
||||
{
|
||||
// Адрес мог смениться в settings.json между запусками окна.
|
||||
m_seasonalMeta->setBaseUrl(seasonalBaseUrl());
|
||||
m_seasonalMeta->ensureLoaded(nullptr, force);
|
||||
}
|
||||
@@ -1952,8 +1848,6 @@ void LauncherBackend::installSeasonalBuild(const QString &seasonalId)
|
||||
m_season = {};
|
||||
m_season.entry = *entry;
|
||||
|
||||
// Сборка с таким seasonalId уже заведена — обновляем её описание под новую
|
||||
// ревизию, а не плодим вторую запись.
|
||||
int index = indexOfSeasonalBuild(seasonalId);
|
||||
if (index < 0) {
|
||||
CustomBuild build;
|
||||
@@ -1964,14 +1858,10 @@ void LauncherBackend::installSeasonalBuild(const QString &seasonalId)
|
||||
build.loader = entry->loader;
|
||||
build.loaderVersion = entry->loaderVersion;
|
||||
build.seasonalId = entry->id;
|
||||
// Ревизия появится только когда файлы лягут на диск: иначе оборванная
|
||||
// установка выглядела бы завершённой.
|
||||
m_builds.append(build);
|
||||
index = m_builds.size() - 1;
|
||||
saveCustomBuilds();
|
||||
emit customBuildsChanged();
|
||||
// maybeInstall() здесь намеренно нет: версию и модлоадер поставит шаг
|
||||
// цепочки, а параллельная загрузка только мешала бы ему.
|
||||
} else {
|
||||
updateCustomBuild(index,
|
||||
{{QStringLiteral("name"), entry->name},
|
||||
@@ -1984,8 +1874,6 @@ void LauncherBackend::installSeasonalBuild(const QString &seasonalId)
|
||||
m_season.buildId = m_builds[index].id;
|
||||
setBusy(true);
|
||||
emit launchProgress(Loc::text("seasonal.progress.installing").arg(entry->name));
|
||||
// Сигнал после seasonAdvance(): шаг цепочки выставляет stage сам, а до его
|
||||
// вызова seasonalInstalling() ещё вернул бы false.
|
||||
seasonAdvance();
|
||||
emit seasonalInstallingChanged();
|
||||
}
|
||||
@@ -1997,9 +1885,6 @@ void LauncherBackend::seasonAdvance()
|
||||
return;
|
||||
}
|
||||
|
||||
// Каждый шаг либо начинает свою асинхронную работу и обрывает цепочку до
|
||||
// следующего сигнала, либо уступает следующему — отсюда провалы между
|
||||
// ветками.
|
||||
switch (m_season.stage) {
|
||||
case SeasonStage::Idle:
|
||||
if (seasonBeginSwitch())
|
||||
@@ -2034,9 +1919,6 @@ bool LauncherBackend::seasonBeginSwitch()
|
||||
if (current == index)
|
||||
return false;
|
||||
|
||||
// Пак ложится на то, что сейчас разложено в .minecraft, поэтому сборка
|
||||
// должна стать активной до всего остального. Содержимое прежней уезжает в
|
||||
// её архив обычным путём.
|
||||
m_season.stage = SeasonStage::Switching;
|
||||
emit launchProgress(Loc::text("build.progress.switchingTo").arg(m_builds[index].name));
|
||||
m_switcher->switchTo(current >= 0 ? m_builds[current].id : -1,
|
||||
@@ -2051,14 +1933,12 @@ bool LauncherBackend::seasonBeginSwitch()
|
||||
|
||||
bool LauncherBackend::seasonBeginJava()
|
||||
{
|
||||
// Сервер может назвать нужную Java прямо; иначе спрашиваем таблицу.
|
||||
const int major = m_season.entry.javaMajor > 0
|
||||
? m_season.entry.javaMajor
|
||||
: JavaRequirement::minimumFor(m_season.entry.minecraftVersion);
|
||||
if (major <= 0)
|
||||
return false;
|
||||
|
||||
// Java уже есть — своя, системная или скачанная раньше.
|
||||
QString error;
|
||||
if (!JavaLocator::select(gameDir(), major, QString(), &error).isEmpty())
|
||||
return false;
|
||||
@@ -2066,7 +1946,6 @@ bool LauncherBackend::seasonBeginJava()
|
||||
m_season.stage = SeasonStage::Java;
|
||||
emit launchProgress(Loc::text("seasonal.progress.installingJava").arg(major));
|
||||
|
||||
// Каталог Java мог ещё ни разу не читаться: окно выбора могли не открывать.
|
||||
m_javaMeta->ensureLoaded([this, major](bool ok, const QString &warning) {
|
||||
if (m_season.stage != SeasonStage::Java)
|
||||
return;
|
||||
@@ -2090,7 +1969,6 @@ bool LauncherBackend::seasonBeginLoader()
|
||||
const CustomBuild &build = m_builds[index];
|
||||
const auto loader = loaderFromKey(build.loader);
|
||||
|
||||
// Ванильная сборка: ставить надо только саму версию игры.
|
||||
if (!loader) {
|
||||
if (checkInstallation(index).isEmpty())
|
||||
return false;
|
||||
@@ -2099,7 +1977,6 @@ bool LauncherBackend::seasonBeginLoader()
|
||||
return true;
|
||||
}
|
||||
|
||||
// Профиль лоадера уже собран и укомплектован — второй раз не ставим.
|
||||
if (!build.resolvedVersionId.isEmpty() && checkInstallation(index).isEmpty())
|
||||
return false;
|
||||
|
||||
@@ -2118,8 +1995,6 @@ bool LauncherBackend::seasonBeginLoader()
|
||||
bool LauncherBackend::seasonBeginDownload()
|
||||
{
|
||||
const SeasonalBuildEntry &entry = m_season.entry;
|
||||
// Точка в начале имени: файл служебный, и BuildSwitcher по этому признаку
|
||||
// не примет его за архив сборки и не сотрёт при следующем переключении.
|
||||
const QString path = LauncherPaths::buildDir(m_season.buildId)
|
||||
+ QStringLiteral("/.pack-r") + QString::number(entry.revision)
|
||||
+ QStringLiteral(".zip");
|
||||
@@ -2140,11 +2015,6 @@ bool LauncherBackend::seasonBeginApply()
|
||||
return true;
|
||||
}
|
||||
|
||||
// Под удаление идёт весь список прошлой ревизии, а не разница с новой:
|
||||
// распаковка всё равно кладёт каждый файл пака заново, поэтому разница
|
||||
// сэкономила бы лишь перезапись того, что и так перезаписывается, а вот
|
||||
// ушедшие из сборки моды так убираются наверняка. Миров и скриншотов в
|
||||
// списке нет — их пак не приносил.
|
||||
const QStringList remove = seasonalPackEntries(m_season.buildId);
|
||||
|
||||
const QJsonObject note{{QStringLiteral("seasonalId"), m_season.entry.id},
|
||||
@@ -2182,16 +2052,12 @@ void LauncherBackend::seasonFail(const QString &message)
|
||||
{
|
||||
const int index = indexOfBuildId(m_season.buildId);
|
||||
const QString name = index >= 0 ? m_builds[index].name : m_season.entry.name;
|
||||
// Недокачанный или нераскатанный пак не должен занимать место: цепочку
|
||||
// всегда можно начать заново с чистого листа.
|
||||
if (!m_season.packPath.isEmpty())
|
||||
QFile::remove(m_season.packPath);
|
||||
|
||||
m_season = {};
|
||||
setBusy(false);
|
||||
emit seasonalInstallingChanged();
|
||||
// Пустое message означает, что о причине уже сообщил тот, кто её нашёл, —
|
||||
// второй раз ту же ошибку не показываем.
|
||||
emit launchError(message.isEmpty()
|
||||
? Loc::text("seasonal.error.installAborted").arg(name)
|
||||
: Loc::text("seasonal.error.installAbortedWhy").arg(name, message));
|
||||
@@ -2216,8 +2082,6 @@ void LauncherBackend::cancelSeasonalInstall()
|
||||
return;
|
||||
case SeasonStage::Switching:
|
||||
case SeasonStage::Applying:
|
||||
// На этих шагах содержимое .minecraft уже разобрано: отступать некуда,
|
||||
// операцию нужно довести до конца.
|
||||
emit launchError(Loc::text("switch.error.cannotCancel"));
|
||||
return;
|
||||
}
|
||||
@@ -2256,8 +2120,6 @@ void LauncherBackend::recordSeasonalPack(int buildId,
|
||||
{QStringLiteral("installedAt"),
|
||||
QDateTime::currentDateTimeUtc().toString(Qt::ISODate)},
|
||||
{QStringLiteral("entries"), QJsonArray::fromStringList(entries)}};
|
||||
// Не через writeJsonFile: файл лежит в папке сборки, а не в корне лаунчера,
|
||||
// и его отсутствие не мешает игре — ошибку достаточно показать.
|
||||
QDir().mkpath(LauncherPaths::buildDir(buildId));
|
||||
QSaveFile file(LauncherPaths::seasonalStateFile(buildId));
|
||||
if (file.open(QIODevice::WriteOnly)) {
|
||||
@@ -2271,8 +2133,6 @@ void LauncherBackend::recordSeasonalPack(int buildId,
|
||||
const int index = indexOfBuildId(buildId);
|
||||
if (index < 0)
|
||||
return;
|
||||
// Ревизия проставляется только здесь: до этого момента файлы сборки на
|
||||
// диске не лежали.
|
||||
updateCustomBuild(index,
|
||||
{{QStringLiteral("seasonalId"), seasonalId},
|
||||
{QStringLiteral("seasonalRevision"), revision}});
|
||||
@@ -2296,8 +2156,6 @@ void LauncherBackend::openGameFolder()
|
||||
emit launchError(Loc::text("launch.error.openGameDirFailed"));
|
||||
}
|
||||
|
||||
// Повреждённый файл не удаляем: отводим в .bak, чтобы данные можно было спасти
|
||||
// руками, а ensureDataFiles() создал на его месте пустой.
|
||||
bool LauncherBackend::moveAsideBroken(const QString &path, const QString &reason)
|
||||
{
|
||||
const QString backup = path + QStringLiteral(".bak");
|
||||
@@ -2319,7 +2177,7 @@ QJsonArray LauncherBackend::readArrayFile(const QString &path)
|
||||
{
|
||||
QFile file(path);
|
||||
if (!file.exists())
|
||||
return {}; // первый запуск — это не ошибка
|
||||
return {};
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
m_storageIssues << Loc::text("common.error.readFailed")
|
||||
.arg(QDir::toNativeSeparators(path), file.errorString());
|
||||
@@ -2367,8 +2225,6 @@ QJsonObject LauncherBackend::readObjectFile(const QString &path)
|
||||
return document.object();
|
||||
}
|
||||
|
||||
// Перед каждой записью убеждаемся, что папка лаунчера на месте: её могли удалить
|
||||
// уже после запуска, и тогда данные молча пропадали бы.
|
||||
bool LauncherBackend::writeJsonFile(const QString &path, const QJsonDocument &document)
|
||||
{
|
||||
QString storageError;
|
||||
@@ -2425,8 +2281,6 @@ void LauncherBackend::loadData()
|
||||
build.name = o["name"].toString();
|
||||
build.serverUrl = o["serverUrl"].toString();
|
||||
build.minecraftVersion = o.value("minecraftVersion").toString();
|
||||
// Файл мог остаться от версии лаунчера до переименования или быть
|
||||
// поправлен руками — старый ключ тоже принимаем.
|
||||
if (build.minecraftVersion.isEmpty())
|
||||
build.minecraftVersion = o.value("versionId").toString();
|
||||
build.loader = o.value("loader").toString();
|
||||
@@ -2435,8 +2289,6 @@ void LauncherBackend::loadData()
|
||||
build.seasonalId = o.value("seasonalId").toString();
|
||||
build.seasonalRevision = o.value("seasonalRevision").toInt();
|
||||
|
||||
// Без имени и без версии запись нерабочая: launchVersionIdOf() вернёт
|
||||
// пустую строку.
|
||||
if (build.name.trimmed().isEmpty() && build.minecraftVersion.trimmed().isEmpty()) {
|
||||
++skippedBuilds;
|
||||
return;
|
||||
@@ -2454,9 +2306,6 @@ void LauncherBackend::loadData()
|
||||
[](const CustomBuild &a, const CustomBuild &b) { return a.id < b.id; });
|
||||
}
|
||||
|
||||
// Первый запуск после переименования «версий» в «сборки»: перекладываем
|
||||
// <root>/versions.json в customBuilds.json. Старый файл не удаляем, а
|
||||
// переименовываем — он остаётся резервной копией.
|
||||
bool LauncherBackend::migrateLegacyBuildsFile()
|
||||
{
|
||||
if (QFile::exists(LauncherPaths::customBuildsFile()))
|
||||
@@ -2464,7 +2313,6 @@ bool LauncherBackend::migrateLegacyBuildsFile()
|
||||
if (!QFile::exists(LauncherPaths::legacyCustomBuildsFile()))
|
||||
return false;
|
||||
|
||||
// readArrayFile() сам отводит битый файл в .bak — тогда мигрировать нечего.
|
||||
const QJsonArray legacy = readArrayFile(LauncherPaths::legacyCustomBuildsFile());
|
||||
if (legacy.isEmpty() && !QFile::exists(LauncherPaths::legacyCustomBuildsFile()))
|
||||
return false;
|
||||
@@ -2481,8 +2329,6 @@ bool LauncherBackend::migrateLegacyBuildsFile()
|
||||
{"resolvedVersionId", QString()}});
|
||||
}
|
||||
|
||||
// Не удалось записать — молча читаем в этой сессии из старого файла.
|
||||
// Без данных пользователь не остаётся ни при каком исходе.
|
||||
if (!writeJsonFile(LauncherPaths::customBuildsFile(), QJsonDocument(migrated)))
|
||||
return false;
|
||||
|
||||
@@ -2497,9 +2343,6 @@ bool LauncherBackend::migrateLegacyBuildsFile()
|
||||
return true;
|
||||
}
|
||||
|
||||
// Сборка описывает то, что уже разложено в .minecraft, поэтому BuildSwitcher не
|
||||
// нужен: активная сборка без архива — штатное состояние. Через addCustomBuild()
|
||||
// не идём, чтобы при старте не началась установка.
|
||||
QString LauncherBackend::importGameDir()
|
||||
{
|
||||
const std::optional<GameDirImport::Detected> found = GameDirImport::detect(gameDir());
|
||||
@@ -2527,8 +2370,6 @@ QString LauncherBackend::importGameDir()
|
||||
return build.name;
|
||||
}
|
||||
|
||||
// Файлы могли не появиться при первом запуске, быть удалены или отложены в .bak —
|
||||
// создаём заново, чтобы папка лаунчера всегда была укомплектована.
|
||||
void LauncherBackend::ensureDataFiles()
|
||||
{
|
||||
if (!QFile::exists(LauncherPaths::settingsFile()))
|
||||
@@ -2581,7 +2422,6 @@ void LauncherBackend::loadSettings()
|
||||
{
|
||||
m_settings = {{QStringLiteral("gameDir"), QString()},
|
||||
{QStringLiteral("javaPath"), QString()},
|
||||
// id сборки Java из <root>/java. Пусто — java ищется сама.
|
||||
{QStringLiteral("javaRuntime"), QString()},
|
||||
{QStringLiteral("minMemoryMb"), 512},
|
||||
{QStringLiteral("maxMemoryMb"), 4096},
|
||||
@@ -2589,20 +2429,14 @@ void LauncherBackend::loadSettings()
|
||||
{QStringLiteral("windowWidth"), 0},
|
||||
{QStringLiteral("windowHeight"), 0},
|
||||
{QStringLiteral("fullscreen"), false},
|
||||
// Язык интерфейса: "system" — по системной локали.
|
||||
{QStringLiteral("language"), QStringLiteral("system")},
|
||||
{QStringLiteral("activeBuildId"), 0},
|
||||
// Сервер готовых сборок. В интерфейс не вынесен: менять его
|
||||
// приходится только при отладке против локального сервера.
|
||||
{QStringLiteral("seasonalBaseUrl"), kSeasonalBaseUrl}};
|
||||
|
||||
const QJsonObject stored = readObjectFile(LauncherPaths::settingsFile());
|
||||
for (auto it = stored.constBegin(); it != stored.constEnd(); ++it)
|
||||
m_settings.insert(it.key(), it.value().toVariant());
|
||||
|
||||
// Имя и версия лаунчера раньше хранились здесь со значением "1.0" и не
|
||||
// обновлялись вместе с программой. Теперь они берутся из QCoreApplication,
|
||||
// а старые ключи вычищаются из файла при следующем сохранении.
|
||||
m_settings.remove(QStringLiteral("launcherName"));
|
||||
m_settings.remove(QStringLiteral("launcherVersion"));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user