Dev to rc updater release #35
No files matched your search
+19
-18
@@ -579,8 +579,27 @@ Dialog {
|
|||||||
}
|
}
|
||||||
Row {
|
Row {
|
||||||
anchors.centerIn: parent
|
anchors.centerIn: parent
|
||||||
|
//anchors.right: parent.right //возможно добавить смещение вправо как в сезонах
|
||||||
spacing: 12
|
spacing: 12
|
||||||
|
|
||||||
|
Button {
|
||||||
|
text: Loc.t.common.button.close
|
||||||
|
width: 120; height: 36
|
||||||
|
enabled: !buildsDialog.backend.switching
|
||||||
|
opacity: enabled ? 1.0 : 0.45
|
||||||
|
contentItem: Text {
|
||||||
|
text: parent.text
|
||||||
|
color: "#ffffff"
|
||||||
|
horizontalAlignment: Text.AlignHCenter
|
||||||
|
verticalAlignment: Text.AlignVCenter
|
||||||
|
}
|
||||||
|
background: Rectangle {
|
||||||
|
color: parent.pressed ? "#444444" : "#333333"
|
||||||
|
radius: 6
|
||||||
|
}
|
||||||
|
onClicked: buildsDialog.close()
|
||||||
|
}
|
||||||
|
|
||||||
Button {
|
Button {
|
||||||
text: Loc.t.common.button.install
|
text: Loc.t.common.button.install
|
||||||
width: 140; height: 36
|
width: 140; height: 36
|
||||||
@@ -618,24 +637,6 @@ Dialog {
|
|||||||
}
|
}
|
||||||
onClicked: buildsDialog.backend.activeBuildIndex = buildsDialog.editIndex
|
onClicked: buildsDialog.backend.activeBuildIndex = buildsDialog.editIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
Button {
|
|
||||||
text: Loc.t.common.button.close
|
|
||||||
width: 120; height: 36
|
|
||||||
enabled: !buildsDialog.backend.switching
|
|
||||||
opacity: enabled ? 1.0 : 0.45
|
|
||||||
contentItem: Text {
|
|
||||||
text: parent.text
|
|
||||||
color: "#ffffff"
|
|
||||||
horizontalAlignment: Text.AlignHCenter
|
|
||||||
verticalAlignment: Text.AlignVCenter
|
|
||||||
}
|
|
||||||
background: Rectangle {
|
|
||||||
color: parent.pressed ? "#444444" : "#333333"
|
|
||||||
radius: 6
|
|
||||||
}
|
|
||||||
onClicked: buildsDialog.close()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+7
-1
@@ -18,4 +18,10 @@
|
|||||||
- Исправлен баг когда невозможно выйти из модального окна сезонных сборок и\или отменить текущую загрузку
|
- Исправлен баг когда невозможно выйти из модального окна сезонных сборок и\или отменить текущую загрузку
|
||||||
- Исправлен баг отображения статуса активной сборки на зелёном фоне
|
- Исправлен баг отображения статуса активной сборки на зелёном фоне
|
||||||
- Исправлен баг, что во время игры можно было потенциально сменить сборку
|
- Исправлен баг, что во время игры можно было потенциально сменить сборку
|
||||||
- Исправлен баг первого запуска после установки лаунчера, если у пользователя была не пустая .minecraft
|
- Исправлен баг первого запуска после установки лаунчера, если у пользователя была не пустая .minecraft
|
||||||
|
|
||||||
|
## [1.0.2-rc1] — 2026-10-23
|
||||||
|
### Добавлено
|
||||||
|
### Исправлено
|
||||||
|
- Исправлен баг с возможностью изменять текущую сборку во время установки сезонной
|
||||||
|
- Мелкие исправления
|
||||||
+5
-1
@@ -1,6 +1,6 @@
|
|||||||
cmake_minimum_required(VERSION 3.20)
|
cmake_minimum_required(VERSION 3.20)
|
||||||
|
|
||||||
project(BiLauncher VERSION 1.0.1 LANGUAGES CXX C)
|
project(BiLauncher VERSION 1.1.0 LANGUAGES CXX C)
|
||||||
|
|
||||||
# Канал сборки (dev / rc / релиз) не хранится в репозитории, а вычисляется
|
# Канал сборки (dev / rc / релиз) не хранится в репозитории, а вычисляется
|
||||||
# при сборке — см. cmake/LauncherVersion.cmake. CI передаёт полную версию:
|
# при сборке — см. cmake/LauncherVersion.cmake. CI передаёт полную версию:
|
||||||
@@ -91,6 +91,8 @@ qt_add_qml_module(BiLauncher
|
|||||||
localization.cpp
|
localization.cpp
|
||||||
launcherbackend.h
|
launcherbackend.h
|
||||||
launcherbackend.cpp
|
launcherbackend.cpp
|
||||||
|
launcherupdates.h
|
||||||
|
launcherupdates.cpp
|
||||||
launcherpaths.h
|
launcherpaths.h
|
||||||
launcherpaths.cpp
|
launcherpaths.cpp
|
||||||
minecraftversion.h
|
minecraftversion.h
|
||||||
@@ -134,6 +136,7 @@ qt_add_qml_module(BiLauncher
|
|||||||
Main.qml
|
Main.qml
|
||||||
DarkCombo.qml
|
DarkCombo.qml
|
||||||
VersionPickerDialog.qml
|
VersionPickerDialog.qml
|
||||||
|
LauncherVersionsDialog.qml
|
||||||
JavaPickerDialog.qml
|
JavaPickerDialog.qml
|
||||||
LabelledField.qml
|
LabelledField.qml
|
||||||
BuildsDialog.qml
|
BuildsDialog.qml
|
||||||
@@ -142,6 +145,7 @@ qt_add_qml_module(BiLauncher
|
|||||||
ProgressPanel.qml
|
ProgressPanel.qml
|
||||||
${LAUNCHER_MSA_QML_FILES}
|
${LAUNCHER_MSA_QML_FILES}
|
||||||
RESOURCES images/Folder/Folder_Active.svg images/Folder/Folder_Idle.svg images/Folder/Folder_Pressed.svg images/Options/Options_active.svg images/Options/Options_Idle.svg images/Options/Options_Pressed.svg images/Play_Button/Play_Active.svg images/Play_Button/Play_Idle.svg images/Play_Button/Play_pressed.svg images/Profile_Box/Asset_23.jpg images/Profile_Box/Asset_23.svg images/Profile_Box/Asset_24.jpg images/Profile_Box/Asset_24.svg images/Profile_Box/Kishka_Profile_Active.svg images/Profile_Box/Kishka_Profile_Idle.svg images/Profile_Box/Kishka_Profile_open.svg images/Scroll/Scroll_Lever.svg images/Scroll/Scroll_palka.svg images/Version_box/Kishka_Profile_Open.svg images/Version_box/Kishka_Ver_Active.svg images/Version_box/Kishka_Ver_idle.svg images/Trash.svg images/Pencil.svg images/GovuztTW8AAHqBf.jpeg images/photo_2025-12-16_15-04-17.jpg images/photo_2025-12-21_02-30-09.jpg i18n/translations.json
|
RESOURCES images/Folder/Folder_Active.svg images/Folder/Folder_Idle.svg images/Folder/Folder_Pressed.svg images/Options/Options_active.svg images/Options/Options_Idle.svg images/Options/Options_Pressed.svg images/Play_Button/Play_Active.svg images/Play_Button/Play_Idle.svg images/Play_Button/Play_pressed.svg images/Profile_Box/Asset_23.jpg images/Profile_Box/Asset_23.svg images/Profile_Box/Asset_24.jpg images/Profile_Box/Asset_24.svg images/Profile_Box/Kishka_Profile_Active.svg images/Profile_Box/Kishka_Profile_Idle.svg images/Profile_Box/Kishka_Profile_open.svg images/Scroll/Scroll_Lever.svg images/Scroll/Scroll_palka.svg images/Version_box/Kishka_Profile_Open.svg images/Version_box/Kishka_Ver_Active.svg images/Version_box/Kishka_Ver_idle.svg images/Trash.svg images/Pencil.svg images/GovuztTW8AAHqBf.jpeg images/photo_2025-12-16_15-04-17.jpg images/photo_2025-12-21_02-30-09.jpg i18n/translations.json
|
||||||
|
RESOURCES images/ExternalLink.svg
|
||||||
RESOURCES images/launcherBackground.png
|
RESOURCES images/launcherBackground.png
|
||||||
RESOURCES images/launcherBackground2static.jpg
|
RESOURCES images/launcherBackground2static.jpg
|
||||||
RESOURCES CHANGELOG.md
|
RESOURCES CHANGELOG.md
|
||||||
|
|||||||
@@ -0,0 +1,263 @@
|
|||||||
|
pragma ComponentBehavior: Bound
|
||||||
|
|
||||||
|
import QtQuick
|
||||||
|
import QtQuick.Controls
|
||||||
|
import QtQuick.Layouts
|
||||||
|
import BiLauncher
|
||||||
|
|
||||||
|
Dialog {
|
||||||
|
id: picker
|
||||||
|
|
||||||
|
required property LauncherUpdates updates
|
||||||
|
property string channel: "release"
|
||||||
|
property string selectedVersion: ""
|
||||||
|
readonly property string state: updates.states[channel] ?? ""
|
||||||
|
readonly property var entries: updates.catalogs[channel] ?? []
|
||||||
|
|
||||||
|
function selectChannel(value) {
|
||||||
|
channel = value
|
||||||
|
selectedVersion = ""
|
||||||
|
if (state !== "ready")
|
||||||
|
updates.refresh(channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
modal: true
|
||||||
|
anchors.centerIn: parent
|
||||||
|
width: Math.min(720, parent.width - 24)
|
||||||
|
height: Math.min(480, parent.height - 24)
|
||||||
|
padding: 0
|
||||||
|
closePolicy: updates.installing ? Popup.NoAutoClose : Popup.CloseOnEscape | Popup.CloseOnPressOutside
|
||||||
|
onAboutToShow: selectChannel(updates.channel === "rc" ? "rc" : "release")
|
||||||
|
|
||||||
|
background: Rectangle {
|
||||||
|
color: "#1e1e1e"
|
||||||
|
radius: 10
|
||||||
|
border.color: "#91B315"
|
||||||
|
}
|
||||||
|
|
||||||
|
header: Item {
|
||||||
|
implicitHeight: 52
|
||||||
|
Text {
|
||||||
|
anchors.centerIn: parent
|
||||||
|
text: Loc.t.app.label.launcherVersions
|
||||||
|
color: "#ffffff"
|
||||||
|
font.pixelSize: 17
|
||||||
|
font.bold: true
|
||||||
|
}
|
||||||
|
Rectangle {
|
||||||
|
anchors.bottom: parent.bottom
|
||||||
|
width: parent.width
|
||||||
|
height: 1
|
||||||
|
color: "#333333"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
contentItem: RowLayout {
|
||||||
|
spacing: 0
|
||||||
|
|
||||||
|
Column {
|
||||||
|
Layout.preferredWidth: 160
|
||||||
|
Layout.fillHeight: true
|
||||||
|
padding: 8
|
||||||
|
spacing: 4
|
||||||
|
enabled: !picker.updates.installing
|
||||||
|
|
||||||
|
Repeater {
|
||||||
|
model: [{ key: "release", title: "Release" }, { key: "rc", title: "Release Candidate" }]
|
||||||
|
delegate: ItemDelegate {
|
||||||
|
id: channelButton
|
||||||
|
required property var modelData
|
||||||
|
width: 144
|
||||||
|
height: 34
|
||||||
|
text: modelData.title
|
||||||
|
contentItem: Text {
|
||||||
|
text: channelButton.text
|
||||||
|
color: "#ffffff"
|
||||||
|
font.pixelSize: 13
|
||||||
|
verticalAlignment: Text.AlignVCenter
|
||||||
|
}
|
||||||
|
background: Rectangle {
|
||||||
|
radius: 5
|
||||||
|
color: picker.channel === channelButton.modelData.key ? "#91B315"
|
||||||
|
: channelButton.hovered || channelButton.activeFocus ? "#2d2d2d" : "transparent"
|
||||||
|
}
|
||||||
|
onClicked: picker.selectChannel(modelData.key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Rectangle {
|
||||||
|
Layout.preferredWidth: 1
|
||||||
|
Layout.fillHeight: true
|
||||||
|
color: "#333333"
|
||||||
|
}
|
||||||
|
|
||||||
|
ColumnLayout {
|
||||||
|
Layout.fillWidth: true
|
||||||
|
Layout.fillHeight: true
|
||||||
|
Layout.margins: 8
|
||||||
|
spacing: 6
|
||||||
|
|
||||||
|
RowLayout {
|
||||||
|
Layout.fillWidth: true
|
||||||
|
Layout.leftMargin: 10
|
||||||
|
Layout.rightMargin: 10
|
||||||
|
Label {
|
||||||
|
Layout.fillWidth: true
|
||||||
|
text: Loc.t.app.label.versionName
|
||||||
|
color: "#aaaaaa"
|
||||||
|
}
|
||||||
|
Label {
|
||||||
|
Layout.preferredWidth: 110
|
||||||
|
text: Loc.t.app.label.releaseDate
|
||||||
|
color: "#aaaaaa"
|
||||||
|
}
|
||||||
|
Label {
|
||||||
|
Layout.preferredWidth: 100
|
||||||
|
text: Loc.t.app.label.changes
|
||||||
|
horizontalAlignment: Text.AlignHCenter
|
||||||
|
color: "#aaaaaa"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ListView {
|
||||||
|
id: versionList
|
||||||
|
Layout.fillWidth: true
|
||||||
|
Layout.fillHeight: true
|
||||||
|
clip: true
|
||||||
|
spacing: 1
|
||||||
|
model: picker.entries
|
||||||
|
enabled: !picker.updates.installing
|
||||||
|
ScrollBar.vertical: ScrollBar {}
|
||||||
|
|
||||||
|
delegate: ItemDelegate {
|
||||||
|
id: versionRow
|
||||||
|
required property var modelData
|
||||||
|
readonly property bool isLatest: picker.channel === picker.updates.channel
|
||||||
|
&& modelData.version === picker.updates.latest
|
||||||
|
width: versionList.width
|
||||||
|
height: 36
|
||||||
|
horizontalPadding: 10
|
||||||
|
verticalPadding: 0
|
||||||
|
hoverEnabled: true
|
||||||
|
onClicked: picker.selectedVersion = modelData.version
|
||||||
|
|
||||||
|
background: Rectangle {
|
||||||
|
radius: 5
|
||||||
|
color: picker.selectedVersion === versionRow.modelData.version ? "#364514"
|
||||||
|
: versionRow.hovered || versionRow.activeFocus ? "#2d2d2d" : "#232323"
|
||||||
|
}
|
||||||
|
|
||||||
|
contentItem: RowLayout {
|
||||||
|
Text {
|
||||||
|
Layout.fillWidth: true
|
||||||
|
text: versionRow.modelData.version
|
||||||
|
color: versionRow.modelData.download ? "#ffffff" : "#aaaaaa"
|
||||||
|
font.pixelSize: 13
|
||||||
|
elide: Text.ElideRight
|
||||||
|
}
|
||||||
|
Text {
|
||||||
|
visible: versionRow.isLatest
|
||||||
|
text: Loc.t.app.status.newVersion
|
||||||
|
color: "#b9d84f"
|
||||||
|
font.pixelSize: 11
|
||||||
|
}
|
||||||
|
Text {
|
||||||
|
Layout.preferredWidth: 110
|
||||||
|
text: Qt.formatDate(versionRow.modelData.date, Qt.locale().dateFormat(Locale.ShortFormat))
|
||||||
|
color: "#aaaaaa"
|
||||||
|
font.pixelSize: 12
|
||||||
|
}
|
||||||
|
Item {
|
||||||
|
Layout.preferredWidth: 100
|
||||||
|
Layout.preferredHeight: 28
|
||||||
|
|
||||||
|
Button {
|
||||||
|
id: changelogButton
|
||||||
|
anchors.centerIn: parent
|
||||||
|
width: 28
|
||||||
|
height: 28
|
||||||
|
padding: 0
|
||||||
|
hoverEnabled: true
|
||||||
|
flat: true
|
||||||
|
display: AbstractButton.IconOnly
|
||||||
|
icon.source: "images/ExternalLink.svg"
|
||||||
|
icon.width: 16
|
||||||
|
icon.height: 16
|
||||||
|
icon.color: "#b9d84f"
|
||||||
|
Accessible.name: Loc.t.app.hint.openChanges
|
||||||
|
ToolTip.text: Accessible.name
|
||||||
|
ToolTip.visible: hovered
|
||||||
|
onClicked: Qt.openUrlExternally(versionRow.modelData.changelog)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Label {
|
||||||
|
anchors.centerIn: parent
|
||||||
|
visible: picker.state !== "ready" || versionList.count === 0
|
||||||
|
text: picker.state === "loading" ? Loc.t.app.status.loadingVersions
|
||||||
|
: picker.state === "error" ? Loc.t.app.error.versionCatalog
|
||||||
|
: Loc.t.app.status.noVersions
|
||||||
|
color: "#aaaaaa"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
footer: Item {
|
||||||
|
implicitHeight: 60
|
||||||
|
|
||||||
|
Rectangle {
|
||||||
|
width: parent.width
|
||||||
|
height: 1
|
||||||
|
color: "#333333"
|
||||||
|
}
|
||||||
|
|
||||||
|
Row {
|
||||||
|
anchors.centerIn: parent
|
||||||
|
spacing: 12
|
||||||
|
|
||||||
|
Button {
|
||||||
|
id: closeButton
|
||||||
|
width: 130
|
||||||
|
height: 36
|
||||||
|
text: Loc.t.common.button.close
|
||||||
|
enabled: !picker.updates.installing
|
||||||
|
contentItem: Text {
|
||||||
|
text: closeButton.text
|
||||||
|
color: "#ffffff"
|
||||||
|
horizontalAlignment: Text.AlignHCenter
|
||||||
|
verticalAlignment: Text.AlignVCenter
|
||||||
|
}
|
||||||
|
background: Rectangle {
|
||||||
|
color: closeButton.hovered || closeButton.activeFocus ? "#444444" : "#333333"
|
||||||
|
radius: 6
|
||||||
|
}
|
||||||
|
onClicked: picker.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
Button {
|
||||||
|
id: installButton
|
||||||
|
width: 170
|
||||||
|
height: 36
|
||||||
|
text: picker.updates.installing ? Loc.t.app.status.downloadingInstaller : Loc.t.common.button.install
|
||||||
|
enabled: !picker.updates.installing && picker.state === "ready"
|
||||||
|
&& picker.entries.some(entry => entry.version === picker.selectedVersion && entry.download)
|
||||||
|
opacity: enabled || picker.updates.installing ? 1 : 0.45
|
||||||
|
contentItem: Text {
|
||||||
|
text: installButton.text
|
||||||
|
color: "#ffffff"
|
||||||
|
horizontalAlignment: Text.AlignHCenter
|
||||||
|
verticalAlignment: Text.AlignVCenter
|
||||||
|
}
|
||||||
|
background: Rectangle {
|
||||||
|
color: installButton.hovered || installButton.activeFocus ? "#a0c51a" : "#91B315"
|
||||||
|
radius: 6
|
||||||
|
}
|
||||||
|
onClicked: picker.updates.install(picker.channel, picker.selectedVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,8 +32,6 @@ Window {
|
|||||||
crashed || exitCode !== 0 ? "#cc3333" : "#555555")
|
crashed || exitCode !== 0 ? "#cc3333" : "#555555")
|
||||||
}
|
}
|
||||||
onMicrosoftLoginUrlReady: (url) => window.openMicrosoftLogin(url)
|
onMicrosoftLoginUrlReady: (url) => window.openMicrosoftLogin(url)
|
||||||
// Выбор в списке здесь не трогаем: новый профиль уже выбран тем, кто
|
|
||||||
// его создал, а повторный вход мог быть и не в последний профиль.
|
|
||||||
onMicrosoftLoginSucceeded: (playerName) =>
|
onMicrosoftLoginSucceeded: (playerName) =>
|
||||||
window.showToast(Loc.t.auth.status.signedInAs.arg(playerName), "#4b7a1f")
|
window.showToast(Loc.t.auth.status.signedInAs.arg(playerName), "#4b7a1f")
|
||||||
onMicrosoftLoginFailed: (message) => window.showToast(message, "#cc3333", 8000)
|
onMicrosoftLoginFailed: (message) => window.showToast(message, "#cc3333", 8000)
|
||||||
@@ -48,8 +46,19 @@ Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Единая всплывающая плашка: сообщения о ходе запуска, ошибки, статус игры.
|
LauncherUpdates {
|
||||||
// timeout === 0 — держим до следующего сообщения.
|
id: launcherUpdates
|
||||||
|
Component.onCompleted: refresh(channel)
|
||||||
|
onInstallationFailed: window.showToast(Loc.t.app.error.launcherInstall, "#cc3333", 8000)
|
||||||
|
}
|
||||||
|
|
||||||
|
LauncherVersionsDialog {
|
||||||
|
id: launcherVersions
|
||||||
|
objectName: "launcherVersions"
|
||||||
|
parent: Overlay.overlay
|
||||||
|
updates: launcherUpdates
|
||||||
|
}
|
||||||
|
|
||||||
function showToast(text, color, timeout) {
|
function showToast(text, color, timeout) {
|
||||||
toastLabel.text = text
|
toastLabel.text = text
|
||||||
toastBackground.color = color
|
toastBackground.color = color
|
||||||
@@ -62,9 +71,6 @@ Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Окно входа Microsoft создаётся по требованию, а не вместе с главным
|
|
||||||
// окном: MicrosoftLoginDialog.qml попадает в модуль только в сборках с Qt
|
|
||||||
// WebEngine, и обычная декларация сломала бы всё окно в остальных.
|
|
||||||
property var microsoftLoginDialog: null
|
property var microsoftLoginDialog: null
|
||||||
|
|
||||||
function openMicrosoftLogin(url) {
|
function openMicrosoftLogin(url) {
|
||||||
@@ -93,34 +99,74 @@ Window {
|
|||||||
anchors.fill: parent
|
anchors.fill: parent
|
||||||
source: "images/launcherBackground.png"
|
source: "images/launcherBackground.png"
|
||||||
|
|
||||||
Text {
|
Button {
|
||||||
id: launcherVersion
|
id: launcherVersion
|
||||||
x: 8
|
x: 8
|
||||||
y: 8
|
y: 8
|
||||||
color: "#ffffff"
|
height: 30
|
||||||
|
hoverEnabled: true
|
||||||
|
enabled: !backend.busy && !backend.gameRunning && !backend.switching && !backend.seasonalInstalling
|
||||||
text: Loc.t.app.label.version.arg(Qt.application.version)
|
text: Loc.t.app.label.version.arg(Qt.application.version)
|
||||||
font.pixelSize: 12
|
font.pixelSize: 12
|
||||||
|
|
||||||
|
horizontalPadding: 8
|
||||||
|
|
||||||
|
contentItem: Row {
|
||||||
|
spacing: 6
|
||||||
|
|
||||||
|
Text {
|
||||||
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
|
text: launcherVersion.text
|
||||||
|
color: "#ffffff"
|
||||||
|
font: launcherVersion.font
|
||||||
|
}
|
||||||
|
|
||||||
|
Rectangle {
|
||||||
|
id: channelBadge
|
||||||
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
|
visible: launcherUpdates.channel === "dev" || launcherUpdates.channel === "rc"
|
||||||
|
width: channelLabel.implicitWidth + 8
|
||||||
|
height: channelLabel.implicitHeight + 2
|
||||||
|
radius: 3
|
||||||
|
color: launcherUpdates.channel === "rc" ? "#c08a1e" : "#b03a3a"
|
||||||
|
|
||||||
|
Text {
|
||||||
|
id: channelLabel
|
||||||
|
anchors.centerIn: parent
|
||||||
|
text: launcherUpdates.channel.toUpperCase()
|
||||||
|
color: "#ffffff"
|
||||||
|
font.pixelSize: 10
|
||||||
|
font.bold: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
background: Rectangle {
|
||||||
|
opacity: 0.36
|
||||||
|
color: launcherVersion.pressed || launcherVersions.opened ? "#91B315" : "#000000"
|
||||||
|
radius: 6
|
||||||
|
border.color: launcherVersion.hovered || launcherVersion.activeFocus ? "#91B315" : color
|
||||||
|
}
|
||||||
|
|
||||||
|
onClicked: launcherVersions.open()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Канал сборки из суффикса версии (cmake/LauncherVersion.cmake): у релиза бейджа нет
|
|
||||||
Rectangle {
|
Rectangle {
|
||||||
id: channelBadge
|
visible: launcherUpdates.latest !== ""
|
||||||
readonly property var channel: /-(dev|rc)/.exec(Qt.application.version)
|
|
||||||
visible: channel !== null
|
|
||||||
anchors.left: launcherVersion.right
|
anchors.left: launcherVersion.right
|
||||||
anchors.leftMargin: 6
|
anchors.leftMargin: 6
|
||||||
anchors.verticalCenter: launcherVersion.verticalCenter
|
anchors.verticalCenter: launcherVersion.verticalCenter
|
||||||
width: channelLabel.implicitWidth + 8
|
width: updateLabel.implicitWidth + 12
|
||||||
height: channelLabel.implicitHeight + 2
|
height: updateLabel.implicitHeight + 6
|
||||||
radius: 3
|
radius: 4
|
||||||
color: channel && channel[1] === "rc" ? "#c08a1e" : "#b03a3a"
|
color: "#4b631c"
|
||||||
|
|
||||||
Text {
|
Text {
|
||||||
id: channelLabel
|
id: updateLabel
|
||||||
anchors.centerIn: parent
|
anchors.centerIn: parent
|
||||||
text: channelBadge.channel ? channelBadge.channel[1].toUpperCase() : ""
|
text: Loc.t.app.status.newVersion
|
||||||
color: "#ffffff"
|
color: "#ffffff"
|
||||||
font.pixelSize: 10
|
font.pixelSize: 11
|
||||||
font.bold: true
|
font.bold: true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -156,9 +202,6 @@ Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Панели хода работ ──────────────────────────────────────────────────
|
// ── Панели хода работ ──────────────────────────────────────────────────
|
||||||
// Загрузка и смена сборки взаимоисключающи по построению: busy() не даёт
|
|
||||||
// начать переключение во время установки и наоборот. Поэтому у панелей
|
|
||||||
// одни и те же якоря.
|
|
||||||
ProgressPanel {
|
ProgressPanel {
|
||||||
id: downloadPanel
|
id: downloadPanel
|
||||||
visible: backend.downloading
|
visible: backend.downloading
|
||||||
@@ -189,8 +232,6 @@ Window {
|
|||||||
title: backend.switchStage
|
title: backend.switchStage
|
||||||
fraction: backend.switchProgress
|
fraction: backend.switchProgress
|
||||||
status: backend.switchStatus
|
status: backend.switchStatus
|
||||||
// Отменять можно только пока идёт архивация: после очистки .minecraft
|
|
||||||
// отступать некуда, операцию нужно довести до конца.
|
|
||||||
cancellable: false
|
cancellable: false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,15 +268,11 @@ Window {
|
|||||||
rotation: 0
|
rotation: 0
|
||||||
editable: false
|
editable: false
|
||||||
hoverEnabled: true
|
hoverEnabled: true
|
||||||
// Пока идёт загрузка или установка, профиль и сборку не меняем:
|
|
||||||
// единственное доступное действие — отмена на панели загрузки.
|
|
||||||
enabled: !backend.busy && !backend.gameRunning
|
enabled: !backend.busy && !backend.gameRunning
|
||||||
opacity: enabled ? 1.0 : 0.45
|
opacity: enabled ? 1.0 : 0.45
|
||||||
|
|
||||||
model: backend.profileNames
|
model: backend.profileNames
|
||||||
|
|
||||||
// Пока список закрыт: открытый popup накрывает кнопку, и подсказка
|
|
||||||
// висела бы поверх собственного меню.
|
|
||||||
ToolTip.visible: profileBox.hovered && !profileBox.down
|
ToolTip.visible: profileBox.hovered && !profileBox.down
|
||||||
ToolTip.text: backend.profileNames.length === 0
|
ToolTip.text: backend.profileNames.length === 0
|
||||||
? Loc.t.profile.hint.addFirst
|
? Loc.t.profile.hint.addFirst
|
||||||
@@ -271,8 +308,6 @@ Window {
|
|||||||
autoTransform: true
|
autoTransform: true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Оформление повторяет кнопку выбора сборок: тёмный фон, зелёная
|
|
||||||
// рамка при наведении и зелёная заливка, пока список раскрыт.
|
|
||||||
background: Rectangle {
|
background: Rectangle {
|
||||||
implicitWidth: 120; implicitHeight: 40
|
implicitWidth: 120; implicitHeight: 40
|
||||||
color: profileBox.down ? "#91B315" : "#232323"
|
color: profileBox.down ? "#91B315" : "#232323"
|
||||||
@@ -285,13 +320,10 @@ Window {
|
|||||||
y: profileBox.height - 1
|
y: profileBox.height - 1
|
||||||
width: profileBox.width
|
width: profileBox.width
|
||||||
padding: 0
|
padding: 0
|
||||||
// Высота = кнопка "+" (32) + элементы списка, не более 200
|
|
||||||
height: 32 + Math.min(profileItemList.contentHeight, 200)
|
height: 32 + Math.min(profileItemList.contentHeight, 200)
|
||||||
|
|
||||||
contentItem: Item {
|
contentItem: Item {
|
||||||
anchors.fill: parent
|
anchors.fill: parent
|
||||||
|
|
||||||
// ── "+" button — всегда сверху ──────────────────────────
|
|
||||||
Rectangle {
|
Rectangle {
|
||||||
id: profileAddBtnBg
|
id: profileAddBtnBg
|
||||||
anchors.top: parent.top
|
anchors.top: parent.top
|
||||||
@@ -316,8 +348,6 @@ Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Добавленные профили — всегда ниже кнопки ───────────
|
|
||||||
ListView {
|
ListView {
|
||||||
id: profileItemList
|
id: profileItemList
|
||||||
anchors.top: profileAddBtnBg.bottom
|
anchors.top: profileAddBtnBg.bottom
|
||||||
@@ -352,8 +382,6 @@ Window {
|
|||||||
profileBox.currentIndex = profileItem.index
|
profileBox.currentIndex = profileItem.index
|
||||||
profileBox.popup.close()
|
profileBox.popup.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Карандаш — видна при наведении на строку ────
|
|
||||||
Image {
|
Image {
|
||||||
id: profilePencil
|
id: profilePencil
|
||||||
width: 16; height: 16
|
width: 16; height: 16
|
||||||
@@ -374,8 +402,6 @@ Window {
|
|||||||
onClicked: editProfileDialog.openFor(profileItem.index)
|
onClicked: editProfileDialog.openFor(profileItem.index)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Корзина — видна при наведении на строку ─────
|
|
||||||
Image {
|
Image {
|
||||||
id: profileTrash
|
id: profileTrash
|
||||||
width: 16; height: 16
|
width: 16; height: 16
|
||||||
@@ -506,10 +532,6 @@ Window {
|
|||||||
|
|
||||||
background: Image {
|
background: Image {
|
||||||
anchors.fill: parent
|
anchors.fill: parent
|
||||||
// Ассеты Options названы наоборот относительно Folder: зелёный
|
|
||||||
// #637a10 лежит в Options_Pressed.svg, а Options_active.svg —
|
|
||||||
// тёмный, как Idle. Берём их по цвету, а не по имени, чтобы
|
|
||||||
// наведение выглядело так же, как у кнопки папки модов.
|
|
||||||
source: settingsButton.pressed ? "images/Options/Options_active.svg"
|
source: settingsButton.pressed ? "images/Options/Options_active.svg"
|
||||||
: settingsButton.hovered ? "images/Options/Options_Pressed.svg"
|
: settingsButton.hovered ? "images/Options/Options_Pressed.svg"
|
||||||
: "images/Options/Options_Idle.svg"
|
: "images/Options/Options_Idle.svg"
|
||||||
@@ -523,8 +545,6 @@ Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Seasonal builds button ─────────────────────────────────────────────
|
// ── Seasonal builds button ─────────────────────────────────────────────
|
||||||
// Правый нижний угол — единственная свободная часть окна: панели хода работ
|
|
||||||
// висят слева, а всё остальное собрано вокруг кнопки запуска.
|
|
||||||
Button {
|
Button {
|
||||||
id: seasonsButton
|
id: seasonsButton
|
||||||
width: 183
|
width: 183
|
||||||
@@ -543,8 +563,6 @@ Window {
|
|||||||
horizontalAlignment: Text.AlignHCenter
|
horizontalAlignment: Text.AlignHCenter
|
||||||
verticalAlignment: Text.AlignVCenter
|
verticalAlignment: Text.AlignVCenter
|
||||||
}
|
}
|
||||||
|
|
||||||
// То же оформление, что у кнопки выбора сборок и списка профилей.
|
|
||||||
background: Rectangle {
|
background: Rectangle {
|
||||||
color: seasonsButton.pressed || seasonalDialog.opened ? "#91B315" : "#232323"
|
color: seasonsButton.pressed || seasonalDialog.opened ? "#91B315" : "#232323"
|
||||||
radius: 6
|
radius: 6
|
||||||
@@ -566,9 +584,6 @@ Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Add Profile Dialog ─────────────────────────────────────────────────
|
// ── Add Profile Dialog ─────────────────────────────────────────────────
|
||||||
// Bug fix: header/footer must be Item (not Rectangle) with explicit
|
|
||||||
// implicitHeight so Dialog correctly computes its own total height.
|
|
||||||
// Rectangle.implicitHeight defaults to 0 regardless of height:.
|
|
||||||
Dialog {
|
Dialog {
|
||||||
id: addProfileDialog
|
id: addProfileDialog
|
||||||
modal: true
|
modal: true
|
||||||
@@ -585,7 +600,7 @@ Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
header: Item {
|
header: Item {
|
||||||
implicitHeight: 52 // tells Dialog how tall the header is
|
implicitHeight: 52
|
||||||
Text {
|
Text {
|
||||||
anchors.centerIn: parent
|
anchors.centerIn: parent
|
||||||
text: Loc.t.profile.title.new
|
text: Loc.t.profile.title.new
|
||||||
@@ -625,7 +640,6 @@ Window {
|
|||||||
id: pfLogin
|
id: pfLogin
|
||||||
x: 20
|
x: 20
|
||||||
width: parent.width - 40
|
width: parent.width - 40
|
||||||
// Ник лицензионного профиля приходит из аккаунта: поля здесь нет.
|
|
||||||
visible: pfAuth.currentIndex !== 2
|
visible: pfAuth.currentIndex !== 2
|
||||||
placeholderText: Loc.t.profile.placeholder.login
|
placeholderText: Loc.t.profile.placeholder.login
|
||||||
color: "#ffffff"
|
color: "#ffffff"
|
||||||
@@ -666,7 +680,7 @@ Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
footer: Item {
|
footer: Item {
|
||||||
implicitHeight: 60 // tells Dialog how tall the footer is
|
implicitHeight: 60
|
||||||
Rectangle {
|
Rectangle {
|
||||||
anchors.top: parent.top
|
anchors.top: parent.top
|
||||||
width: parent.width
|
width: parent.width
|
||||||
@@ -716,14 +730,11 @@ Window {
|
|||||||
const type = pfAuth.currentIndex === 2 ? "microsoft"
|
const type = pfAuth.currentIndex === 2 ? "microsoft"
|
||||||
: pfAuth.currentIndex === 1 ? "elyby" : "offline"
|
: pfAuth.currentIndex === 1 ? "elyby" : "offline"
|
||||||
if (name !== "") {
|
if (name !== "") {
|
||||||
// Скрытые поля не сохраняем: в них мог остаться текст, набранный
|
|
||||||
// до переключения типа профиля.
|
|
||||||
backend.addProfile(name,
|
backend.addProfile(name,
|
||||||
type === "microsoft" ? "" : pfLogin.text.trim(),
|
type === "microsoft" ? "" : pfLogin.text.trim(),
|
||||||
type === "elyby" ? pfPassword.text : "",
|
type === "elyby" ? pfPassword.text : "",
|
||||||
type)
|
type)
|
||||||
profileBox.currentIndex = backend.profileNames.length - 1
|
profileBox.currentIndex = backend.profileNames.length - 1
|
||||||
// Профиль Microsoft без входа бесполезен: сразу показываем окно.
|
|
||||||
if (type === "microsoft")
|
if (type === "microsoft")
|
||||||
backend.startMicrosoftLogin(backend.profileNames.length - 1)
|
backend.startMicrosoftLogin(backend.profileNames.length - 1)
|
||||||
}
|
}
|
||||||
@@ -735,8 +746,6 @@ Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Edit Profile Dialog ────────────────────────────────────────────────
|
// ── Edit Profile Dialog ────────────────────────────────────────────────
|
||||||
// Идентичен диалогу создания, но с предзаполненными данными выбранного
|
|
||||||
// профиля. По нажатию ОК данные перезаписываются под тем же индексом.
|
|
||||||
Dialog {
|
Dialog {
|
||||||
id: editProfileDialog
|
id: editProfileDialog
|
||||||
modal: true
|
modal: true
|
||||||
@@ -746,7 +755,6 @@ Window {
|
|||||||
padding: 0
|
padding: 0
|
||||||
|
|
||||||
property int editIndex: -1
|
property int editIndex: -1
|
||||||
// Состояние входа в Microsoft у открытого профиля — для строки статуса.
|
|
||||||
property bool msProfile: false
|
property bool msProfile: false
|
||||||
property bool msLinked: false
|
property bool msLinked: false
|
||||||
property string msName: ""
|
property string msName: ""
|
||||||
@@ -813,7 +821,6 @@ Window {
|
|||||||
id: epLogin
|
id: epLogin
|
||||||
x: 20
|
x: 20
|
||||||
width: parent.width - 40
|
width: parent.width - 40
|
||||||
// Для лицензии логин не вводят: ниже показан ник из аккаунта.
|
|
||||||
visible: epAuth.currentIndex !== 2
|
visible: epAuth.currentIndex !== 2
|
||||||
placeholderText: Loc.t.profile.placeholder.login
|
placeholderText: Loc.t.profile.placeholder.login
|
||||||
color: "#ffffff"
|
color: "#ffffff"
|
||||||
@@ -826,9 +833,6 @@ Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Логин лицензионного профиля — ник, полученный при официальной
|
|
||||||
// авторизации. Отдельное поле, а не подмена epLogin.text: биндинг
|
|
||||||
// сломался бы первым же вводом в поле логина обычного профиля.
|
|
||||||
TextField {
|
TextField {
|
||||||
id: epMsLogin
|
id: epMsLogin
|
||||||
x: 20
|
x: 20
|
||||||
@@ -866,15 +870,11 @@ Window {
|
|||||||
id: epAuth
|
id: epAuth
|
||||||
x: 20
|
x: 20
|
||||||
width: parent.width - 40
|
width: parent.width - 40
|
||||||
// Тип уже сохранённого профиля показываем всегда: иначе в
|
|
||||||
// сборке без WebEngine он молча стал бы офлайновым.
|
|
||||||
model: (backend.microsoftAvailable || editProfileDialog.msProfile)
|
model: (backend.microsoftAvailable || editProfileDialog.msProfile)
|
||||||
? Loc.t.profile.authTypes
|
? Loc.t.profile.authTypes
|
||||||
: Loc.t.profile.authTypes.slice(0, 2)
|
: Loc.t.profile.authTypes.slice(0, 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Состояние аккаунта Microsoft и кнопка повторного входа: токен
|
|
||||||
// может протухнуть, а сменить аккаунт иначе нечем.
|
|
||||||
Column {
|
Column {
|
||||||
x: 20
|
x: 20
|
||||||
width: parent.width - 40
|
width: parent.width - 40
|
||||||
@@ -903,9 +903,6 @@ Window {
|
|||||||
radius: 6
|
radius: 6
|
||||||
}
|
}
|
||||||
onClicked: {
|
onClicked: {
|
||||||
// Тип профиля мог быть только что переключён на
|
|
||||||
// Microsoft — сохраняем его до входа, иначе backend
|
|
||||||
// припишет токены профилю другого типа.
|
|
||||||
backend.updateProfile(editProfileDialog.editIndex,
|
backend.updateProfile(editProfileDialog.editIndex,
|
||||||
epName.text.trim(), "", "", "microsoft")
|
epName.text.trim(), "", "", "microsoft")
|
||||||
editProfileDialog.close()
|
editProfileDialog.close()
|
||||||
@@ -988,8 +985,6 @@ Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Two-factor Dialog ──────────────────────────────────────────────────
|
// ── Two-factor Dialog ──────────────────────────────────────────────────
|
||||||
// Ely.by отклоняет пароль с пометкой two factor — код добираем здесь и
|
|
||||||
// продолжаем прерванный запуск.
|
|
||||||
Dialog {
|
Dialog {
|
||||||
id: twoFactorDialog
|
id: twoFactorDialog
|
||||||
modal: true
|
modal: true
|
||||||
@@ -1116,15 +1111,8 @@ Window {
|
|||||||
x: (window.width - width) / 2
|
x: (window.width - width) / 2
|
||||||
y: (window.height - height) / 2
|
y: (window.height - height) / 2
|
||||||
padding: 0
|
padding: 0
|
||||||
|
|
||||||
// Выбранная сборка Java живёт в свойстве, а не в поле ввода: её выбирают
|
|
||||||
// в отдельном окне, а записывается она только по «Сохранить».
|
|
||||||
property string javaRuntimeId: ""
|
property string javaRuntimeId: ""
|
||||||
// Раскрытый путь к папке игры: хранится свойством, а не присваивается
|
|
||||||
// тексту напрямую, — иначе подпись не пережила бы смену языка.
|
|
||||||
property string resolvedGameDir: ""
|
property string resolvedGameDir: ""
|
||||||
// Не привязка: javaRuntimeInfo() — обычный вызов, и сам он не
|
|
||||||
// пересчитается, когда сборка докачается. Обновляем по событиям.
|
|
||||||
property var javaRuntimeInfo: null
|
property var javaRuntimeInfo: null
|
||||||
onJavaRuntimeIdChanged: settingsDialog.refreshJavaInfo()
|
onJavaRuntimeIdChanged: settingsDialog.refreshJavaInfo()
|
||||||
|
|
||||||
@@ -1184,8 +1172,6 @@ Window {
|
|||||||
topPadding: 18
|
topPadding: 18
|
||||||
bottomPadding: 18
|
bottomPadding: 18
|
||||||
|
|
||||||
// Язык — настройка уровня приложения, поэтому стоит над параметрами
|
|
||||||
// запуска. Подписи в модели переводятся, коды рядом — нет.
|
|
||||||
Column {
|
Column {
|
||||||
x: 20
|
x: 20
|
||||||
width: parent.width - 40
|
width: parent.width - 40
|
||||||
@@ -1223,8 +1209,6 @@ Window {
|
|||||||
placeholder: Loc.t.settings.placeholder.javaPath
|
placeholder: Loc.t.settings.placeholder.javaPath
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сборка Java из папки лаунчера. Выбрана — запуск идёт ей, а не тем,
|
|
||||||
// что нашлось в системе; путь выше остаётся запасным вариантом.
|
|
||||||
Column {
|
Column {
|
||||||
x: 20
|
x: 20
|
||||||
width: parent.width - 40
|
width: parent.width - 40
|
||||||
@@ -1343,8 +1327,6 @@ Window {
|
|||||||
x: 20
|
x: 20
|
||||||
text: Loc.t.settings.label.fullscreen
|
text: Loc.t.settings.label.fullscreen
|
||||||
|
|
||||||
// Индикатор Basic-стиля — крупный светлый квадрат, на тёмном
|
|
||||||
// фоне диалога он не читается. Рисуем свой в палитре окна.
|
|
||||||
indicator: Rectangle {
|
indicator: Rectangle {
|
||||||
implicitWidth: 18
|
implicitWidth: 18
|
||||||
implicitHeight: 18
|
implicitHeight: 18
|
||||||
@@ -1452,8 +1434,6 @@ Window {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Окно выбора Java. Живёт рядом с настройками, а не внутри: оно шире их и
|
|
||||||
// центрируется по самому окну лаунчера.
|
|
||||||
JavaPickerDialog {
|
JavaPickerDialog {
|
||||||
id: javaPicker
|
id: javaPicker
|
||||||
backend: backend
|
backend: backend
|
||||||
|
|||||||
@@ -22,8 +22,6 @@ Dialog {
|
|||||||
padding: 0
|
padding: 0
|
||||||
width: 960
|
width: 960
|
||||||
height: 560
|
height: 560
|
||||||
// Закрывается и во время установки: отменить её можно только на панели
|
|
||||||
// загрузки главного окна, а модальное окно эту панель перекрывает.
|
|
||||||
closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
|
closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
|
||||||
|
|
||||||
background: Rectangle {
|
background: Rectangle {
|
||||||
@@ -175,8 +173,6 @@ Dialog {
|
|||||||
|
|
||||||
width: modelData.width
|
width: modelData.width
|
||||||
text: seasons.cellText(buildRow.modelData, modelData.key)
|
text: seasons.cellText(buildRow.modelData, modelData.key)
|
||||||
// Подсвеченная строка залита зелёным — тёмный текст
|
|
||||||
// на ней читается, светлый нет.
|
|
||||||
color: buildRow.highlighted
|
color: buildRow.highlighted
|
||||||
? "#1e1e1e"
|
? "#1e1e1e"
|
||||||
: (modelData.key === "status"
|
: (modelData.key === "status"
|
||||||
@@ -266,6 +262,25 @@ Dialog {
|
|||||||
anchors.verticalCenter: parent.verticalCenter
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
spacing: 12
|
spacing: 12
|
||||||
|
|
||||||
|
Button {
|
||||||
|
id: closeButton
|
||||||
|
text: Loc.t.common.button.close
|
||||||
|
width: 120; height: 36
|
||||||
|
enabled: !seasons.backend.switching
|
||||||
|
opacity: enabled ? 1.0 : 0.45
|
||||||
|
contentItem: Text {
|
||||||
|
text: parent.text
|
||||||
|
color: "#ffffff"
|
||||||
|
horizontalAlignment: Text.AlignHCenter
|
||||||
|
verticalAlignment: Text.AlignVCenter
|
||||||
|
}
|
||||||
|
background: Rectangle {
|
||||||
|
color: parent.pressed ? "#444444" : "#333333"
|
||||||
|
radius: 6
|
||||||
|
}
|
||||||
|
onClicked: seasons.close()
|
||||||
|
}
|
||||||
|
|
||||||
Button {
|
Button {
|
||||||
id: refreshButton
|
id: refreshButton
|
||||||
width: 150
|
width: 150
|
||||||
|
|||||||
@@ -85,7 +85,6 @@ void AuthService::postJson(
|
|||||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||||
const QByteArray payload = reply->readAll();
|
const QByteArray payload = reply->readAll();
|
||||||
|
|
||||||
// Сетевую ошибку отличаем от ответа сервера: при 401 статус есть, а error — есть всегда.
|
|
||||||
QString transportError;
|
QString transportError;
|
||||||
if (status == 0 && reply->error() != QNetworkReply::NoError)
|
if (status == 0 && reply->error() != QNetworkReply::NoError)
|
||||||
transportError = reply->errorString();
|
transportError = reply->errorString();
|
||||||
@@ -136,7 +135,6 @@ void AuthService::loginElyBy(const QString &login,
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Токен протух — пробуем продлить его, не спрашивая пароль.
|
|
||||||
emit progress(Loc::text("auth.ely.progress.refreshingToken"));
|
emit progress(Loc::text("auth.ely.progress.refreshingToken"));
|
||||||
postJson(QStringLiteral("/auth/refresh"),
|
postJson(QStringLiteral("/auth/refresh"),
|
||||||
{{QStringLiteral("accessToken"), accessToken},
|
{{QStringLiteral("accessToken"), accessToken},
|
||||||
|
|||||||
@@ -20,8 +20,6 @@ struct AuthResult
|
|||||||
QString accessToken; // ${auth_access_token}
|
QString accessToken; // ${auth_access_token}
|
||||||
QString clientToken; // ${clientid}
|
QString clientToken; // ${clientid}
|
||||||
QString userType; // ${user_type}: legacy / msa / ELYBY
|
QString userType; // ${user_type}: legacy / msa / ELYBY
|
||||||
|
|
||||||
// Только для аккаунтов Microsoft.
|
|
||||||
QString refreshToken; // продлевает сессию без ввода пароля
|
QString refreshToken; // продлевает сессию без ввода пароля
|
||||||
QString xuid; // ${auth_xuid}
|
QString xuid; // ${auth_xuid}
|
||||||
QDateTime expiresAt; // UTC-время, когда протухает accessToken
|
QDateTime expiresAt; // UTC-время, когда протухает accessToken
|
||||||
|
|||||||
@@ -14,9 +14,6 @@
|
|||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
// Признаки того, что в папке играли: это принадлежит сборке. Служебные файлы
|
|
||||||
// чужих лаунчеров (launcher_log.txt, webcache2 и т. п.) сюда не входят, иначе
|
|
||||||
// пустая папка официального лаунчера давала бы сборку без версии.
|
|
||||||
const QStringList kContentMarkers = {QStringLiteral("mods"),
|
const QStringList kContentMarkers = {QStringLiteral("mods"),
|
||||||
QStringLiteral("saves"),
|
QStringLiteral("saves"),
|
||||||
QStringLiteral("resourcepacks"),
|
QStringLiteral("resourcepacks"),
|
||||||
@@ -72,9 +69,6 @@ QDateTime parseLastUsed(const QString &text)
|
|||||||
return when;
|
return when;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Версии из launcher_profiles.json, которые есть в versions/, свежие сверху.
|
|
||||||
// Профили latest-release/latest-snapshot без lastVersionId пропускаются: без
|
|
||||||
// манифеста не узнать, во что они разворачивались.
|
|
||||||
QStringList profileVersions(const QString &gameDir, const QStringList &installed)
|
QStringList profileVersions(const QString &gameDir, const QStringList &installed)
|
||||||
{
|
{
|
||||||
const QJsonObject profiles =
|
const QJsonObject profiles =
|
||||||
@@ -95,7 +89,6 @@ QStringList profileVersions(const QString &gameDir, const QStringList &installed
|
|||||||
continue;
|
continue;
|
||||||
used.append({id, parseLastUsed(profile.value(QStringLiteral("lastUsed")).toString())});
|
used.append({id, parseLastUsed(profile.value(QStringLiteral("lastUsed")).toString())});
|
||||||
}
|
}
|
||||||
// Профиль без даты считается самым старым.
|
|
||||||
std::stable_sort(used.begin(), used.end(), [](const Used &a, const Used &b) {
|
std::stable_sort(used.begin(), used.end(), [](const Used &a, const Used &b) {
|
||||||
if (a.when.isValid() != b.when.isValid())
|
if (a.when.isValid() != b.when.isValid())
|
||||||
return a.when.isValid();
|
return a.when.isValid();
|
||||||
@@ -110,7 +103,6 @@ QStringList profileVersions(const QString &gameDir, const QStringList &installed
|
|||||||
return ids;
|
return ids;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Установленные версии по времени правки описания, свежие сверху.
|
|
||||||
QStringList versionsByMtime(const QString &gameDir, QStringList installed)
|
QStringList versionsByMtime(const QString &gameDir, QStringList installed)
|
||||||
{
|
{
|
||||||
std::stable_sort(installed.begin(), installed.end(), [&](const QString &a, const QString &b) {
|
std::stable_sort(installed.begin(), installed.end(), [&](const QString &a, const QString &b) {
|
||||||
@@ -125,7 +117,6 @@ QList<Candidate> load(const QString &gameDir, const QStringList &ids)
|
|||||||
QList<Candidate> out;
|
QList<Candidate> out;
|
||||||
for (const QString &id : ids) {
|
for (const QString &id : ids) {
|
||||||
const QJsonObject json = readObject(versionJsonPath(gameDir, id));
|
const QJsonObject json = readObject(versionJsonPath(gameDir, id));
|
||||||
// Битое описание не запустится — такую версию не предлагаем.
|
|
||||||
if (json.isEmpty())
|
if (json.isEmpty())
|
||||||
continue;
|
continue;
|
||||||
out.append({id, json, !json.value(QStringLiteral("inheritsFrom")).toString().isEmpty()});
|
out.append({id, json, !json.value(QStringLiteral("inheritsFrom")).toString().isEmpty()});
|
||||||
@@ -133,8 +124,6 @@ QList<Candidate> load(const QString &gameDir, const QStringList &ids)
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// "1.20.1-47.2.0" → "47.2.0". Хвост "-1.7.10" у старых Forge остаётся: в
|
|
||||||
// каталоге модлоадеров версии записаны так же.
|
|
||||||
QString stripGamePrefix(const QString &version, const QString &game)
|
QString stripGamePrefix(const QString &version, const QString &game)
|
||||||
{
|
{
|
||||||
if (!game.isEmpty() && version.startsWith(game + u'-'))
|
if (!game.isEmpty() && version.startsWith(game + u'-'))
|
||||||
@@ -163,15 +152,12 @@ LoaderInfo loaderOf(const QJsonObject &versionJson)
|
|||||||
return {QStringLiteral("quilt"), version};
|
return {QStringLiteral("quilt"), version};
|
||||||
if (coord == QLatin1String("net.neoforged:neoforge"))
|
if (coord == QLatin1String("net.neoforged:neoforge"))
|
||||||
return {QStringLiteral("neoforge"), version};
|
return {QStringLiteral("neoforge"), version};
|
||||||
// NeoForge для 1.20.1 публиковался под старым именем артефакта.
|
|
||||||
if (coord == QLatin1String("net.neoforged:forge"))
|
if (coord == QLatin1String("net.neoforged:forge"))
|
||||||
return {QStringLiteral("neoforge"), stripGamePrefix(version, game)};
|
return {QStringLiteral("neoforge"), stripGamePrefix(version, game)};
|
||||||
if (coord == QLatin1String("net.minecraftforge:forge"))
|
if (coord == QLatin1String("net.minecraftforge:forge"))
|
||||||
return {QStringLiteral("forge"), stripGamePrefix(version, game)};
|
return {QStringLiteral("forge"), stripGamePrefix(version, game)};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Библиотек модлоадера в описании может не быть (их вынесли в родителя или
|
|
||||||
// описание урезали руками) — тогда смотрим на имя, которое дают установщики.
|
|
||||||
const QString id = versionJson.value(QStringLiteral("id")).toString();
|
const QString id = versionJson.value(QStringLiteral("id")).toString();
|
||||||
for (const auto &[key, prefix] : {std::pair{QStringLiteral("fabric"), QStringLiteral("fabric-loader-")},
|
for (const auto &[key, prefix] : {std::pair{QStringLiteral("fabric"), QStringLiteral("fabric-loader-")},
|
||||||
std::pair{QStringLiteral("quilt"), QStringLiteral("quilt-loader-")}}) {
|
std::pair{QStringLiteral("quilt"), QStringLiteral("quilt-loader-")}}) {
|
||||||
@@ -200,8 +186,6 @@ std::optional<Detected> detect(const QString &gameDir)
|
|||||||
const QList<Candidate> fromProfiles = load(gameDir, profileVersions(gameDir, installed));
|
const QList<Candidate> fromProfiles = load(gameDir, profileVersions(gameDir, installed));
|
||||||
const QList<Candidate> fromVersions = load(gameDir, versionsByMtime(gameDir, installed));
|
const QList<Candidate> fromVersions = load(gameDir, versionsByMtime(gameDir, installed));
|
||||||
|
|
||||||
// С модами в папке ванильная версия почти наверняка не та, с которой играли:
|
|
||||||
// сначала ищем профиль модлоадера, и только потом берём что есть.
|
|
||||||
const Candidate *chosen = nullptr;
|
const Candidate *chosen = nullptr;
|
||||||
QString source;
|
QString source;
|
||||||
auto pick = [&](const QList<Candidate> &list, const QString &from, bool needInherits) {
|
auto pick = [&](const QList<Candidate> &list, const QString &from, bool needInherits) {
|
||||||
|
|||||||
@@ -5,34 +5,25 @@
|
|||||||
|
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
|
||||||
// Что уже разложено в папке игры, когда лаунчер запускают впервые. Только
|
|
||||||
// читает файлы: .minecraft не меняется ни при каком исходе.
|
|
||||||
namespace GameDirImport {
|
namespace GameDirImport {
|
||||||
|
|
||||||
// Модлоадер, найденный в описании профиля versions/<id>/<id>.json.
|
|
||||||
struct LoaderInfo
|
struct LoaderInfo
|
||||||
{
|
{
|
||||||
QString key; // "" | forge | fabric | neoforge | quilt
|
QString key; // "" | forge | fabric | neoforge | quilt
|
||||||
QString version; // в том же виде, что и в каталоге ModLoaderVersionService
|
QString version; // в том же виде, что и в каталоге ModLoaderVersionService
|
||||||
};
|
};
|
||||||
|
|
||||||
// Сборка, которую стоит завести под содержимое папки игры.
|
|
||||||
struct Detected
|
struct Detected
|
||||||
{
|
{
|
||||||
QString minecraftVersion; // inheritsFrom профиля, а без него — сам id
|
QString minecraftVersion; // inheritsFrom профиля, а без него — сам id
|
||||||
QString resolvedVersionId; // id профиля, если он наследует другую версию
|
QString resolvedVersionId; // id профиля, если он наследует другую версию
|
||||||
QString loader;
|
QString loader;
|
||||||
QString loaderVersion;
|
QString loaderVersion;
|
||||||
// Откуда взята версия: "launcher_profiles", "versions" или "content" —
|
|
||||||
// версии не нашлось, но моды или миры есть. Для тестов и отладки.
|
|
||||||
QString source;
|
QString source;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Модлоадер по библиотекам профиля, а если по ним не понять — по его id.
|
|
||||||
// Незнакомый профиль (OptiFine, LabyMod) даёт пустой key.
|
|
||||||
LoaderInfo loaderOf(const QJsonObject &versionJson);
|
LoaderInfo loaderOf(const QJsonObject &versionJson);
|
||||||
|
|
||||||
// nullopt — в папке нет ни установленных версий, ни модов, миров и настроек игры.
|
|
||||||
std::optional<Detected> detect(const QString &gameDir);
|
std::optional<Detected> detect(const QString &gameDir);
|
||||||
|
|
||||||
}
|
}
|
||||||
+2
-14
@@ -29,8 +29,6 @@ QString nativeToken(const QString &path)
|
|||||||
return QDir::toNativeSeparators(path);
|
return QDir::toNativeSeparators(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Подставляет ${...}. Аргументы, в которых после подстановки остались
|
|
||||||
// неизвестные плейсхолдеры, вызывающий выбрасывает.
|
|
||||||
QString substitute(QString argument, const QHash<QString, QString> &variables)
|
QString substitute(QString argument, const QHash<QString, QString> &variables)
|
||||||
{
|
{
|
||||||
for (auto it = variables.cbegin(); it != variables.cend(); ++it)
|
for (auto it = variables.cbegin(); it != variables.cend(); ++it)
|
||||||
@@ -47,14 +45,12 @@ bool isNativeLibraryFile(const QString &fileName)
|
|||||||
for (const QString &suffix : suffixes)
|
for (const QString &suffix : suffixes)
|
||||||
if (fileName.endsWith(suffix, Qt::CaseInsensitive))
|
if (fileName.endsWith(suffix, Qt::CaseInsensitive))
|
||||||
return true;
|
return true;
|
||||||
// Версионированные so (libfoo.so.1, libfoo.so.1.2.3). Хвост — строго цифры,
|
|
||||||
// иначе в натив попадают служебные файлы LWJGL вроде liblwjgl.so.sha1 / .so.git.
|
|
||||||
static const QRegularExpression versionedSo(QStringLiteral("\\.so(\\.\\d+)+$"),
|
static const QRegularExpression versionedSo(QStringLiteral("\\.so(\\.\\d+)+$"),
|
||||||
QRegularExpression::CaseInsensitiveOption);
|
QRegularExpression::CaseInsensitiveOption);
|
||||||
return versionedSo.match(fileName).hasMatch();
|
return versionedSo.match(fileName).hasMatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
}
|
||||||
|
|
||||||
GameLauncher::GameLauncher(QObject *parent)
|
GameLauncher::GameLauncher(QObject *parent)
|
||||||
: QObject(parent)
|
: QObject(parent)
|
||||||
@@ -113,7 +109,7 @@ bool ignoreListCovers(const QString &ignoreListArgument, const QString &fileName
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
}
|
||||||
|
|
||||||
QStringList GameLauncher::buildArguments(const LaunchOptions &options,
|
QStringList GameLauncher::buildArguments(const LaunchOptions &options,
|
||||||
const MinecraftVersion &version,
|
const MinecraftVersion &version,
|
||||||
@@ -163,7 +159,6 @@ QStringList GameLauncher::buildArguments(const LaunchOptions &options,
|
|||||||
|
|
||||||
QStringList arguments;
|
QStringList arguments;
|
||||||
|
|
||||||
// Свои jvm-аргументы идут первыми — как в строке запуска из примера.
|
|
||||||
if (!options.authlibInjectorPath.isEmpty()) {
|
if (!options.authlibInjectorPath.isEmpty()) {
|
||||||
arguments << QStringLiteral("-javaagent:%1=%2")
|
arguments << QStringLiteral("-javaagent:%1=%2")
|
||||||
.arg(nativeToken(options.authlibInjectorPath), options.authlibInjectorApi)
|
.arg(nativeToken(options.authlibInjectorPath), options.authlibInjectorApi)
|
||||||
@@ -175,12 +170,6 @@ QStringList GameLauncher::buildArguments(const LaunchOptions &options,
|
|||||||
arguments << QStringLiteral("-Xmx%1M").arg(options.maxMemoryMb);
|
arguments << QStringLiteral("-Xmx%1M").arg(options.maxMemoryMb);
|
||||||
arguments += options.extraJvmArgs;
|
arguments += options.extraJvmArgs;
|
||||||
|
|
||||||
// Forge 1.17+ собирает слой модулей из classpath, пропуская всё, чьё имя
|
|
||||||
// начинается с записи в -DignoreList. Ванильный клиентский jar записан там
|
|
||||||
// как ${version_name}.jar — с расчётом на лаунчер Mojang, который кладёт в
|
|
||||||
// classpath jar самого профиля. Своего jar у профиля Forge нет, мы кладём
|
|
||||||
// родительский, и без его имени в списке он становится вторым модулем с
|
|
||||||
// классами Minecraft: «Modules minecraft and _1._20._1 export package ...».
|
|
||||||
const QString clientJarName = QFileInfo(version.clientJarPath).fileName();
|
const QString clientJarName = QFileInfo(version.clientJarPath).fileName();
|
||||||
|
|
||||||
for (const QString &argument : version.jvmArgs) {
|
for (const QString &argument : version.jvmArgs) {
|
||||||
@@ -344,7 +333,6 @@ bool GameLauncher::launch(const LaunchOptions &options,
|
|||||||
m_process->deleteLater();
|
m_process->deleteLater();
|
||||||
m_process = nullptr;
|
m_process = nullptr;
|
||||||
});
|
});
|
||||||
// Токен в лог не попадает — маскируем его в отображаемой строке запуска.
|
|
||||||
QStringList shown = arguments;
|
QStringList shown = arguments;
|
||||||
const int tokenIndex = shown.indexOf(QStringLiteral("--accessToken"));
|
const int tokenIndex = shown.indexOf(QStringLiteral("--accessToken"));
|
||||||
if (tokenIndex >= 0 && tokenIndex + 1 < shown.size())
|
if (tokenIndex >= 0 && tokenIndex + 1 < shown.size())
|
||||||
|
|||||||
+4
-6
@@ -8,7 +8,6 @@
|
|||||||
|
|
||||||
class QProcess;
|
class QProcess;
|
||||||
|
|
||||||
// Всё, что лаунчер знает к моменту нажатия PLAY.
|
|
||||||
struct LaunchOptions
|
struct LaunchOptions
|
||||||
{
|
{
|
||||||
QString gameDir; // .minecraft
|
QString gameDir; // .minecraft
|
||||||
@@ -19,19 +18,18 @@ struct LaunchOptions
|
|||||||
QString accessToken;
|
QString accessToken;
|
||||||
QString userType;
|
QString userType;
|
||||||
QString clientToken;
|
QString clientToken;
|
||||||
QString xuid; // Пусто — подставится "0", как в офлайне
|
QString xuid;
|
||||||
|
QString javaPath;
|
||||||
QString javaPath; // Пусто — ищем сами
|
|
||||||
int minMemoryMb = 512;
|
int minMemoryMb = 512;
|
||||||
int maxMemoryMb = 4096;
|
int maxMemoryMb = 4096;
|
||||||
QStringList extraJvmArgs;
|
QStringList extraJvmArgs;
|
||||||
|
|
||||||
int windowWidth = 0; // 0 — не передавать --width/--height
|
int windowWidth = 0;
|
||||||
int windowHeight = 0;
|
int windowHeight = 0;
|
||||||
bool fullscreen = false;
|
bool fullscreen = false;
|
||||||
|
|
||||||
QString serverAddress; // host[:port] — автозаход на сервер
|
QString serverAddress; // host[:port] — автозаход на сервер
|
||||||
QString authlibInjectorPath; // Пусто — не подключаем
|
QString authlibInjectorPath;
|
||||||
QString authlibInjectorApi = QStringLiteral("ely.by");
|
QString authlibInjectorApi = QStringLiteral("ely.by");
|
||||||
|
|
||||||
QString launcherName = QStringLiteral("BiLauncher");
|
QString launcherName = QStringLiteral("BiLauncher");
|
||||||
|
|||||||
@@ -31,6 +31,50 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"strings": {
|
"strings": {
|
||||||
|
"app.label.launcherVersions": {
|
||||||
|
"ru": "Версии лаунчера",
|
||||||
|
"en": "Launcher versions"
|
||||||
|
},
|
||||||
|
"app.label.versionName": {
|
||||||
|
"ru": "Версия",
|
||||||
|
"en": "Version"
|
||||||
|
},
|
||||||
|
"app.label.releaseDate": {
|
||||||
|
"ru": "Дата выпуска",
|
||||||
|
"en": "Release date"
|
||||||
|
},
|
||||||
|
"app.label.changes": {
|
||||||
|
"ru": "Изменения",
|
||||||
|
"en": "Changes"
|
||||||
|
},
|
||||||
|
"app.hint.openChanges": {
|
||||||
|
"ru": "Открыть изменения в браузере",
|
||||||
|
"en": "Open changes in browser"
|
||||||
|
},
|
||||||
|
"app.status.newVersion": {
|
||||||
|
"ru": "Есть новая версия",
|
||||||
|
"en": "New version available"
|
||||||
|
},
|
||||||
|
"app.status.loadingVersions": {
|
||||||
|
"ru": "Загрузка списка версий…",
|
||||||
|
"en": "Loading versions…"
|
||||||
|
},
|
||||||
|
"app.status.noVersions": {
|
||||||
|
"ru": "Нет опубликованных версий",
|
||||||
|
"en": "No published versions"
|
||||||
|
},
|
||||||
|
"app.status.downloadingInstaller": {
|
||||||
|
"ru": "Скачивание…",
|
||||||
|
"en": "Downloading…"
|
||||||
|
},
|
||||||
|
"app.error.versionCatalog": {
|
||||||
|
"ru": "Не удалось загрузить список версий",
|
||||||
|
"en": "Could not load the version list"
|
||||||
|
},
|
||||||
|
"app.error.launcherInstall": {
|
||||||
|
"ru": "Не удалось скачать или установить лаунчер",
|
||||||
|
"en": "Could not download or install the launcher"
|
||||||
|
},
|
||||||
"app.label.version": {
|
"app.label.version": {
|
||||||
"ru": "Версия: %1",
|
"ru": "Версия: %1",
|
||||||
"en": "Version: %1"
|
"en": "Version: %1"
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
|
||||||
|
stroke="#b9d84f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M11 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-5"/>
|
||||||
|
<path d="M14 4h6v6m0-6-9 9"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 271 B |
+1
-1
@@ -55,7 +55,7 @@ public:
|
|||||||
|
|
||||||
qint64 bytesDone() const;
|
qint64 bytesDone() const;
|
||||||
qint64 bytesTotal() const { return m_bytesTotal; }
|
qint64 bytesTotal() const { return m_bytesTotal; }
|
||||||
double fraction() const; // 0..1, либо -1 пока итог неизвестен
|
double fraction() const;
|
||||||
|
|
||||||
void install(const JavaRuntimeEntry &entry);
|
void install(const JavaRuntimeEntry &entry);
|
||||||
void cancel();
|
void cancel();
|
||||||
|
|||||||
+12
-12
@@ -19,17 +19,17 @@ QString javaKindTitle(JavaRuntimeKind kind);
|
|||||||
|
|
||||||
struct JavaRuntimeEntry
|
struct JavaRuntimeEntry
|
||||||
{
|
{
|
||||||
QString id; // temurin-jdk-21.0.12.1_1 | mojang-java-runtime-delta
|
QString id;
|
||||||
JavaRuntimeKind kind = JavaRuntimeKind::Jdk;
|
JavaRuntimeKind kind = JavaRuntimeKind::Jdk;
|
||||||
int major = 0; // 8, 17, 21…
|
int major = 0;
|
||||||
QString version; // 21.0.12.1+1 | 21.0.7
|
QString version;
|
||||||
QString component; // java-runtime-delta — только у сборок Mojang
|
QString component;
|
||||||
QDateTime released;
|
QDateTime released;
|
||||||
QUrl url; // архив Temurin либо manifest.json компонента
|
QUrl url;
|
||||||
QString checksum; // sha256 архива Temurin, sha1 манифеста Mojang
|
QString checksum;
|
||||||
qint64 size = 0; // размер загрузки, 0 — неизвестен
|
qint64 size = 0;
|
||||||
QString archive; // zip | tar.gz | mojang
|
QString archive;
|
||||||
QString architecture; // x64 | aarch64 — на macOS бывает и не родная
|
QString architecture;
|
||||||
bool lts = false;
|
bool lts = false;
|
||||||
|
|
||||||
bool isValid() const { return !id.isEmpty() && major > 0 && url.isValid(); }
|
bool isValid() const { return !id.isEmpty() && major > 0 && url.isValid(); }
|
||||||
@@ -38,11 +38,11 @@ struct JavaRuntimeEntry
|
|||||||
struct InstalledJavaRuntime
|
struct InstalledJavaRuntime
|
||||||
{
|
{
|
||||||
QString id;
|
QString id;
|
||||||
QString kind; // java | jdk | jre
|
QString kind;
|
||||||
int major = 0;
|
int major = 0;
|
||||||
QString version;
|
QString version;
|
||||||
QString javaPath; // абсолютный путь к java/java.exe
|
QString javaPath;
|
||||||
qint64 size = 0; // сколько заняло на диске по итогам установки
|
qint64 size = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
namespace JavaRuntimeStore {
|
namespace JavaRuntimeStore {
|
||||||
|
|||||||
@@ -12,41 +12,19 @@
|
|||||||
|
|
||||||
class QNetworkAccessManager;
|
class QNetworkAccessManager;
|
||||||
|
|
||||||
// Каталог сборок Java, которые лаунчер умеет скачать: качает, кэширует в папке
|
|
||||||
// лаунчера и отдаёт из кэша, пока тот не устарел. Устроен как
|
|
||||||
// VersionManifestService и работает в GUI-потоке.
|
|
||||||
//
|
|
||||||
// Источников два и они дополняют друг друга:
|
|
||||||
//
|
|
||||||
// * Mojang (категория «Java») — ровно тот рантайм, которым запускает игру
|
|
||||||
// официальный лаунчер. Версий немного, зато они заведомо совместимы.
|
|
||||||
//
|
|
||||||
// * Eclipse Temurin (категории JDK и JRE) — свежие сборки всех мажорных
|
|
||||||
// версий, включая те, до которых Mojang ещё не дошёл.
|
|
||||||
//
|
|
||||||
// Отдаются только сборки под текущие ОС и архитектуру: выбрать заведомо
|
|
||||||
// неработающую нечем. Исключение — macOS на Apple Silicon, где под Java 8 и 16
|
|
||||||
// сборок aarch64 нет вовсе и приходится брать x64 (работает через Rosetta).
|
|
||||||
class JavaRuntimeService : public QObject
|
class JavaRuntimeService : public QObject
|
||||||
{
|
{
|
||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// ok = true и непустой warning — данные отдали из устаревшего кэша.
|
|
||||||
using Callback = std::function<void(bool ok, const QString &warning)>;
|
using Callback = std::function<void(bool ok, const QString &warning)>;
|
||||||
|
|
||||||
explicit JavaRuntimeService(QObject *parent = nullptr);
|
explicit JavaRuntimeService(QObject *parent = nullptr);
|
||||||
|
|
||||||
void ensureLoaded(Callback callback, bool forceRefresh = false);
|
void ensureLoaded(Callback callback, bool forceRefresh = false);
|
||||||
|
|
||||||
// Новые версии сверху.
|
|
||||||
QList<JavaRuntimeEntry> entries(JavaRuntimeKind kind) const;
|
QList<JavaRuntimeEntry> entries(JavaRuntimeKind kind) const;
|
||||||
std::optional<JavaRuntimeEntry> find(const QString &id) const;
|
std::optional<JavaRuntimeEntry> find(const QString &id) const;
|
||||||
|
|
||||||
// Что скачать, если для версии игры нужна Java major, а подходящей в
|
|
||||||
// системе нет. Точное совпадение мажорной версии предпочтительнее более
|
|
||||||
// новой, JDK — предпочтительнее JRE: установщики Forge и NeoForge иногда
|
|
||||||
// требуют инструментов из полного комплекта. Пусто — предложить нечего.
|
|
||||||
std::optional<JavaRuntimeEntry> bestFor(int major) const;
|
std::optional<JavaRuntimeEntry> bestFor(int major) const;
|
||||||
|
|
||||||
bool isRefreshing() const { return m_outstanding > 0; }
|
bool isRefreshing() const { return m_outstanding > 0; }
|
||||||
@@ -59,12 +37,9 @@ signals:
|
|||||||
private:
|
private:
|
||||||
void startRefresh();
|
void startRefresh();
|
||||||
void requestAdoptiumReleases();
|
void requestAdoptiumReleases();
|
||||||
// allowFallback — на macOS/aarch64 разрешено переспросить сборку под x64.
|
|
||||||
void requestFeatureRelease(int major, const QString &architecture, bool allowFallback);
|
void requestFeatureRelease(int major, const QString &architecture, bool allowFallback);
|
||||||
void requestMojangRuntimes();
|
void requestMojangRuntimes();
|
||||||
|
|
||||||
// Общий хвост любого запроса: считает незавершённые и, когда их не
|
|
||||||
// осталось, применяет накопленное.
|
|
||||||
void requestFinished(const QString &warning);
|
void requestFinished(const QString &warning);
|
||||||
void finishRefresh();
|
void finishRefresh();
|
||||||
|
|
||||||
@@ -83,8 +58,6 @@ private:
|
|||||||
QDateTime m_fetchedAt;
|
QDateTime m_fetchedAt;
|
||||||
bool m_cacheRead = false;
|
bool m_cacheRead = false;
|
||||||
|
|
||||||
// Накопитель одного обновления: ответы приходят вразнобой, каталог
|
|
||||||
// подменяется целиком и только когда пришли все.
|
|
||||||
QList<JavaRuntimeEntry> m_incoming;
|
QList<JavaRuntimeEntry> m_incoming;
|
||||||
QStringList m_warnings;
|
QStringList m_warnings;
|
||||||
QSet<int> m_ltsVersions;
|
QSet<int> m_ltsVersions;
|
||||||
|
|||||||
+5
-171
@@ -42,16 +42,10 @@ const QString kOffline = QStringLiteral("offline");
|
|||||||
const QString kElyBy = QStringLiteral("elyby");
|
const QString kElyBy = QStringLiteral("elyby");
|
||||||
const QString kMicrosoft = QStringLiteral("microsoft");
|
const QString kMicrosoft = QStringLiteral("microsoft");
|
||||||
|
|
||||||
// Токен Minecraft живёт около суток, но обновляем его чуть раньше срока: игра
|
|
||||||
// проверяет сессию не в первую секунду после старта.
|
|
||||||
const int kTokenRenewMarginSecs = 120;
|
const int kTokenRenewMarginSecs = 120;
|
||||||
|
|
||||||
// Сервер готовых сборок по умолчанию. Переопределяется ключом seasonalBaseUrl
|
|
||||||
// в settings.json — это нужно, чтобы прогонять установку против локального
|
|
||||||
// http-сервера, не трогая боевой.
|
|
||||||
const QString kSeasonalBaseUrl = QStringLiteral("https://launcher-builds.galeonworx.com");
|
const QString kSeasonalBaseUrl = QStringLiteral("https://launcher-builds.galeonworx.com");
|
||||||
|
|
||||||
// Тип авторизации профиля: всё, что лаунчер не знает, считается офлайном.
|
|
||||||
QString normalizedAuthType(const QString &value)
|
QString normalizedAuthType(const QString &value)
|
||||||
{
|
{
|
||||||
if (value == kElyBy)
|
if (value == kElyBy)
|
||||||
@@ -61,7 +55,6 @@ QString normalizedAuthType(const QString &value)
|
|||||||
return kOffline;
|
return kOffline;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Дата сезона в таблице: год нужен, время — нет.
|
|
||||||
QString formatSeasonDate(const QDate &date)
|
QString formatSeasonDate(const QDate &date)
|
||||||
{
|
{
|
||||||
return date.isValid() ? date.toString(QStringLiteral("dd.MM.yyyy")) : QStringLiteral("—");
|
return date.isValid() ? date.toString(QStringLiteral("dd.MM.yyyy")) : QStringLiteral("—");
|
||||||
@@ -92,32 +85,20 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
, m_seasonalMeta(new SeasonalBuildService(this))
|
, m_seasonalMeta(new SeasonalBuildService(this))
|
||||||
, m_packDownloader(new SeasonalPackDownloader(this))
|
, m_packDownloader(new SeasonalPackDownloader(this))
|
||||||
{
|
{
|
||||||
// Папка лаунчера создаётся при первом запуске и проверяется при каждом
|
|
||||||
// следующем — если её удалили, она появится снова.
|
|
||||||
QString storageError;
|
QString storageError;
|
||||||
if (!LauncherPaths::ensureRootExists(&storageError))
|
if (!LauncherPaths::ensureRootExists(&storageError))
|
||||||
m_storageIssues << Loc::text("storage.error.launcherDirFailed").arg(storageError);
|
m_storageIssues << Loc::text("storage.error.launcherDirFailed").arg(storageError);
|
||||||
|
|
||||||
// Первый запуск — ни настроек, ни списка сборок, ни старого versions.json.
|
|
||||||
// Смотреть надо до loadData(): битый файл она отводит в .bak, а
|
|
||||||
// ensureDataFiles() создаёт пустые. Пустой customBuilds.json — это уже
|
|
||||||
// решение пользователя «сборок нет», и сборку из папки игры мы не заводим.
|
|
||||||
const bool firstRun = !QFile::exists(LauncherPaths::settingsFile())
|
const bool firstRun = !QFile::exists(LauncherPaths::settingsFile())
|
||||||
&& !QFile::exists(LauncherPaths::customBuildsFile())
|
&& !QFile::exists(LauncherPaths::customBuildsFile())
|
||||||
&& !QFile::exists(LauncherPaths::legacyCustomBuildsFile());
|
&& !QFile::exists(LauncherPaths::legacyCustomBuildsFile());
|
||||||
|
|
||||||
loadSettings();
|
loadSettings();
|
||||||
// Порядок важен: миграция должна успеть до того, как ensureDataFiles()
|
|
||||||
// создаст пустой customBuilds.json поверх старых данных.
|
|
||||||
migrateLegacyBuildsFile();
|
migrateLegacyBuildsFile();
|
||||||
loadData();
|
loadData();
|
||||||
const QString importedBuild = firstRun && m_builds.isEmpty() ? importGameDir() : QString();
|
const QString importedBuild = firstRun && m_builds.isEmpty() ? importGameDir() : QString();
|
||||||
ensureDataFiles();
|
ensureDataFiles();
|
||||||
|
|
||||||
// Прошлое переключение оборвалось на середине. Доигрываем его сами, а не
|
|
||||||
// предлагаем пользователю переключиться заново: архив прежней сборки уже
|
|
||||||
// записан целиком, а вот повторное переключение сначала заархивировало бы
|
|
||||||
// поверх него нынешнее — наполовину разобранное — содержимое .minecraft.
|
|
||||||
const QString interrupted = m_switcher->interruptedSwitchWarning();
|
const QString interrupted = m_switcher->interruptedSwitchWarning();
|
||||||
if (!interrupted.isEmpty()) {
|
if (!interrupted.isEmpty()) {
|
||||||
m_storageIssues << interrupted;
|
m_storageIssues << interrupted;
|
||||||
@@ -190,23 +171,17 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
});
|
});
|
||||||
connect(m_installer, &VersionInstaller::progressChanged,
|
connect(m_installer, &VersionInstaller::progressChanged,
|
||||||
this, &LauncherBackend::downloadChanged);
|
this, &LauncherBackend::downloadChanged);
|
||||||
// Порядок важен: на installedVersionsChanged интерфейс перечитывает каталог,
|
|
||||||
// и устаревший кэш вернулся бы наружу.
|
|
||||||
connect(m_installer, &VersionInstaller::finished, this, [this](const QString &id) {
|
connect(m_installer, &VersionInstaller::finished, this, [this](const QString &id) {
|
||||||
invalidateCatalog();
|
invalidateCatalog();
|
||||||
emit installedVersionsChanged();
|
emit installedVersionsChanged();
|
||||||
emit downloadChanged();
|
emit downloadChanged();
|
||||||
emit busyChanged();
|
emit busyChanged();
|
||||||
emit launchProgress(Loc::text("version.status.downloaded").arg(id));
|
emit launchProgress(Loc::text("version.status.downloaded").arg(id));
|
||||||
// У ванильной сезонной сборки этот установщик и есть весь шаг Loader.
|
|
||||||
// Внутри установки модлоадера он тоже отчитывается — тогда ход
|
|
||||||
// передаст ModLoaderInstaller, а не он.
|
|
||||||
if (m_season.stage == SeasonStage::Loader && !m_loaderInstaller->isRunning())
|
if (m_season.stage == SeasonStage::Loader && !m_loaderInstaller->isRunning())
|
||||||
seasonAdvance();
|
seasonAdvance();
|
||||||
});
|
});
|
||||||
connect(m_installer, &VersionInstaller::failed, this, [this](const QString &id,
|
connect(m_installer, &VersionInstaller::failed, this, [this](const QString &id,
|
||||||
const QString &message) {
|
const QString &message) {
|
||||||
// Часть файлов всё же появилась — список установленного мог измениться.
|
|
||||||
invalidateCatalog();
|
invalidateCatalog();
|
||||||
emit installedVersionsChanged();
|
emit installedVersionsChanged();
|
||||||
emit downloadChanged();
|
emit downloadChanged();
|
||||||
@@ -220,8 +195,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
emit busyChanged();
|
emit busyChanged();
|
||||||
});
|
});
|
||||||
connect(m_switcher, &BuildSwitcher::finished, this, [this](int toBuildId) {
|
connect(m_switcher, &BuildSwitcher::finished, this, [this](int toBuildId) {
|
||||||
// Активной сборка становится только здесь: провалившееся переключение
|
|
||||||
// оставляет активной прежнюю.
|
|
||||||
m_settings.insert(QStringLiteral("activeBuildId"), toBuildId);
|
m_settings.insert(QStringLiteral("activeBuildId"), toBuildId);
|
||||||
saveSettings();
|
saveSettings();
|
||||||
invalidateCatalog();
|
invalidateCatalog();
|
||||||
@@ -233,8 +206,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
emit launchProgress(Loc::text("build.status.active")
|
emit launchProgress(Loc::text("build.status.active")
|
||||||
.arg(index >= 0 ? m_builds[index].name : QString()));
|
.arg(index >= 0 ? m_builds[index].name : QString()));
|
||||||
|
|
||||||
// Раскатка пака могла быть и той, что доигралась после перезапуска —
|
|
||||||
// тогда цепочки установки уже нет, а записать ревизию всё равно надо.
|
|
||||||
const QJsonObject note = m_switcher->lastPackNote();
|
const QJsonObject note = m_switcher->lastPackNote();
|
||||||
if (!note.isEmpty())
|
if (!note.isEmpty())
|
||||||
recordSeasonalPack(toBuildId, note, m_switcher->lastPackEntries());
|
recordSeasonalPack(toBuildId, note, m_switcher->lastPackEntries());
|
||||||
@@ -250,10 +221,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
emit installedVersionsChanged();
|
emit installedVersionsChanged();
|
||||||
emit switchChanged();
|
emit switchChanged();
|
||||||
emit busyChanged();
|
emit busyChanged();
|
||||||
// Раскатка пака и смена сборки приходят одним сигналом, а
|
|
||||||
// сказать пользователю надо разное: после сорванного
|
|
||||||
// переключения .minecraft лежит разобранной, а сорванная
|
|
||||||
// раскатка означает лишь наполовину обновлённую сборку.
|
|
||||||
if (m_season.stage == SeasonStage::Applying) {
|
if (m_season.stage == SeasonStage::Applying) {
|
||||||
emit launchError(gameDirIntact
|
emit launchError(gameDirIntact
|
||||||
? Loc::text("build.error.filesNotInstalled").arg(message)
|
? Loc::text("build.error.filesNotInstalled").arg(message)
|
||||||
@@ -276,8 +243,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
connect(m_loaderMeta, &ModLoaderVersionService::refreshingChanged,
|
connect(m_loaderMeta, &ModLoaderVersionService::refreshingChanged,
|
||||||
this, &LauncherBackend::downloadChanged);
|
this, &LauncherBackend::downloadChanged);
|
||||||
|
|
||||||
// Установщик лоадера делит панель прогресса и флаг занятости с обычным
|
|
||||||
// установщиком версий — сигналы у них одни и те же.
|
|
||||||
connect(m_loaderInstaller, &ModLoaderInstaller::started, this, [this](const QString &label) {
|
connect(m_loaderInstaller, &ModLoaderInstaller::started, this, [this](const QString &label) {
|
||||||
emit busyChanged();
|
emit busyChanged();
|
||||||
emit downloadChanged();
|
emit downloadChanged();
|
||||||
@@ -343,8 +308,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
this, &LauncherBackend::invalidateSeasonalCatalog);
|
this, &LauncherBackend::invalidateSeasonalCatalog);
|
||||||
connect(m_seasonalMeta, &SeasonalBuildService::refreshingChanged,
|
connect(m_seasonalMeta, &SeasonalBuildService::refreshingChanged,
|
||||||
this, &LauncherBackend::seasonalCatalogLoadingChanged);
|
this, &LauncherBackend::seasonalCatalogLoadingChanged);
|
||||||
// Статус строки («установлена», «доступно обновление») считается по
|
|
||||||
// локальным записям — их изменение обновляет и таблицу.
|
|
||||||
connect(this, &LauncherBackend::customBuildsChanged,
|
connect(this, &LauncherBackend::customBuildsChanged,
|
||||||
this, &LauncherBackend::invalidateSeasonalCatalog);
|
this, &LauncherBackend::invalidateSeasonalCatalog);
|
||||||
|
|
||||||
@@ -379,8 +342,6 @@ LauncherBackend::LauncherBackend(QObject *parent)
|
|||||||
seasonFail({});
|
seasonFail({});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Интерфейс подключается к сигналам уже после конструктора — сообщаем отложенно.
|
|
||||||
// Ошибки хранилища идут следом: плашка одна, и важнее показать их.
|
|
||||||
if (!importedBuild.isEmpty()) {
|
if (!importedBuild.isEmpty()) {
|
||||||
QTimer::singleShot(0, this, [this, importedBuild] { emit gameDirImported(importedBuild); });
|
QTimer::singleShot(0, this, [this, importedBuild] { emit gameDirImported(importedBuild); });
|
||||||
}
|
}
|
||||||
@@ -448,8 +409,6 @@ void LauncherBackend::addCustomBuild(const QString &name,
|
|||||||
m_builds.append(build);
|
m_builds.append(build);
|
||||||
saveCustomBuilds();
|
saveCustomBuilds();
|
||||||
emit customBuildsChanged();
|
emit customBuildsChanged();
|
||||||
// Без версии игры ставить нечего: launchVersionIdOf() вернул бы имя сборки,
|
|
||||||
// и установщик пошёл бы искать в манифесте «Сборка 1».
|
|
||||||
if (!minecraftVersion.trimmed().isEmpty())
|
if (!minecraftVersion.trimmed().isEmpty())
|
||||||
maybeInstall(minecraftVersion.trimmed());
|
maybeInstall(minecraftVersion.trimmed());
|
||||||
}
|
}
|
||||||
@@ -466,15 +425,11 @@ void LauncherBackend::updateProfile(int index,
|
|||||||
Profile &profile = m_profiles[index];
|
Profile &profile = m_profiles[index];
|
||||||
const QString type = normalizedAuthType(authType);
|
const QString type = normalizedAuthType(authType);
|
||||||
|
|
||||||
// Смена логина или пароля обесценивает сохранённый токен Ely.by. У аккаунта
|
|
||||||
// Microsoft ни того ни другого нет, и переименование профиля не должно
|
|
||||||
// выкидывать из аккаунта.
|
|
||||||
if (profile.authType == kElyBy && (profile.login != login || profile.password != password)) {
|
if (profile.authType == kElyBy && (profile.login != login || profile.password != password)) {
|
||||||
profile.accessToken.clear();
|
profile.accessToken.clear();
|
||||||
profile.uuid.clear();
|
profile.uuid.clear();
|
||||||
profile.resolvedName.clear();
|
profile.resolvedName.clear();
|
||||||
}
|
}
|
||||||
// Смена типа авторизации: чужие учётные данные к новому типу не подходят.
|
|
||||||
if (profile.authType != type) {
|
if (profile.authType != type) {
|
||||||
profile.accessToken.clear();
|
profile.accessToken.clear();
|
||||||
profile.refreshToken.clear();
|
profile.refreshToken.clear();
|
||||||
@@ -509,8 +464,6 @@ void LauncherBackend::updateCustomBuild(int index, const QVariantMap &fields)
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Сменилась версия игры — выбранная сборка модлоадера к ней уже не подходит.
|
|
||||||
// Сам лоадер оставляем: чекбокс не должен слетать, он просто перевыберет версию.
|
|
||||||
const QString previousMinecraft = build.minecraftVersion;
|
const QString previousMinecraft = build.minecraftVersion;
|
||||||
|
|
||||||
take("name", build.name);
|
take("name", build.name);
|
||||||
@@ -531,10 +484,7 @@ void LauncherBackend::updateCustomBuild(int index, const QVariantMap &fields)
|
|||||||
|
|
||||||
saveCustomBuilds();
|
saveCustomBuilds();
|
||||||
emit customBuildsChanged();
|
emit customBuildsChanged();
|
||||||
emit activeBuildChanged(); // имя активной сборки могло измениться
|
emit activeBuildChanged();
|
||||||
// maybeInstall() здесь намеренно нет: карточка сборки сохраняется по ходу
|
|
||||||
// правки, и загрузка стартовала бы почти на каждое действие. Для этого есть
|
|
||||||
// installCustomBuild().
|
|
||||||
}
|
}
|
||||||
|
|
||||||
QVariantMap LauncherBackend::profileAt(int index) const
|
QVariantMap LauncherBackend::profileAt(int index) const
|
||||||
@@ -649,7 +599,6 @@ int LauncherBackend::activeBuildIndex() const
|
|||||||
if (m_builds.isEmpty())
|
if (m_builds.isEmpty())
|
||||||
return -1;
|
return -1;
|
||||||
const int index = indexOfBuildId(m_settings.value(QStringLiteral("activeBuildId")).toInt());
|
const int index = indexOfBuildId(m_settings.value(QStringLiteral("activeBuildId")).toInt());
|
||||||
// Настройка могла указывать на удалённую сборку — тогда активна первая.
|
|
||||||
return index >= 0 ? index : 0;
|
return index >= 0 ? index : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -672,8 +621,6 @@ void LauncherBackend::setActiveBuildIndex(int index)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Содержимое .minecraft принадлежит прежней сборке: сначала оно уезжает в
|
|
||||||
// её архив, и только потом на его место разворачивается выбранная.
|
|
||||||
const CustomBuild &target = m_builds[index];
|
const CustomBuild &target = m_builds[index];
|
||||||
emit launchProgress(Loc::text("build.progress.switchingTo").arg(target.name));
|
emit launchProgress(Loc::text("build.progress.switchingTo").arg(target.name));
|
||||||
m_switcher->switchTo(current >= 0 ? m_builds[current].id : -1,
|
m_switcher->switchTo(current >= 0 ? m_builds[current].id : -1,
|
||||||
@@ -693,16 +640,11 @@ QString LauncherBackend::activeBuildName() const
|
|||||||
|
|
||||||
void LauncherBackend::installCustomBuild(int index)
|
void LauncherBackend::installCustomBuild(int index)
|
||||||
{
|
{
|
||||||
// Установка сборки — это установка её версии игры и, если выбран,
|
|
||||||
// модлоадера: они ставятся одной цепочкой.
|
|
||||||
installLoaderForBuild(index);
|
installLoaderForBuild(index);
|
||||||
}
|
}
|
||||||
|
|
||||||
QString LauncherBackend::launchVersionIdOf(const CustomBuild &build) const
|
QString LauncherBackend::launchVersionIdOf(const CustomBuild &build) const
|
||||||
{
|
{
|
||||||
// resolvedVersionId появляется после установки модлоадера. Пользователь мог
|
|
||||||
// назвать сборку как угодно — тогда версией считаем само имя: так работали
|
|
||||||
// записи, созданные до появления каталога версий.
|
|
||||||
if (!build.resolvedVersionId.isEmpty())
|
if (!build.resolvedVersionId.isEmpty())
|
||||||
return build.resolvedVersionId;
|
return build.resolvedVersionId;
|
||||||
return build.minecraftVersion.isEmpty() ? build.name : build.minecraftVersion;
|
return build.minecraftVersion.isEmpty() ? build.name : build.minecraftVersion;
|
||||||
@@ -751,7 +693,6 @@ bool LauncherBackend::catalogLoading() const
|
|||||||
|
|
||||||
void LauncherBackend::refreshVersionCatalog(bool force)
|
void LauncherBackend::refreshVersionCatalog(bool force)
|
||||||
{
|
{
|
||||||
// Список установленного мог поменяться и без нас (папку добавили руками).
|
|
||||||
invalidateCatalog();
|
invalidateCatalog();
|
||||||
m_manifest->ensureLoaded([this](bool ok, const QString &warning) {
|
m_manifest->ensureLoaded([this](bool ok, const QString &warning) {
|
||||||
if (!ok && !warning.isEmpty())
|
if (!ok && !warning.isEmpty())
|
||||||
@@ -773,8 +714,6 @@ QVariantMap LauncherBackend::versionRemovalInfo(const QString &versionId) const
|
|||||||
return {};
|
return {};
|
||||||
|
|
||||||
const qint64 bytes = VersionLoader::installedSize(gameDir(), id);
|
const qint64 bytes = VersionLoader::installedSize(gameDir(), id);
|
||||||
// Сборки не правим при удалении — ссылка на неустановленную версию это
|
|
||||||
// рабочее состояние. Но перечислить, кого заденет, надо.
|
|
||||||
QStringList builds;
|
QStringList builds;
|
||||||
for (const CustomBuild &build : m_builds) {
|
for (const CustomBuild &build : m_builds) {
|
||||||
if (build.minecraftVersion == id || build.resolvedVersionId == id
|
if (build.minecraftVersion == id || build.resolvedVersionId == id
|
||||||
@@ -805,8 +744,6 @@ void LauncherBackend::removeVersion(const QString &versionId)
|
|||||||
emit launchError(Loc::text("common.error.busyOperation"));
|
emit launchError(Loc::text("common.error.busyOperation"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Какой версией сейчас играют, GameLauncher наружу не отдаёт, поэтому на
|
|
||||||
// время игры удаление запрещено целиком.
|
|
||||||
if (m_launcher->isRunning()) {
|
if (m_launcher->isRunning()) {
|
||||||
emit launchError(Loc::text("common.error.closeGameFirst"));
|
emit launchError(Loc::text("common.error.closeGameFirst"));
|
||||||
return;
|
return;
|
||||||
@@ -836,9 +773,6 @@ void LauncherBackend::rebuildCatalog() const
|
|||||||
{
|
{
|
||||||
m_catalog.clear();
|
m_catalog.clear();
|
||||||
|
|
||||||
// Плоский список в порядке манифеста — новые версии сверху. Раскладку по
|
|
||||||
// категориям и отбор делает окно выбора версии: ему нужен один список,
|
|
||||||
// который можно фильтровать, а не готовая структура с разделителями.
|
|
||||||
const QList<RemoteVersionEntry> remote = m_manifest->versions();
|
const QList<RemoteVersionEntry> remote = m_manifest->versions();
|
||||||
const QStringList installed = VersionLoader::installedVersions(gameDir());
|
const QStringList installed = VersionLoader::installedVersions(gameDir());
|
||||||
const QSet<QString> installedSet(installed.cbegin(), installed.cend());
|
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)));
|
m_catalog.append(makeVersionRow(entry.id, entry.type, installedSet.contains(entry.id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сборки модлоадеров манифест не знает — они попадают в «Прочие».
|
|
||||||
QStringList unknown;
|
QStringList unknown;
|
||||||
for (const QString &id : installed) {
|
for (const QString &id : installed) {
|
||||||
if (!known.contains(id))
|
if (!known.contains(id))
|
||||||
@@ -887,8 +820,6 @@ void LauncherBackend::maybeInstall(const QString &versionId)
|
|||||||
return;
|
return;
|
||||||
if (m_installer->versionId() == id || m_installer->isQueued(id))
|
if (m_installer->versionId() == id || m_installer->isQueued(id))
|
||||||
return;
|
return;
|
||||||
// Манифест здесь не спрашиваем: установщик сам скажет, что версии в нём нет,
|
|
||||||
// и это правильный ответ на вручную вписанный id сборки.
|
|
||||||
m_installer->install(gameDir(), id);
|
m_installer->install(gameDir(), id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -904,7 +835,6 @@ void LauncherBackend::installVersion(const QString &versionId)
|
|||||||
|
|
||||||
void LauncherBackend::cancelDownload()
|
void LauncherBackend::cancelDownload()
|
||||||
{
|
{
|
||||||
// Установщик лоадера сам остановит вложенную установку версии.
|
|
||||||
if (m_loaderInstaller->isRunning())
|
if (m_loaderInstaller->isRunning())
|
||||||
m_loaderInstaller->cancel();
|
m_loaderInstaller->cancel();
|
||||||
else if (m_installer->isRunning())
|
else if (m_installer->isRunning())
|
||||||
@@ -915,24 +845,18 @@ void LauncherBackend::cancelDownload()
|
|||||||
m_packDownloader->cancel();
|
m_packDownloader->cancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Панель загрузки одна на три установщика: пока идёт установка модлоадера, она
|
|
||||||
// показывает его стадии, включая вложенную загрузку файлов версии. Установка
|
|
||||||
// Java начинается только когда остальные не заняты, поэтому за панель они не спорят.
|
|
||||||
bool LauncherBackend::downloading() const
|
bool LauncherBackend::downloading() const
|
||||||
{
|
{
|
||||||
return m_loaderInstaller->isRunning() || m_installer->isRunning()
|
return m_loaderInstaller->isRunning() || m_installer->isRunning()
|
||||||
|| m_javaInstaller->isRunning() || m_packDownloader->isRunning();
|
|| m_javaInstaller->isRunning() || m_packDownloader->isRunning();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Java качается сама по себе, а версия и лоадер — вместе; отсюда и порядок проверок.
|
|
||||||
bool LauncherBackend::javaDownloadShown() const
|
bool LauncherBackend::javaDownloadShown() const
|
||||||
{
|
{
|
||||||
return m_javaInstaller->isRunning() && !m_installer->isRunning()
|
return m_javaInstaller->isRunning() && !m_installer->isRunning()
|
||||||
&& !m_loaderInstaller->isRunning();
|
&& !m_loaderInstaller->isRunning();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Пак качается отдельным шагом цепочки, когда остальные установщики уже
|
|
||||||
// отработали, — за панель они не спорят.
|
|
||||||
bool LauncherBackend::packDownloadShown() const
|
bool LauncherBackend::packDownloadShown() const
|
||||||
{
|
{
|
||||||
return m_packDownloader->isRunning() && !m_installer->isRunning()
|
return m_packDownloader->isRunning() && !m_installer->isRunning()
|
||||||
@@ -947,7 +871,6 @@ double LauncherBackend::downloadProgress() const
|
|||||||
return m_javaInstaller->fraction();
|
return m_javaInstaller->fraction();
|
||||||
if (!m_loaderInstaller->isRunning())
|
if (!m_loaderInstaller->isRunning())
|
||||||
return m_installer->fraction();
|
return m_installer->fraction();
|
||||||
// Внутри установки лоадера файлы качает VersionInstaller — его доля точнее.
|
|
||||||
return m_installer->isRunning() ? m_installer->fraction() : m_loaderInstaller->fraction();
|
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) {
|
bool ok, const QString &warning) {
|
||||||
if (!ok && !warning.isEmpty())
|
if (!ok && !warning.isEmpty())
|
||||||
emit launchError(warning);
|
emit launchError(warning);
|
||||||
// Кэш мог ответить сразу, без сигнала versionsChanged.
|
|
||||||
emit loaderVersionsChanged(loaderKey, gameVersion);
|
emit loaderVersionsChanged(loaderKey, gameVersion);
|
||||||
}, force);
|
}, force);
|
||||||
}
|
}
|
||||||
@@ -1069,7 +991,6 @@ void LauncherBackend::installLoaderForBuild(int index)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Лоадер не выбран — сборка ванильная, ставим саму версию игры.
|
|
||||||
const auto loader = loaderFromKey(build.loader);
|
const auto loader = loaderFromKey(build.loader);
|
||||||
if (!loader) {
|
if (!loader) {
|
||||||
if (build.resolvedVersionId != build.minecraftVersion)
|
if (build.resolvedVersionId != build.minecraftVersion)
|
||||||
@@ -1105,8 +1026,6 @@ void LauncherBackend::launchGame(int profileIndex, int buildIndex)
|
|||||||
.arg(m_installer->versionId()));
|
.arg(m_installer->versionId()));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Игра ищет java при запуске: стартовать посреди её установки — значит
|
|
||||||
// найти половину распакованного дерева.
|
|
||||||
if (m_javaInstaller->isRunning()) {
|
if (m_javaInstaller->isRunning()) {
|
||||||
emit launchError(Loc::text("java.error.installBusy")
|
emit launchError(Loc::text("java.error.installBusy")
|
||||||
.arg(m_javaInstaller->label()));
|
.arg(m_javaInstaller->label()));
|
||||||
@@ -1185,8 +1104,6 @@ void LauncherBackend::launchGame(int profileIndex, int buildIndex)
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_pendingProfile = profileIndex;
|
m_pendingProfile = profileIndex;
|
||||||
// Держим id, а не индекс: пока идёт авторизация, сборку могли удалить из
|
|
||||||
// модального окна, и индекс уехал бы на чужую запись.
|
|
||||||
m_pendingBuild = entry.id;
|
m_pendingBuild = entry.id;
|
||||||
m_pendingInjectorPath.clear();
|
m_pendingInjectorPath.clear();
|
||||||
beginAuthentication();
|
beginAuthentication();
|
||||||
@@ -1198,8 +1115,6 @@ void LauncherBackend::startMicrosoftLogin(int profileIndex)
|
|||||||
emit microsoftLoginFailed(Loc::text("auth.msa.error.noWebEngine"));
|
emit microsoftLoginFailed(Loc::text("auth.msa.error.noWebEngine"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// -1 из QML означает «профиля ещё нет»; внутри держим -2, чтобы отличать
|
|
||||||
// это состояние от закрытого окна.
|
|
||||||
if (profileIndex >= m_profiles.size()) {
|
if (profileIndex >= m_profiles.size()) {
|
||||||
emit microsoftLoginFailed(Loc::text("profile.error.notFound"));
|
emit microsoftLoginFailed(Loc::text("profile.error.notFound"));
|
||||||
return;
|
return;
|
||||||
@@ -1236,7 +1151,7 @@ void LauncherBackend::finishMicrosoftLogin(const QString &code)
|
|||||||
const int target = m_msaLoginProfile;
|
const int target = m_msaLoginProfile;
|
||||||
m_msaLoginProfile = -1;
|
m_msaLoginProfile = -1;
|
||||||
if (target == -1)
|
if (target == -1)
|
||||||
return; // окно закрыли, пока шла авторизация
|
return;
|
||||||
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
emit microsoftLoginFailed(result.error);
|
emit microsoftLoginFailed(result.error);
|
||||||
@@ -1244,7 +1159,6 @@ void LauncherBackend::finishMicrosoftLogin(const QString &code)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (target == -2) {
|
if (target == -2) {
|
||||||
// Профиля ещё нет — заводим его на ник из аккаунта.
|
|
||||||
Profile profile;
|
Profile profile;
|
||||||
profile.id = m_nextProfileId++;
|
profile.id = m_nextProfileId++;
|
||||||
profile.name = result.playerName;
|
profile.name = result.playerName;
|
||||||
@@ -1270,8 +1184,6 @@ void LauncherBackend::finishMicrosoftLogin(const QString &code)
|
|||||||
void LauncherBackend::applyMicrosoftResult(Profile &profile, const AuthResult &auth)
|
void LauncherBackend::applyMicrosoftResult(Profile &profile, const AuthResult &auth)
|
||||||
{
|
{
|
||||||
profile.accessToken = auth.accessToken;
|
profile.accessToken = auth.accessToken;
|
||||||
// Microsoft выдаёт новый refresh-токен и при продлении, но если в ответе
|
|
||||||
// его не было — прежний остаётся рабочим.
|
|
||||||
if (!auth.refreshToken.isEmpty())
|
if (!auth.refreshToken.isEmpty())
|
||||||
profile.refreshToken = auth.refreshToken;
|
profile.refreshToken = auth.refreshToken;
|
||||||
if (!auth.uuid.isEmpty())
|
if (!auth.uuid.isEmpty())
|
||||||
@@ -1297,7 +1209,6 @@ void LauncherBackend::beginMicrosoftAuthentication()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сохранённый токен ещё жив — идём в игру, не дёргая Microsoft.
|
|
||||||
const QDateTime expiry = QDateTime::fromString(profile.tokenExpiry, Qt::ISODate);
|
const QDateTime expiry = QDateTime::fromString(profile.tokenExpiry, Qt::ISODate);
|
||||||
if (!profile.accessToken.isEmpty() && expiry.isValid()
|
if (!profile.accessToken.isEmpty() && expiry.isValid()
|
||||||
&& QDateTime::currentDateTimeUtc().addSecs(kTokenRenewMarginSecs) < expiry) {
|
&& QDateTime::currentDateTimeUtc().addSecs(kTokenRenewMarginSecs) < expiry) {
|
||||||
@@ -1317,7 +1228,7 @@ void LauncherBackend::beginMicrosoftAuthentication()
|
|||||||
|
|
||||||
m_msa->loginWithRefreshToken(profile.refreshToken, [this](const AuthResult &result) {
|
m_msa->loginWithRefreshToken(profile.refreshToken, [this](const AuthResult &result) {
|
||||||
if (m_pendingProfile < 0)
|
if (m_pendingProfile < 0)
|
||||||
return; // запуск отменили, пока шло продление
|
return;
|
||||||
if (result.licenseMissing) {
|
if (result.licenseMissing) {
|
||||||
failLaunch(result.error);
|
failLaunch(result.error);
|
||||||
return;
|
return;
|
||||||
@@ -1353,12 +1264,10 @@ void LauncherBackend::beginAuthentication()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ely.by работает только вместе с authlib-injector — без него игра пойдёт
|
|
||||||
// в сессионный сервер Mojang и токен окажется недействительным.
|
|
||||||
m_auth->ensureAuthlibInjector(LauncherPaths::runtimeDir(),
|
m_auth->ensureAuthlibInjector(LauncherPaths::runtimeDir(),
|
||||||
[this](const QString &path, const QString &error) {
|
[this](const QString &path, const QString &error) {
|
||||||
if (m_pendingProfile < 0)
|
if (m_pendingProfile < 0)
|
||||||
return; // запуск отменили, пока качался инжектор
|
return;
|
||||||
if (!error.isEmpty()) {
|
if (!error.isEmpty()) {
|
||||||
failLaunch(error);
|
failLaunch(error);
|
||||||
return;
|
return;
|
||||||
@@ -1439,8 +1348,6 @@ void LauncherBackend::continueLaunch(const AuthResult &auth)
|
|||||||
Profile &profile = m_profiles[m_pendingProfile];
|
Profile &profile = m_profiles[m_pendingProfile];
|
||||||
const CustomBuild &build = m_builds[buildIndex];
|
const CustomBuild &build = m_builds[buildIndex];
|
||||||
|
|
||||||
// Ely.by возвращает игровой ник и UUID аккаунта — их и запоминаем,
|
|
||||||
// чтобы в следующий раз обойтись без пароля.
|
|
||||||
if (profile.authType == kMicrosoft && auth.ok) {
|
if (profile.authType == kMicrosoft && auth.ok) {
|
||||||
applyMicrosoftResult(profile, auth);
|
applyMicrosoftResult(profile, auth);
|
||||||
saveProfiles();
|
saveProfiles();
|
||||||
@@ -1467,8 +1374,6 @@ void LauncherBackend::continueLaunch(const AuthResult &auth)
|
|||||||
options.userType = auth.userType;
|
options.userType = auth.userType;
|
||||||
options.xuid = auth.xuid;
|
options.xuid = auth.xuid;
|
||||||
|
|
||||||
// Скачанная лаунчером сборка важнее пути из настроек: её выбрали явно в
|
|
||||||
// окне выбора версии Java.
|
|
||||||
options.javaPath = managedJavaPath();
|
options.javaPath = managedJavaPath();
|
||||||
if (options.javaPath.isEmpty()) {
|
if (options.javaPath.isEmpty()) {
|
||||||
if (!m_settings.value(QStringLiteral("javaRuntime")).toString().trimmed().isEmpty())
|
if (!m_settings.value(QStringLiteral("javaRuntime")).toString().trimmed().isEmpty())
|
||||||
@@ -1587,9 +1492,6 @@ void LauncherBackend::updateSettings(const QVariantMap &values)
|
|||||||
saveSettings();
|
saveSettings();
|
||||||
emit settingsChanged();
|
emit settingsChanged();
|
||||||
|
|
||||||
// Язык переключается после записи: порядок «сохранили → переключили»
|
|
||||||
// гарантирует, что выбор переживёт падение сразу после переключения.
|
|
||||||
// Сам Localization в settings.json не пишет — файл ведёт только бэкенд.
|
|
||||||
const QString language = m_settings.value(QStringLiteral("language")).toString();
|
const QString language = m_settings.value(QStringLiteral("language")).toString();
|
||||||
if (language != previousLanguage)
|
if (language != previousLanguage)
|
||||||
Localization::instance().setLanguage(language);
|
Localization::instance().setLanguage(language);
|
||||||
@@ -1629,7 +1531,6 @@ bool LauncherBackend::javaCatalogLoading() const
|
|||||||
|
|
||||||
void LauncherBackend::refreshJavaCatalog(bool force)
|
void LauncherBackend::refreshJavaCatalog(bool force)
|
||||||
{
|
{
|
||||||
// Список установленного мог поменяться и без нас (папку удалили руками).
|
|
||||||
invalidateJavaCatalog();
|
invalidateJavaCatalog();
|
||||||
m_javaMeta->ensureLoaded([this](bool ok, const QString &warning) {
|
m_javaMeta->ensureLoaded([this](bool ok, const QString &warning) {
|
||||||
if (!ok && !warning.isEmpty())
|
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()}};
|
QStringLiteral("%1 %2 %3 %4").arg(version, QString::number(major), kind, detail).toLower()}};
|
||||||
};
|
};
|
||||||
|
|
||||||
// Скачанное — сверху: этим уже можно пользоваться прямо сейчас.
|
|
||||||
QSet<QString> listed;
|
QSet<QString> listed;
|
||||||
for (const InstalledJavaRuntime &runtime : installed) {
|
for (const InstalledJavaRuntime &runtime : installed) {
|
||||||
listed.insert(runtime.id);
|
listed.insert(runtime.id);
|
||||||
@@ -1760,7 +1660,6 @@ void LauncherBackend::removeJavaRuntime(const QString &runtimeId)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Удалили выбранную — настройка указывала бы в пустоту.
|
|
||||||
if (m_settings.value(QStringLiteral("javaRuntime")).toString() == runtimeId) {
|
if (m_settings.value(QStringLiteral("javaRuntime")).toString() == runtimeId) {
|
||||||
m_settings.insert(QStringLiteral("javaRuntime"), QString());
|
m_settings.insert(QStringLiteral("javaRuntime"), QString());
|
||||||
saveSettings();
|
saveSettings();
|
||||||
@@ -1786,7 +1685,6 @@ QVariantMap LauncherBackend::javaRuntimeInfo(const QString &runtimeId) const
|
|||||||
{QStringLiteral("installed"), true}};
|
{QStringLiteral("installed"), true}};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Выбрана, но ещё не скачана: подпись всё равно нужна.
|
|
||||||
const auto entry = m_javaMeta->find(runtimeId);
|
const auto entry = m_javaMeta->find(runtimeId);
|
||||||
if (!entry)
|
if (!entry)
|
||||||
return QVariantMap{{QStringLiteral("id"), runtimeId},
|
return QVariantMap{{QStringLiteral("id"), runtimeId},
|
||||||
@@ -1825,7 +1723,6 @@ QUrl LauncherBackend::seasonalBaseUrl() const
|
|||||||
const QString configured =
|
const QString configured =
|
||||||
m_settings.value(QStringLiteral("seasonalBaseUrl")).toString().trimmed();
|
m_settings.value(QStringLiteral("seasonalBaseUrl")).toString().trimmed();
|
||||||
QUrl url(configured.isEmpty() ? kSeasonalBaseUrl : configured);
|
QUrl url(configured.isEmpty() ? kSeasonalBaseUrl : configured);
|
||||||
// Хвостовой слэш превратил бы адрес каталога в «…//index.json».
|
|
||||||
while (url.path().endsWith(u'/'))
|
while (url.path().endsWith(u'/'))
|
||||||
url.setPath(url.path().chopped(1));
|
url.setPath(url.path().chopped(1));
|
||||||
return url;
|
return url;
|
||||||
@@ -1921,7 +1818,6 @@ bool LauncherBackend::seasonalInstalling() const
|
|||||||
|
|
||||||
void LauncherBackend::refreshSeasonalCatalog(bool force)
|
void LauncherBackend::refreshSeasonalCatalog(bool force)
|
||||||
{
|
{
|
||||||
// Адрес мог смениться в settings.json между запусками окна.
|
|
||||||
m_seasonalMeta->setBaseUrl(seasonalBaseUrl());
|
m_seasonalMeta->setBaseUrl(seasonalBaseUrl());
|
||||||
m_seasonalMeta->ensureLoaded(nullptr, force);
|
m_seasonalMeta->ensureLoaded(nullptr, force);
|
||||||
}
|
}
|
||||||
@@ -1952,8 +1848,6 @@ void LauncherBackend::installSeasonalBuild(const QString &seasonalId)
|
|||||||
m_season = {};
|
m_season = {};
|
||||||
m_season.entry = *entry;
|
m_season.entry = *entry;
|
||||||
|
|
||||||
// Сборка с таким seasonalId уже заведена — обновляем её описание под новую
|
|
||||||
// ревизию, а не плодим вторую запись.
|
|
||||||
int index = indexOfSeasonalBuild(seasonalId);
|
int index = indexOfSeasonalBuild(seasonalId);
|
||||||
if (index < 0) {
|
if (index < 0) {
|
||||||
CustomBuild build;
|
CustomBuild build;
|
||||||
@@ -1964,14 +1858,10 @@ void LauncherBackend::installSeasonalBuild(const QString &seasonalId)
|
|||||||
build.loader = entry->loader;
|
build.loader = entry->loader;
|
||||||
build.loaderVersion = entry->loaderVersion;
|
build.loaderVersion = entry->loaderVersion;
|
||||||
build.seasonalId = entry->id;
|
build.seasonalId = entry->id;
|
||||||
// Ревизия появится только когда файлы лягут на диск: иначе оборванная
|
|
||||||
// установка выглядела бы завершённой.
|
|
||||||
m_builds.append(build);
|
m_builds.append(build);
|
||||||
index = m_builds.size() - 1;
|
index = m_builds.size() - 1;
|
||||||
saveCustomBuilds();
|
saveCustomBuilds();
|
||||||
emit customBuildsChanged();
|
emit customBuildsChanged();
|
||||||
// maybeInstall() здесь намеренно нет: версию и модлоадер поставит шаг
|
|
||||||
// цепочки, а параллельная загрузка только мешала бы ему.
|
|
||||||
} else {
|
} else {
|
||||||
updateCustomBuild(index,
|
updateCustomBuild(index,
|
||||||
{{QStringLiteral("name"), entry->name},
|
{{QStringLiteral("name"), entry->name},
|
||||||
@@ -1984,8 +1874,6 @@ void LauncherBackend::installSeasonalBuild(const QString &seasonalId)
|
|||||||
m_season.buildId = m_builds[index].id;
|
m_season.buildId = m_builds[index].id;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
emit launchProgress(Loc::text("seasonal.progress.installing").arg(entry->name));
|
emit launchProgress(Loc::text("seasonal.progress.installing").arg(entry->name));
|
||||||
// Сигнал после seasonAdvance(): шаг цепочки выставляет stage сам, а до его
|
|
||||||
// вызова seasonalInstalling() ещё вернул бы false.
|
|
||||||
seasonAdvance();
|
seasonAdvance();
|
||||||
emit seasonalInstallingChanged();
|
emit seasonalInstallingChanged();
|
||||||
}
|
}
|
||||||
@@ -1997,9 +1885,6 @@ void LauncherBackend::seasonAdvance()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Каждый шаг либо начинает свою асинхронную работу и обрывает цепочку до
|
|
||||||
// следующего сигнала, либо уступает следующему — отсюда провалы между
|
|
||||||
// ветками.
|
|
||||||
switch (m_season.stage) {
|
switch (m_season.stage) {
|
||||||
case SeasonStage::Idle:
|
case SeasonStage::Idle:
|
||||||
if (seasonBeginSwitch())
|
if (seasonBeginSwitch())
|
||||||
@@ -2034,9 +1919,6 @@ bool LauncherBackend::seasonBeginSwitch()
|
|||||||
if (current == index)
|
if (current == index)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Пак ложится на то, что сейчас разложено в .minecraft, поэтому сборка
|
|
||||||
// должна стать активной до всего остального. Содержимое прежней уезжает в
|
|
||||||
// её архив обычным путём.
|
|
||||||
m_season.stage = SeasonStage::Switching;
|
m_season.stage = SeasonStage::Switching;
|
||||||
emit launchProgress(Loc::text("build.progress.switchingTo").arg(m_builds[index].name));
|
emit launchProgress(Loc::text("build.progress.switchingTo").arg(m_builds[index].name));
|
||||||
m_switcher->switchTo(current >= 0 ? m_builds[current].id : -1,
|
m_switcher->switchTo(current >= 0 ? m_builds[current].id : -1,
|
||||||
@@ -2051,14 +1933,12 @@ bool LauncherBackend::seasonBeginSwitch()
|
|||||||
|
|
||||||
bool LauncherBackend::seasonBeginJava()
|
bool LauncherBackend::seasonBeginJava()
|
||||||
{
|
{
|
||||||
// Сервер может назвать нужную Java прямо; иначе спрашиваем таблицу.
|
|
||||||
const int major = m_season.entry.javaMajor > 0
|
const int major = m_season.entry.javaMajor > 0
|
||||||
? m_season.entry.javaMajor
|
? m_season.entry.javaMajor
|
||||||
: JavaRequirement::minimumFor(m_season.entry.minecraftVersion);
|
: JavaRequirement::minimumFor(m_season.entry.minecraftVersion);
|
||||||
if (major <= 0)
|
if (major <= 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Java уже есть — своя, системная или скачанная раньше.
|
|
||||||
QString error;
|
QString error;
|
||||||
if (!JavaLocator::select(gameDir(), major, QString(), &error).isEmpty())
|
if (!JavaLocator::select(gameDir(), major, QString(), &error).isEmpty())
|
||||||
return false;
|
return false;
|
||||||
@@ -2066,7 +1946,6 @@ bool LauncherBackend::seasonBeginJava()
|
|||||||
m_season.stage = SeasonStage::Java;
|
m_season.stage = SeasonStage::Java;
|
||||||
emit launchProgress(Loc::text("seasonal.progress.installingJava").arg(major));
|
emit launchProgress(Loc::text("seasonal.progress.installingJava").arg(major));
|
||||||
|
|
||||||
// Каталог Java мог ещё ни разу не читаться: окно выбора могли не открывать.
|
|
||||||
m_javaMeta->ensureLoaded([this, major](bool ok, const QString &warning) {
|
m_javaMeta->ensureLoaded([this, major](bool ok, const QString &warning) {
|
||||||
if (m_season.stage != SeasonStage::Java)
|
if (m_season.stage != SeasonStage::Java)
|
||||||
return;
|
return;
|
||||||
@@ -2090,7 +1969,6 @@ bool LauncherBackend::seasonBeginLoader()
|
|||||||
const CustomBuild &build = m_builds[index];
|
const CustomBuild &build = m_builds[index];
|
||||||
const auto loader = loaderFromKey(build.loader);
|
const auto loader = loaderFromKey(build.loader);
|
||||||
|
|
||||||
// Ванильная сборка: ставить надо только саму версию игры.
|
|
||||||
if (!loader) {
|
if (!loader) {
|
||||||
if (checkInstallation(index).isEmpty())
|
if (checkInstallation(index).isEmpty())
|
||||||
return false;
|
return false;
|
||||||
@@ -2099,7 +1977,6 @@ bool LauncherBackend::seasonBeginLoader()
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Профиль лоадера уже собран и укомплектован — второй раз не ставим.
|
|
||||||
if (!build.resolvedVersionId.isEmpty() && checkInstallation(index).isEmpty())
|
if (!build.resolvedVersionId.isEmpty() && checkInstallation(index).isEmpty())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@@ -2118,8 +1995,6 @@ bool LauncherBackend::seasonBeginLoader()
|
|||||||
bool LauncherBackend::seasonBeginDownload()
|
bool LauncherBackend::seasonBeginDownload()
|
||||||
{
|
{
|
||||||
const SeasonalBuildEntry &entry = m_season.entry;
|
const SeasonalBuildEntry &entry = m_season.entry;
|
||||||
// Точка в начале имени: файл служебный, и BuildSwitcher по этому признаку
|
|
||||||
// не примет его за архив сборки и не сотрёт при следующем переключении.
|
|
||||||
const QString path = LauncherPaths::buildDir(m_season.buildId)
|
const QString path = LauncherPaths::buildDir(m_season.buildId)
|
||||||
+ QStringLiteral("/.pack-r") + QString::number(entry.revision)
|
+ QStringLiteral("/.pack-r") + QString::number(entry.revision)
|
||||||
+ QStringLiteral(".zip");
|
+ QStringLiteral(".zip");
|
||||||
@@ -2140,11 +2015,6 @@ bool LauncherBackend::seasonBeginApply()
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Под удаление идёт весь список прошлой ревизии, а не разница с новой:
|
|
||||||
// распаковка всё равно кладёт каждый файл пака заново, поэтому разница
|
|
||||||
// сэкономила бы лишь перезапись того, что и так перезаписывается, а вот
|
|
||||||
// ушедшие из сборки моды так убираются наверняка. Миров и скриншотов в
|
|
||||||
// списке нет — их пак не приносил.
|
|
||||||
const QStringList remove = seasonalPackEntries(m_season.buildId);
|
const QStringList remove = seasonalPackEntries(m_season.buildId);
|
||||||
|
|
||||||
const QJsonObject note{{QStringLiteral("seasonalId"), m_season.entry.id},
|
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 int index = indexOfBuildId(m_season.buildId);
|
||||||
const QString name = index >= 0 ? m_builds[index].name : m_season.entry.name;
|
const QString name = index >= 0 ? m_builds[index].name : m_season.entry.name;
|
||||||
// Недокачанный или нераскатанный пак не должен занимать место: цепочку
|
|
||||||
// всегда можно начать заново с чистого листа.
|
|
||||||
if (!m_season.packPath.isEmpty())
|
if (!m_season.packPath.isEmpty())
|
||||||
QFile::remove(m_season.packPath);
|
QFile::remove(m_season.packPath);
|
||||||
|
|
||||||
m_season = {};
|
m_season = {};
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
emit seasonalInstallingChanged();
|
emit seasonalInstallingChanged();
|
||||||
// Пустое message означает, что о причине уже сообщил тот, кто её нашёл, —
|
|
||||||
// второй раз ту же ошибку не показываем.
|
|
||||||
emit launchError(message.isEmpty()
|
emit launchError(message.isEmpty()
|
||||||
? Loc::text("seasonal.error.installAborted").arg(name)
|
? Loc::text("seasonal.error.installAborted").arg(name)
|
||||||
: Loc::text("seasonal.error.installAbortedWhy").arg(name, message));
|
: Loc::text("seasonal.error.installAbortedWhy").arg(name, message));
|
||||||
@@ -2216,8 +2082,6 @@ void LauncherBackend::cancelSeasonalInstall()
|
|||||||
return;
|
return;
|
||||||
case SeasonStage::Switching:
|
case SeasonStage::Switching:
|
||||||
case SeasonStage::Applying:
|
case SeasonStage::Applying:
|
||||||
// На этих шагах содержимое .minecraft уже разобрано: отступать некуда,
|
|
||||||
// операцию нужно довести до конца.
|
|
||||||
emit launchError(Loc::text("switch.error.cannotCancel"));
|
emit launchError(Loc::text("switch.error.cannotCancel"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -2256,8 +2120,6 @@ void LauncherBackend::recordSeasonalPack(int buildId,
|
|||||||
{QStringLiteral("installedAt"),
|
{QStringLiteral("installedAt"),
|
||||||
QDateTime::currentDateTimeUtc().toString(Qt::ISODate)},
|
QDateTime::currentDateTimeUtc().toString(Qt::ISODate)},
|
||||||
{QStringLiteral("entries"), QJsonArray::fromStringList(entries)}};
|
{QStringLiteral("entries"), QJsonArray::fromStringList(entries)}};
|
||||||
// Не через writeJsonFile: файл лежит в папке сборки, а не в корне лаунчера,
|
|
||||||
// и его отсутствие не мешает игре — ошибку достаточно показать.
|
|
||||||
QDir().mkpath(LauncherPaths::buildDir(buildId));
|
QDir().mkpath(LauncherPaths::buildDir(buildId));
|
||||||
QSaveFile file(LauncherPaths::seasonalStateFile(buildId));
|
QSaveFile file(LauncherPaths::seasonalStateFile(buildId));
|
||||||
if (file.open(QIODevice::WriteOnly)) {
|
if (file.open(QIODevice::WriteOnly)) {
|
||||||
@@ -2271,8 +2133,6 @@ void LauncherBackend::recordSeasonalPack(int buildId,
|
|||||||
const int index = indexOfBuildId(buildId);
|
const int index = indexOfBuildId(buildId);
|
||||||
if (index < 0)
|
if (index < 0)
|
||||||
return;
|
return;
|
||||||
// Ревизия проставляется только здесь: до этого момента файлы сборки на
|
|
||||||
// диске не лежали.
|
|
||||||
updateCustomBuild(index,
|
updateCustomBuild(index,
|
||||||
{{QStringLiteral("seasonalId"), seasonalId},
|
{{QStringLiteral("seasonalId"), seasonalId},
|
||||||
{QStringLiteral("seasonalRevision"), revision}});
|
{QStringLiteral("seasonalRevision"), revision}});
|
||||||
@@ -2296,8 +2156,6 @@ void LauncherBackend::openGameFolder()
|
|||||||
emit launchError(Loc::text("launch.error.openGameDirFailed"));
|
emit launchError(Loc::text("launch.error.openGameDirFailed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Повреждённый файл не удаляем: отводим в .bak, чтобы данные можно было спасти
|
|
||||||
// руками, а ensureDataFiles() создал на его месте пустой.
|
|
||||||
bool LauncherBackend::moveAsideBroken(const QString &path, const QString &reason)
|
bool LauncherBackend::moveAsideBroken(const QString &path, const QString &reason)
|
||||||
{
|
{
|
||||||
const QString backup = path + QStringLiteral(".bak");
|
const QString backup = path + QStringLiteral(".bak");
|
||||||
@@ -2319,7 +2177,7 @@ QJsonArray LauncherBackend::readArrayFile(const QString &path)
|
|||||||
{
|
{
|
||||||
QFile file(path);
|
QFile file(path);
|
||||||
if (!file.exists())
|
if (!file.exists())
|
||||||
return {}; // первый запуск — это не ошибка
|
return {};
|
||||||
if (!file.open(QIODevice::ReadOnly)) {
|
if (!file.open(QIODevice::ReadOnly)) {
|
||||||
m_storageIssues << Loc::text("common.error.readFailed")
|
m_storageIssues << Loc::text("common.error.readFailed")
|
||||||
.arg(QDir::toNativeSeparators(path), file.errorString());
|
.arg(QDir::toNativeSeparators(path), file.errorString());
|
||||||
@@ -2367,8 +2225,6 @@ QJsonObject LauncherBackend::readObjectFile(const QString &path)
|
|||||||
return document.object();
|
return document.object();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Перед каждой записью убеждаемся, что папка лаунчера на месте: её могли удалить
|
|
||||||
// уже после запуска, и тогда данные молча пропадали бы.
|
|
||||||
bool LauncherBackend::writeJsonFile(const QString &path, const QJsonDocument &document)
|
bool LauncherBackend::writeJsonFile(const QString &path, const QJsonDocument &document)
|
||||||
{
|
{
|
||||||
QString storageError;
|
QString storageError;
|
||||||
@@ -2425,8 +2281,6 @@ void LauncherBackend::loadData()
|
|||||||
build.name = o["name"].toString();
|
build.name = o["name"].toString();
|
||||||
build.serverUrl = o["serverUrl"].toString();
|
build.serverUrl = o["serverUrl"].toString();
|
||||||
build.minecraftVersion = o.value("minecraftVersion").toString();
|
build.minecraftVersion = o.value("minecraftVersion").toString();
|
||||||
// Файл мог остаться от версии лаунчера до переименования или быть
|
|
||||||
// поправлен руками — старый ключ тоже принимаем.
|
|
||||||
if (build.minecraftVersion.isEmpty())
|
if (build.minecraftVersion.isEmpty())
|
||||||
build.minecraftVersion = o.value("versionId").toString();
|
build.minecraftVersion = o.value("versionId").toString();
|
||||||
build.loader = o.value("loader").toString();
|
build.loader = o.value("loader").toString();
|
||||||
@@ -2435,8 +2289,6 @@ void LauncherBackend::loadData()
|
|||||||
build.seasonalId = o.value("seasonalId").toString();
|
build.seasonalId = o.value("seasonalId").toString();
|
||||||
build.seasonalRevision = o.value("seasonalRevision").toInt();
|
build.seasonalRevision = o.value("seasonalRevision").toInt();
|
||||||
|
|
||||||
// Без имени и без версии запись нерабочая: launchVersionIdOf() вернёт
|
|
||||||
// пустую строку.
|
|
||||||
if (build.name.trimmed().isEmpty() && build.minecraftVersion.trimmed().isEmpty()) {
|
if (build.name.trimmed().isEmpty() && build.minecraftVersion.trimmed().isEmpty()) {
|
||||||
++skippedBuilds;
|
++skippedBuilds;
|
||||||
return;
|
return;
|
||||||
@@ -2454,9 +2306,6 @@ void LauncherBackend::loadData()
|
|||||||
[](const CustomBuild &a, const CustomBuild &b) { return a.id < b.id; });
|
[](const CustomBuild &a, const CustomBuild &b) { return a.id < b.id; });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Первый запуск после переименования «версий» в «сборки»: перекладываем
|
|
||||||
// <root>/versions.json в customBuilds.json. Старый файл не удаляем, а
|
|
||||||
// переименовываем — он остаётся резервной копией.
|
|
||||||
bool LauncherBackend::migrateLegacyBuildsFile()
|
bool LauncherBackend::migrateLegacyBuildsFile()
|
||||||
{
|
{
|
||||||
if (QFile::exists(LauncherPaths::customBuildsFile()))
|
if (QFile::exists(LauncherPaths::customBuildsFile()))
|
||||||
@@ -2464,7 +2313,6 @@ bool LauncherBackend::migrateLegacyBuildsFile()
|
|||||||
if (!QFile::exists(LauncherPaths::legacyCustomBuildsFile()))
|
if (!QFile::exists(LauncherPaths::legacyCustomBuildsFile()))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// readArrayFile() сам отводит битый файл в .bak — тогда мигрировать нечего.
|
|
||||||
const QJsonArray legacy = readArrayFile(LauncherPaths::legacyCustomBuildsFile());
|
const QJsonArray legacy = readArrayFile(LauncherPaths::legacyCustomBuildsFile());
|
||||||
if (legacy.isEmpty() && !QFile::exists(LauncherPaths::legacyCustomBuildsFile()))
|
if (legacy.isEmpty() && !QFile::exists(LauncherPaths::legacyCustomBuildsFile()))
|
||||||
return false;
|
return false;
|
||||||
@@ -2481,8 +2329,6 @@ bool LauncherBackend::migrateLegacyBuildsFile()
|
|||||||
{"resolvedVersionId", QString()}});
|
{"resolvedVersionId", QString()}});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Не удалось записать — молча читаем в этой сессии из старого файла.
|
|
||||||
// Без данных пользователь не остаётся ни при каком исходе.
|
|
||||||
if (!writeJsonFile(LauncherPaths::customBuildsFile(), QJsonDocument(migrated)))
|
if (!writeJsonFile(LauncherPaths::customBuildsFile(), QJsonDocument(migrated)))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@@ -2497,9 +2343,6 @@ bool LauncherBackend::migrateLegacyBuildsFile()
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сборка описывает то, что уже разложено в .minecraft, поэтому BuildSwitcher не
|
|
||||||
// нужен: активная сборка без архива — штатное состояние. Через addCustomBuild()
|
|
||||||
// не идём, чтобы при старте не началась установка.
|
|
||||||
QString LauncherBackend::importGameDir()
|
QString LauncherBackend::importGameDir()
|
||||||
{
|
{
|
||||||
const std::optional<GameDirImport::Detected> found = GameDirImport::detect(gameDir());
|
const std::optional<GameDirImport::Detected> found = GameDirImport::detect(gameDir());
|
||||||
@@ -2527,8 +2370,6 @@ QString LauncherBackend::importGameDir()
|
|||||||
return build.name;
|
return build.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Файлы могли не появиться при первом запуске, быть удалены или отложены в .bak —
|
|
||||||
// создаём заново, чтобы папка лаунчера всегда была укомплектована.
|
|
||||||
void LauncherBackend::ensureDataFiles()
|
void LauncherBackend::ensureDataFiles()
|
||||||
{
|
{
|
||||||
if (!QFile::exists(LauncherPaths::settingsFile()))
|
if (!QFile::exists(LauncherPaths::settingsFile()))
|
||||||
@@ -2581,7 +2422,6 @@ void LauncherBackend::loadSettings()
|
|||||||
{
|
{
|
||||||
m_settings = {{QStringLiteral("gameDir"), QString()},
|
m_settings = {{QStringLiteral("gameDir"), QString()},
|
||||||
{QStringLiteral("javaPath"), QString()},
|
{QStringLiteral("javaPath"), QString()},
|
||||||
// id сборки Java из <root>/java. Пусто — java ищется сама.
|
|
||||||
{QStringLiteral("javaRuntime"), QString()},
|
{QStringLiteral("javaRuntime"), QString()},
|
||||||
{QStringLiteral("minMemoryMb"), 512},
|
{QStringLiteral("minMemoryMb"), 512},
|
||||||
{QStringLiteral("maxMemoryMb"), 4096},
|
{QStringLiteral("maxMemoryMb"), 4096},
|
||||||
@@ -2589,20 +2429,14 @@ void LauncherBackend::loadSettings()
|
|||||||
{QStringLiteral("windowWidth"), 0},
|
{QStringLiteral("windowWidth"), 0},
|
||||||
{QStringLiteral("windowHeight"), 0},
|
{QStringLiteral("windowHeight"), 0},
|
||||||
{QStringLiteral("fullscreen"), false},
|
{QStringLiteral("fullscreen"), false},
|
||||||
// Язык интерфейса: "system" — по системной локали.
|
|
||||||
{QStringLiteral("language"), QStringLiteral("system")},
|
{QStringLiteral("language"), QStringLiteral("system")},
|
||||||
{QStringLiteral("activeBuildId"), 0},
|
{QStringLiteral("activeBuildId"), 0},
|
||||||
// Сервер готовых сборок. В интерфейс не вынесен: менять его
|
|
||||||
// приходится только при отладке против локального сервера.
|
|
||||||
{QStringLiteral("seasonalBaseUrl"), kSeasonalBaseUrl}};
|
{QStringLiteral("seasonalBaseUrl"), kSeasonalBaseUrl}};
|
||||||
|
|
||||||
const QJsonObject stored = readObjectFile(LauncherPaths::settingsFile());
|
const QJsonObject stored = readObjectFile(LauncherPaths::settingsFile());
|
||||||
for (auto it = stored.constBegin(); it != stored.constEnd(); ++it)
|
for (auto it = stored.constBegin(); it != stored.constEnd(); ++it)
|
||||||
m_settings.insert(it.key(), it.value().toVariant());
|
m_settings.insert(it.key(), it.value().toVariant());
|
||||||
|
|
||||||
// Имя и версия лаунчера раньше хранились здесь со значением "1.0" и не
|
|
||||||
// обновлялись вместе с программой. Теперь они берутся из QCoreApplication,
|
|
||||||
// а старые ключи вычищаются из файла при следующем сохранении.
|
|
||||||
m_settings.remove(QStringLiteral("launcherName"));
|
m_settings.remove(QStringLiteral("launcherName"));
|
||||||
m_settings.remove(QStringLiteral("launcherVersion"));
|
m_settings.remove(QStringLiteral("launcherVersion"));
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-90
@@ -33,47 +33,32 @@ class LauncherBackend : public QObject
|
|||||||
Q_PROPERTY(QStringList profileNames READ profileNames NOTIFY profilesChanged)
|
Q_PROPERTY(QStringList profileNames READ profileNames NOTIFY profilesChanged)
|
||||||
Q_PROPERTY(QStringList customBuildNames READ customBuildNames NOTIFY customBuildsChanged)
|
Q_PROPERTY(QStringList customBuildNames READ customBuildNames NOTIFY customBuildsChanged)
|
||||||
|
|
||||||
// Сборка, которую запускает кнопка игры. Хранится по id сборки, а не по
|
|
||||||
// индексу: удаление соседней записи не должно переназначать активную.
|
|
||||||
Q_PROPERTY(int activeBuildIndex READ activeBuildIndex WRITE setActiveBuildIndex
|
Q_PROPERTY(int activeBuildIndex READ activeBuildIndex WRITE setActiveBuildIndex
|
||||||
NOTIFY activeBuildChanged)
|
NOTIFY activeBuildChanged)
|
||||||
Q_PROPERTY(QString activeBuildName READ activeBuildName NOTIFY activeBuildChanged)
|
Q_PROPERTY(QString activeBuildName READ activeBuildName NOTIFY activeBuildChanged)
|
||||||
Q_PROPERTY(QStringList installedVersions READ installedVersions NOTIFY installedVersionsChanged)
|
Q_PROPERTY(QStringList installedVersions READ installedVersions NOTIFY installedVersionsChanged)
|
||||||
Q_PROPERTY(bool gameRunning READ gameRunning NOTIFY gameRunningChanged)
|
Q_PROPERTY(bool gameRunning READ gameRunning NOTIFY gameRunningChanged)
|
||||||
|
|
||||||
// Идёт архивация/распаковка .minecraft при смене сборки. Отдельно от busy,
|
|
||||||
// потому что на это время блокируется ещё и список сборок.
|
|
||||||
Q_PROPERTY(bool switching READ switching NOTIFY switchChanged)
|
Q_PROPERTY(bool switching READ switching NOTIFY switchChanged)
|
||||||
Q_PROPERTY(double switchProgress READ switchProgress NOTIFY switchChanged)
|
Q_PROPERTY(double switchProgress READ switchProgress NOTIFY switchChanged)
|
||||||
Q_PROPERTY(QString switchStage READ switchStage NOTIFY switchChanged)
|
Q_PROPERTY(QString switchStage READ switchStage NOTIFY switchChanged)
|
||||||
Q_PROPERTY(QString switchStatus READ switchStatus NOTIFY switchChanged)
|
Q_PROPERTY(QString switchStatus READ switchStatus NOTIFY switchChanged)
|
||||||
Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
|
Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
|
||||||
|
|
||||||
// Собран ли лаунчер с Qt WebEngine. Без него окно входа Microsoft
|
|
||||||
// показать нечем, и интерфейс не должен предлагать этот путь.
|
|
||||||
Q_PROPERTY(bool microsoftAvailable READ microsoftAvailable CONSTANT)
|
Q_PROPERTY(bool microsoftAvailable READ microsoftAvailable CONSTANT)
|
||||||
|
|
||||||
// Объединённый список для выпадающего меню версий: установленные, разделитель,
|
|
||||||
// затем весь каталог Mojang.
|
|
||||||
Q_PROPERTY(QVariantList versionCatalog READ versionCatalog NOTIFY versionCatalogChanged)
|
Q_PROPERTY(QVariantList versionCatalog READ versionCatalog NOTIFY versionCatalogChanged)
|
||||||
Q_PROPERTY(bool catalogLoading READ catalogLoading NOTIFY catalogLoadingChanged)
|
Q_PROPERTY(bool catalogLoading READ catalogLoading NOTIFY catalogLoadingChanged)
|
||||||
|
|
||||||
// Сборки Java для окна выбора: скачиваемые из сети плюс те, что уже лежат
|
|
||||||
// в папке лаунчера.
|
|
||||||
Q_PROPERTY(QVariantList javaCatalog READ javaCatalog NOTIFY javaCatalogChanged)
|
Q_PROPERTY(QVariantList javaCatalog READ javaCatalog NOTIFY javaCatalogChanged)
|
||||||
Q_PROPERTY(bool javaCatalogLoading READ javaCatalogLoading NOTIFY javaCatalogLoadingChanged)
|
Q_PROPERTY(bool javaCatalogLoading READ javaCatalogLoading NOTIFY javaCatalogLoadingChanged)
|
||||||
|
|
||||||
// Готовые сборки с сервера. Строки таблицы уже сведены с локальными
|
|
||||||
// записями: окно показывает статус, не считая ничего само.
|
|
||||||
Q_PROPERTY(QVariantList seasonalCatalog READ seasonalCatalog NOTIFY seasonalCatalogChanged)
|
Q_PROPERTY(QVariantList seasonalCatalog READ seasonalCatalog NOTIFY seasonalCatalogChanged)
|
||||||
Q_PROPERTY(bool seasonalCatalogLoading READ seasonalCatalogLoading
|
Q_PROPERTY(bool seasonalCatalogLoading READ seasonalCatalogLoading
|
||||||
NOTIFY seasonalCatalogLoadingChanged)
|
NOTIFY seasonalCatalogLoadingChanged)
|
||||||
Q_PROPERTY(QString seasonalCatalogError READ seasonalCatalogError NOTIFY seasonalCatalogChanged)
|
Q_PROPERTY(QString seasonalCatalogError READ seasonalCatalogError NOTIFY seasonalCatalogChanged)
|
||||||
// Идёт установка сезонной сборки: окно не даёт начать вторую.
|
|
||||||
Q_PROPERTY(bool seasonalInstalling READ seasonalInstalling NOTIFY seasonalInstallingChanged)
|
Q_PROPERTY(bool seasonalInstalling READ seasonalInstalling NOTIFY seasonalInstallingChanged)
|
||||||
|
|
||||||
// Одного сигнала на все свойства загрузки достаточно: установщик уже
|
|
||||||
// ограничивает частоту, а QML всё равно перечитывает их разом.
|
|
||||||
Q_PROPERTY(bool downloading READ downloading NOTIFY downloadChanged)
|
Q_PROPERTY(bool downloading READ downloading NOTIFY downloadChanged)
|
||||||
Q_PROPERTY(double downloadProgress READ downloadProgress NOTIFY downloadChanged)
|
Q_PROPERTY(double downloadProgress READ downloadProgress NOTIFY downloadChanged)
|
||||||
Q_PROPERTY(QString downloadVersion READ downloadVersion NOTIFY downloadChanged)
|
Q_PROPERTY(QString downloadVersion READ downloadVersion NOTIFY downloadChanged)
|
||||||
@@ -96,7 +81,6 @@ public:
|
|||||||
double switchProgress() const;
|
double switchProgress() const;
|
||||||
QString switchStage() const;
|
QString switchStage() const;
|
||||||
QString switchStatus() const;
|
QString switchStatus() const;
|
||||||
// Пока идёт загрузка версии, лаунчер тоже занят: кнопка запуска гаснет.
|
|
||||||
bool busy() const;
|
bool busy() const;
|
||||||
bool microsoftAvailable() const;
|
bool microsoftAvailable() const;
|
||||||
|
|
||||||
@@ -130,51 +114,34 @@ public:
|
|||||||
const QString &login,
|
const QString &login,
|
||||||
const QString &password,
|
const QString &password,
|
||||||
const QString &authType = QStringLiteral("offline"));
|
const QString &authType = QStringLiteral("offline"));
|
||||||
// Мержит только присланные ключи: name, serverUrl, minecraftVersion,
|
|
||||||
// loader, loaderVersion, resolvedVersionId.
|
|
||||||
Q_INVOKABLE void updateCustomBuild(int index, const QVariantMap &fields);
|
Q_INVOKABLE void updateCustomBuild(int index, const QVariantMap &fields);
|
||||||
Q_INVOKABLE QVariantMap profileAt(int index) const;
|
Q_INVOKABLE QVariantMap profileAt(int index) const;
|
||||||
|
|
||||||
// Вход в аккаунт Microsoft. profileIndex = -1 — вход ещё не привязан к
|
|
||||||
// профилю: он создастся по нику, который вернут Minecraft Services.
|
|
||||||
Q_INVOKABLE void startMicrosoftLogin(int profileIndex);
|
Q_INVOKABLE void startMicrosoftLogin(int profileIndex);
|
||||||
Q_INVOKABLE void finishMicrosoftLogin(const QString &code);
|
Q_INVOKABLE void finishMicrosoftLogin(const QString &code);
|
||||||
Q_INVOKABLE void cancelMicrosoftLogin();
|
Q_INVOKABLE void cancelMicrosoftLogin();
|
||||||
// Разбор адреса, на который встроенное окно возвращается после входа.
|
|
||||||
// Живёт в C++, чтобы правила совпадения не разъезжались с сервисом.
|
|
||||||
Q_INVOKABLE QVariantMap inspectMicrosoftRedirect(const QString &url) const;
|
Q_INVOKABLE QVariantMap inspectMicrosoftRedirect(const QString &url) const;
|
||||||
Q_INVOKABLE QVariantMap customBuildAt(int index) const;
|
Q_INVOKABLE QVariantMap customBuildAt(int index) const;
|
||||||
Q_INVOKABLE void removeProfile(int index);
|
Q_INVOKABLE void removeProfile(int index);
|
||||||
// Что именно потеряется при удалении — для текста предупреждения.
|
|
||||||
Q_INVOKABLE QVariantMap customBuildRemovalInfo(int index) const;
|
Q_INVOKABLE QVariantMap customBuildRemovalInfo(int index) const;
|
||||||
Q_INVOKABLE void removeCustomBuild(int index);
|
Q_INVOKABLE void removeCustomBuild(int index);
|
||||||
|
|
||||||
// Докачать то, чего не хватает выбранной сборке. Отдельной кнопкой, потому
|
|
||||||
// что карточка сборки сохраняет правки по ходу редактирования.
|
|
||||||
Q_INVOKABLE void installCustomBuild(int index);
|
Q_INVOKABLE void installCustomBuild(int index);
|
||||||
|
|
||||||
// Главная кнопка. Проверяет выбор профиля и версии, комплектность .minecraft,
|
|
||||||
// при необходимости авторизуется и стартует игру.
|
|
||||||
Q_INVOKABLE void launchGame(int profileIndex, int buildIndex);
|
Q_INVOKABLE void launchGame(int profileIndex, int buildIndex);
|
||||||
Q_INVOKABLE void submitTwoFactorCode(const QString &code);
|
Q_INVOKABLE void submitTwoFactorCode(const QString &code);
|
||||||
Q_INVOKABLE void cancelPendingLaunch();
|
Q_INVOKABLE void cancelPendingLaunch();
|
||||||
Q_INVOKABLE void stopGame();
|
Q_INVOKABLE void stopGame();
|
||||||
|
|
||||||
// Проверка без запуска — для подсказки в интерфейсе.
|
|
||||||
Q_INVOKABLE QStringList checkInstallation(int buildIndex) const;
|
Q_INVOKABLE QStringList checkInstallation(int buildIndex) const;
|
||||||
|
|
||||||
// Вызывается при открытии выпадающего списка версий: свежий кэш — без сети.
|
|
||||||
Q_INVOKABLE void refreshVersionCatalog(bool force = false);
|
Q_INVOKABLE void refreshVersionCatalog(bool force = false);
|
||||||
Q_INVOKABLE bool isVersionInstalled(const QString &versionId) const;
|
Q_INVOKABLE bool isVersionInstalled(const QString &versionId) const;
|
||||||
Q_INVOKABLE void installVersion(const QString &versionId);
|
Q_INVOKABLE void installVersion(const QString &versionId);
|
||||||
// Что потеряется при удалении версии — для текста предупреждения.
|
|
||||||
Q_INVOKABLE QVariantMap versionRemovalInfo(const QString &versionId) const;
|
Q_INVOKABLE QVariantMap versionRemovalInfo(const QString &versionId) const;
|
||||||
Q_INVOKABLE void removeVersion(const QString &versionId);
|
Q_INVOKABLE void removeVersion(const QString &versionId);
|
||||||
Q_INVOKABLE void cancelDownload();
|
Q_INVOKABLE void cancelDownload();
|
||||||
|
|
||||||
// Версии модлоадеров для выбранной версии игры. Возвращает список карт
|
|
||||||
// {version, label, recommended, stable}; несовместимых строк в нём нет —
|
|
||||||
// отбор заложен в сам источник данных.
|
|
||||||
Q_INVOKABLE QVariantList loaderVersions(const QString &loaderKey,
|
Q_INVOKABLE QVariantList loaderVersions(const QString &loaderKey,
|
||||||
const QString &gameVersion) const;
|
const QString &gameVersion) const;
|
||||||
Q_INVOKABLE void refreshLoaderVersions(const QString &loaderKey,
|
Q_INVOKABLE void refreshLoaderVersions(const QString &loaderKey,
|
||||||
@@ -182,8 +149,6 @@ public:
|
|||||||
bool force = false);
|
bool force = false);
|
||||||
Q_INVOKABLE bool loaderVersionsLoading(const QString &loaderKey,
|
Q_INVOKABLE bool loaderVersionsLoading(const QString &loaderKey,
|
||||||
const QString &gameVersion) const;
|
const QString &gameVersion) const;
|
||||||
// Ставит модлоадер, выбранный в сборке, и записывает получившийся профиль
|
|
||||||
// в resolvedVersionId.
|
|
||||||
Q_INVOKABLE void installLoaderForBuild(int index);
|
Q_INVOKABLE void installLoaderForBuild(int index);
|
||||||
|
|
||||||
Q_INVOKABLE QVariantMap settings() const;
|
Q_INVOKABLE QVariantMap settings() const;
|
||||||
@@ -191,19 +156,14 @@ public:
|
|||||||
Q_INVOKABLE QStringList detectedJava() const;
|
Q_INVOKABLE QStringList detectedJava() const;
|
||||||
|
|
||||||
// ── Сборки Java ─────────────────────────────────────────────────────
|
// ── Сборки Java ─────────────────────────────────────────────────────
|
||||||
// Вызывается при открытии окна выбора: свежий кэш — без сети.
|
|
||||||
Q_INVOKABLE void refreshJavaCatalog(bool force = false);
|
Q_INVOKABLE void refreshJavaCatalog(bool force = false);
|
||||||
Q_INVOKABLE void installJavaRuntime(const QString &runtimeId);
|
Q_INVOKABLE void installJavaRuntime(const QString &runtimeId);
|
||||||
Q_INVOKABLE void removeJavaRuntime(const QString &runtimeId);
|
Q_INVOKABLE void removeJavaRuntime(const QString &runtimeId);
|
||||||
// Пусто — сборки с таким id в папке лаунчера нет.
|
|
||||||
Q_INVOKABLE QVariantMap javaRuntimeInfo(const QString &runtimeId) const;
|
Q_INVOKABLE QVariantMap javaRuntimeInfo(const QString &runtimeId) const;
|
||||||
// Минимальная Java для версии игры выбранной сборки; 0 — версия не выбрана.
|
|
||||||
Q_INVOKABLE int requiredJavaMajor(int buildIndex) const;
|
Q_INVOKABLE int requiredJavaMajor(int buildIndex) const;
|
||||||
|
|
||||||
// ── Сезонные сборки ─────────────────────────────────────────────────
|
// ── Сезонные сборки ─────────────────────────────────────────────────
|
||||||
Q_INVOKABLE void refreshSeasonalCatalog(bool force = false);
|
Q_INVOKABLE void refreshSeasonalCatalog(bool force = false);
|
||||||
// Ставит или обновляет сборку целиком: запись, версия, модлоадер, Java и
|
|
||||||
// файлы — одной цепочкой.
|
|
||||||
Q_INVOKABLE void installSeasonalBuild(const QString &seasonalId);
|
Q_INVOKABLE void installSeasonalBuild(const QString &seasonalId);
|
||||||
Q_INVOKABLE void cancelSeasonalInstall();
|
Q_INVOKABLE void cancelSeasonalInstall();
|
||||||
|
|
||||||
@@ -229,24 +189,19 @@ signals:
|
|||||||
void seasonalInstallingChanged();
|
void seasonalInstallingChanged();
|
||||||
void downloadChanged();
|
void downloadChanged();
|
||||||
|
|
||||||
// Сезонная сборка установлена и активна — можно запускать игру.
|
|
||||||
void seasonalInstallFinished(const QString &seasonalId, const QString &buildName);
|
void seasonalInstallFinished(const QString &seasonalId, const QString &buildName);
|
||||||
|
|
||||||
// Первый запуск: по содержимому папки игры заведена активная сборка.
|
|
||||||
void gameDirImported(const QString &buildName);
|
void gameDirImported(const QString &buildName);
|
||||||
|
|
||||||
// Сборка Java установлена: окно настроек обновляет подпись, не переоткрываясь.
|
|
||||||
void javaRuntimeInstalled(const QString &runtimeId);
|
void javaRuntimeInstalled(const QString &runtimeId);
|
||||||
|
|
||||||
void launchProgress(const QString &message);
|
void launchProgress(const QString &message);
|
||||||
void launched(const QString &profileName, const QString &buildName, const QString &serverUrl);
|
void launched(const QString &profileName, const QString &buildName, const QString &serverUrl);
|
||||||
void launchError(const QString &message);
|
void launchError(const QString &message);
|
||||||
void twoFactorRequired(const QString &profileName);
|
void twoFactorRequired(const QString &profileName);
|
||||||
// Окну входа Microsoft: открыться на этом адресе.
|
|
||||||
void microsoftLoginUrlReady(const QString &url);
|
void microsoftLoginUrlReady(const QString &url);
|
||||||
void microsoftLoginSucceeded(const QString &playerName);
|
void microsoftLoginSucceeded(const QString &playerName);
|
||||||
void microsoftLoginFailed(const QString &message);
|
void microsoftLoginFailed(const QString &message);
|
||||||
// Сессия профиля протухла настолько, что нужен повторный вход руками.
|
|
||||||
void microsoftReloginRequired(int profileIndex);
|
void microsoftReloginRequired(int profileIndex);
|
||||||
void gameOutput(const QString &line);
|
void gameOutput(const QString &line);
|
||||||
void gameFinished(int exitCode, bool crashed);
|
void gameFinished(int exitCode, bool crashed);
|
||||||
@@ -256,39 +211,28 @@ private:
|
|||||||
{
|
{
|
||||||
int id = 0;
|
int id = 0;
|
||||||
QString name, login, password;
|
QString name, login, password;
|
||||||
QString authType = QStringLiteral("offline"); // offline | elyby | microsoft
|
QString authType = QStringLiteral("offline");
|
||||||
QString clientToken, accessToken, uuid, resolvedName, userType;
|
QString clientToken, accessToken, uuid, resolvedName, userType;
|
||||||
// Только для microsoft: продление сессии, ${auth_xuid} и срок жизни
|
|
||||||
// accessToken в ISO-8601 (чтобы класть в JSON без конвертеров).
|
|
||||||
QString refreshToken, xuid, tokenExpiry;
|
QString refreshToken, xuid, tokenExpiry;
|
||||||
};
|
};
|
||||||
// Пользовательская сборка: имя, сервер, версия Minecraft и, начиная со
|
|
||||||
// второго этапа, выбранный модлоадер.
|
|
||||||
struct CustomBuild
|
struct CustomBuild
|
||||||
{
|
{
|
||||||
int id = 0;
|
int id = 0;
|
||||||
QString name, serverUrl;
|
QString name, serverUrl;
|
||||||
QString minecraftVersion; // 1.20.1
|
QString minecraftVersion;
|
||||||
QString loader; // "" | forge | fabric | neoforge | quilt
|
QString loader;
|
||||||
QString loaderVersion; // 47.4.0 | 0.19.3
|
QString loaderVersion;
|
||||||
QString resolvedVersionId; // versions/<id>, который реально запускается
|
QString resolvedVersionId;
|
||||||
// Сборка приехала с сервера сезонных сборок: id её строки в каталоге и
|
|
||||||
// установленная ревизия. Пусто — обычная пользовательская сборка.
|
|
||||||
QString seasonalId;
|
QString seasonalId;
|
||||||
int seasonalRevision = 0;
|
int seasonalRevision = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Шаг установки сезонной сборки. Порядок жёсткий: Java нужна установщику
|
|
||||||
// Forge, а раскатывать файлы поверх имеет смысл только когда всё остальное
|
|
||||||
// на месте.
|
|
||||||
enum class SeasonStage { Idle, Switching, Java, Loader, Downloading, Applying };
|
enum class SeasonStage { Idle, Switching, Java, Loader, Downloading, Applying };
|
||||||
struct SeasonalInstall
|
struct SeasonalInstall
|
||||||
{
|
{
|
||||||
SeasonStage stage = SeasonStage::Idle;
|
SeasonStage stage = SeasonStage::Idle;
|
||||||
int buildId = -1;
|
int buildId = -1;
|
||||||
QString packPath;
|
QString packPath;
|
||||||
// Копия строки каталога на момент старта: обновление списка посреди
|
|
||||||
// установки не должно менять то, что ставится.
|
|
||||||
SeasonalBuildEntry entry;
|
SeasonalBuildEntry entry;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -299,25 +243,17 @@ private:
|
|||||||
void saveCustomBuilds();
|
void saveCustomBuilds();
|
||||||
void saveSettings();
|
void saveSettings();
|
||||||
|
|
||||||
// Чтение файлов лаунчера. Отсутствие файла — норма (первый запуск), а вот
|
|
||||||
// повреждённое содержимое отводится в .bak, чтобы файл создался заново.
|
|
||||||
QJsonArray readArrayFile(const QString &path);
|
QJsonArray readArrayFile(const QString &path);
|
||||||
QJsonObject readObjectFile(const QString &path);
|
QJsonObject readObjectFile(const QString &path);
|
||||||
bool moveAsideBroken(const QString &path, const QString &reason);
|
bool moveAsideBroken(const QString &path, const QString &reason);
|
||||||
|
|
||||||
// Проверяет папку лаунчера и пишет документ. Об ошибке сообщает через launchError.
|
|
||||||
bool writeJsonFile(const QString &path, const QJsonDocument &document);
|
bool writeJsonFile(const QString &path, const QJsonDocument &document);
|
||||||
|
|
||||||
QString gameDir() const;
|
QString gameDir() const;
|
||||||
// id профиля в <gameDir>/versions, который запускает эта сборка.
|
|
||||||
QString launchVersionIdOf(const CustomBuild &build) const;
|
QString launchVersionIdOf(const CustomBuild &build) const;
|
||||||
int indexOfBuildId(int buildId) const;
|
int indexOfBuildId(int buildId) const;
|
||||||
|
|
||||||
// Перекладывает <root>/versions.json в customBuilds.json при первом запуске
|
|
||||||
// после переименования. true — миграция прошла, читать нужно новый файл.
|
|
||||||
bool migrateLegacyBuildsFile();
|
bool migrateLegacyBuildsFile();
|
||||||
// Первый запуск: заводит активную сборку под то, что уже лежит в папке игры.
|
|
||||||
// Папку игры только читает. Возвращает имя сборки или пустую строку.
|
|
||||||
QString importGameDir();
|
QString importGameDir();
|
||||||
|
|
||||||
void invalidateCatalog();
|
void invalidateCatalog();
|
||||||
@@ -326,34 +262,22 @@ private:
|
|||||||
void rebuildJavaCatalog() const;
|
void rebuildJavaCatalog() const;
|
||||||
void invalidateSeasonalCatalog();
|
void invalidateSeasonalCatalog();
|
||||||
void rebuildSeasonalCatalog() const;
|
void rebuildSeasonalCatalog() const;
|
||||||
// Панель загрузки занята скачиванием пака сезонной сборки.
|
|
||||||
bool packDownloadShown() const;
|
bool packDownloadShown() const;
|
||||||
|
|
||||||
// ── Установка сезонной сборки ───────────────────────────────────────
|
|
||||||
// Каждый шаг либо запускает асинхронную операцию и возвращает true, либо
|
|
||||||
// решает, что делать нечего, и уступает следующему.
|
|
||||||
void seasonAdvance();
|
void seasonAdvance();
|
||||||
bool seasonBeginSwitch();
|
bool seasonBeginSwitch();
|
||||||
bool seasonBeginJava();
|
bool seasonBeginJava();
|
||||||
bool seasonBeginLoader();
|
bool seasonBeginLoader();
|
||||||
bool seasonBeginDownload();
|
bool seasonBeginDownload();
|
||||||
bool seasonBeginApply();
|
bool seasonBeginApply();
|
||||||
// message пусто — о причине уже сообщил тот, кто её обнаружил.
|
|
||||||
void seasonFail(const QString &message);
|
void seasonFail(const QString &message);
|
||||||
void seasonFinish();
|
void seasonFinish();
|
||||||
int indexOfSeasonalBuild(const QString &seasonalId) const;
|
int indexOfSeasonalBuild(const QString &seasonalId) const;
|
||||||
// Что принесла установленная ревизия сборки; пусто — сезонных файлов нет.
|
|
||||||
QStringList seasonalPackEntries(int buildId) const;
|
QStringList seasonalPackEntries(int buildId) const;
|
||||||
// Запоминает раскатанную ревизию: и в builds/<id>/season.json, и в записи
|
|
||||||
// сборки. Вызывается и после доигрывания прерванной установки.
|
|
||||||
void recordSeasonalPack(int buildId, const QJsonObject ¬e, const QStringList &entries);
|
void recordSeasonalPack(int buildId, const QJsonObject ¬e, const QStringList &entries);
|
||||||
QUrl seasonalBaseUrl() const;
|
QUrl seasonalBaseUrl() const;
|
||||||
// Панель загрузки занята установкой Java, а не версии или модлоадера.
|
|
||||||
bool javaDownloadShown() const;
|
bool javaDownloadShown() const;
|
||||||
// Путь к java выбранной сборки из папки лаунчера. Пусто — сборка не выбрана
|
|
||||||
// или ещё не скачана; тогда в дело идёт javaPath и автопоиск.
|
|
||||||
QString managedJavaPath() const;
|
QString managedJavaPath() const;
|
||||||
// Версия выбрана, но её нет в .minecraft — ставим в фоне.
|
|
||||||
void maybeInstall(const QString &versionId);
|
void maybeInstall(const QString &versionId);
|
||||||
|
|
||||||
void setBusy(bool busy);
|
void setBusy(bool busy);
|
||||||
@@ -366,8 +290,6 @@ private:
|
|||||||
QList<Profile> m_profiles;
|
QList<Profile> m_profiles;
|
||||||
QList<CustomBuild> m_builds;
|
QList<CustomBuild> m_builds;
|
||||||
QVariantMap m_settings;
|
QVariantMap m_settings;
|
||||||
// Проблемы хранилища, замеченные на старте: показываются одним сообщением,
|
|
||||||
// когда интерфейс уже подключился к сигналам.
|
|
||||||
QStringList m_storageIssues;
|
QStringList m_storageIssues;
|
||||||
int m_nextProfileId = 1;
|
int m_nextProfileId = 1;
|
||||||
int m_nextBuildId = 1;
|
int m_nextBuildId = 1;
|
||||||
@@ -385,16 +307,10 @@ private:
|
|||||||
SeasonalBuildService *m_seasonalMeta;
|
SeasonalBuildService *m_seasonalMeta;
|
||||||
SeasonalPackDownloader *m_packDownloader;
|
SeasonalPackDownloader *m_packDownloader;
|
||||||
|
|
||||||
// Сборка, для которой сейчас ставится модлоадер: по её id находим запись,
|
|
||||||
// когда установщик отчитается.
|
|
||||||
int m_loaderInstallBuildId = -1;
|
int m_loaderInstallBuildId = -1;
|
||||||
|
|
||||||
// Профиль, для которого открыто окно входа Microsoft. -1 — окно закрыто,
|
|
||||||
// -2 — вход для профиля, которого ещё нет.
|
|
||||||
int m_msaLoginProfile = -1;
|
int m_msaLoginProfile = -1;
|
||||||
|
|
||||||
// Каталог версий пересобирается только по изменениям: QML читает свойство
|
|
||||||
// помногу раз за кадр, пока открыт список.
|
|
||||||
mutable QVariantList m_catalog;
|
mutable QVariantList m_catalog;
|
||||||
mutable bool m_catalogDirty = true;
|
mutable bool m_catalogDirty = true;
|
||||||
|
|
||||||
@@ -408,7 +324,6 @@ private:
|
|||||||
|
|
||||||
bool m_busy = false;
|
bool m_busy = false;
|
||||||
|
|
||||||
// Состояние запуска, начатого до асинхронной авторизации.
|
|
||||||
int m_pendingProfile = -1;
|
int m_pendingProfile = -1;
|
||||||
int m_pendingBuild = -1;
|
int m_pendingBuild = -1;
|
||||||
MinecraftVersion m_pendingVersionData;
|
MinecraftVersion m_pendingVersionData;
|
||||||
|
|||||||
+2
-7
@@ -9,18 +9,16 @@ namespace {
|
|||||||
|
|
||||||
const QString kFolderName = QStringLiteral("BiLauncher");
|
const QString kFolderName = QStringLiteral("BiLauncher");
|
||||||
|
|
||||||
// Домашняя папка, от которой строятся все пути (см. LauncherPaths::homeOverride()).
|
|
||||||
QString homeBase()
|
QString homeBase()
|
||||||
{
|
{
|
||||||
const QString overridden = LauncherPaths::homeOverride();
|
const QString overridden = LauncherPaths::homeOverride();
|
||||||
return overridden.isEmpty() ? QDir::homePath() : overridden;
|
return overridden.isEmpty() ? QDir::homePath() : overridden;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
}
|
||||||
|
|
||||||
QString LauncherPaths::homeOverride()
|
QString LauncherPaths::homeOverride()
|
||||||
{
|
{
|
||||||
// Относительный путь зависел бы от текущей папки процесса — такой не принимаем.
|
|
||||||
const QString value = QDir::fromNativeSeparators(qEnvironmentVariable("BILAUNCHER_HOME"));
|
const QString value = QDir::fromNativeSeparators(qEnvironmentVariable("BILAUNCHER_HOME"));
|
||||||
if (value.isEmpty() || !QDir::isAbsolutePath(value))
|
if (value.isEmpty() || !QDir::isAbsolutePath(value))
|
||||||
return QString();
|
return QString();
|
||||||
@@ -33,7 +31,7 @@ QString LauncherPaths::containerDir()
|
|||||||
return homeBase() + QStringLiteral("/AppData/Roaming");
|
return homeBase() + QStringLiteral("/AppData/Roaming");
|
||||||
#elif defined(Q_OS_MACOS)
|
#elif defined(Q_OS_MACOS)
|
||||||
return homeBase() + QStringLiteral("/Library/Application Support");
|
return homeBase() + QStringLiteral("/Library/Application Support");
|
||||||
#else // Linux и прочие Unix-системы
|
#else
|
||||||
return homeBase();
|
return homeBase();
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
@@ -46,7 +44,6 @@ QString LauncherPaths::rootDir()
|
|||||||
QString LauncherPaths::defaultMinecraftDir()
|
QString LauncherPaths::defaultMinecraftDir()
|
||||||
{
|
{
|
||||||
#if defined(Q_OS_MACOS)
|
#if defined(Q_OS_MACOS)
|
||||||
// На macOS папка игры исторически без точки.
|
|
||||||
return containerDir() + QStringLiteral("/minecraft");
|
return containerDir() + QStringLiteral("/minecraft");
|
||||||
#else
|
#else
|
||||||
return containerDir() + QStringLiteral("/.minecraft");
|
return containerDir() + QStringLiteral("/.minecraft");
|
||||||
@@ -145,8 +142,6 @@ bool LauncherPaths::ensureRootExists(QString *error)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// mkpath отвечает true и для существующего каталога, в который нельзя писать,
|
|
||||||
// и для подсунутого вместо папки файла — тогда все сохранения провалились бы молча.
|
|
||||||
const QFileInfo info(path);
|
const QFileInfo info(path);
|
||||||
if (!info.isDir() || !info.isWritable()) {
|
if (!info.isDir() || !info.isWritable()) {
|
||||||
if (error)
|
if (error)
|
||||||
|
|||||||
@@ -0,0 +1,279 @@
|
|||||||
|
#include "launcherupdates.h"
|
||||||
|
#include "launcherversion.h"
|
||||||
|
|
||||||
|
#include <QCoreApplication>
|
||||||
|
#include <QDateTime>
|
||||||
|
#include <QDir>
|
||||||
|
#include <QFile>
|
||||||
|
#include <QFileInfo>
|
||||||
|
#include <QJsonArray>
|
||||||
|
#include <QJsonDocument>
|
||||||
|
#include <QJsonObject>
|
||||||
|
#include <QNetworkReply>
|
||||||
|
#include <QProcess>
|
||||||
|
#include <QRegularExpression>
|
||||||
|
#include <QSaveFile>
|
||||||
|
#include <QUrlQuery>
|
||||||
|
#include <QVersionNumber>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
#ifdef Q_OS_WIN
|
||||||
|
#include <windows.h>
|
||||||
|
#include <shellapi.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
const QString origin = QStringLiteral("https://projects-live.galeonworx.com");
|
||||||
|
const QString repository = origin + QStringLiteral("/galeon/BiLauncher");
|
||||||
|
|
||||||
|
QNetworkRequest request(const QUrl &url)
|
||||||
|
{
|
||||||
|
QNetworkRequest result(url);
|
||||||
|
result.setTransferTimeout(30000);
|
||||||
|
result.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::SameOriginRedirectPolicy);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto versionKey(const QString &version)
|
||||||
|
{
|
||||||
|
qsizetype suffix = 0;
|
||||||
|
const auto number = QVersionNumber::fromString(version, &suffix);
|
||||||
|
const int candidate = version.mid(suffix + 3).toInt();
|
||||||
|
return std::pair(number, candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
QString assetName(const QString &version)
|
||||||
|
{
|
||||||
|
const auto prefix = QStringLiteral("BiLauncher-") + version;
|
||||||
|
#if defined(Q_OS_WIN)
|
||||||
|
return prefix + QStringLiteral("-win64-setup.exe");
|
||||||
|
#elif defined(Q_OS_MACOS)
|
||||||
|
return prefix + QStringLiteral("-macOS-universal.dmg");
|
||||||
|
#elif defined(Q_OS_LINUX) && defined(Q_PROCESSOR_X86_64)
|
||||||
|
return prefix + QStringLiteral("-x86_64.AppImage");
|
||||||
|
#else
|
||||||
|
return {};
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
LauncherUpdates::LauncherUpdates(QObject *parent)
|
||||||
|
: QObject(parent)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
LauncherUpdates::~LauncherUpdates() = default;
|
||||||
|
|
||||||
|
QString LauncherUpdates::channel() const
|
||||||
|
{
|
||||||
|
return QStringLiteral(LAUNCHER_CHANNEL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void LauncherUpdates::refresh(const QString &channel)
|
||||||
|
{
|
||||||
|
if ((channel != "release" && channel != "rc") || m_states.value(channel) == "loading")
|
||||||
|
return;
|
||||||
|
|
||||||
|
m_states.insert(channel, QStringLiteral("loading"));
|
||||||
|
emit catalogChanged();
|
||||||
|
fetchPage(channel, 1, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
void LauncherUpdates::fetchPage(const QString &channel, int page, QVariantList entries)
|
||||||
|
{
|
||||||
|
QUrl url(origin + QStringLiteral("/api/v1/repos/galeon/BiLauncher/releases"));
|
||||||
|
QUrlQuery query;
|
||||||
|
query.addQueryItem(QStringLiteral("draft"), QStringLiteral("false"));
|
||||||
|
query.addQueryItem(QStringLiteral("pre-release"), channel == "rc" ? QStringLiteral("true") : QStringLiteral("false"));
|
||||||
|
query.addQueryItem(QStringLiteral("page"), QString::number(page));
|
||||||
|
query.addQueryItem(QStringLiteral("limit"), QStringLiteral("50"));
|
||||||
|
url.setQuery(query);
|
||||||
|
|
||||||
|
auto *reply = m_network.get(request(url));
|
||||||
|
connect(reply, &QNetworkReply::finished, this, [this, reply, channel, page, entries = std::move(entries)]() mutable {
|
||||||
|
reply->deleteLater();
|
||||||
|
const auto document = QJsonDocument::fromJson(reply->readAll());
|
||||||
|
if (reply->error() != QNetworkReply::NoError || !document.isArray()) {
|
||||||
|
qWarning() << "BiLauncher release catalog:" << reply->errorString();
|
||||||
|
m_states.insert(channel, QStringLiteral("error"));
|
||||||
|
emit catalogChanged();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto releases = document.array();
|
||||||
|
static const QRegularExpression tagPattern(QStringLiteral("^v([0-9]+\\.[0-9]+\\.[0-9]+)(-rc[0-9]+)?$"));
|
||||||
|
for (const auto &item : releases) {
|
||||||
|
const auto release = item.toObject();
|
||||||
|
const auto tag = release.value("tag_name").toString();
|
||||||
|
const auto match = tagPattern.match(tag);
|
||||||
|
const bool candidate = channel == "rc";
|
||||||
|
const bool candidateTag = !match.captured(2).isEmpty();
|
||||||
|
if (!match.hasMatch() || release.value("draft").toBool()
|
||||||
|
|| release.value("prerelease").toBool() != candidate
|
||||||
|
|| candidateTag != candidate)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
const auto version = tag.mid(1);
|
||||||
|
const auto name = assetName(version);
|
||||||
|
const auto expectedUrl = repository + QStringLiteral("/releases/download/") + tag + u'/' + name;
|
||||||
|
qint64 size = 0;
|
||||||
|
for (const auto &item : release.value("assets").toArray()) {
|
||||||
|
const auto asset = item.toObject();
|
||||||
|
if (!name.isEmpty() && asset.value("name").toString() == name
|
||||||
|
&& asset.value("browser_download_url").toString() == expectedUrl) {
|
||||||
|
size = asset.value("size").toInteger();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
entries.append(QVariantMap{
|
||||||
|
{"version", version},
|
||||||
|
{"date", QDateTime::fromString(release.value("published_at").toString(), Qt::ISODate)},
|
||||||
|
{"changelog", repository + QStringLiteral("/src/tag/") + tag + QStringLiteral("/CHANGELOG.md")},
|
||||||
|
{"download", size > 0 ? expectedUrl : QString()},
|
||||||
|
{"size", size},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!releases.isEmpty()) {
|
||||||
|
fetchPage(channel, page + 1, std::move(entries));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::sort(entries.begin(), entries.end(), [](const QVariant &a, const QVariant &b) {
|
||||||
|
return versionKey(a.toMap().value("version").toString()) > versionKey(b.toMap().value("version").toString());
|
||||||
|
});
|
||||||
|
if (channel == this->channel()) {
|
||||||
|
m_latest.clear();
|
||||||
|
for (const auto &item : std::as_const(entries)) {
|
||||||
|
const auto entry = item.toMap();
|
||||||
|
const auto version = entry.value("version").toString();
|
||||||
|
if (!entry.value("download").toString().isEmpty()
|
||||||
|
&& versionKey(version) > versionKey(QStringLiteral(LAUNCHER_VERSION))) {
|
||||||
|
m_latest = version;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m_catalogs.insert(channel, entries);
|
||||||
|
m_states.insert(channel, QStringLiteral("ready"));
|
||||||
|
emit catalogChanged();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void LauncherUpdates::install(const QString &channel, const QString &version)
|
||||||
|
{
|
||||||
|
if (installing())
|
||||||
|
return;
|
||||||
|
|
||||||
|
QVariantMap release;
|
||||||
|
for (const auto &item : m_catalogs.value(channel).toList()) {
|
||||||
|
if (item.toMap().value("version") == version) {
|
||||||
|
release = item.toMap();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const QUrl url(release.value("download").toString());
|
||||||
|
if (url.isEmpty()) {
|
||||||
|
emit installationFailed();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_temp = std::make_unique<QTemporaryDir>();
|
||||||
|
if (!m_temp->isValid()) {
|
||||||
|
qWarning() << "BiLauncher update:" << m_temp->errorString();
|
||||||
|
m_temp.reset();
|
||||||
|
emit installationFailed();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const QString path = m_temp->filePath(url.fileName());
|
||||||
|
m_download = std::make_unique<QFile>(path);
|
||||||
|
if (!m_download->open(QIODevice::WriteOnly)) {
|
||||||
|
qWarning() << "BiLauncher update:" << m_download->errorString();
|
||||||
|
m_download.reset();
|
||||||
|
m_temp.reset();
|
||||||
|
emit installationFailed();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const qint64 size = release.value("size").toLongLong();
|
||||||
|
auto *reply = m_network.get(request(url));
|
||||||
|
reply->setReadBufferSize(256 * 1024);
|
||||||
|
const auto writeChunk = [this, reply, size] {
|
||||||
|
const auto chunk = reply->readAll();
|
||||||
|
if (m_download->pos() + chunk.size() > size || m_download->write(chunk) != chunk.size()) {
|
||||||
|
qWarning() << "BiLauncher update: failed to write installer";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
connect(reply, &QNetworkReply::readyRead, this, [reply, writeChunk] {
|
||||||
|
if (!writeChunk())
|
||||||
|
reply->abort();
|
||||||
|
});
|
||||||
|
connect(reply, &QNetworkReply::finished, this, [this, reply, path, size, writeChunk] {
|
||||||
|
reply->deleteLater();
|
||||||
|
const bool downloaded = reply->error() == QNetworkReply::NoError
|
||||||
|
&& writeChunk() && m_download->pos() == size && m_download->flush();
|
||||||
|
m_download.reset();
|
||||||
|
|
||||||
|
if (downloaded && startInstallation(path)) {
|
||||||
|
#if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
|
||||||
|
m_temp->setAutoRemove(false);
|
||||||
|
#endif
|
||||||
|
m_temp.reset();
|
||||||
|
QCoreApplication::quit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
qWarning() << "BiLauncher update failed:" << path << reply->errorString();
|
||||||
|
m_temp.reset();
|
||||||
|
emit installationChanged();
|
||||||
|
emit installationFailed();
|
||||||
|
});
|
||||||
|
emit installationChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LauncherUpdates::startInstallation(const QString &path)
|
||||||
|
{
|
||||||
|
#ifdef Q_OS_WIN
|
||||||
|
const auto nativePath = QDir::toNativeSeparators(path).toStdWString();
|
||||||
|
return reinterpret_cast<INT_PTR>(
|
||||||
|
ShellExecuteW(nullptr, L"open", nativePath.c_str(), nullptr, nullptr, SW_SHOWNORMAL)) > 32;
|
||||||
|
#elif defined(Q_OS_MACOS)
|
||||||
|
return QProcess::startDetached(QStringLiteral("/usr/bin/open"), {path});
|
||||||
|
#elif defined(Q_OS_LINUX)
|
||||||
|
QString destination = qEnvironmentVariable("APPIMAGE");
|
||||||
|
if (destination.isEmpty()) {
|
||||||
|
const QDir home = QDir::home();
|
||||||
|
if (!home.mkpath(QStringLiteral("Applications")))
|
||||||
|
return false;
|
||||||
|
destination = home.filePath(QStringLiteral("Applications/BiLauncher.AppImage"));
|
||||||
|
} else {
|
||||||
|
destination = QFileInfo(destination).canonicalFilePath();
|
||||||
|
if (destination.isEmpty())
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
QFile source(path);
|
||||||
|
QSaveFile installed(destination);
|
||||||
|
if (!source.open(QIODevice::ReadOnly) || !installed.open(QIODevice::WriteOnly)
|
||||||
|
|| !installed.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner
|
||||||
|
| QFileDevice::ReadGroup | QFileDevice::ExeGroup
|
||||||
|
| QFileDevice::ReadOther | QFileDevice::ExeOther))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
while (!source.atEnd()) {
|
||||||
|
const auto chunk = source.read(256 * 1024);
|
||||||
|
if (chunk.isEmpty() || installed.write(chunk) != chunk.size())
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return installed.commit();
|
||||||
|
#else
|
||||||
|
return false;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QNetworkAccessManager>
|
||||||
|
#include <QTemporaryDir>
|
||||||
|
#include <QVariantMap>
|
||||||
|
#include <QtQml/qqmlregistration.h>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
class QFile;
|
||||||
|
|
||||||
|
class LauncherUpdates : public QObject
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
QML_ELEMENT
|
||||||
|
Q_PROPERTY(QString channel READ channel CONSTANT)
|
||||||
|
Q_PROPERTY(QVariantMap catalogs READ catalogs NOTIFY catalogChanged)
|
||||||
|
Q_PROPERTY(QVariantMap states READ states NOTIFY catalogChanged)
|
||||||
|
Q_PROPERTY(QString latest READ latest NOTIFY catalogChanged)
|
||||||
|
Q_PROPERTY(bool installing READ installing NOTIFY installationChanged)
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit LauncherUpdates(QObject *parent = nullptr);
|
||||||
|
~LauncherUpdates() override;
|
||||||
|
|
||||||
|
QString channel() const;
|
||||||
|
QVariantMap catalogs() const { return m_catalogs; }
|
||||||
|
QVariantMap states() const { return m_states; }
|
||||||
|
QString latest() const { return m_latest; }
|
||||||
|
bool installing() const { return bool(m_download); }
|
||||||
|
|
||||||
|
Q_INVOKABLE void refresh(const QString &channel);
|
||||||
|
Q_INVOKABLE void install(const QString &channel, const QString &version);
|
||||||
|
|
||||||
|
signals:
|
||||||
|
void catalogChanged();
|
||||||
|
void installationChanged();
|
||||||
|
void installationFailed();
|
||||||
|
|
||||||
|
private:
|
||||||
|
void fetchPage(const QString &channel, int page, QVariantList entries);
|
||||||
|
bool startInstallation(const QString &path);
|
||||||
|
|
||||||
|
QNetworkAccessManager m_network;
|
||||||
|
QVariantMap m_catalogs;
|
||||||
|
QVariantMap m_states;
|
||||||
|
QString m_latest;
|
||||||
|
std::unique_ptr<QTemporaryDir> m_temp;
|
||||||
|
std::unique_ptr<QFile> m_download;
|
||||||
|
};
|
||||||
+5
-43
@@ -13,22 +13,6 @@
|
|||||||
class QQmlEngine;
|
class QQmlEngine;
|
||||||
class QJSEngine;
|
class QJSEngine;
|
||||||
|
|
||||||
// Единственный источник всех текстов интерфейса. Каталог — i18n/translations.json,
|
|
||||||
// он лежит в ресурсах и правится руками; штатных .ts/.qm в проекте нет намеренно.
|
|
||||||
//
|
|
||||||
// Из QML читается свойством: text: Loc.t.settings.title
|
|
||||||
// Из C++ — свободной функцией: Loc::text("settings.title")
|
|
||||||
//
|
|
||||||
// Почему свойство, а не Q_INVOKABLE: вызов метода не регистрирует зависимость
|
|
||||||
// привязки, и text: Loc.t("ключ") никогда бы не обновился при смене языка.
|
|
||||||
// Чтение же Q_PROPERTY с сигналом NOTIFY зависимость регистрирует, поэтому
|
|
||||||
// languageChanged перевычисляет все привязки разом. Дальнейшие .settings.title —
|
|
||||||
// обычные обращения к членам JS-объекта, и отслеживать их не нужно: при смене
|
|
||||||
// языка дерево заменяется целиком.
|
|
||||||
//
|
|
||||||
// Тип свойства — QJSValue, а не QVariantMap: QVariantMap пересобирался бы в новый
|
|
||||||
// JS-объект при каждом чтении, а привязок в проекте полторы сотни. QJSValue
|
|
||||||
// строится один раз на смену языка.
|
|
||||||
class Localization : public QObject
|
class Localization : public QObject
|
||||||
{
|
{
|
||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
@@ -36,36 +20,24 @@ class Localization : public QObject
|
|||||||
QML_SINGLETON
|
QML_SINGLETON
|
||||||
|
|
||||||
Q_PROPERTY(QJSValue t READ t NOTIFY languageChanged)
|
Q_PROPERTY(QJSValue t READ t NOTIFY languageChanged)
|
||||||
// Что выбрано пользователем: "system", "ru" или "en".
|
|
||||||
Q_PROPERTY(QString language READ language NOTIFY languageChanged)
|
Q_PROPERTY(QString language READ language NOTIFY languageChanged)
|
||||||
// Во что это разрешилось: всегда "ru" или "en", никогда "system".
|
|
||||||
Q_PROPERTY(QString resolvedLanguage READ resolvedLanguage NOTIFY languageChanged)
|
Q_PROPERTY(QString resolvedLanguage READ resolvedLanguage NOTIFY languageChanged)
|
||||||
|
|
||||||
public:
|
public:
|
||||||
static Localization &instance();
|
static Localization &instance();
|
||||||
|
|
||||||
// Фабрика синглтона для движка QML. Объект к этому моменту уже загружен
|
|
||||||
// из main(), здесь только запоминается движок и строится дерево.
|
|
||||||
static Localization *create(QQmlEngine *qmlEngine, QJSEngine *jsEngine);
|
static Localization *create(QQmlEngine *qmlEngine, QJSEngine *jsEngine);
|
||||||
|
|
||||||
// Читает каталог из ресурсов и язык из settings.json. Вызывается ровно один
|
|
||||||
// раз из main() до создания QQmlApplicationEngine. false — каталога нет или
|
|
||||||
// он битый; это ошибка сборки, и запускаться дальше незачем.
|
|
||||||
bool load();
|
bool load();
|
||||||
|
|
||||||
QJSValue t() const { return m_tree; }
|
QJSValue t() const { return m_tree; }
|
||||||
QString language() const { return m_language; }
|
QString language() const { return m_language; }
|
||||||
QString resolvedLanguage() const;
|
QString resolvedLanguage() const;
|
||||||
|
|
||||||
// Только из GUI-потока: меняет дерево и рассылает languageChanged.
|
|
||||||
void setLanguage(const QString &code);
|
void setLanguage(const QString &code);
|
||||||
|
|
||||||
// Для комбобокса в настройках: [{ "code": "ru", "name": "Русский" }, …],
|
|
||||||
// первым пунктом — "system".
|
|
||||||
Q_INVOKABLE QVariantList availableLanguages() const;
|
Q_INVOKABLE QVariantList availableLanguages() const;
|
||||||
|
|
||||||
// Рабочие лошадки Loc::text/Loc::list. Потокобезопасны: см. комментарий к
|
|
||||||
// полям ниже.
|
|
||||||
[[nodiscard]] QString textFor(const char *key) const;
|
[[nodiscard]] QString textFor(const char *key) const;
|
||||||
[[nodiscard]] QStringList listFor(const char *key) const;
|
[[nodiscard]] QStringList listFor(const char *key) const;
|
||||||
|
|
||||||
@@ -77,32 +49,22 @@ private:
|
|||||||
|
|
||||||
void rebuildTree();
|
void rebuildTree();
|
||||||
|
|
||||||
// Каталог заполняется один раз в load() и дальше только читается — поэтому
|
QHash<QString, QStringList> m_singles;
|
||||||
// обращаться к нему можно из любого потока без блокировок. Единственное, что
|
QHash<QString, QList<QStringList>> m_lists;
|
||||||
// меняется на ходу, — m_index, и он атомарный.
|
QStringList m_codes;
|
||||||
QHash<QString, QStringList> m_singles; // ключ -> значения по языкам
|
|
||||||
QHash<QString, QList<QStringList>> m_lists; // ключ -> списки по языкам
|
|
||||||
QStringList m_codes; // ["ru", "en"] — порядок из _meta
|
|
||||||
QHash<QString, QString> m_displayNames;
|
QHash<QString, QString> m_displayNames;
|
||||||
|
|
||||||
QAtomicInt m_index{0}; // индекс текущего языка в m_codes
|
QAtomicInt m_index{0};
|
||||||
QString m_language{QStringLiteral("system")};
|
QString m_language{QStringLiteral("system")};
|
||||||
|
|
||||||
QJSEngine *m_engine = nullptr;
|
QJSEngine *m_engine = nullptr;
|
||||||
QJSValue m_tree;
|
QJSValue m_tree;
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Доступ из C++ ───────────────────────────────────────────────────────────
|
|
||||||
//
|
|
||||||
// Свободные функции, а не методы: их вызывают и из namespace-обёрток
|
|
||||||
// (LauncherPaths, JavaLocator, ZlibReference), где никакого QObject нет.
|
|
||||||
namespace Loc {
|
namespace Loc {
|
||||||
|
|
||||||
// Перевод по ключу. Ключа нет — возвращается сам ключ, в отладочной сборке ещё
|
|
||||||
// и qWarning: строка вида "launch.error.gameRunning" в интерфейсе сразу видна.
|
|
||||||
[[nodiscard]] QString text(const char *key);
|
[[nodiscard]] QString text(const char *key);
|
||||||
|
|
||||||
// Для ключей со значением-списком (модели комбобоксов).
|
|
||||||
[[nodiscard]] QStringList list(const char *key);
|
[[nodiscard]] QStringList list(const char *key);
|
||||||
|
|
||||||
} // namespace Loc
|
}
|
||||||
@@ -8,9 +8,11 @@
|
|||||||
#include "fixtures.h"
|
#include "fixtures.h"
|
||||||
|
|
||||||
#include "launcherpaths.h"
|
#include "launcherpaths.h"
|
||||||
|
#include "launcherversion.h"
|
||||||
#include "localization.h"
|
#include "localization.h"
|
||||||
|
|
||||||
#include <QGuiApplication>
|
#include <QGuiApplication>
|
||||||
|
#include <QJSValue>
|
||||||
#include <QQmlApplicationEngine>
|
#include <QQmlApplicationEngine>
|
||||||
#include <QQuickStyle>
|
#include <QQuickStyle>
|
||||||
#include <QQuickWindow>
|
#include <QQuickWindow>
|
||||||
@@ -66,6 +68,19 @@ private slots:
|
|||||||
// Один движок на весь тест, как в приложении: Localization держит указатель
|
// Один движок на весь тест, как в приложении: Localization держит указатель
|
||||||
// на JS-движок, создавший синглтон, и второй QQmlApplicationEngine после
|
// на JS-движок, создавший синглтон, и второй QQmlApplicationEngine после
|
||||||
// уничтожения первого оставил бы его висячим.
|
// уничтожения первого оставил бы его висячим.
|
||||||
|
const QString releasesUrl = QStringLiteral(
|
||||||
|
"https://projects-live.galeonworx.com/api/v1/repos/galeon/BiLauncher/releases");
|
||||||
|
const bool candidate = QStringLiteral(LAUNCHER_CHANNEL) == "rc";
|
||||||
|
const auto release = candidate
|
||||||
|
? R"([{"tag_name":"v1.0.0-rc1","prerelease":true,"published_at":"2026-10-14T10:52:02Z"}])"
|
||||||
|
: R"([{"tag_name":"v1.0.0","prerelease":false,"published_at":"2026-10-14T10:52:02Z"}])";
|
||||||
|
m_net.route(releasesUrl, [candidate, release](const FakeRequest &request) {
|
||||||
|
const auto query = request.queryItems();
|
||||||
|
if (query.queryItemValue("pre-release") != (candidate ? "true" : "false"))
|
||||||
|
return FakeResponse::error(400);
|
||||||
|
return FakeResponse::json(query.queryItemValue("page") == "1" ? release : "[]");
|
||||||
|
});
|
||||||
|
|
||||||
QQmlApplicationEngine engine;
|
QQmlApplicationEngine engine;
|
||||||
QStringList warnings;
|
QStringList warnings;
|
||||||
connect(&engine, &QQmlEngine::warnings, this, [&](const QList<QQmlError> &list) {
|
connect(&engine, &QQmlEngine::warnings, this, [&](const QList<QQmlError> &list) {
|
||||||
@@ -83,6 +98,19 @@ private slots:
|
|||||||
QVERIFY2(warnings.isEmpty(), qPrintable(warnings.join(u'\n')));
|
QVERIFY2(warnings.isEmpty(), qPrintable(warnings.join(u'\n')));
|
||||||
QVERIFY2(g_problems.isEmpty(), qPrintable(g_problems.join(u'\n')));
|
QVERIFY2(g_problems.isEmpty(), qPrintable(g_problems.join(u'\n')));
|
||||||
|
|
||||||
|
auto *versions = window->findChild<QObject *>(QStringLiteral("launcherVersions"));
|
||||||
|
QVERIFY(versions);
|
||||||
|
QVERIFY(QMetaObject::invokeMethod(versions, "open"));
|
||||||
|
QTRY_COMPARE(versions->property("state").toString(), QStringLiteral("ready"));
|
||||||
|
const auto entriesProperty = versions->property("entries");
|
||||||
|
const auto entries = entriesProperty.metaType() == QMetaType::fromType<QJSValue>()
|
||||||
|
? entriesProperty.value<QJSValue>().toVariant().toList()
|
||||||
|
: entriesProperty.toList();
|
||||||
|
QCOMPARE(entries.size(), 1);
|
||||||
|
QCOMPARE(entries.first().toMap().value("version").toString(),
|
||||||
|
candidate ? QStringLiteral("1.0.0-rc1") : QStringLiteral("1.0.0"));
|
||||||
|
QVERIFY(QMetaObject::invokeMethod(versions, "close"));
|
||||||
|
|
||||||
// Смена языка на лету перестраивает Loc.t — биндинги не должны ломаться.
|
// Смена языка на лету перестраивает Loc.t — биндинги не должны ломаться.
|
||||||
const QString titleEn = window->title();
|
const QString titleEn = window->title();
|
||||||
Localization::instance().setLanguage(QStringLiteral("ru"));
|
Localization::instance().setLanguage(QStringLiteral("ru"));
|
||||||
|
|||||||
Reference in new issue
Block a user