From 7d5787025aa5cebf6778f71e79f248f10b8541c9 Mon Sep 17 00:00:00 2001 From: Jan Dalheimer Date: Fri, 24 Jan 2014 18:12:02 +0100 Subject: Change naming from Derp -> OneSix until the new instance type supports legacy --- CMakeLists.txt | 38 +-- gui/MainWindow.cpp | 4 +- gui/dialogs/DerpModEditDialog.cpp | 306 ------------------------ gui/dialogs/DerpModEditDialog.h | 67 ------ gui/dialogs/DerpModEditDialog.ui | 317 ------------------------- gui/dialogs/OneSixModEditDialog.cpp | 306 ++++++++++++++++++++++++ gui/dialogs/OneSixModEditDialog.h | 67 ++++++ gui/dialogs/OneSixModEditDialog.ui | 317 +++++++++++++++++++++++++ logic/BaseInstaller.cpp | 12 +- logic/BaseInstaller.h | 10 +- logic/BaseInstance.h | 2 +- logic/DerpFTBInstance.cpp | 123 ---------- logic/DerpFTBInstance.h | 22 -- logic/DerpInstance.cpp | 388 ------------------------------ logic/DerpInstance.h | 75 ------ logic/DerpInstance_p.h | 27 --- logic/DerpLibrary.cpp | 268 --------------------- logic/DerpLibrary.h | 132 ----------- logic/DerpRule.cpp | 89 ------- logic/DerpRule.h | 98 -------- logic/DerpUpdate.cpp | 372 ----------------------------- logic/DerpUpdate.h | 63 ----- logic/DerpVersion.cpp | 194 --------------- logic/DerpVersion.h | 115 --------- logic/DerpVersionBuilder.cpp | 446 ----------------------------------- logic/DerpVersionBuilder.h | 53 ----- logic/ForgeInstaller.cpp | 14 +- logic/ForgeInstaller.h | 6 +- logic/InstanceFactory.cpp | 32 +-- logic/LegacyInstance.h | 2 +- logic/LiteLoaderInstaller.cpp | 14 +- logic/LiteLoaderInstaller.h | 4 +- logic/MinecraftVersion.h | 6 +- logic/NostalgiaInstance.cpp | 2 +- logic/NostalgiaInstance.h | 4 +- logic/OneSixFTBInstance.cpp | 123 ++++++++++ logic/OneSixFTBInstance.h | 22 ++ logic/OneSixInstance.cpp | 388 ++++++++++++++++++++++++++++++ logic/OneSixInstance.h | 75 ++++++ logic/OneSixInstance_p.h | 27 +++ logic/OneSixLibrary.cpp | 268 +++++++++++++++++++++ logic/OneSixLibrary.h | 132 +++++++++++ logic/OneSixRule.cpp | 89 +++++++ logic/OneSixRule.h | 98 ++++++++ logic/OneSixUpdate.cpp | 372 +++++++++++++++++++++++++++++ logic/OneSixUpdate.h | 63 +++++ logic/OneSixVersion.cpp | 292 ++++++----------------- logic/OneSixVersion.h | 45 ++-- logic/OneSixVersionBuilder.cpp | 446 +++++++++++++++++++++++++++++++++++ logic/OneSixVersionBuilder.h | 53 +++++ logic/lists/MinecraftVersionList.cpp | 6 +- 51 files changed, 3024 insertions(+), 3470 deletions(-) delete mode 100644 gui/dialogs/DerpModEditDialog.cpp delete mode 100644 gui/dialogs/DerpModEditDialog.h delete mode 100644 gui/dialogs/DerpModEditDialog.ui create mode 100644 gui/dialogs/OneSixModEditDialog.cpp create mode 100644 gui/dialogs/OneSixModEditDialog.h create mode 100644 gui/dialogs/OneSixModEditDialog.ui delete mode 100644 logic/DerpFTBInstance.cpp delete mode 100644 logic/DerpFTBInstance.h delete mode 100644 logic/DerpInstance.cpp delete mode 100644 logic/DerpInstance.h delete mode 100644 logic/DerpInstance_p.h delete mode 100644 logic/DerpLibrary.cpp delete mode 100644 logic/DerpLibrary.h delete mode 100644 logic/DerpRule.cpp delete mode 100644 logic/DerpRule.h delete mode 100644 logic/DerpUpdate.cpp delete mode 100644 logic/DerpUpdate.h delete mode 100644 logic/DerpVersion.cpp delete mode 100644 logic/DerpVersion.h delete mode 100644 logic/DerpVersionBuilder.cpp delete mode 100644 logic/DerpVersionBuilder.h create mode 100644 logic/OneSixFTBInstance.cpp create mode 100644 logic/OneSixFTBInstance.h create mode 100644 logic/OneSixInstance.cpp create mode 100644 logic/OneSixInstance.h create mode 100644 logic/OneSixInstance_p.h create mode 100644 logic/OneSixLibrary.cpp create mode 100644 logic/OneSixLibrary.h create mode 100644 logic/OneSixRule.cpp create mode 100644 logic/OneSixRule.h create mode 100644 logic/OneSixUpdate.cpp create mode 100644 logic/OneSixUpdate.h create mode 100644 logic/OneSixVersionBuilder.cpp create mode 100644 logic/OneSixVersionBuilder.h diff --git a/CMakeLists.txt b/CMakeLists.txt index c5339a30..6218ee7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -297,8 +297,8 @@ gui/dialogs/IconPickerDialog.h gui/dialogs/IconPickerDialog.cpp gui/dialogs/LegacyModEditDialog.h gui/dialogs/LegacyModEditDialog.cpp -gui/dialogs/DerpModEditDialog.h -gui/dialogs/DerpModEditDialog.cpp +gui/dialogs/OneSixModEditDialog.h +gui/dialogs/OneSixModEditDialog.cpp gui/dialogs/ModEditDialogCommon.h gui/dialogs/ModEditDialogCommon.cpp gui/dialogs/EditNotesDialog.h @@ -405,15 +405,15 @@ logic/LegacyUpdate.cpp logic/LegacyForge.h logic/LegacyForge.cpp -# Derp instances -logic/DerpUpdate.h -logic/DerpUpdate.cpp -logic/DerpVersion.h -logic/DerpVersion.cpp -logic/DerpLibrary.h -logic/DerpLibrary.cpp -logic/DerpRule.h -logic/DerpRule.cpp +# OneSix instances +logic/OneSixUpdate.h +logic/OneSixUpdate.cpp +logic/OneSixVersion.h +logic/OneSixVersion.cpp +logic/OneSixLibrary.h +logic/OneSixLibrary.cpp +logic/OneSixRule.h +logic/OneSixRule.cpp logic/OpSys.h logic/OpSys.cpp logic/BaseInstaller.h @@ -422,19 +422,19 @@ logic/ForgeInstaller.h logic/ForgeInstaller.cpp logic/LiteLoaderInstaller.h logic/LiteLoaderInstaller.cpp -logic/DerpInstance.h -logic/DerpInstance.cpp -logic/DerpInstance_p.h -logic/DerpVersionBuilder.h -logic/DerpVersionBuilder.cpp +logic/OneSixInstance.h +logic/OneSixInstance.cpp +logic/OneSixInstance_p.h +logic/OneSixVersionBuilder.h +logic/OneSixVersionBuilder.cpp # Nostalgia logic/NostalgiaInstance.h logic/NostalgiaInstance.cpp # FTB -logic/DerpFTBInstance.h -logic/DerpFTBInstance.cpp +logic/OneSixFTBInstance.h +logic/OneSixFTBInstance.cpp logic/LegacyFTBInstance.h logic/LegacyFTBInstance.cpp @@ -510,7 +510,7 @@ gui/dialogs/InstanceSettings.ui gui/dialogs/ProgressDialog.ui gui/dialogs/IconPickerDialog.ui gui/dialogs/LegacyModEditDialog.ui -gui/dialogs/DerpModEditDialog.ui +gui/dialogs/OneSixModEditDialog.ui gui/dialogs/EditNotesDialog.ui gui/dialogs/AccountListDialog.ui gui/dialogs/AccountSelectDialog.ui diff --git a/gui/MainWindow.cpp b/gui/MainWindow.cpp index ba394a94..ee9c3fad 100644 --- a/gui/MainWindow.cpp +++ b/gui/MainWindow.cpp @@ -84,7 +84,7 @@ #include "logic/BaseInstance.h" #include "logic/InstanceFactory.h" #include "logic/MinecraftProcess.h" -#include "logic/DerpUpdate.h" +#include "logic/OneSixUpdate.h" #include "logic/JavaUtils.h" #include "logic/NagUtils.h" #include "logic/SkinUtils.h" @@ -1257,7 +1257,7 @@ void MainWindow::on_actionChangeInstMCVersion_triggered() VersionSelectDialog vselect(m_selectedInstance->versionList().get(), tr("Change Minecraft version"), this); - vselect.setFilter(1, "Derp"); + vselect.setFilter(1, "OneSix"); if(!vselect.exec() || !vselect.selectedVersion()) return; diff --git a/gui/dialogs/DerpModEditDialog.cpp b/gui/dialogs/DerpModEditDialog.cpp deleted file mode 100644 index 216aa59d..00000000 --- a/gui/dialogs/DerpModEditDialog.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "MultiMC.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "DerpModEditDialog.h" -#include "ModEditDialogCommon.h" -#include "ui_DerpModEditDialog.h" - -#include "gui/Platform.h" -#include "gui/dialogs/CustomMessageBox.h" -#include "gui/dialogs/VersionSelectDialog.h" - -#include "gui/dialogs/ProgressDialog.h" - -#include "logic/ModList.h" -#include "logic/DerpVersion.h" -#include "logic/EnabledItemFilter.h" -#include "logic/lists/ForgeVersionList.h" -#include "logic/ForgeInstaller.h" -#include "logic/LiteLoaderInstaller.h" - -DerpModEditDialog::DerpModEditDialog(DerpInstance *inst, QWidget *parent) - : QDialog(parent), ui(new Ui::DerpModEditDialog), m_inst(inst) -{ - MultiMCPlatform::fixWM_CLASS(this); - ui->setupUi(this); - // libraries! - - m_version = m_inst->getFullVersion(); - if (m_version) - { - main_model = new EnabledItemFilter(this); - main_model->setActive(true); - main_model->setSourceModel(m_version.get()); - ui->libraryTreeView->setModel(main_model); - ui->libraryTreeView->installEventFilter(this); - updateVersionControls(); - } - else - { - disableVersionControls(); - } - // Loader mods - { - ensureFolderPathExists(m_inst->loaderModsDir()); - m_mods = m_inst->loaderModList(); - ui->loaderModTreeView->setModel(m_mods.get()); - ui->loaderModTreeView->installEventFilter(this); - m_mods->startWatching(); - auto smodel = ui->loaderModTreeView->selectionModel(); - connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), - SLOT(loaderCurrent(QModelIndex, QModelIndex))); - } - // resource packs - { - ensureFolderPathExists(m_inst->resourcePacksDir()); - m_resourcepacks = m_inst->resourcePackList(); - ui->resPackTreeView->setModel(m_resourcepacks.get()); - ui->resPackTreeView->installEventFilter(this); - m_resourcepacks->startWatching(); - } - - connect(m_inst, &DerpInstance::versionReloaded, this, &DerpModEditDialog::updateVersionControls); -} - -DerpModEditDialog::~DerpModEditDialog() -{ - m_mods->stopWatching(); - m_resourcepacks->stopWatching(); - delete ui; -} - -void DerpModEditDialog::updateVersionControls() -{ - bool customVersion = m_inst->versionIsCustom(); - ui->forgeBtn->setEnabled(true); - ui->liteloaderBtn->setEnabled(LiteLoaderInstaller().canApply(m_inst)); - ui->customEditorBtn->setEnabled(customVersion); - ui->mainClassEdit->setText(m_version->mainClass); -} - -void DerpModEditDialog::disableVersionControls() -{ - ui->forgeBtn->setEnabled(false); - ui->liteloaderBtn->setEnabled(false); - ui->customEditorBtn->setEnabled(false); - ui->mainClassEdit->setText(""); -} - -void DerpModEditDialog::on_customEditorBtn_clicked() -{ - if (QDir(m_inst->instanceRoot()).exists("custom.json")) - { - if (!MMC->openJsonEditor(m_inst->instanceRoot() + "/custom.json")) - { - QMessageBox::warning(this, tr("Error"), tr("Unable to open custom.json, check the settings")); - } - } -} - -void DerpModEditDialog::on_forgeBtn_clicked() -{ - VersionSelectDialog vselect(MMC->forgelist().get(), tr("Select Forge version"), this); - vselect.setFilter(1, m_inst->currentVersionId()); - if (vselect.exec() && vselect.selectedVersion()) - { - ForgeVersionPtr forgeVersion = - std::dynamic_pointer_cast(vselect.selectedVersion()); - if (!forgeVersion) - return; - auto entry = MMC->metacache()->resolveEntry("minecraftforge", forgeVersion->filename); - if (entry->stale) - { - NetJob *fjob = new NetJob("Forge download"); - fjob->addNetAction(CacheDownload::make(forgeVersion->installer_url, entry)); - ProgressDialog dlg(this); - dlg.exec(fjob); - if (dlg.result() == QDialog::Accepted) - { - // install - QString forgePath = entry->getFullPath(); - ForgeInstaller forge(forgePath, forgeVersion->universal_url); - if (!forge.add(m_inst)) - { - QLOG_ERROR() << "Failure installing forge"; - } - } - else - { - // failed to download forge :/ - } - } - else - { - // install - QString forgePath = entry->getFullPath(); - ForgeInstaller forge(forgePath, forgeVersion->universal_url); - if (!forge.add(m_inst)) - { - QLOG_ERROR() << "Failure installing forge"; - } - } - } - m_inst->reloadFullVersion(this); -} - -void DerpModEditDialog::on_liteloaderBtn_clicked() -{ - LiteLoaderInstaller liteloader; - if (!liteloader.canApply(m_inst)) - { - QMessageBox::critical( - this, tr("LiteLoader"), - tr("There is no information available on how to install LiteLoader " - "into this version of Minecraft")); - return; - } - if (!liteloader.add(m_inst)) - { - QMessageBox::critical( - this, tr("LiteLoader"), - tr("For reasons unknown, the LiteLoader installation failed. Check your MultiMC log files for details.")); - } - else - { - m_inst->reloadFullVersion(this); - } -} - -bool DerpModEditDialog::loaderListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Delete: - on_rmModBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addModBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->loaderModTreeView, keyEvent); -} - -bool DerpModEditDialog::resourcePackListFilter(QKeyEvent *keyEvent) -{ - switch (keyEvent->key()) - { - case Qt::Key_Delete: - on_rmResPackBtn_clicked(); - return true; - case Qt::Key_Plus: - on_addResPackBtn_clicked(); - return true; - default: - break; - } - return QDialog::eventFilter(ui->resPackTreeView, keyEvent); -} - -bool DerpModEditDialog::eventFilter(QObject *obj, QEvent *ev) -{ - if (ev->type() != QEvent::KeyPress) - { - return QDialog::eventFilter(obj, ev); - } - QKeyEvent *keyEvent = static_cast(ev); - if (obj == ui->loaderModTreeView) - return loaderListFilter(keyEvent); - if (obj == ui->resPackTreeView) - return resourcePackListFilter(keyEvent); - return QDialog::eventFilter(obj, ev); -} - -void DerpModEditDialog::on_buttonBox_rejected() -{ - close(); -} - -void DerpModEditDialog::on_addModBtn_clicked() -{ - QStringList fileNames = QFileDialog::getOpenFileNames( - this, QApplication::translate("LegacyModEditDialog", "Select Loader Mods")); - for (auto filename : fileNames) - { - m_mods->stopWatching(); - m_mods->installMod(QFileInfo(filename)); - m_mods->startWatching(); - } -} -void DerpModEditDialog::on_rmModBtn_clicked() -{ - int first, last; - auto list = ui->loaderModTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_mods->stopWatching(); - m_mods->deleteMods(first, last); - m_mods->startWatching(); -} -void DerpModEditDialog::on_viewModBtn_clicked() -{ - openDirInDefaultProgram(m_inst->loaderModsDir(), true); -} - -void DerpModEditDialog::on_addResPackBtn_clicked() -{ - QStringList fileNames = QFileDialog::getOpenFileNames( - this, QApplication::translate("LegacyModEditDialog", "Select Resource Packs")); - for (auto filename : fileNames) - { - m_resourcepacks->stopWatching(); - m_resourcepacks->installMod(QFileInfo(filename)); - m_resourcepacks->startWatching(); - } -} -void DerpModEditDialog::on_rmResPackBtn_clicked() -{ - int first, last; - auto list = ui->resPackTreeView->selectionModel()->selectedRows(); - - if (!lastfirst(list, first, last)) - return; - m_resourcepacks->stopWatching(); - m_resourcepacks->deleteMods(first, last); - m_resourcepacks->startWatching(); -} -void DerpModEditDialog::on_viewResPackBtn_clicked() -{ - openDirInDefaultProgram(m_inst->resourcePacksDir(), true); -} - -void DerpModEditDialog::loaderCurrent(QModelIndex current, QModelIndex previous) -{ - if (!current.isValid()) - { - ui->frame->clear(); - return; - } - int row = current.row(); - Mod &m = m_mods->operator[](row); - ui->frame->updateWithMod(m); -} diff --git a/gui/dialogs/DerpModEditDialog.h b/gui/dialogs/DerpModEditDialog.h deleted file mode 100644 index e9e61c65..00000000 --- a/gui/dialogs/DerpModEditDialog.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once -#include - -#include - -class EnabledItemFilter; -namespace Ui -{ -class DerpModEditDialog; -} - -class DerpModEditDialog : public QDialog -{ - Q_OBJECT - -public: - explicit DerpModEditDialog(DerpInstance *inst, QWidget *parent = 0); - virtual ~DerpModEditDialog(); - -private -slots: - void on_addModBtn_clicked(); - void on_rmModBtn_clicked(); - void on_viewModBtn_clicked(); - - void on_addResPackBtn_clicked(); - void on_rmResPackBtn_clicked(); - void on_viewResPackBtn_clicked(); - // Questionable: SettingsDialog doesn't need this for some reason? - void on_buttonBox_rejected(); - void on_forgeBtn_clicked(); - void on_liteloaderBtn_clicked(); - void on_customEditorBtn_clicked(); - void updateVersionControls(); - void disableVersionControls(); - -protected: - bool eventFilter(QObject *obj, QEvent *ev); - bool loaderListFilter(QKeyEvent *ev); - bool resourcePackListFilter(QKeyEvent *ev); - -private: - Ui::DerpModEditDialog *ui; - std::shared_ptr m_version; - std::shared_ptr m_mods; - std::shared_ptr m_resourcepacks; - EnabledItemFilter *main_model; - DerpInstance *m_inst; -public -slots: - void loaderCurrent(QModelIndex current, QModelIndex previous); -}; diff --git a/gui/dialogs/DerpModEditDialog.ui b/gui/dialogs/DerpModEditDialog.ui deleted file mode 100644 index 7aaf1564..00000000 --- a/gui/dialogs/DerpModEditDialog.ui +++ /dev/null @@ -1,317 +0,0 @@ - - - DerpModEditDialog - - - - 0 - 0 - 555 - 463 - - - - Manage Mods - - - - - - true - - - - 0 - 0 - - - - 1 - - - - Version - - - - - - - - Qt::ScrollBarAlwaysOn - - - Qt::ScrollBarAlwaysOff - - - - - - - - - Main Class: - - - - - - - false - - - - - - - - - - - - - Replace any current custom version with Minecraft Forge - - - Install Forge - - - - - - - Install LiteLoader - - - - - - - QFrame::Sunken - - - Qt::Horizontal - - - - - - - false - - - Add new libraries - - - &Add - - - - - - - false - - - Remove selected libraries - - - &Remove - - - - - - - Qt::Horizontal - - - - - - - Open custom.json - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - Loader Mods - - - - - - - - - - - 0 - 0 - - - - true - - - QAbstractItemView::DropOnly - - - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - - - 0 - 0 - - - - - - - - - Resource Packs - - - - - - true - - - QAbstractItemView::DropOnly - - - - - - - - - &Add - - - - - - - &Remove - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - &View Folder - - - - - - - - - - - - - false - - - QDialogButtonBox::Close - - - - - - - - ModListView - QTreeView -
gui/widgets/ModListView.h
-
- - MCModInfoFrame - QFrame -
gui/widgets/MCModInfoFrame.h
- 1 -
-
- - -
diff --git a/gui/dialogs/OneSixModEditDialog.cpp b/gui/dialogs/OneSixModEditDialog.cpp new file mode 100644 index 00000000..625a7c91 --- /dev/null +++ b/gui/dialogs/OneSixModEditDialog.cpp @@ -0,0 +1,306 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "MultiMC.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "OneSixModEditDialog.h" +#include "ModEditDialogCommon.h" +#include "ui_OneSixModEditDialog.h" + +#include "gui/Platform.h" +#include "gui/dialogs/CustomMessageBox.h" +#include "gui/dialogs/VersionSelectDialog.h" + +#include "gui/dialogs/ProgressDialog.h" + +#include "logic/ModList.h" +#include "logic/OneSixVersion.h" +#include "logic/EnabledItemFilter.h" +#include "logic/lists/ForgeVersionList.h" +#include "logic/ForgeInstaller.h" +#include "logic/LiteLoaderInstaller.h" + +OneSixModEditDialog::OneSixModEditDialog(OneSixInstance *inst, QWidget *parent) + : QDialog(parent), ui(new Ui::OneSixModEditDialog), m_inst(inst) +{ + MultiMCPlatform::fixWM_CLASS(this); + ui->setupUi(this); + // libraries! + + m_version = m_inst->getFullVersion(); + if (m_version) + { + main_model = new EnabledItemFilter(this); + main_model->setActive(true); + main_model->setSourceModel(m_version.get()); + ui->libraryTreeView->setModel(main_model); + ui->libraryTreeView->installEventFilter(this); + updateVersionControls(); + } + else + { + disableVersionControls(); + } + // Loader mods + { + ensureFolderPathExists(m_inst->loaderModsDir()); + m_mods = m_inst->loaderModList(); + ui->loaderModTreeView->setModel(m_mods.get()); + ui->loaderModTreeView->installEventFilter(this); + m_mods->startWatching(); + auto smodel = ui->loaderModTreeView->selectionModel(); + connect(smodel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), + SLOT(loaderCurrent(QModelIndex, QModelIndex))); + } + // resource packs + { + ensureFolderPathExists(m_inst->resourcePacksDir()); + m_resourcepacks = m_inst->resourcePackList(); + ui->resPackTreeView->setModel(m_resourcepacks.get()); + ui->resPackTreeView->installEventFilter(this); + m_resourcepacks->startWatching(); + } + + connect(m_inst, &OneSixInstance::versionReloaded, this, &OneSixModEditDialog::updateVersionControls); +} + +OneSixModEditDialog::~OneSixModEditDialog() +{ + m_mods->stopWatching(); + m_resourcepacks->stopWatching(); + delete ui; +} + +void OneSixModEditDialog::updateVersionControls() +{ + bool customVersion = m_inst->versionIsCustom(); + ui->forgeBtn->setEnabled(true); + ui->liteloaderBtn->setEnabled(LiteLoaderInstaller().canApply(m_inst)); + ui->customEditorBtn->setEnabled(customVersion); + ui->mainClassEdit->setText(m_version->mainClass); +} + +void OneSixModEditDialog::disableVersionControls() +{ + ui->forgeBtn->setEnabled(false); + ui->liteloaderBtn->setEnabled(false); + ui->customEditorBtn->setEnabled(false); + ui->mainClassEdit->setText(""); +} + +void OneSixModEditDialog::on_customEditorBtn_clicked() +{ + if (QDir(m_inst->instanceRoot()).exists("custom.json")) + { + if (!MMC->openJsonEditor(m_inst->instanceRoot() + "/custom.json")) + { + QMessageBox::warning(this, tr("Error"), tr("Unable to open custom.json, check the settings")); + } + } +} + +void OneSixModEditDialog::on_forgeBtn_clicked() +{ + VersionSelectDialog vselect(MMC->forgelist().get(), tr("Select Forge version"), this); + vselect.setFilter(1, m_inst->currentVersionId()); + if (vselect.exec() && vselect.selectedVersion()) + { + ForgeVersionPtr forgeVersion = + std::dynamic_pointer_cast(vselect.selectedVersion()); + if (!forgeVersion) + return; + auto entry = MMC->metacache()->resolveEntry("minecraftforge", forgeVersion->filename); + if (entry->stale) + { + NetJob *fjob = new NetJob("Forge download"); + fjob->addNetAction(CacheDownload::make(forgeVersion->installer_url, entry)); + ProgressDialog dlg(this); + dlg.exec(fjob); + if (dlg.result() == QDialog::Accepted) + { + // install + QString forgePath = entry->getFullPath(); + ForgeInstaller forge(forgePath, forgeVersion->universal_url); + if (!forge.add(m_inst)) + { + QLOG_ERROR() << "Failure installing forge"; + } + } + else + { + // failed to download forge :/ + } + } + else + { + // install + QString forgePath = entry->getFullPath(); + ForgeInstaller forge(forgePath, forgeVersion->universal_url); + if (!forge.add(m_inst)) + { + QLOG_ERROR() << "Failure installing forge"; + } + } + } + m_inst->reloadFullVersion(this); +} + +void OneSixModEditDialog::on_liteloaderBtn_clicked() +{ + LiteLoaderInstaller liteloader; + if (!liteloader.canApply(m_inst)) + { + QMessageBox::critical( + this, tr("LiteLoader"), + tr("There is no information available on how to install LiteLoader " + "into this version of Minecraft")); + return; + } + if (!liteloader.add(m_inst)) + { + QMessageBox::critical( + this, tr("LiteLoader"), + tr("For reasons unknown, the LiteLoader installation failed. Check your MultiMC log files for details.")); + } + else + { + m_inst->reloadFullVersion(this); + } +} + +bool OneSixModEditDialog::loaderListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Delete: + on_rmModBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addModBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->loaderModTreeView, keyEvent); +} + +bool OneSixModEditDialog::resourcePackListFilter(QKeyEvent *keyEvent) +{ + switch (keyEvent->key()) + { + case Qt::Key_Delete: + on_rmResPackBtn_clicked(); + return true; + case Qt::Key_Plus: + on_addResPackBtn_clicked(); + return true; + default: + break; + } + return QDialog::eventFilter(ui->resPackTreeView, keyEvent); +} + +bool OneSixModEditDialog::eventFilter(QObject *obj, QEvent *ev) +{ + if (ev->type() != QEvent::KeyPress) + { + return QDialog::eventFilter(obj, ev); + } + QKeyEvent *keyEvent = static_cast(ev); + if (obj == ui->loaderModTreeView) + return loaderListFilter(keyEvent); + if (obj == ui->resPackTreeView) + return resourcePackListFilter(keyEvent); + return QDialog::eventFilter(obj, ev); +} + +void OneSixModEditDialog::on_buttonBox_rejected() +{ + close(); +} + +void OneSixModEditDialog::on_addModBtn_clicked() +{ + QStringList fileNames = QFileDialog::getOpenFileNames( + this, QApplication::translate("LegacyModEditDialog", "Select Loader Mods")); + for (auto filename : fileNames) + { + m_mods->stopWatching(); + m_mods->installMod(QFileInfo(filename)); + m_mods->startWatching(); + } +} +void OneSixModEditDialog::on_rmModBtn_clicked() +{ + int first, last; + auto list = ui->loaderModTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_mods->stopWatching(); + m_mods->deleteMods(first, last); + m_mods->startWatching(); +} +void OneSixModEditDialog::on_viewModBtn_clicked() +{ + openDirInDefaultProgram(m_inst->loaderModsDir(), true); +} + +void OneSixModEditDialog::on_addResPackBtn_clicked() +{ + QStringList fileNames = QFileDialog::getOpenFileNames( + this, QApplication::translate("LegacyModEditDialog", "Select Resource Packs")); + for (auto filename : fileNames) + { + m_resourcepacks->stopWatching(); + m_resourcepacks->installMod(QFileInfo(filename)); + m_resourcepacks->startWatching(); + } +} +void OneSixModEditDialog::on_rmResPackBtn_clicked() +{ + int first, last; + auto list = ui->resPackTreeView->selectionModel()->selectedRows(); + + if (!lastfirst(list, first, last)) + return; + m_resourcepacks->stopWatching(); + m_resourcepacks->deleteMods(first, last); + m_resourcepacks->startWatching(); +} +void OneSixModEditDialog::on_viewResPackBtn_clicked() +{ + openDirInDefaultProgram(m_inst->resourcePacksDir(), true); +} + +void OneSixModEditDialog::loaderCurrent(QModelIndex current, QModelIndex previous) +{ + if (!current.isValid()) + { + ui->frame->clear(); + return; + } + int row = current.row(); + Mod &m = m_mods->operator[](row); + ui->frame->updateWithMod(m); +} diff --git a/gui/dialogs/OneSixModEditDialog.h b/gui/dialogs/OneSixModEditDialog.h new file mode 100644 index 00000000..161604c9 --- /dev/null +++ b/gui/dialogs/OneSixModEditDialog.h @@ -0,0 +1,67 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include + +#include + +class EnabledItemFilter; +namespace Ui +{ +class OneSixModEditDialog; +} + +class OneSixModEditDialog : public QDialog +{ + Q_OBJECT + +public: + explicit OneSixModEditDialog(OneSixInstance *inst, QWidget *parent = 0); + virtual ~OneSixModEditDialog(); + +private +slots: + void on_addModBtn_clicked(); + void on_rmModBtn_clicked(); + void on_viewModBtn_clicked(); + + void on_addResPackBtn_clicked(); + void on_rmResPackBtn_clicked(); + void on_viewResPackBtn_clicked(); + // Questionable: SettingsDialog doesn't need this for some reason? + void on_buttonBox_rejected(); + void on_forgeBtn_clicked(); + void on_liteloaderBtn_clicked(); + void on_customEditorBtn_clicked(); + void updateVersionControls(); + void disableVersionControls(); + +protected: + bool eventFilter(QObject *obj, QEvent *ev); + bool loaderListFilter(QKeyEvent *ev); + bool resourcePackListFilter(QKeyEvent *ev); + +private: + Ui::OneSixModEditDialog *ui; + std::shared_ptr m_version; + std::shared_ptr m_mods; + std::shared_ptr m_resourcepacks; + EnabledItemFilter *main_model; + OneSixInstance *m_inst; +public +slots: + void loaderCurrent(QModelIndex current, QModelIndex previous); +}; diff --git a/gui/dialogs/OneSixModEditDialog.ui b/gui/dialogs/OneSixModEditDialog.ui new file mode 100644 index 00000000..d57d0f85 --- /dev/null +++ b/gui/dialogs/OneSixModEditDialog.ui @@ -0,0 +1,317 @@ + + + OneSixModEditDialog + + + + 0 + 0 + 555 + 463 + + + + Manage Mods + + + + + + true + + + + 0 + 0 + + + + 1 + + + + Version + + + + + + + + Qt::ScrollBarAlwaysOn + + + Qt::ScrollBarAlwaysOff + + + + + + + + + Main Class: + + + + + + + false + + + + + + + + + + + + + Replace any current custom version with Minecraft Forge + + + Install Forge + + + + + + + Install LiteLoader + + + + + + + QFrame::Sunken + + + Qt::Horizontal + + + + + + + false + + + Add new libraries + + + &Add + + + + + + + false + + + Remove selected libraries + + + &Remove + + + + + + + Qt::Horizontal + + + + + + + Open custom.json + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + Loader Mods + + + + + + + + + + + 0 + 0 + + + + true + + + QAbstractItemView::DropOnly + + + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + &View Folder + + + + + + + + + + + + 0 + 0 + + + + + + + + + Resource Packs + + + + + + true + + + QAbstractItemView::DropOnly + + + + + + + + + &Add + + + + + + + &Remove + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + &View Folder + + + + + + + + + + + + + false + + + QDialogButtonBox::Close + + + + + + + + ModListView + QTreeView +
gui/widgets/ModListView.h
+
+ + MCModInfoFrame + QFrame +
gui/widgets/MCModInfoFrame.h
+ 1 +
+
+ + +
diff --git a/logic/BaseInstaller.cpp b/logic/BaseInstaller.cpp index 74a8e909..92aa0c92 100644 --- a/logic/BaseInstaller.cpp +++ b/logic/BaseInstaller.cpp @@ -17,9 +17,9 @@ #include -#include "DerpVersion.h" -#include "DerpLibrary.h" -#include "DerpInstance.h" +#include "OneSixVersion.h" +#include "OneSixLibrary.h" +#include "OneSixInstance.h" #include "cmdutils.h" @@ -28,12 +28,12 @@ BaseInstaller::BaseInstaller() } -bool BaseInstaller::isApplied(DerpInstance *on) +bool BaseInstaller::isApplied(OneSixInstance *on) { return QFile::exists(filename(on->instanceRoot())); } -bool BaseInstaller::add(DerpInstance *to) +bool BaseInstaller::add(OneSixInstance *to) { if (!patchesDir(to->instanceRoot()).exists()) { @@ -51,7 +51,7 @@ bool BaseInstaller::add(DerpInstance *to) return true; } -bool BaseInstaller::remove(DerpInstance *from) +bool BaseInstaller::remove(OneSixInstance *from) { return QFile::remove(filename(from->instanceRoot())); } diff --git a/logic/BaseInstaller.h b/logic/BaseInstaller.h index 08f78bfc..df7eab89 100644 --- a/logic/BaseInstaller.h +++ b/logic/BaseInstaller.h @@ -17,7 +17,7 @@ #include -class DerpInstance; +class OneSixInstance; class QDir; class QString; @@ -26,11 +26,11 @@ class BaseInstaller public: BaseInstaller(); - virtual bool canApply(DerpInstance *instance) const { return true; } - bool isApplied(DerpInstance *on); + virtual bool canApply(OneSixInstance *instance) const { return true; } + bool isApplied(OneSixInstance *on); - virtual bool add(DerpInstance *to); - virtual bool remove(DerpInstance *from); + virtual bool add(OneSixInstance *to); + virtual bool remove(OneSixInstance *from); protected: virtual QString id() const = 0; diff --git a/logic/BaseInstance.h b/logic/BaseInstance.h index 79640c84..a861e9b2 100644 --- a/logic/BaseInstance.h +++ b/logic/BaseInstance.h @@ -27,7 +27,7 @@ class QDialog; class Task; class MinecraftProcess; -class DerpUpdate; +class OneSixUpdate; class InstanceList; class BaseInstancePrivate; diff --git a/logic/DerpFTBInstance.cpp b/logic/DerpFTBInstance.cpp deleted file mode 100644 index 9b687461..00000000 --- a/logic/DerpFTBInstance.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "DerpFTBInstance.h" - -#include "DerpVersion.h" -#include "DerpLibrary.h" -#include "tasks/SequentialTask.h" -#include "ForgeInstaller.h" -#include "lists/ForgeVersionList.h" -#include "MultiMC.h" - -class DerpFTBInstanceForge : public Task -{ - Q_OBJECT -public: - explicit DerpFTBInstanceForge(const QString &version, DerpFTBInstance *inst, QObject *parent = 0) : - Task(parent), instance(inst), version("Forge " + version) - { - } - - void executeTask() - { - for (int i = 0; i < MMC->forgelist()->count(); ++i) - { - if (MMC->forgelist()->at(i)->name() == version) - { - forgeVersion = std::dynamic_pointer_cast(MMC->forgelist()->at(i)); - break; - } - } - if (!forgeVersion) - { - emitFailed(QString("Couldn't find forge version ") + version ); - return; - } - entry = MMC->metacache()->resolveEntry("minecraftforge", forgeVersion->filename); - if (entry->stale) - { - setStatus(tr("Downloading Forge...")); - fjob = new NetJob("Forge download"); - fjob->addNetAction(CacheDownload::make(forgeVersion->installer_url, entry)); - connect(fjob, &NetJob::failed, [this](){emitFailed(m_failReason);}); - connect(fjob, &NetJob::succeeded, this, &DerpFTBInstanceForge::installForge); - connect(fjob, &NetJob::progress, [this](qint64 c, qint64 total){ setProgress(100 * c / total); }); - fjob->start(); - } - else - { - installForge(); - } - } - -private -slots: - void installForge() - { - setStatus(tr("Installing Forge...")); - QString forgePath = entry->getFullPath(); - ForgeInstaller forge(forgePath, forgeVersion->universal_url); - if (!instance->reloadFullVersion()) - { - emitFailed(tr("Couldn't load the version config")); - return; - } - auto version = instance->getFullVersion(); - if (!forge.add(instance)) - { - emitFailed(tr("Couldn't install Forge")); - return; - } - emitSucceeded(); - } - -private: - DerpFTBInstance *instance; - QString version; - ForgeVersionPtr forgeVersion; - MetaEntryPtr entry; - NetJob *fjob; -}; - -DerpFTBInstance::DerpFTBInstance(const QString &rootDir, SettingsObject *settings, QObject *parent) : - DerpInstance(rootDir, settings, parent) -{ - QFile f(QDir(minecraftRoot()).absoluteFilePath("pack.json")); - if (f.open(QFile::ReadOnly)) - { - QString data = QString::fromUtf8(f.readAll()); - QRegularExpressionMatch match = QRegularExpression("net.minecraftforge:minecraftforge:[\\.\\d]*").match(data); - m_forge.reset(new DerpLibrary(match.captured())); - m_forge->finalize(); - } -} - -QString DerpFTBInstance::id() const -{ - return "FTB/" + BaseInstance::id(); -} - -QString DerpFTBInstance::getStatusbarDescription() -{ - return "Derp FTB: " + intendedVersionId(); -} -bool DerpFTBInstance::menuActionEnabled(QString action_name) const -{ - return false; -} - -std::shared_ptr DerpFTBInstance::doUpdate(bool only_prepare) -{ - std::shared_ptr task; - task.reset(new SequentialTask(this)); - if (!MMC->forgelist()->isLoaded()) - { - task->addTask(std::shared_ptr(MMC->forgelist()->getLoadTask())); - } - task->addTask(DerpInstance::doUpdate(only_prepare)); - task->addTask(std::shared_ptr(new DerpFTBInstanceForge(m_forge->version(), this, this))); - //FIXME: yes. this may appear dumb. but the previous step can change the list, so we do it all again. - //TODO: Add a graph task. Construct graphs of tasks so we may capture the logic properly. - task->addTask(DerpInstance::doUpdate(only_prepare)); - return task; -} - -#include "DerpFTBInstance.moc" diff --git a/logic/DerpFTBInstance.h b/logic/DerpFTBInstance.h deleted file mode 100644 index c16998bf..00000000 --- a/logic/DerpFTBInstance.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "DerpInstance.h" - -class DerpLibrary; - -class DerpFTBInstance : public DerpInstance -{ - Q_OBJECT -public: - explicit DerpFTBInstance(const QString &rootDir, SettingsObject *settings, - QObject *parent = 0); - virtual QString getStatusbarDescription(); - virtual bool menuActionEnabled(QString action_name) const; - - virtual std::shared_ptr doUpdate(bool only_prepare) override; - - virtual QString id() const; - -private: - std::shared_ptr m_forge; -}; diff --git a/logic/DerpInstance.cpp b/logic/DerpInstance.cpp deleted file mode 100644 index e6b92b1f..00000000 --- a/logic/DerpInstance.cpp +++ /dev/null @@ -1,388 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "DerpInstance.h" - -#include - -#include "DerpInstance_p.h" -#include "DerpUpdate.h" -#include "DerpVersion.h" -#include "pathutils.h" -#include "logger/QsLog.h" -#include "assets/AssetsUtils.h" -#include "MultiMC.h" -#include "icons/IconList.h" -#include "MinecraftProcess.h" -#include "gui/dialogs/DerpModEditDialog.h" - -DerpInstance::DerpInstance(const QString &rootDir, SettingsObject *settings, QObject *parent) - : BaseInstance(new DerpInstancePrivate(), rootDir, settings, parent) -{ - I_D(DerpInstance); - d->m_settings->registerSetting("IntendedVersion", ""); - d->m_settings->registerSetting("ShouldUpdate", false); - d->version.reset(new DerpVersion(this, this)); - if (QDir(instanceRoot()).exists("version.json")) - { - reloadFullVersion(); - } - else - { - clearFullVersion(); - } -} - -std::shared_ptr DerpInstance::doUpdate(bool only_prepare) -{ - return std::shared_ptr(new DerpUpdate(this, only_prepare)); -} - -QString replaceTokensIn(QString text, QMap with) -{ - QString result; - QRegExp token_regexp("\\$\\{(.+)\\}"); - token_regexp.setMinimal(true); - QStringList list; - int tail = 0; - int head = 0; - while ((head = token_regexp.indexIn(text, head)) != -1) - { - result.append(text.mid(tail, head - tail)); - QString key = token_regexp.cap(1); - auto iter = with.find(key); - if (iter != with.end()) - { - result.append(*iter); - } - head += token_regexp.matchedLength(); - tail = head; - } - result.append(text.mid(tail)); - return result; -} - -QDir DerpInstance::reconstructAssets(std::shared_ptr version) -{ - QDir assetsDir = QDir("assets/"); - QDir indexDir = QDir(PathCombine(assetsDir.path(), "indexes")); - QDir objectDir = QDir(PathCombine(assetsDir.path(), "objects")); - QDir virtualDir = QDir(PathCombine(assetsDir.path(), "virtual")); - - QString indexPath = PathCombine(indexDir.path(), version->assets + ".json"); - QFile indexFile(indexPath); - QDir virtualRoot(PathCombine(virtualDir.path(), version->assets)); - - if (!indexFile.exists()) - { - QLOG_ERROR() << "No assets index file" << indexPath << "; can't reconstruct assets"; - return virtualRoot; - } - - QLOG_DEBUG() << "reconstructAssets" << assetsDir.path() << indexDir.path() - << objectDir.path() << virtualDir.path() << virtualRoot.path(); - - AssetsIndex index; - bool loadAssetsIndex = AssetsUtils::loadAssetsIndexJson(indexPath, &index); - - if (loadAssetsIndex && index.isVirtual) - { - QLOG_INFO() << "Reconstructing virtual assets folder at" << virtualRoot.path(); - - for (QString map : index.objects.keys()) - { - AssetObject asset_object = index.objects.value(map); - QString target_path = PathCombine(virtualRoot.path(), map); - QFile target(target_path); - - QString tlk = asset_object.hash.left(2); - - QString original_path = - PathCombine(PathCombine(objectDir.path(), tlk), asset_object.hash); - QFile original(original_path); - if(!original.exists()) - continue; - if (!target.exists()) - { - QFileInfo info(target_path); - QDir target_dir = info.dir(); - // QLOG_DEBUG() << target_dir; - if (!target_dir.exists()) - QDir("").mkpath(target_dir.path()); - - bool couldCopy = original.copy(target_path); - QLOG_DEBUG() << " Copying" << original_path << "to" << target_path - << QString::number(couldCopy); // << original.errorString(); - } - } - - // TODO: Write last used time to virtualRoot/.lastused - } - - return virtualRoot; -} - -QStringList DerpInstance::processMinecraftArgs(MojangAccountPtr account) -{ - I_D(DerpInstance); - auto version = d->version; - QString args_pattern = version->minecraftArguments; - - QMap token_mapping; - // yggdrasil! - token_mapping["auth_username"] = account->username(); - token_mapping["auth_session"] = account->sessionId(); - token_mapping["auth_access_token"] = account->accessToken(); - token_mapping["auth_player_name"] = account->currentProfile()->name; - token_mapping["auth_uuid"] = account->currentProfile()->id; - - // this is for offline?: - /* - map["auth_player_name"] = "Player"; - map["auth_player_name"] = "00000000-0000-0000-0000-000000000000"; - */ - - // these do nothing and are stupid. - token_mapping["profile_name"] = name(); - token_mapping["version_name"] = version->id; - - QString absRootDir = QDir(minecraftRoot()).absolutePath(); - token_mapping["game_directory"] = absRootDir; - QString absAssetsDir = QDir("assets/").absolutePath(); - token_mapping["game_assets"] = reconstructAssets(d->version).absolutePath(); - - auto user = account->user(); - QJsonObject userAttrs; - for (auto key : user.properties.keys()) - { - auto array = QJsonArray::fromStringList(user.properties.values(key)); - userAttrs.insert(key, array); - } - QJsonDocument value(userAttrs); - - token_mapping["user_properties"] = value.toJson(QJsonDocument::Compact); - token_mapping["user_type"] = account->currentProfile()->legacy ? "legacy" : "mojang"; - // 1.7.3+ assets tokens - token_mapping["assets_root"] = absAssetsDir; - token_mapping["assets_index_name"] = version->assets; - - QStringList parts = args_pattern.split(' ', QString::SkipEmptyParts); - for (int i = 0; i < parts.length(); i++) - { - parts[i] = replaceTokensIn(parts[i], token_mapping); - } - return parts; -} - -MinecraftProcess *DerpInstance::prepareForLaunch(MojangAccountPtr account) -{ - I_D(DerpInstance); - - QIcon icon = MMC->icons()->getIcon(iconKey()); - auto pixmap = icon.pixmap(128, 128); - pixmap.save(PathCombine(minecraftRoot(), "icon.png"), "PNG"); - - auto version = d->version; - if (!version) - return nullptr; - QString launchScript; - { - auto libs = version->getActiveNormalLibs(); - for (auto lib : libs) - { - QFileInfo fi(QString("libraries/") + lib->storagePath()); - launchScript += "cp " + fi.absoluteFilePath() + "\n"; - } - QString targetstr = "versions/" + version->id + "/" + version->id + ".jar"; - QFileInfo fi(targetstr); - launchScript += "cp " + fi.absoluteFilePath() + "\n"; - } - launchScript += "mainClass " + version->mainClass + "\n"; - - for (auto param : processMinecraftArgs(account)) - { - launchScript += "param " + param + "\n"; - } - - // Set the width and height for 1.6 instances - bool maximize = settings().get("LaunchMaximized").toBool(); - if (maximize) - { - // this is probably a BAD idea - // launchScript += "param --fullscreen\n"; - } - else - { - launchScript += - "param --width\nparam " + settings().get("MinecraftWinWidth").toString() + "\n"; - launchScript += - "param --height\nparam " + settings().get("MinecraftWinHeight").toString() + "\n"; - } - QDir natives_dir(PathCombine(instanceRoot(), "natives/")); - launchScript += "windowTitle " + windowTitle() + "\n"; - for(auto native: version->getActiveNativeLibs()) - { - QFileInfo finfo(PathCombine("libraries", native->storagePath())); - launchScript += "ext " + finfo.absoluteFilePath() + "\n"; - } - launchScript += "natives " + natives_dir.absolutePath() + "\n"; - launchScript += "launch onesix\n"; - - // create the process and set its parameters - MinecraftProcess *proc = new MinecraftProcess(this); - proc->setWorkdir(minecraftRoot()); - proc->setLaunchScript(launchScript); - // proc->setNativeFolder(natives_dir.absolutePath()); - return proc; -} - -void DerpInstance::cleanupAfterRun() -{ - QString target_dir = PathCombine(instanceRoot(), "natives/"); - QDir dir(target_dir); - dir.removeRecursively(); -} - -std::shared_ptr DerpInstance::loaderModList() -{ - I_D(DerpInstance); - if (!d->loader_mod_list) - { - d->loader_mod_list.reset(new ModList(loaderModsDir())); - } - d->loader_mod_list->update(); - return d->loader_mod_list; -} - -std::shared_ptr DerpInstance::resourcePackList() -{ - I_D(DerpInstance); - if (!d->resource_pack_list) - { - d->resource_pack_list.reset(new ModList(resourcePacksDir())); - } - d->resource_pack_list->update(); - return d->resource_pack_list; -} - -QDialog *DerpInstance::createModEditDialog(QWidget *parent) -{ - return new DerpModEditDialog(this, parent); -} - -bool DerpInstance::setIntendedVersionId(QString version) -{ - settings().set("IntendedVersion", version); - setShouldUpdate(true); - QFile::remove(PathCombine(instanceRoot(), "version.json")); - clearFullVersion(); - return true; -} - -QString DerpInstance::intendedVersionId() const -{ - return settings().get("IntendedVersion").toString(); -} - -void DerpInstance::setShouldUpdate(bool val) -{ - settings().set("ShouldUpdate", val); -} - -bool DerpInstance::shouldUpdate() const -{ - QVariant var = settings().get("ShouldUpdate"); - if (!var.isValid() || var.toBool() == false) - { - return intendedVersionId() != currentVersionId(); - } - return true; -} - -bool DerpInstance::versionIsCustom() -{ - QDir patches(PathCombine(instanceRoot(), "patches/")); - return QFile::exists(PathCombine(instanceRoot(), "custom.json")) - || (patches.exists() && patches.count() >= 0); -} - -QString DerpInstance::currentVersionId() const -{ - return intendedVersionId(); -} - -bool DerpInstance::reloadFullVersion(QWidget *widgetParent) -{ - I_D(DerpInstance); - - bool ret = d->version->reload(widgetParent); - emit versionReloaded(); - return ret; -} - -void DerpInstance::clearFullVersion() -{ - I_D(DerpInstance); - d->version->clear(); - emit versionReloaded(); -} - -std::shared_ptr DerpInstance::getFullVersion() -{ - I_D(DerpInstance); - return d->version; -} - -QString DerpInstance::defaultBaseJar() const -{ - return "versions/" + intendedVersionId() + "/" + intendedVersionId() + ".jar"; -} - -QString DerpInstance::defaultCustomBaseJar() const -{ - return PathCombine(instanceRoot(), "custom.jar"); -} - -bool DerpInstance::menuActionEnabled(QString action_name) const -{ - if (action_name == "actionChangeInstLWJGLVersion") - return false; - return true; -} - -QString DerpInstance::getStatusbarDescription() -{ - QString descr = "Derp : " + intendedVersionId(); - if (versionIsCustom()) - { - descr + " (custom)"; - } - return descr; -} - -QString DerpInstance::loaderModsDir() const -{ - return PathCombine(minecraftRoot(), "mods"); -} - -QString DerpInstance::resourcePacksDir() const -{ - return PathCombine(minecraftRoot(), "resourcepacks"); -} - -QString DerpInstance::instanceConfigFolder() const -{ - return PathCombine(minecraftRoot(), "config"); -} diff --git a/logic/DerpInstance.h b/logic/DerpInstance.h deleted file mode 100644 index 46f953c0..00000000 --- a/logic/DerpInstance.h +++ /dev/null @@ -1,75 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "BaseInstance.h" - -#include "DerpVersion.h" -#include "ModList.h" - -class DerpInstance : public BaseInstance -{ - Q_OBJECT -public: - explicit DerpInstance(const QString &rootDir, SettingsObject *settings, - QObject *parent = 0); - - ////// Mod Lists ////// - std::shared_ptr loaderModList(); - std::shared_ptr resourcePackList(); - - ////// Directories ////// - QString resourcePacksDir() const; - QString loaderModsDir() const; - virtual QString instanceConfigFolder() const override; - - virtual std::shared_ptr doUpdate(bool only_prepare) override; - virtual MinecraftProcess *prepareForLaunch(MojangAccountPtr account) override; - - virtual void cleanupAfterRun() override; - - virtual QString intendedVersionId() const override; - virtual bool setIntendedVersionId(QString version) override; - - virtual QString currentVersionId() const override; - - virtual bool shouldUpdate() const override; - virtual void setShouldUpdate(bool val) override; - - virtual QDialog *createModEditDialog(QWidget *parent) override; - - /// reload the full version json files. return true on success! - bool reloadFullVersion(QWidget *widgetParent = 0); - /// clears all version information in preparation for an update - void clearFullVersion(); - /// get the current full version info - std::shared_ptr getFullVersion(); - /// is the current version original, or custom? - virtual bool versionIsCustom() override; - - virtual QString defaultBaseJar() const override; - virtual QString defaultCustomBaseJar() const override; - - virtual bool menuActionEnabled(QString action_name) const override; - virtual QString getStatusbarDescription() override; - -signals: - void versionReloaded(); - -private: - QStringList processMinecraftArgs(MojangAccountPtr account); - QDir reconstructAssets(std::shared_ptr version); -}; diff --git a/logic/DerpInstance_p.h b/logic/DerpInstance_p.h deleted file mode 100644 index 41f7b62d..00000000 --- a/logic/DerpInstance_p.h +++ /dev/null @@ -1,27 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "BaseInstance_p.h" -#include "DerpVersion.h" -#include "ModList.h" - -struct DerpInstancePrivate : public BaseInstancePrivate -{ - std::shared_ptr version; - std::shared_ptr loader_mod_list; - std::shared_ptr resource_pack_list; -}; diff --git a/logic/DerpLibrary.cpp b/logic/DerpLibrary.cpp deleted file mode 100644 index ba4d516b..00000000 --- a/logic/DerpLibrary.cpp +++ /dev/null @@ -1,268 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "DerpLibrary.h" -#include "DerpRule.h" -#include "OpSys.h" -#include "logic/net/URLConstants.h" -#include -#include -#include "logger/QsLog.h" - -void DerpLibrary::finalize() -{ - QStringList parts = m_name.split(':'); - QString relative = parts[0]; - relative.replace('.', '/'); - relative += '/' + parts[1] + '/' + parts[2] + '/' + parts[1] + '-' + parts[2]; - - if (!m_is_native) - relative += ".jar"; - else - { - if (m_native_suffixes.contains(currentSystem)) - { - relative += "-" + m_native_suffixes[currentSystem] + ".jar"; - } - else - { - // really, bad. - relative += ".jar"; - } - } - - m_decentname = parts[1]; - m_decentversion = parts[2]; - m_storage_path = relative; - m_download_url = m_base_url + relative; - - if (m_rules.empty()) - { - m_is_active = true; - } - else - { - RuleAction result = Disallow; - for (auto rule : m_rules) - { - RuleAction temp = rule->apply(this); - if (temp != Defer) - result = temp; - } - m_is_active = (result == Allow); - } - if (m_is_native) - { - m_is_active = m_is_active && m_native_suffixes.contains(currentSystem); - m_decenttype = "Native"; - } - else - { - m_decenttype = "Java"; - } -} - -void DerpLibrary::setName(const QString &name) -{ - m_name = name; -} -void DerpLibrary::setBaseUrl(const QString &base_url) -{ - m_base_url = base_url; -} -void DerpLibrary::setIsNative() -{ - m_is_native = true; -} -void DerpLibrary::addNative(OpSys os, const QString &suffix) -{ - m_is_native = true; - m_native_suffixes[os] = suffix; -} -void DerpLibrary::setRules(QList> rules) -{ - m_rules = rules; -} -bool DerpLibrary::isActive() const -{ - return m_is_active; -} -bool DerpLibrary::isNative() const -{ - return m_is_native; -} -QString DerpLibrary::downloadUrl() const -{ - if (m_absolute_url.size()) - return m_absolute_url; - return m_download_url; -} -QString DerpLibrary::storagePath() const -{ - return m_storage_path; -} - -void DerpLibrary::setAbsoluteUrl(const QString &absolute_url) -{ - m_absolute_url = absolute_url; -} - -QString DerpLibrary::absoluteUrl() const -{ - return m_absolute_url; -} - -void DerpLibrary::setHint(const QString &hint) -{ - m_hint = hint; -} - -QString DerpLibrary::hint() const -{ - return m_hint; -} - -bool DerpLibrary::filesExist() -{ - QString storage = storagePath(); - if (storage.contains("${arch}")) - { - QString cooked_storage = storage; - cooked_storage.replace("${arch}", "32"); - QFileInfo info32(PathCombine("libraries", cooked_storage)); - if (!info32.exists()) - { - return false; - } - cooked_storage = storage; - cooked_storage.replace("${arch}", "64"); - QFileInfo info64(PathCombine("libraries", cooked_storage)); - if (!info64.exists()) - { - return false; - } - } - else - { - QFileInfo info(PathCombine("libraries", storage)); - if (!info.exists()) - { - return false; - } - } - return true; -} - -bool DerpLibrary::extractTo(QString target_dir) -{ - QString storage = storagePath(); - if (storage.contains("${arch}")) - { - QString cooked_storage = storage; - cooked_storage.replace("${arch}", "32"); - QString origin = PathCombine("libraries", cooked_storage); - QString target_dir_cooked = PathCombine(target_dir, "32"); - if(!ensureFolderPathExists(target_dir_cooked)) - { - QLOG_ERROR() << "Couldn't create folder " + target_dir_cooked; - return false; - } - if (JlCompress::extractWithExceptions(origin, target_dir_cooked, extract_excludes) - .isEmpty()) - { - QLOG_ERROR() << "Couldn't extract " + origin; - return false; - } - cooked_storage = storage; - cooked_storage.replace("${arch}", "64"); - origin = PathCombine("libraries", cooked_storage); - target_dir_cooked = PathCombine(target_dir, "64"); - if(!ensureFolderPathExists(target_dir_cooked)) - { - QLOG_ERROR() << "Couldn't create folder " + target_dir_cooked; - return false; - } - if (JlCompress::extractWithExceptions(origin, target_dir_cooked, extract_excludes) - .isEmpty()) - { - QLOG_ERROR() << "Couldn't extract " + origin; - return false; - } - } - else - { - if(!ensureFolderPathExists(target_dir)) - { - QLOG_ERROR() << "Couldn't create folder " + target_dir; - return false; - } - QString path = PathCombine("libraries", storage); - if (JlCompress::extractWithExceptions(path, target_dir, extract_excludes).isEmpty()) - { - QLOG_ERROR() << "Couldn't extract " + path; - return false; - } - } - return true; -} - -QJsonObject DerpLibrary::toJson() -{ - QJsonObject libRoot; - libRoot.insert("name", m_name); - if (m_absolute_url.size()) - libRoot.insert("MMC-absoluteUrl", m_absolute_url); - if (m_hint.size()) - libRoot.insert("MMC-hint", m_hint); - if (m_base_url != "http://" + URLConstants::AWS_DOWNLOAD_LIBRARIES && - m_base_url != "https://" + URLConstants::AWS_DOWNLOAD_LIBRARIES && - m_base_url != "https://" + URLConstants::LIBRARY_BASE) - libRoot.insert("url", m_base_url); - if (isNative() && m_native_suffixes.size()) - { - QJsonObject nativeList; - auto iter = m_native_suffixes.begin(); - while (iter != m_native_suffixes.end()) - { - nativeList.insert(OpSys_toString(iter.key()), iter.value()); - iter++; - } - libRoot.insert("natives", nativeList); - } - if (isNative() && extract_excludes.size()) - { - QJsonArray excludes; - QJsonObject extract; - for (auto exclude : extract_excludes) - { - excludes.append(exclude); - } - extract.insert("exclude", excludes); - libRoot.insert("extract", extract); - } - if (m_rules.size()) - { - QJsonArray allRules; - for (auto &rule : m_rules) - { - QJsonObject ruleObj = rule->toJson(); - allRules.append(ruleObj); - } - libRoot.insert("rules", allRules); - } - return libRoot; -} diff --git a/logic/DerpLibrary.h b/logic/DerpLibrary.h deleted file mode 100644 index d1cee843..00000000 --- a/logic/DerpLibrary.h +++ /dev/null @@ -1,132 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include -#include -#include - -#include "logic/net/URLConstants.h" -#include "OpSys.h" - -class Rule; - -class DerpLibrary -{ -private: - // basic values used internally (so far) - QString m_name; - QString m_base_url = "https://" + URLConstants::LIBRARY_BASE; - QList> m_rules; - - // custom values - /// absolute URL. takes precedence over m_download_path, if defined - QString m_absolute_url; - /// download hint - how to actually get the library - QString m_hint; - - // derived values used for real things - /// a decent name fit for display - QString m_decentname; - /// a decent version fit for display - QString m_decentversion; - /// a decent type fit for display - QString m_decenttype; - /// where to store the lib locally - QString m_storage_path; - /// where to download the lib from - QString m_download_url; - /// is this lib actually active on the current OS? - bool m_is_active = false; - /// is the library a native? - bool m_is_native = false; - /// native suffixes per OS - QMap m_native_suffixes; - -public: - QStringList extract_excludes; - -public: - /// Constructor - DerpLibrary(const QString &name) - { - m_name = name; - } - - /// Returns the raw name field - QString rawName() const - { - return m_name; - } - - QJsonObject toJson(); - - /** - * finalize the library, processing the input values into derived values and state - * - * This SHALL be called after all the values are parsed or after any further change. - */ - void finalize(); - - /// Set the library composite name - void setName(const QString &name); - /// get a decent-looking name - QString name() const - { - return m_decentname; - } - /// get a decent-looking version - QString version() const - { - return m_decentversion; - } - /// what kind of library is it? (for display) - QString type() const - { - return m_decenttype; - } - /// Set the url base for downloads - void setBaseUrl(const QString &base_url); - - /// Call this to mark the library as 'native' (it's a zip archive with DLLs) - void setIsNative(); - /// Attach a name suffix to the specified OS native - void addNative(OpSys os, const QString &suffix); - /// Set the load rules - void setRules(QList> rules); - - /// Returns true if the library should be loaded (or extracted, in case of natives) - bool isActive() const; - /// Returns true if the library is native - bool isNative() const; - /// Get the URL to download the library from - QString downloadUrl() const; - /// Get the relative path where the library should be saved - QString storagePath() const; - - /// set an absolute URL for the library. This is an MMC extension. - void setAbsoluteUrl(const QString &absolute_url); - QString absoluteUrl() const; - - /// set a hint about how to treat the library. This is an MMC extension. - void setHint(const QString &hint); - QString hint() const; - - bool extractTo(QString target_dir); - bool filesExist(); -}; diff --git a/logic/DerpRule.cpp b/logic/DerpRule.cpp deleted file mode 100644 index 5ed200e3..00000000 --- a/logic/DerpRule.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "DerpRule.h" - -QList> rulesFromJsonV4(const QJsonObject &objectWithRules) -{ - QList> rules; - auto rulesVal = objectWithRules.value("rules"); - if (!rulesVal.isArray()) - return rules; - - QJsonArray ruleList = rulesVal.toArray(); - for (auto ruleVal : ruleList) - { - std::shared_ptr rule; - if (!ruleVal.isObject()) - continue; - auto ruleObj = ruleVal.toObject(); - auto actionVal = ruleObj.value("action"); - if (!actionVal.isString()) - continue; - auto action = RuleAction_fromString(actionVal.toString()); - if (action == Defer) - continue; - - auto osVal = ruleObj.value("os"); - if (!osVal.isObject()) - { - // add a new implicit action rule - rules.append(ImplicitRule::create(action)); - continue; - } - - auto osObj = osVal.toObject(); - auto osNameVal = osObj.value("name"); - if (!osNameVal.isString()) - continue; - OpSys requiredOs = OpSys_fromString(osNameVal.toString()); - QString versionRegex = osObj.value("version").toString(); - // add a new OS rule - rules.append(OsRule::create(action, requiredOs, versionRegex)); - } - return rules; -} - -QJsonObject ImplicitRule::toJson() -{ - QJsonObject ruleObj; - ruleObj.insert("action", m_result == Allow ? QString("allow") : QString("disallow")); - return ruleObj; -} - -QJsonObject OsRule::toJson() -{ - QJsonObject ruleObj; - ruleObj.insert("action", m_result == Allow ? QString("allow") : QString("disallow")); - QJsonObject osObj; - { - osObj.insert("name", OpSys_toString(m_system)); - osObj.insert("version", m_version_regexp); - } - ruleObj.insert("os", osObj); - return ruleObj; -} - -RuleAction RuleAction_fromString(QString name) -{ - if (name == "allow") - return Allow; - if (name == "disallow") - return Disallow; - return Defer; -} diff --git a/logic/DerpRule.h b/logic/DerpRule.h deleted file mode 100644 index 0254028c..00000000 --- a/logic/DerpRule.h +++ /dev/null @@ -1,98 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#include "logic/DerpLibrary.h" - -enum RuleAction -{ - Allow, - Disallow, - Defer -}; - -RuleAction RuleAction_fromString(QString); -QList> rulesFromJsonV4(const QJsonObject &objectWithRules); - -class Rule -{ -protected: - RuleAction m_result; - virtual bool applies(DerpLibrary *parent) = 0; - -public: - Rule(RuleAction result) : m_result(result) - { - } - virtual ~Rule() {}; - virtual QJsonObject toJson() = 0; - RuleAction apply(DerpLibrary *parent) - { - if (applies(parent)) - return m_result; - else - return Defer; - } - ; -}; - -class OsRule : public Rule -{ -private: - // the OS - OpSys m_system; - // the OS version regexp - QString m_version_regexp; - -protected: - virtual bool applies(DerpLibrary *) - { - return (m_system == currentSystem); - } - OsRule(RuleAction result, OpSys system, QString version_regexp) - : Rule(result), m_system(system), m_version_regexp(version_regexp) - { - } - -public: - virtual QJsonObject toJson(); - static std::shared_ptr create(RuleAction result, OpSys system, - QString version_regexp) - { - return std::shared_ptr(new OsRule(result, system, version_regexp)); - } -}; - -class ImplicitRule : public Rule -{ -protected: - virtual bool applies(DerpLibrary *) - { - return true; - } - ImplicitRule(RuleAction result) : Rule(result) - { - } - -public: - virtual QJsonObject toJson(); - static std::shared_ptr create(RuleAction result) - { - return std::shared_ptr(new ImplicitRule(result)); - } -}; diff --git a/logic/DerpUpdate.cpp b/logic/DerpUpdate.cpp deleted file mode 100644 index 5686e4ac..00000000 --- a/logic/DerpUpdate.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "MultiMC.h" -#include "DerpUpdate.h" - -#include - -#include -#include -#include -#include - -#include "BaseInstance.h" -#include "lists/MinecraftVersionList.h" -#include "DerpVersion.h" -#include "DerpLibrary.h" -#include "DerpInstance.h" -#include "net/ForgeMirrors.h" -#include "net/URLConstants.h" -#include "assets/AssetsUtils.h" - -#include "pathutils.h" -#include - -DerpUpdate::DerpUpdate(BaseInstance *inst, bool only_prepare, QObject *parent) - : Task(parent), m_inst(inst), m_only_prepare(only_prepare) -{ -} - -void DerpUpdate::executeTask() -{ - QString intendedVersion = m_inst->intendedVersionId(); - - // Make directories - QDir mcDir(m_inst->minecraftRoot()); - if (!mcDir.exists() && !mcDir.mkpath(".")) - { - emitFailed("Failed to create bin folder."); - return; - } - - if (m_only_prepare) - { - prepareForLaunch(); - return; - } - - if (m_inst->shouldUpdate()) - { - // Get a pointer to the version object that corresponds to the instance's version. - targetVersion = std::dynamic_pointer_cast( - MMC->minecraftlist()->findVersion(intendedVersion)); - if (targetVersion == nullptr) - { - // don't do anything if it was invalid - emitFailed("The specified Minecraft version is invalid. Choose a different one."); - return; - } - versionFileStart(); - } - else - { - jarlibStart(); - } -} - -void DerpUpdate::versionFileStart() -{ - QLOG_INFO() << m_inst->name() << ": getting version file."; - setStatus(tr("Getting the version files from Mojang...")); - - QString urlstr = "http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + - targetVersion->descriptor() + "/" + targetVersion->descriptor() + ".json"; - auto job = new NetJob("Version index"); - job->addNetAction(ByteArrayDownload::make(QUrl(urlstr))); - specificVersionDownloadJob.reset(job); - connect(specificVersionDownloadJob.get(), SIGNAL(succeeded()), SLOT(versionFileFinished())); - connect(specificVersionDownloadJob.get(), SIGNAL(failed()), SLOT(versionFileFailed())); - connect(specificVersionDownloadJob.get(), SIGNAL(progress(qint64, qint64)), - SIGNAL(progress(qint64, qint64))); - specificVersionDownloadJob->start(); -} - -void DerpUpdate::versionFileFinished() -{ - NetActionPtr DlJob = specificVersionDownloadJob->first(); - DerpInstance *inst = (DerpInstance *)m_inst; - - QString version_id = targetVersion->descriptor(); - QString inst_dir = m_inst->instanceRoot(); - // save the version file in $instanceId/version.json - { - QString version1 = PathCombine(inst_dir, "/version.json"); - ensureFilePathExists(version1); - // FIXME: detect errors here, download to a temp file, swap - QSaveFile vfile1(version1); - if (!vfile1.open(QIODevice::Truncate | QIODevice::WriteOnly)) - { - emitFailed("Can't open " + version1 + " for writing."); - return; - } - auto data = std::dynamic_pointer_cast(DlJob)->m_data; - qint64 actual = 0; - if ((actual = vfile1.write(data)) != data.size()) - { - emitFailed("Failed to write into " + version1 + ". Written " + actual + " out of " + - data.size() + '.'); - return; - } - if (!vfile1.commit()) - { - emitFailed("Can't commit changes to " + version1); - return; - } - } - - // the version is downloaded safely. update is 'done' at this point - m_inst->setShouldUpdate(false); - - // delete any custom version inside the instance (it's no longer relevant, we did an update) - QString custom = PathCombine(inst_dir, "/custom.json"); - QFile finfo(custom); - if (finfo.exists()) - { - finfo.remove(); - } - inst->reloadFullVersion(); - - jarlibStart(); -} - -void DerpUpdate::versionFileFailed() -{ - emitFailed("Failed to download the version description. Try again."); -} - -void DerpUpdate::assetIndexStart() -{ - setStatus(tr("Updating assets index...")); - DerpInstance *inst = (DerpInstance *)m_inst; - std::shared_ptr version = inst->getFullVersion(); - QString assetName = version->assets; - QUrl indexUrl = "http://" + URLConstants::AWS_DOWNLOAD_INDEXES + assetName + ".json"; - QString localPath = assetName + ".json"; - auto job = new NetJob("Asset index for " + inst->name()); - - auto metacache = MMC->metacache(); - auto entry = metacache->resolveEntry("asset_indexes", localPath); - job->addNetAction(CacheDownload::make(indexUrl, entry)); - jarlibDownloadJob.reset(job); - - connect(jarlibDownloadJob.get(), SIGNAL(succeeded()), SLOT(assetIndexFinished())); - connect(jarlibDownloadJob.get(), SIGNAL(failed()), SLOT(assetIndexFailed())); - connect(jarlibDownloadJob.get(), SIGNAL(progress(qint64, qint64)), - SIGNAL(progress(qint64, qint64))); - - jarlibDownloadJob->start(); -} - -void DerpUpdate::assetIndexFinished() -{ - AssetsIndex index; - - DerpInstance *inst = (DerpInstance *)m_inst; - std::shared_ptr version = inst->getFullVersion(); - QString assetName = version->assets; - - QString asset_fname = "assets/indexes/" + assetName + ".json"; - if (!AssetsUtils::loadAssetsIndexJson(asset_fname, &index)) - { - emitFailed("Failed to read the assets index!"); - } - - QList dls; - for (auto object : index.objects.values()) - { - QString objectName = object.hash.left(2) + "/" + object.hash; - QFileInfo objectFile("assets/objects/" + objectName); - if ((!objectFile.isFile()) || (objectFile.size() != object.size)) - { - auto objectDL = MD5EtagDownload::make( - QUrl("http://" + URLConstants::RESOURCE_BASE + objectName), - objectFile.filePath()); - objectDL->m_total_progress = object.size; - dls.append(objectDL); - } - } - if (dls.size()) - { - setStatus(tr("Getting the assets files from Mojang...")); - auto job = new NetJob("Assets for " + inst->name()); - for (auto dl : dls) - job->addNetAction(dl); - jarlibDownloadJob.reset(job); - connect(jarlibDownloadJob.get(), SIGNAL(succeeded()), SLOT(assetsFinished())); - connect(jarlibDownloadJob.get(), SIGNAL(failed()), SLOT(assetsFailed())); - connect(jarlibDownloadJob.get(), SIGNAL(progress(qint64, qint64)), - SIGNAL(progress(qint64, qint64))); - jarlibDownloadJob->start(); - return; - } - assetsFinished(); -} - -void DerpUpdate::assetIndexFailed() -{ - emitFailed("Failed to download the assets index!"); -} - -void DerpUpdate::assetsFinished() -{ - prepareForLaunch(); -} - -void DerpUpdate::assetsFailed() -{ - emitFailed("Failed to download assets!"); -} - -void DerpUpdate::jarlibStart() -{ - setStatus(tr("Getting the library files from Mojang...")); - QLOG_INFO() << m_inst->name() << ": downloading libraries"; - DerpInstance *inst = (DerpInstance *)m_inst; - bool successful = inst->reloadFullVersion(); - if (!successful) - { - emitFailed("Failed to load the version description file. It might be " - "corrupted, missing or simply too new."); - return; - } - - // Build a list of URLs that will need to be downloaded. - std::shared_ptr version = inst->getFullVersion(); - // minecraft.jar for this version - { - QString version_id = version->id; - QString localPath = version_id + "/" + version_id + ".jar"; - QString urlstr = "http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + localPath; - - auto job = new NetJob("Libraries for instance " + inst->name()); - - auto metacache = MMC->metacache(); - auto entry = metacache->resolveEntry("versions", localPath); - job->addNetAction(CacheDownload::make(QUrl(urlstr), entry)); - - jarlibDownloadJob.reset(job); - } - - auto libs = version->getActiveNativeLibs(); - libs.append(version->getActiveNormalLibs()); - - auto metacache = MMC->metacache(); - QList ForgeLibs; - for (auto lib : libs) - { - if (lib->hint() == "local") - continue; - - QString raw_storage = lib->storagePath(); - QString raw_dl = lib->downloadUrl(); - - auto f = [&](QString storage, QString dl) - { - auto entry = metacache->resolveEntry("libraries", storage); - if (entry->stale) - { - if (lib->hint() == "forge-pack-xz") - { - ForgeLibs.append(ForgeXzDownload::make(storage, entry)); - } - else - { - jarlibDownloadJob->addNetAction(CacheDownload::make(dl, entry)); - } - } - }; - if (raw_storage.contains("${arch}")) - { - QString cooked_storage = raw_storage; - QString cooked_dl = raw_dl; - f(cooked_storage.replace("${arch}", "32"), cooked_dl.replace("${arch}", "32")); - cooked_storage = raw_storage; - cooked_dl = raw_dl; - f(cooked_storage.replace("${arch}", "64"), cooked_dl.replace("${arch}", "64")); - } - else - { - f(raw_storage, raw_dl); - } - } - // TODO: think about how to propagate this from the original json file... or IF AT ALL - QString forgeMirrorList = "http://files.minecraftforge.net/mirror-brand.list"; - if (!ForgeLibs.empty()) - { - jarlibDownloadJob->addNetAction( - ForgeMirrors::make(ForgeLibs, jarlibDownloadJob, forgeMirrorList)); - } - - connect(jarlibDownloadJob.get(), SIGNAL(succeeded()), SLOT(jarlibFinished())); - connect(jarlibDownloadJob.get(), SIGNAL(failed()), SLOT(jarlibFailed())); - connect(jarlibDownloadJob.get(), SIGNAL(progress(qint64, qint64)), - SIGNAL(progress(qint64, qint64))); - - jarlibDownloadJob->start(); -} - -void DerpUpdate::jarlibFinished() -{ - assetIndexStart(); -} - -void DerpUpdate::jarlibFailed() -{ - QStringList failed = jarlibDownloadJob->getFailedFiles(); - QString failed_all = failed.join("\n"); - emitFailed("Failed to download the following files:\n" + failed_all + - "\n\nPlease try again."); -} - -void DerpUpdate::prepareForLaunch() -{ - setStatus(tr("Preparing for launch...")); - QLOG_INFO() << m_inst->name() << ": preparing for launch"; - auto derp_inst = (DerpInstance *)m_inst; - - // delete any leftovers, if they are present. - derp_inst->cleanupAfterRun(); - - QString natives_dir_raw = PathCombine(derp_inst->instanceRoot(), "natives/"); - auto version = derp_inst->getFullVersion(); - if (!version) - { - emitFailed("The version information for this instance is not complete. Try re-creating " - "it or changing the version."); - return; - } - /* - for (auto lib : version->getActiveNativeLibs()) - { - if (!lib->filesExist()) - { - emitFailed("Native library is missing some files:\n" + lib->storagePath() + - "\n\nRun the instance at least once in online mode to get all the " - "required files."); - return; - } - if (!lib->extractTo(natives_dir_raw)) - { - emitFailed("Could not extract the native library:\n" + lib->storagePath() + " to " + - natives_dir_raw + - "\n\nMake sure MultiMC has appropriate permissions and there is enough " - "space on the storage device."); - return; - } - } -*/ - emitSucceeded(); -} diff --git a/logic/DerpUpdate.h b/logic/DerpUpdate.h deleted file mode 100644 index 475f6c35..00000000 --- a/logic/DerpUpdate.h +++ /dev/null @@ -1,63 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include - -#include "logic/net/NetJob.h" -#include "logic/tasks/Task.h" - -class MinecraftVersion; -class BaseInstance; - -class DerpUpdate : public Task -{ - Q_OBJECT -public: - explicit DerpUpdate(BaseInstance *inst, bool prepare_for_launch, QObject *parent = 0); - virtual void executeTask(); - -private -slots: - void versionFileStart(); - void versionFileFinished(); - void versionFileFailed(); - - void jarlibStart(); - void jarlibFinished(); - void jarlibFailed(); - - void assetIndexStart(); - void assetIndexFinished(); - void assetIndexFailed(); - - void assetsFinished(); - void assetsFailed(); - - // extract the appropriate libraries - void prepareForLaunch(); - -private: - NetJobPtr specificVersionDownloadJob; - NetJobPtr jarlibDownloadJob; - - // target version, determined during this task - std::shared_ptr targetVersion; - BaseInstance *m_inst = nullptr; - bool m_only_prepare = false; -}; diff --git a/logic/DerpVersion.cpp b/logic/DerpVersion.cpp deleted file mode 100644 index f4a8dd97..00000000 --- a/logic/DerpVersion.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "DerpVersion.h" - -#include - -#include "DerpVersionBuilder.h" - -DerpVersion::DerpVersion(DerpInstance *instance, QObject *parent) - : QAbstractListModel(parent), m_instance(instance) -{ - clear(); -} - -bool DerpVersion::reload(QWidget *widgetParent) -{ - return DerpVersionBuilder::build(this, m_instance, widgetParent); -} - -void DerpVersion::clear() -{ - id.clear(); - time.clear(); - releaseTime.clear(); - type.clear(); - assets.clear(); - processArguments.clear(); - minecraftArguments.clear(); - minimumLauncherVersion = 0xDEADBEAF; - mainClass.clear(); - libraries.clear(); -} - -void DerpVersion::dump() const -{ - qDebug().nospace() << "DerpVersion(" - << "\n\tid=" << id - << "\n\ttime=" << time - << "\n\treleaseTime=" << releaseTime - << "\n\ttype=" << type - << "\n\tassets=" << assets - << "\n\tprocessArguments=" << processArguments - << "\n\tminecraftArguments=" << minecraftArguments - << "\n\tminimumLauncherVersion=" << minimumLauncherVersion - << "\n\tmainClass=" << mainClass - << "\n\tlibraries="; - for (auto lib : libraries) - { - qDebug().nospace() << "\n\t\t" << lib.get(); - } - qDebug().nospace() << "\n)"; -} - -QList > DerpVersion::getActiveNormalLibs() -{ - QList > output; - for (auto lib : libraries) - { - if (lib->isActive() && !lib->isNative()) - { - output.append(lib); - } - } - return output; -} - -QList > DerpVersion::getActiveNativeLibs() -{ - QList > output; - for (auto lib : libraries) - { - if (lib->isActive() && lib->isNative()) - { - output.append(lib); - } - } - return output; -} - -std::shared_ptr DerpVersion::fromJson(const QJsonObject &obj) -{ - std::shared_ptr version(new DerpVersion(0)); - if (DerpVersionBuilder::read(version.get(), obj)) - { - return version; - } - return 0; -} - -QVariant DerpVersion::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return QVariant(); - - int row = index.row(); - int column = index.column(); - - if (row < 0 || row >= libraries.size()) - return QVariant(); - - if (role == Qt::DisplayRole) - { - switch (column) - { - case 0: - return libraries[row]->name(); - case 1: - return libraries[row]->type(); - case 2: - return libraries[row]->version(); - default: - return QVariant(); - } - } - return QVariant(); -} - -Qt::ItemFlags DerpVersion::flags(const QModelIndex &index) const -{ - if (!index.isValid()) - return Qt::NoItemFlags; - int row = index.row(); - if (libraries[row]->isActive()) - { - return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - } - else - { - return Qt::ItemNeverHasChildren; - } - // return QAbstractListModel::flags(index); -} - -QVariant DerpVersion::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (role != Qt::DisplayRole || orientation != Qt::Horizontal) - return QVariant(); - switch (section) - { - case 0: - return QString("Name"); - case 1: - return QString("Type"); - case 2: - return QString("Version"); - default: - return QString(); - } -} - -int DerpVersion::rowCount(const QModelIndex &parent) const -{ - return libraries.size(); -} - -int DerpVersion::columnCount(const QModelIndex &parent) const -{ - return 3; -} - -QDebug operator<<(QDebug &dbg, const DerpVersion *version) -{ - version->dump(); - return dbg.maybeSpace(); -} -QDebug operator<<(QDebug &dbg, const DerpLibrary *library) -{ - dbg.nospace() << "DerpLibrary(" - << "\n\t\t\trawName=" << library->rawName() - << "\n\t\t\tname=" << library->name() - << "\n\t\t\tversion=" << library->version() - << "\n\t\t\ttype=" << library->type() - << "\n\t\t\tisActive=" << library->isActive() - << "\n\t\t\tisNative=" << library->isNative() - << "\n\t\t\tdownloadUrl=" << library->downloadUrl() - << "\n\t\t\tstoragePath=" << library->storagePath() - << "\n\t\t\tabsolutePath=" << library->absoluteUrl() - << "\n\t\t\thint=" << library->hint(); - dbg.nospace() << "\n\t\t)"; - return dbg.maybeSpace(); -} diff --git a/logic/DerpVersion.h b/logic/DerpVersion.h deleted file mode 100644 index 4481d146..00000000 --- a/logic/DerpVersion.h +++ /dev/null @@ -1,115 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#include -#include -#include - -#include "DerpLibrary.h" - -class DerpInstance; - -class DerpVersion : public QAbstractListModel -{ - Q_OBJECT -public: - explicit DerpVersion(DerpInstance *instance, QObject *parent = 0); - - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; - virtual QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; - virtual int columnCount(const QModelIndex &parent) const; - virtual Qt::ItemFlags flags(const QModelIndex &index) const; - - bool reload(QWidget *widgetParent); - void clear(); - - void dump() const; - -public: - QList> getActiveNormalLibs(); - QList> getActiveNativeLibs(); - - static std::shared_ptr fromJson(const QJsonObject &obj); - - // data members -public: - /// the ID - determines which jar to use! ACTUALLY IMPORTANT! - QString id; - /// Last updated time - as a string - QString time; - /// Release time - as a string - QString releaseTime; - /// Release type - "release" or "snapshot" - QString type; - /// Assets type - "legacy" or a version ID - QString assets; - /** - * DEPRECATED: Old versions of the new vanilla launcher used this - * ex: "username_session_version" - */ - QString processArguments; - /** - * arguments that should be used for launching minecraft - * - * ex: "--username ${auth_player_name} --session ${auth_session} - * --version ${version_name} --gameDir ${game_directory} --assetsDir ${game_assets}" - */ - QString minecraftArguments; - /** - * the minimum launcher version required by this version ... current is 4 (at point of - * writing) - */ - int minimumLauncherVersion = 0xDEADBEEF; - /** - * The main class to load first - */ - QString mainClass; - - /// the list of libs - both active and inactive, native and java - QList> libraries; - - /* - FIXME: add support for those rules here? Looks like a pile of quick hacks to me though. - - "rules": [ - { - "action": "allow" - }, - { - "action": "disallow", - "os": { - "name": "osx", - "version": "^10\\.5\\.\\d$" - } - } - ], - "incompatibilityReason": "There is a bug in LWJGL which makes it incompatible with OSX - 10.5.8. Please go to New Profile and use 1.5.2 for now. Sorry!" - } - */ - // QList rules; - -private: - DerpInstance *m_instance; -}; - -QDebug operator<<(QDebug &dbg, const DerpVersion *version); -QDebug operator<<(QDebug &dbg, const DerpLibrary *library); diff --git a/logic/DerpVersionBuilder.cpp b/logic/DerpVersionBuilder.cpp deleted file mode 100644 index 20f43404..00000000 --- a/logic/DerpVersionBuilder.cpp +++ /dev/null @@ -1,446 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "DerpVersionBuilder.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "DerpVersion.h" -#include "DerpInstance.h" -#include "DerpRule.h" -#include "logger/QsLog.h" - -DerpVersionBuilder::DerpVersionBuilder() -{ - -} - -bool DerpVersionBuilder::build(DerpVersion *version, DerpInstance *instance, QWidget *widgetParent) -{ - DerpVersionBuilder builder; - builder.m_version = version; - builder.m_instance = instance; - builder.m_widgetParent = widgetParent; - return builder.build(); -} - -bool DerpVersionBuilder::read(DerpVersion *version, const QJsonObject &obj) -{ - DerpVersionBuilder builder; - builder.m_version = version; - builder.m_instance = 0; - builder.m_widgetParent = 0; - return builder.read(obj); -} - -bool DerpVersionBuilder::build() -{ - m_version->clear(); - - QDir root(m_instance->instanceRoot()); - QDir patches(root.absoluteFilePath("patches/")); - - // version.json -> patches/*.json -> custom.json - - // version.json - { - QLOG_INFO() << "Reading version.json"; - QJsonObject obj; - if (!read(QFileInfo(root.absoluteFilePath("version.json")), &obj)) - { - return false; - } - if (!apply(obj)) - { - return false; - } - } - - // patches/ - { - // load all, put into map for ordering, apply in the right order - - QMap objects; - for (auto info : patches.entryInfoList(QStringList() << "*.json", QDir::Files)) - { - QLOG_INFO() << "Reading" << info.fileName(); - QJsonObject obj; - if (!read(info, &obj)) - { - return false; - } - if (!obj.contains("order") || !obj.value("order").isDouble()) - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Missing or invalid 'order' in %1").arg(info.absoluteFilePath())); - return false; - } - objects.insert(obj.value("order").toDouble(), obj); - } - for (auto object : objects.values()) - { - qDebug() << "Applying object with order" << objects.key(object); - if (!apply(object)) - { - return false; - } - } - } - - // custom.json - { - if (QFile::exists(root.absoluteFilePath("custom.json"))) - { - QLOG_INFO() << "Reading custom.json"; - QJsonObject obj; - if (!read(QFileInfo(root.absoluteFilePath("custom.json")), &obj)) - { - return false; - } - if (!apply(obj)) - { - return false; - } - } - } - - return true; -} - -bool DerpVersionBuilder::read(const QJsonObject &obj) -{ - m_version->clear(); - - return apply(obj); -} - -void applyString(const QJsonObject &obj, const QString &key, QString &out, const bool onlyOverride = true) -{ - if (obj.contains(key) && obj.value(key).isString()) - { - out = obj.value(key).toString(); - } - else if (!onlyOverride) - { - if (obj.contains("+" + key) && obj.value("+" + key).isString()) - { - out += obj.value("+" + key).toString(); - } - else if (obj.contains("-" + key) && obj.value("-" + key).isString()) - { - out.remove(obj.value("-" + key).toString()); - } - } -} -void applyString(const QJsonObject &obj, const QString &key, std::shared_ptr lib, void(DerpLibrary::*func)(const QString &val)) -{ - if (obj.contains(key) && obj.value(key).isString()) - { - (lib.get()->*func)(obj.value(key).toString()); - } -} -bool DerpVersionBuilder::apply(const QJsonObject &object) -{ - applyString(object, "id", m_version->id); - applyString(object, "mainClass", m_version->mainClass); - applyString(object, "minecraftArguments", m_version->minecraftArguments, false); - applyString(object, "processArguments", m_version->processArguments, false); - if (m_version->minecraftArguments.isEmpty()) - { - const QString toCompare = m_version->processArguments.toLower(); - if (toCompare == "legacy") - { - m_version->minecraftArguments = " ${auth_player_name} ${auth_session}"; - } - else if (toCompare == "username_session") - { - m_version->minecraftArguments = "--username ${auth_player_name} --session ${auth_session}"; - } - else if (toCompare == "username_session_version") - { - m_version->minecraftArguments = "--username ${auth_player_name} --session ${auth_session} --version ${profile_name}"; - } - } - applyString(object, "type", m_version->type); - applyString(object, "releaseTime", m_version->releaseTime); - applyString(object, "time", m_version->time); - applyString(object, "assets", m_version->assets); - { - if (m_version->assets.isEmpty()) - { - m_version->assets = "legacy"; - } - } - if (object.contains("minimumLauncherVersion")) - { - auto minLauncherVersionVal = object.value("minimumLauncherVersion"); - if (minLauncherVersionVal.isDouble()) - { - m_version->minimumLauncherVersion = minLauncherVersionVal.toDouble(); - } - } - - // libraries - if (object.contains("libraries")) - { - m_version->libraries.clear(); - auto librariesValue = object.value("libraries"); - if (!librariesValue.isArray()) - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("One json files contains a libraries field, but it's not an array")); - return false; - } - auto array = librariesValue.toArray(); - for (auto libVal : array) - { - if (libVal.isObject()) - { - if (!applyLibrary(libVal.toObject(), Override)) - { - return false; - } - } - - } - } - - // +libraries - if (object.contains("+libraries")) - { - auto librariesValue = object.value("+libraries"); - if (!librariesValue.isArray()) - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("One json files contains a libraries field, but it's not an array")); - return false; - } - for (auto libVal : librariesValue.toArray()) - { - if (libVal.isObject()) - { - applyLibrary(libVal.toObject(), Add); - } - - } - } - - // -libraries - if (object.contains("-libraries")) - { - auto librariesValue = object.value("-libraries"); - if (!librariesValue.isArray()) - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("One json files contains a libraries field, but it's not an array")); - return false; - } - for (auto libVal : librariesValue.toArray()) - { - if (libVal.isObject()) - { - applyLibrary(libVal.toObject(), Remove); - } - - } - } - - return true; -} - -int findLibrary(QList > haystack, const QString &needle) -{ - for (int i = 0; i < haystack.size(); ++i) - { - if (QRegExp(needle, Qt::CaseSensitive, QRegExp::WildcardUnix).indexIn(haystack.at(i)->rawName()) != -1) - { - return i; - } - } - return -1; -} - -bool DerpVersionBuilder::applyLibrary(const QJsonObject &lib, const DerpVersionBuilder::Type type) -{ - // Library name - auto nameVal = lib.value("name"); - if (!nameVal.isString()) - { - return false; - } - auto name = nameVal.toString(); - - if (type == Remove) - { - int index = findLibrary(m_version->libraries, name); - if (index >= 0) - { - m_version->libraries.removeAt(index); - } - return true; - } - - if (type == Add && !lib.contains("insert")) - { - return false; - } - - std::shared_ptr library; - - if (lib.value("insert").toString() != "apply" && type == Add) - { - QMutableListIterator > it(m_version->libraries); - while (it.hasNext()) - { - if (it.next()->rawName() == name) - { - it.remove(); - } - } - } - - if (lib.value("insert").toString() == "apply" && type == Add) - { - library = m_version->libraries[findLibrary(m_version->libraries, name)]; - } - else - { - library.reset(new DerpLibrary(nameVal.toString())); - } - - applyString(lib, "url", library, &DerpLibrary::setBaseUrl); - applyString(lib, "MMC-hint", library, &DerpLibrary::setHint); - applyString(lib, "MMC-absulute_url", library, &DerpLibrary::setAbsoluteUrl); - applyString(lib, "MMC-absoluteUrl", library, &DerpLibrary::setAbsoluteUrl); - - auto extractVal = lib.value("extract"); - if (extractVal.isObject()) - { - QStringList excludes; - auto extractObj = extractVal.toObject(); - auto excludesVal = extractObj.value("exclude"); - if (excludesVal.isArray()) - { - auto excludesList = excludesVal.toArray(); - for (auto excludeVal : excludesList) - { - if (excludeVal.isString()) - { - excludes.append(excludeVal.toString()); - } - } - library->extract_excludes = excludes; - } - } - - auto nativesVal = lib.value("natives"); - if (nativesVal.isObject()) - { - library->setIsNative(); - auto nativesObj = nativesVal.toObject(); - for (auto it = nativesObj.begin(); it != nativesObj.end(); ++it) - { - auto osType = OpSys_fromString(it.key()); - if (osType == Os_Other) - { - continue; - } - if (!it.value().isString()) - { - continue; - } - library->addNative(osType, it.value().toString()); - } - } - - if (lib.contains("rules")) - { - library->setRules(rulesFromJsonV4(lib)); - } - library->finalize(); - if (type == Override) - { - m_version->libraries.append(library); - } - else if (lib.value("insert").toString() != "apply") - { - if (lib.value("insert").toString() == "append") - { - m_version->libraries.append(library); - } - else if (lib.value("insert").toString() == "prepend") - { - m_version->libraries.prepend(library); - } - else if (lib.value("insert").isObject()) - { - QJsonObject insertObj = lib.value("insert").toObject(); - if (insertObj.isEmpty()) - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("'insert' object empty")); - return false; - } - const QString key = insertObj.keys().first(); - const QString value = insertObj.value(key).toString(); - const int index = findLibrary(m_version->libraries, value); - if (index >= 0) - { - if (key == "before") - { - m_version->libraries.insert(index, library); - } - else if (key == "after") - { - m_version->libraries.insert(index + 1, library); - } - else - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Invalid value for 'insert': %1").arg(lib.value("insert").toString())); - return false; - } - } - } - else - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Invalid value for 'insert': %1").arg(lib.value("insert").toString())); - return false; - } - } - return true; -} - -bool DerpVersionBuilder::read(const QFileInfo &fileInfo, QJsonObject *out) -{ - QFile file(fileInfo.absoluteFilePath()); - if (!file.open(QFile::ReadOnly)) - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Unable to open %1: %2").arg(file.fileName(), file.errorString())); - return false; - } - QJsonParseError error; - QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error); - if (error.error != QJsonParseError::NoError) - { - QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Unable to parse %1: %2 at %3").arg(file.fileName(), error.errorString()).arg(error.offset)); - return false; - } - *out = doc.object(); - return true; -} diff --git a/logic/DerpVersionBuilder.h b/logic/DerpVersionBuilder.h deleted file mode 100644 index b94cd8e9..00000000 --- a/logic/DerpVersionBuilder.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright 2013 MultiMC Contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -class DerpVersion; -class DerpInstance; -class QWidget; -class QJsonObject; -class QFileInfo; - -class DerpVersionBuilder -{ - DerpVersionBuilder(); -public: - static bool build(DerpVersion *version, DerpInstance *instance, QWidget *widgetParent); - static bool read(DerpVersion *version, const QJsonObject &obj); - -private: - DerpVersion *m_version; - DerpInstance *m_instance; - QWidget *m_widgetParent; - - enum Type - { - Override, - Add, - Remove - }; - - bool build(); - bool read(const QJsonObject &obj); - - void clear(); - bool apply(const QJsonObject &object); - bool applyLibrary(const QJsonObject &lib, const Type type); - - bool read(const QFileInfo &fileInfo, QJsonObject *out); -}; diff --git a/logic/ForgeInstaller.cpp b/logic/ForgeInstaller.cpp index 35663ddd..863c3dfd 100644 --- a/logic/ForgeInstaller.cpp +++ b/logic/ForgeInstaller.cpp @@ -14,15 +14,15 @@ */ #include "ForgeInstaller.h" -#include "DerpVersion.h" -#include "DerpLibrary.h" +#include "OneSixVersion.h" +#include "OneSixLibrary.h" #include "net/HttpMetaCache.h" #include #include #include #include #include "MultiMC.h" -#include "DerpInstance.h" +#include "OneSixInstance.h" #include #include @@ -31,7 +31,7 @@ ForgeInstaller::ForgeInstaller(QString filename, QString universal_url) { - std::shared_ptr newVersion; + std::shared_ptr newVersion; m_universal_url = universal_url; QuaZip zip(filename); @@ -64,7 +64,7 @@ ForgeInstaller::ForgeInstaller(QString filename, QString universal_url) // read the forge version info { - newVersion = DerpVersion::fromJson(versionInfoVal.toObject()); + newVersion = OneSixVersion::fromJson(versionInfoVal.toObject()); if (!newVersion) return; } @@ -74,7 +74,7 @@ ForgeInstaller::ForgeInstaller(QString filename, QString universal_url) internalPath = installObj.value("filePath").toString(); // where do we put the library? decode the mojang path - DerpLibrary lib(libraryName); + OneSixLibrary lib(libraryName); lib.finalize(); auto cacheentry = MMC->metacache()->resolveEntry("libraries", lib.storagePath()); @@ -109,7 +109,7 @@ ForgeInstaller::ForgeInstaller(QString filename, QString universal_url) realVersionId = m_forge_version->id = installObj.value("minecraft").toString(); } -bool ForgeInstaller::add(DerpInstance *to) +bool ForgeInstaller::add(OneSixInstance *to) { if (!BaseInstaller::add(to)) { diff --git a/logic/ForgeInstaller.h b/logic/ForgeInstaller.h index 6490b5bf..eb8ecd79 100644 --- a/logic/ForgeInstaller.h +++ b/logic/ForgeInstaller.h @@ -20,20 +20,20 @@ #include #include -class DerpVersion; +class OneSixVersion; class ForgeInstaller : public BaseInstaller { public: ForgeInstaller(QString filename, QString universal_url); - bool add(DerpInstance *to) override; + bool add(OneSixInstance *to) override; QString id() const override { return "net.minecraftforge"; } private: // the version, read from the installer - std::shared_ptr m_forge_version; + std::shared_ptr m_forge_version; QString internalPath; QString finalPath; QString realVersionId; diff --git a/logic/InstanceFactory.cpp b/logic/InstanceFactory.cpp index c50ec4e4..730bcd69 100644 --- a/logic/InstanceFactory.cpp +++ b/logic/InstanceFactory.cpp @@ -21,10 +21,10 @@ #include "BaseInstance.h" #include "LegacyInstance.h" #include "LegacyFTBInstance.h" -#include "DerpInstance.h" -#include "DerpFTBInstance.h" +#include "OneSixInstance.h" +#include "OneSixFTBInstance.h" #include "NostalgiaInstance.h" -#include "DerpInstance.h" +#include "OneSixInstance.h" #include "BaseVersion.h" #include "MinecraftVersion.h" @@ -51,9 +51,9 @@ InstanceFactory::InstLoadError InstanceFactory::loadInstance(BaseInstance *&inst QString inst_type = m_settings->get("InstanceType").toString(); // FIXME: replace with a map lookup, where instance classes register their types - if (inst_type == "Derp" || inst_type == "OneSix") + if (inst_type == "OneSix" || inst_type == "OneSix") { - inst = new DerpInstance(instDir, m_settings, this); + inst = new OneSixInstance(instDir, m_settings, this); } else if (inst_type == "Legacy") { @@ -67,9 +67,9 @@ InstanceFactory::InstLoadError InstanceFactory::loadInstance(BaseInstance *&inst { inst = new LegacyFTBInstance(instDir, m_settings, this); } - else if (inst_type == "OneSixFTB" || inst_type == "DerpFTB") + else if (inst_type == "OneSixFTB" || inst_type == "OneSixFTB") { - inst = new DerpFTBInstance(instDir, m_settings, this); + inst = new OneSixFTBInstance(instDir, m_settings, this); } else { @@ -102,15 +102,15 @@ InstanceFactory::InstCreateError InstanceFactory::createInstance(BaseInstance *& switch (mcVer->type) { case MinecraftVersion::Legacy: - // TODO derp + // TODO OneSix m_settings->set("InstanceType", "Legacy"); inst = new LegacyInstance(instDir, m_settings, this); inst->setIntendedVersionId(version->descriptor()); inst->setShouldUseCustomBaseJar(false); break; - case MinecraftVersion::Derp: - m_settings->set("InstanceType", "Derp"); - inst = new DerpInstance(instDir, m_settings, this); + case MinecraftVersion::OneSix: + m_settings->set("InstanceType", "OneSix"); + inst = new OneSixInstance(instDir, m_settings, this); inst->setIntendedVersionId(version->descriptor()); inst->setShouldUseCustomBaseJar(false); break; @@ -137,9 +137,9 @@ InstanceFactory::InstCreateError InstanceFactory::createInstance(BaseInstance *& inst->setIntendedVersionId(version->descriptor()); inst->setShouldUseCustomBaseJar(false); break; - case MinecraftVersion::Derp: - m_settings->set("InstanceType", "DerpFTB"); - inst = new DerpFTBInstance(instDir, m_settings, this); + case MinecraftVersion::OneSix: + m_settings->set("InstanceType", "OneSixFTB"); + inst = new OneSixFTBInstance(instDir, m_settings, this); inst->setIntendedVersionId(version->descriptor()); inst->setShouldUseCustomBaseJar(false); break; @@ -176,8 +176,8 @@ InstanceFactory::InstCreateError InstanceFactory::copyInstance(BaseInstance *&ne m_settings->registerSetting("InstanceType", "Legacy"); QString inst_type = m_settings->get("InstanceType").toString(); - if(inst_type == "OneSixFTB" || inst_type == "DerpFTB") - m_settings->set("InstanceType", "Derp"); + if(inst_type == "OneSixFTB" || inst_type == "OneSixFTB") + m_settings->set("InstanceType", "OneSix"); if(inst_type == "LegacyFTB") m_settings->set("InstanceType", "Legacy"); diff --git a/logic/LegacyInstance.h b/logic/LegacyInstance.h index 1ff17cbd..1e7d9eb6 100644 --- a/logic/LegacyInstance.h +++ b/logic/LegacyInstance.h @@ -68,7 +68,7 @@ public: virtual QString intendedVersionId() const override; virtual bool setIntendedVersionId(QString version) override; // the `version' of Legacy instances is defined by the launcher code. - // in contrast with Derp, where `version' is described in a json file + // in contrast with OneSix, where `version' is described in a json file virtual bool versionIsCustom() override { return false; diff --git a/logic/LiteLoaderInstaller.cpp b/logic/LiteLoaderInstaller.cpp index 71c7011f..1ce9d3f4 100644 --- a/logic/LiteLoaderInstaller.cpp +++ b/logic/LiteLoaderInstaller.cpp @@ -20,9 +20,9 @@ #include "logger/QsLog.h" -#include "DerpVersion.h" -#include "DerpLibrary.h" -#include "DerpInstance.h" +#include "OneSixVersion.h" +#include "OneSixLibrary.h" +#include "OneSixInstance.h" QMap LiteLoaderInstaller::m_launcherWrapperVersionMapping; @@ -38,12 +38,12 @@ LiteLoaderInstaller::LiteLoaderInstaller() } } -bool LiteLoaderInstaller::canApply(DerpInstance *instance) const +bool LiteLoaderInstaller::canApply(OneSixInstance *instance) const { return m_launcherWrapperVersionMapping.contains(instance->intendedVersionId()); } -bool LiteLoaderInstaller::add(DerpInstance *to) +bool LiteLoaderInstaller::add(OneSixInstance *to) { if (!BaseInstaller::add(to)) { @@ -60,7 +60,7 @@ bool LiteLoaderInstaller::add(DerpInstance *to) // launchwrapper { - DerpLibrary launchwrapperLib("net.minecraft:launchwrapper:" + m_launcherWrapperVersionMapping[to->intendedVersionId()]); + OneSixLibrary launchwrapperLib("net.minecraft:launchwrapper:" + m_launcherWrapperVersionMapping[to->intendedVersionId()]); launchwrapperLib.finalize(); QJsonObject lwLibObj = launchwrapperLib.toJson(); lwLibObj.insert("insert", QString("prepend")); @@ -69,7 +69,7 @@ bool LiteLoaderInstaller::add(DerpInstance *to) // liteloader { - DerpLibrary liteloaderLib("com.mumfrey:liteloader:" + to->intendedVersionId()); + OneSixLibrary liteloaderLib("com.mumfrey:liteloader:" + to->intendedVersionId()); liteloaderLib.setBaseUrl("http://dl.liteloader.com/versions/"); liteloaderLib.finalize(); QJsonObject llLibObj = liteloaderLib.toJson(); diff --git a/logic/LiteLoaderInstaller.h b/logic/LiteLoaderInstaller.h index c128ee22..5e01b16c 100644 --- a/logic/LiteLoaderInstaller.h +++ b/logic/LiteLoaderInstaller.h @@ -25,8 +25,8 @@ class LiteLoaderInstaller : public BaseInstaller public: LiteLoaderInstaller(); - bool canApply(DerpInstance *instance) const override; - bool add(DerpInstance *to) override; + bool canApply(OneSixInstance *instance) const override; + bool add(OneSixInstance *to) override; private: virtual QString id() const override { return "com.mumfrey.liteloader"; } diff --git a/logic/MinecraftVersion.h b/logic/MinecraftVersion.h index dd849ce9..504381a8 100644 --- a/logic/MinecraftVersion.h +++ b/logic/MinecraftVersion.h @@ -32,7 +32,7 @@ struct MinecraftVersion : public BaseVersion /// This version's type. Used internally to identify what kind of version this is. enum VersionType { - Derp, + OneSix, Legacy, Nostalgia } type; @@ -66,8 +66,8 @@ struct MinecraftVersion : public BaseVersion } switch (type) { - case Derp: - pre_final.append("Derp"); + case OneSix: + pre_final.append("OneSix"); break; case Legacy: pre_final.append("Legacy"); diff --git a/logic/NostalgiaInstance.cpp b/logic/NostalgiaInstance.cpp index f27954a7..2e23ee71 100644 --- a/logic/NostalgiaInstance.cpp +++ b/logic/NostalgiaInstance.cpp @@ -17,7 +17,7 @@ NostalgiaInstance::NostalgiaInstance(const QString &rootDir, SettingsObject *settings, QObject *parent) - : DerpInstance(rootDir, settings, parent) + : OneSixInstance(rootDir, settings, parent) { } diff --git a/logic/NostalgiaInstance.h b/logic/NostalgiaInstance.h index 6a6b91a1..a26f7f0a 100644 --- a/logic/NostalgiaInstance.h +++ b/logic/NostalgiaInstance.h @@ -15,9 +15,9 @@ #pragma once -#include "DerpInstance.h" +#include "OneSixInstance.h" -class NostalgiaInstance : public DerpInstance +class NostalgiaInstance : public OneSixInstance { Q_OBJECT public: diff --git a/logic/OneSixFTBInstance.cpp b/logic/OneSixFTBInstance.cpp new file mode 100644 index 00000000..71bc1470 --- /dev/null +++ b/logic/OneSixFTBInstance.cpp @@ -0,0 +1,123 @@ +#include "OneSixFTBInstance.h" + +#include "OneSixVersion.h" +#include "OneSixLibrary.h" +#include "tasks/SequentialTask.h" +#include "ForgeInstaller.h" +#include "lists/ForgeVersionList.h" +#include "MultiMC.h" + +class OneSixFTBInstanceForge : public Task +{ + Q_OBJECT +public: + explicit OneSixFTBInstanceForge(const QString &version, OneSixFTBInstance *inst, QObject *parent = 0) : + Task(parent), instance(inst), version("Forge " + version) + { + } + + void executeTask() + { + for (int i = 0; i < MMC->forgelist()->count(); ++i) + { + if (MMC->forgelist()->at(i)->name() == version) + { + forgeVersion = std::dynamic_pointer_cast(MMC->forgelist()->at(i)); + break; + } + } + if (!forgeVersion) + { + emitFailed(QString("Couldn't find forge version ") + version ); + return; + } + entry = MMC->metacache()->resolveEntry("minecraftforge", forgeVersion->filename); + if (entry->stale) + { + setStatus(tr("Downloading Forge...")); + fjob = new NetJob("Forge download"); + fjob->addNetAction(CacheDownload::make(forgeVersion->installer_url, entry)); + connect(fjob, &NetJob::failed, [this](){emitFailed(m_failReason);}); + connect(fjob, &NetJob::succeeded, this, &OneSixFTBInstanceForge::installForge); + connect(fjob, &NetJob::progress, [this](qint64 c, qint64 total){ setProgress(100 * c / total); }); + fjob->start(); + } + else + { + installForge(); + } + } + +private +slots: + void installForge() + { + setStatus(tr("Installing Forge...")); + QString forgePath = entry->getFullPath(); + ForgeInstaller forge(forgePath, forgeVersion->universal_url); + if (!instance->reloadFullVersion()) + { + emitFailed(tr("Couldn't load the version config")); + return; + } + auto version = instance->getFullVersion(); + if (!forge.add(instance)) + { + emitFailed(tr("Couldn't install Forge")); + return; + } + emitSucceeded(); + } + +private: + OneSixFTBInstance *instance; + QString version; + ForgeVersionPtr forgeVersion; + MetaEntryPtr entry; + NetJob *fjob; +}; + +OneSixFTBInstance::OneSixFTBInstance(const QString &rootDir, SettingsObject *settings, QObject *parent) : + OneSixInstance(rootDir, settings, parent) +{ + QFile f(QDir(minecraftRoot()).absoluteFilePath("pack.json")); + if (f.open(QFile::ReadOnly)) + { + QString data = QString::fromUtf8(f.readAll()); + QRegularExpressionMatch match = QRegularExpression("net.minecraftforge:minecraftforge:[\\.\\d]*").match(data); + m_forge.reset(new OneSixLibrary(match.captured())); + m_forge->finalize(); + } +} + +QString OneSixFTBInstance::id() const +{ + return "FTB/" + BaseInstance::id(); +} + +QString OneSixFTBInstance::getStatusbarDescription() +{ + return "OneSix FTB: " + intendedVersionId(); +} +bool OneSixFTBInstance::menuActionEnabled(QString action_name) const +{ + return false; +} + +std::shared_ptr OneSixFTBInstance::doUpdate(bool only_prepare) +{ + std::shared_ptr task; + task.reset(new SequentialTask(this)); + if (!MMC->forgelist()->isLoaded()) + { + task->addTask(std::shared_ptr(MMC->forgelist()->getLoadTask())); + } + task->addTask(OneSixInstance::doUpdate(only_prepare)); + task->addTask(std::shared_ptr(new OneSixFTBInstanceForge(m_forge->version(), this, this))); + //FIXME: yes. this may appear dumb. but the previous step can change the list, so we do it all again. + //TODO: Add a graph task. Construct graphs of tasks so we may capture the logic properly. + task->addTask(OneSixInstance::doUpdate(only_prepare)); + return task; +} + +#include "OneSixFTBInstance.moc" diff --git a/logic/OneSixFTBInstance.h b/logic/OneSixFTBInstance.h new file mode 100644 index 00000000..dc028819 --- /dev/null +++ b/logic/OneSixFTBInstance.h @@ -0,0 +1,22 @@ +#pragma once + +#include "OneSixInstance.h" + +class OneSixLibrary; + +class OneSixFTBInstance : public OneSixInstance +{ + Q_OBJECT +public: + explicit OneSixFTBInstance(const QString &rootDir, SettingsObject *settings, + QObject *parent = 0); + virtual QString getStatusbarDescription(); + virtual bool menuActionEnabled(QString action_name) const; + + virtual std::shared_ptr doUpdate(bool only_prepare) override; + + virtual QString id() const; + +private: + std::shared_ptr m_forge; +}; diff --git a/logic/OneSixInstance.cpp b/logic/OneSixInstance.cpp new file mode 100644 index 00000000..c43a5187 --- /dev/null +++ b/logic/OneSixInstance.cpp @@ -0,0 +1,388 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "OneSixInstance.h" + +#include + +#include "OneSixInstance_p.h" +#include "OneSixUpdate.h" +#include "OneSixVersion.h" +#include "pathutils.h" +#include "logger/QsLog.h" +#include "assets/AssetsUtils.h" +#include "MultiMC.h" +#include "icons/IconList.h" +#include "MinecraftProcess.h" +#include "gui/dialogs/OneSixModEditDialog.h" + +OneSixInstance::OneSixInstance(const QString &rootDir, SettingsObject *settings, QObject *parent) + : BaseInstance(new OneSixInstancePrivate(), rootDir, settings, parent) +{ + I_D(OneSixInstance); + d->m_settings->registerSetting("IntendedVersion", ""); + d->m_settings->registerSetting("ShouldUpdate", false); + d->version.reset(new OneSixVersion(this, this)); + if (QDir(instanceRoot()).exists("version.json")) + { + reloadFullVersion(); + } + else + { + clearFullVersion(); + } +} + +std::shared_ptr OneSixInstance::doUpdate(bool only_prepare) +{ + return std::shared_ptr(new OneSixUpdate(this, only_prepare)); +} + +QString replaceTokensIn(QString text, QMap with) +{ + QString result; + QRegExp token_regexp("\\$\\{(.+)\\}"); + token_regexp.setMinimal(true); + QStringList list; + int tail = 0; + int head = 0; + while ((head = token_regexp.indexIn(text, head)) != -1) + { + result.append(text.mid(tail, head - tail)); + QString key = token_regexp.cap(1); + auto iter = with.find(key); + if (iter != with.end()) + { + result.append(*iter); + } + head += token_regexp.matchedLength(); + tail = head; + } + result.append(text.mid(tail)); + return result; +} + +QDir OneSixInstance::reconstructAssets(std::shared_ptr version) +{ + QDir assetsDir = QDir("assets/"); + QDir indexDir = QDir(PathCombine(assetsDir.path(), "indexes")); + QDir objectDir = QDir(PathCombine(assetsDir.path(), "objects")); + QDir virtualDir = QDir(PathCombine(assetsDir.path(), "virtual")); + + QString indexPath = PathCombine(indexDir.path(), version->assets + ".json"); + QFile indexFile(indexPath); + QDir virtualRoot(PathCombine(virtualDir.path(), version->assets)); + + if (!indexFile.exists()) + { + QLOG_ERROR() << "No assets index file" << indexPath << "; can't reconstruct assets"; + return virtualRoot; + } + + QLOG_DEBUG() << "reconstructAssets" << assetsDir.path() << indexDir.path() + << objectDir.path() << virtualDir.path() << virtualRoot.path(); + + AssetsIndex index; + bool loadAssetsIndex = AssetsUtils::loadAssetsIndexJson(indexPath, &index); + + if (loadAssetsIndex && index.isVirtual) + { + QLOG_INFO() << "Reconstructing virtual assets folder at" << virtualRoot.path(); + + for (QString map : index.objects.keys()) + { + AssetObject asset_object = index.objects.value(map); + QString target_path = PathCombine(virtualRoot.path(), map); + QFile target(target_path); + + QString tlk = asset_object.hash.left(2); + + QString original_path = + PathCombine(PathCombine(objectDir.path(), tlk), asset_object.hash); + QFile original(original_path); + if(!original.exists()) + continue; + if (!target.exists()) + { + QFileInfo info(target_path); + QDir target_dir = info.dir(); + // QLOG_DEBUG() << target_dir; + if (!target_dir.exists()) + QDir("").mkpath(target_dir.path()); + + bool couldCopy = original.copy(target_path); + QLOG_DEBUG() << " Copying" << original_path << "to" << target_path + << QString::number(couldCopy); // << original.errorString(); + } + } + + // TODO: Write last used time to virtualRoot/.lastused + } + + return virtualRoot; +} + +QStringList OneSixInstance::processMinecraftArgs(MojangAccountPtr account) +{ + I_D(OneSixInstance); + auto version = d->version; + QString args_pattern = version->minecraftArguments; + + QMap token_mapping; + // yggdrasil! + token_mapping["auth_username"] = account->username(); + token_mapping["auth_session"] = account->sessionId(); + token_mapping["auth_access_token"] = account->accessToken(); + token_mapping["auth_player_name"] = account->currentProfile()->name; + token_mapping["auth_uuid"] = account->currentProfile()->id; + + // this is for offline?: + /* + map["auth_player_name"] = "Player"; + map["auth_player_name"] = "00000000-0000-0000-0000-000000000000"; + */ + + // these do nothing and are stupid. + token_mapping["profile_name"] = name(); + token_mapping["version_name"] = version->id; + + QString absRootDir = QDir(minecraftRoot()).absolutePath(); + token_mapping["game_directory"] = absRootDir; + QString absAssetsDir = QDir("assets/").absolutePath(); + token_mapping["game_assets"] = reconstructAssets(d->version).absolutePath(); + + auto user = account->user(); + QJsonObject userAttrs; + for (auto key : user.properties.keys()) + { + auto array = QJsonArray::fromStringList(user.properties.values(key)); + userAttrs.insert(key, array); + } + QJsonDocument value(userAttrs); + + token_mapping["user_properties"] = value.toJson(QJsonDocument::Compact); + token_mapping["user_type"] = account->currentProfile()->legacy ? "legacy" : "mojang"; + // 1.7.3+ assets tokens + token_mapping["assets_root"] = absAssetsDir; + token_mapping["assets_index_name"] = version->assets; + + QStringList parts = args_pattern.split(' ', QString::SkipEmptyParts); + for (int i = 0; i < parts.length(); i++) + { + parts[i] = replaceTokensIn(parts[i], token_mapping); + } + return parts; +} + +MinecraftProcess *OneSixInstance::prepareForLaunch(MojangAccountPtr account) +{ + I_D(OneSixInstance); + + QIcon icon = MMC->icons()->getIcon(iconKey()); + auto pixmap = icon.pixmap(128, 128); + pixmap.save(PathCombine(minecraftRoot(), "icon.png"), "PNG"); + + auto version = d->version; + if (!version) + return nullptr; + QString launchScript; + { + auto libs = version->getActiveNormalLibs(); + for (auto lib : libs) + { + QFileInfo fi(QString("libraries/") + lib->storagePath()); + launchScript += "cp " + fi.absoluteFilePath() + "\n"; + } + QString targetstr = "versions/" + version->id + "/" + version->id + ".jar"; + QFileInfo fi(targetstr); + launchScript += "cp " + fi.absoluteFilePath() + "\n"; + } + launchScript += "mainClass " + version->mainClass + "\n"; + + for (auto param : processMinecraftArgs(account)) + { + launchScript += "param " + param + "\n"; + } + + // Set the width and height for 1.6 instances + bool maximize = settings().get("LaunchMaximized").toBool(); + if (maximize) + { + // this is probably a BAD idea + // launchScript += "param --fullscreen\n"; + } + else + { + launchScript += + "param --width\nparam " + settings().get("MinecraftWinWidth").toString() + "\n"; + launchScript += + "param --height\nparam " + settings().get("MinecraftWinHeight").toString() + "\n"; + } + QDir natives_dir(PathCombine(instanceRoot(), "natives/")); + launchScript += "windowTitle " + windowTitle() + "\n"; + for(auto native: version->getActiveNativeLibs()) + { + QFileInfo finfo(PathCombine("libraries", native->storagePath())); + launchScript += "ext " + finfo.absoluteFilePath() + "\n"; + } + launchScript += "natives " + natives_dir.absolutePath() + "\n"; + launchScript += "launch onesix\n"; + + // create the process and set its parameters + MinecraftProcess *proc = new MinecraftProcess(this); + proc->setWorkdir(minecraftRoot()); + proc->setLaunchScript(launchScript); + // proc->setNativeFolder(natives_dir.absolutePath()); + return proc; +} + +void OneSixInstance::cleanupAfterRun() +{ + QString target_dir = PathCombine(instanceRoot(), "natives/"); + QDir dir(target_dir); + dir.removeRecursively(); +} + +std::shared_ptr OneSixInstance::loaderModList() +{ + I_D(OneSixInstance); + if (!d->loader_mod_list) + { + d->loader_mod_list.reset(new ModList(loaderModsDir())); + } + d->loader_mod_list->update(); + return d->loader_mod_list; +} + +std::shared_ptr OneSixInstance::resourcePackList() +{ + I_D(OneSixInstance); + if (!d->resource_pack_list) + { + d->resource_pack_list.reset(new ModList(resourcePacksDir())); + } + d->resource_pack_list->update(); + return d->resource_pack_list; +} + +QDialog *OneSixInstance::createModEditDialog(QWidget *parent) +{ + return new OneSixModEditDialog(this, parent); +} + +bool OneSixInstance::setIntendedVersionId(QString version) +{ + settings().set("IntendedVersion", version); + setShouldUpdate(true); + QFile::remove(PathCombine(instanceRoot(), "version.json")); + clearFullVersion(); + return true; +} + +QString OneSixInstance::intendedVersionId() const +{ + return settings().get("IntendedVersion").toString(); +} + +void OneSixInstance::setShouldUpdate(bool val) +{ + settings().set("ShouldUpdate", val); +} + +bool OneSixInstance::shouldUpdate() const +{ + QVariant var = settings().get("ShouldUpdate"); + if (!var.isValid() || var.toBool() == false) + { + return intendedVersionId() != currentVersionId(); + } + return true; +} + +bool OneSixInstance::versionIsCustom() +{ + QDir patches(PathCombine(instanceRoot(), "patches/")); + return QFile::exists(PathCombine(instanceRoot(), "custom.json")) + || (patches.exists() && patches.count() >= 0); +} + +QString OneSixInstance::currentVersionId() const +{ + return intendedVersionId(); +} + +bool OneSixInstance::reloadFullVersion(QWidget *widgetParent) +{ + I_D(OneSixInstance); + + bool ret = d->version->reload(widgetParent); + emit versionReloaded(); + return ret; +} + +void OneSixInstance::clearFullVersion() +{ + I_D(OneSixInstance); + d->version->clear(); + emit versionReloaded(); +} + +std::shared_ptr OneSixInstance::getFullVersion() +{ + I_D(OneSixInstance); + return d->version; +} + +QString OneSixInstance::defaultBaseJar() const +{ + return "versions/" + intendedVersionId() + "/" + intendedVersionId() + ".jar"; +} + +QString OneSixInstance::defaultCustomBaseJar() const +{ + return PathCombine(instanceRoot(), "custom.jar"); +} + +bool OneSixInstance::menuActionEnabled(QString action_name) const +{ + if (action_name == "actionChangeInstLWJGLVersion") + return false; + return true; +} + +QString OneSixInstance::getStatusbarDescription() +{ + QString descr = "OneSix : " + intendedVersionId(); + if (versionIsCustom()) + { + descr + " (custom)"; + } + return descr; +} + +QString OneSixInstance::loaderModsDir() const +{ + return PathCombine(minecraftRoot(), "mods"); +} + +QString OneSixInstance::resourcePacksDir() const +{ + return PathCombine(minecraftRoot(), "resourcepacks"); +} + +QString OneSixInstance::instanceConfigFolder() const +{ + return PathCombine(minecraftRoot(), "config"); +} diff --git a/logic/OneSixInstance.h b/logic/OneSixInstance.h new file mode 100644 index 00000000..94577828 --- /dev/null +++ b/logic/OneSixInstance.h @@ -0,0 +1,75 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "BaseInstance.h" + +#include "OneSixVersion.h" +#include "ModList.h" + +class OneSixInstance : public BaseInstance +{ + Q_OBJECT +public: + explicit OneSixInstance(const QString &rootDir, SettingsObject *settings, + QObject *parent = 0); + + ////// Mod Lists ////// + std::shared_ptr loaderModList(); + std::shared_ptr resourcePackList(); + + ////// Directories ////// + QString resourcePacksDir() const; + QString loaderModsDir() const; + virtual QString instanceConfigFolder() const override; + + virtual std::shared_ptr doUpdate(bool only_prepare) override; + virtual MinecraftProcess *prepareForLaunch(MojangAccountPtr account) override; + + virtual void cleanupAfterRun() override; + + virtual QString intendedVersionId() const override; + virtual bool setIntendedVersionId(QString version) override; + + virtual QString currentVersionId() const override; + + virtual bool shouldUpdate() const override; + virtual void setShouldUpdate(bool val) override; + + virtual QDialog *createModEditDialog(QWidget *parent) override; + + /// reload the full version json files. return true on success! + bool reloadFullVersion(QWidget *widgetParent = 0); + /// clears all version information in preparation for an update + void clearFullVersion(); + /// get the current full version info + std::shared_ptr getFullVersion(); + /// is the current version original, or custom? + virtual bool versionIsCustom() override; + + virtual QString defaultBaseJar() const override; + virtual QString defaultCustomBaseJar() const override; + + virtual bool menuActionEnabled(QString action_name) const override; + virtual QString getStatusbarDescription() override; + +signals: + void versionReloaded(); + +private: + QStringList processMinecraftArgs(MojangAccountPtr account); + QDir reconstructAssets(std::shared_ptr version); +}; diff --git a/logic/OneSixInstance_p.h b/logic/OneSixInstance_p.h new file mode 100644 index 00000000..a2b70ac9 --- /dev/null +++ b/logic/OneSixInstance_p.h @@ -0,0 +1,27 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "BaseInstance_p.h" +#include "OneSixVersion.h" +#include "ModList.h" + +struct OneSixInstancePrivate : public BaseInstancePrivate +{ + std::shared_ptr version; + std::shared_ptr loader_mod_list; + std::shared_ptr resource_pack_list; +}; diff --git a/logic/OneSixLibrary.cpp b/logic/OneSixLibrary.cpp new file mode 100644 index 00000000..4d892d53 --- /dev/null +++ b/logic/OneSixLibrary.cpp @@ -0,0 +1,268 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "OneSixLibrary.h" +#include "OneSixRule.h" +#include "OpSys.h" +#include "logic/net/URLConstants.h" +#include +#include +#include "logger/QsLog.h" + +void OneSixLibrary::finalize() +{ + QStringList parts = m_name.split(':'); + QString relative = parts[0]; + relative.replace('.', '/'); + relative += '/' + parts[1] + '/' + parts[2] + '/' + parts[1] + '-' + parts[2]; + + if (!m_is_native) + relative += ".jar"; + else + { + if (m_native_suffixes.contains(currentSystem)) + { + relative += "-" + m_native_suffixes[currentSystem] + ".jar"; + } + else + { + // really, bad. + relative += ".jar"; + } + } + + m_decentname = parts[1]; + m_decentversion = parts[2]; + m_storage_path = relative; + m_download_url = m_base_url + relative; + + if (m_rules.empty()) + { + m_is_active = true; + } + else + { + RuleAction result = Disallow; + for (auto rule : m_rules) + { + RuleAction temp = rule->apply(this); + if (temp != Defer) + result = temp; + } + m_is_active = (result == Allow); + } + if (m_is_native) + { + m_is_active = m_is_active && m_native_suffixes.contains(currentSystem); + m_decenttype = "Native"; + } + else + { + m_decenttype = "Java"; + } +} + +void OneSixLibrary::setName(const QString &name) +{ + m_name = name; +} +void OneSixLibrary::setBaseUrl(const QString &base_url) +{ + m_base_url = base_url; +} +void OneSixLibrary::setIsNative() +{ + m_is_native = true; +} +void OneSixLibrary::addNative(OpSys os, const QString &suffix) +{ + m_is_native = true; + m_native_suffixes[os] = suffix; +} +void OneSixLibrary::setRules(QList> rules) +{ + m_rules = rules; +} +bool OneSixLibrary::isActive() const +{ + return m_is_active; +} +bool OneSixLibrary::isNative() const +{ + return m_is_native; +} +QString OneSixLibrary::downloadUrl() const +{ + if (m_absolute_url.size()) + return m_absolute_url; + return m_download_url; +} +QString OneSixLibrary::storagePath() const +{ + return m_storage_path; +} + +void OneSixLibrary::setAbsoluteUrl(const QString &absolute_url) +{ + m_absolute_url = absolute_url; +} + +QString OneSixLibrary::absoluteUrl() const +{ + return m_absolute_url; +} + +void OneSixLibrary::setHint(const QString &hint) +{ + m_hint = hint; +} + +QString OneSixLibrary::hint() const +{ + return m_hint; +} + +bool OneSixLibrary::filesExist() +{ + QString storage = storagePath(); + if (storage.contains("${arch}")) + { + QString cooked_storage = storage; + cooked_storage.replace("${arch}", "32"); + QFileInfo info32(PathCombine("libraries", cooked_storage)); + if (!info32.exists()) + { + return false; + } + cooked_storage = storage; + cooked_storage.replace("${arch}", "64"); + QFileInfo info64(PathCombine("libraries", cooked_storage)); + if (!info64.exists()) + { + return false; + } + } + else + { + QFileInfo info(PathCombine("libraries", storage)); + if (!info.exists()) + { + return false; + } + } + return true; +} + +bool OneSixLibrary::extractTo(QString target_dir) +{ + QString storage = storagePath(); + if (storage.contains("${arch}")) + { + QString cooked_storage = storage; + cooked_storage.replace("${arch}", "32"); + QString origin = PathCombine("libraries", cooked_storage); + QString target_dir_cooked = PathCombine(target_dir, "32"); + if(!ensureFolderPathExists(target_dir_cooked)) + { + QLOG_ERROR() << "Couldn't create folder " + target_dir_cooked; + return false; + } + if (JlCompress::extractWithExceptions(origin, target_dir_cooked, extract_excludes) + .isEmpty()) + { + QLOG_ERROR() << "Couldn't extract " + origin; + return false; + } + cooked_storage = storage; + cooked_storage.replace("${arch}", "64"); + origin = PathCombine("libraries", cooked_storage); + target_dir_cooked = PathCombine(target_dir, "64"); + if(!ensureFolderPathExists(target_dir_cooked)) + { + QLOG_ERROR() << "Couldn't create folder " + target_dir_cooked; + return false; + } + if (JlCompress::extractWithExceptions(origin, target_dir_cooked, extract_excludes) + .isEmpty()) + { + QLOG_ERROR() << "Couldn't extract " + origin; + return false; + } + } + else + { + if(!ensureFolderPathExists(target_dir)) + { + QLOG_ERROR() << "Couldn't create folder " + target_dir; + return false; + } + QString path = PathCombine("libraries", storage); + if (JlCompress::extractWithExceptions(path, target_dir, extract_excludes).isEmpty()) + { + QLOG_ERROR() << "Couldn't extract " + path; + return false; + } + } + return true; +} + +QJsonObject OneSixLibrary::toJson() +{ + QJsonObject libRoot; + libRoot.insert("name", m_name); + if (m_absolute_url.size()) + libRoot.insert("MMC-absoluteUrl", m_absolute_url); + if (m_hint.size()) + libRoot.insert("MMC-hint", m_hint); + if (m_base_url != "http://" + URLConstants::AWS_DOWNLOAD_LIBRARIES && + m_base_url != "https://" + URLConstants::AWS_DOWNLOAD_LIBRARIES && + m_base_url != "https://" + URLConstants::LIBRARY_BASE) + libRoot.insert("url", m_base_url); + if (isNative() && m_native_suffixes.size()) + { + QJsonObject nativeList; + auto iter = m_native_suffixes.begin(); + while (iter != m_native_suffixes.end()) + { + nativeList.insert(OpSys_toString(iter.key()), iter.value()); + iter++; + } + libRoot.insert("natives", nativeList); + } + if (isNative() && extract_excludes.size()) + { + QJsonArray excludes; + QJsonObject extract; + for (auto exclude : extract_excludes) + { + excludes.append(exclude); + } + extract.insert("exclude", excludes); + libRoot.insert("extract", extract); + } + if (m_rules.size()) + { + QJsonArray allRules; + for (auto &rule : m_rules) + { + QJsonObject ruleObj = rule->toJson(); + allRules.append(ruleObj); + } + libRoot.insert("rules", allRules); + } + return libRoot; +} diff --git a/logic/OneSixLibrary.h b/logic/OneSixLibrary.h new file mode 100644 index 00000000..52f89969 --- /dev/null +++ b/logic/OneSixLibrary.h @@ -0,0 +1,132 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "logic/net/URLConstants.h" +#include "OpSys.h" + +class Rule; + +class OneSixLibrary +{ +private: + // basic values used internally (so far) + QString m_name; + QString m_base_url = "https://" + URLConstants::LIBRARY_BASE; + QList> m_rules; + + // custom values + /// absolute URL. takes precedence over m_download_path, if defined + QString m_absolute_url; + /// download hint - how to actually get the library + QString m_hint; + + // derived values used for real things + /// a decent name fit for display + QString m_decentname; + /// a decent version fit for display + QString m_decentversion; + /// a decent type fit for display + QString m_decenttype; + /// where to store the lib locally + QString m_storage_path; + /// where to download the lib from + QString m_download_url; + /// is this lib actually active on the current OS? + bool m_is_active = false; + /// is the library a native? + bool m_is_native = false; + /// native suffixes per OS + QMap m_native_suffixes; + +public: + QStringList extract_excludes; + +public: + /// Constructor + OneSixLibrary(const QString &name) + { + m_name = name; + } + + /// Returns the raw name field + QString rawName() const + { + return m_name; + } + + QJsonObject toJson(); + + /** + * finalize the library, processing the input values into derived values and state + * + * This SHALL be called after all the values are parsed or after any further change. + */ + void finalize(); + + /// Set the library composite name + void setName(const QString &name); + /// get a decent-looking name + QString name() const + { + return m_decentname; + } + /// get a decent-looking version + QString version() const + { + return m_decentversion; + } + /// what kind of library is it? (for display) + QString type() const + { + return m_decenttype; + } + /// Set the url base for downloads + void setBaseUrl(const QString &base_url); + + /// Call this to mark the library as 'native' (it's a zip archive with DLLs) + void setIsNative(); + /// Attach a name suffix to the specified OS native + void addNative(OpSys os, const QString &suffix); + /// Set the load rules + void setRules(QList> rules); + + /// Returns true if the library should be loaded (or extracted, in case of natives) + bool isActive() const; + /// Returns true if the library is native + bool isNative() const; + /// Get the URL to download the library from + QString downloadUrl() const; + /// Get the relative path where the library should be saved + QString storagePath() const; + + /// set an absolute URL for the library. This is an MMC extension. + void setAbsoluteUrl(const QString &absolute_url); + QString absoluteUrl() const; + + /// set a hint about how to treat the library. This is an MMC extension. + void setHint(const QString &hint); + QString hint() const; + + bool extractTo(QString target_dir); + bool filesExist(); +}; diff --git a/logic/OneSixRule.cpp b/logic/OneSixRule.cpp new file mode 100644 index 00000000..d8d13b50 --- /dev/null +++ b/logic/OneSixRule.cpp @@ -0,0 +1,89 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "OneSixRule.h" + +QList> rulesFromJsonV4(const QJsonObject &objectWithRules) +{ + QList> rules; + auto rulesVal = objectWithRules.value("rules"); + if (!rulesVal.isArray()) + return rules; + + QJsonArray ruleList = rulesVal.toArray(); + for (auto ruleVal : ruleList) + { + std::shared_ptr rule; + if (!ruleVal.isObject()) + continue; + auto ruleObj = ruleVal.toObject(); + auto actionVal = ruleObj.value("action"); + if (!actionVal.isString()) + continue; + auto action = RuleAction_fromString(actionVal.toString()); + if (action == Defer) + continue; + + auto osVal = ruleObj.value("os"); + if (!osVal.isObject()) + { + // add a new implicit action rule + rules.append(ImplicitRule::create(action)); + continue; + } + + auto osObj = osVal.toObject(); + auto osNameVal = osObj.value("name"); + if (!osNameVal.isString()) + continue; + OpSys requiredOs = OpSys_fromString(osNameVal.toString()); + QString versionRegex = osObj.value("version").toString(); + // add a new OS rule + rules.append(OsRule::create(action, requiredOs, versionRegex)); + } + return rules; +} + +QJsonObject ImplicitRule::toJson() +{ + QJsonObject ruleObj; + ruleObj.insert("action", m_result == Allow ? QString("allow") : QString("disallow")); + return ruleObj; +} + +QJsonObject OsRule::toJson() +{ + QJsonObject ruleObj; + ruleObj.insert("action", m_result == Allow ? QString("allow") : QString("disallow")); + QJsonObject osObj; + { + osObj.insert("name", OpSys_toString(m_system)); + osObj.insert("version", m_version_regexp); + } + ruleObj.insert("os", osObj); + return ruleObj; +} + +RuleAction RuleAction_fromString(QString name) +{ + if (name == "allow") + return Allow; + if (name == "disallow") + return Disallow; + return Defer; +} diff --git a/logic/OneSixRule.h b/logic/OneSixRule.h new file mode 100644 index 00000000..426e2886 --- /dev/null +++ b/logic/OneSixRule.h @@ -0,0 +1,98 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include "logic/OneSixLibrary.h" + +enum RuleAction +{ + Allow, + Disallow, + Defer +}; + +RuleAction RuleAction_fromString(QString); +QList> rulesFromJsonV4(const QJsonObject &objectWithRules); + +class Rule +{ +protected: + RuleAction m_result; + virtual bool applies(OneSixLibrary *parent) = 0; + +public: + Rule(RuleAction result) : m_result(result) + { + } + virtual ~Rule() {}; + virtual QJsonObject toJson() = 0; + RuleAction apply(OneSixLibrary *parent) + { + if (applies(parent)) + return m_result; + else + return Defer; + } + ; +}; + +class OsRule : public Rule +{ +private: + // the OS + OpSys m_system; + // the OS version regexp + QString m_version_regexp; + +protected: + virtual bool applies(OneSixLibrary *) + { + return (m_system == currentSystem); + } + OsRule(RuleAction result, OpSys system, QString version_regexp) + : Rule(result), m_system(system), m_version_regexp(version_regexp) + { + } + +public: + virtual QJsonObject toJson(); + static std::shared_ptr create(RuleAction result, OpSys system, + QString version_regexp) + { + return std::shared_ptr(new OsRule(result, system, version_regexp)); + } +}; + +class ImplicitRule : public Rule +{ +protected: + virtual bool applies(OneSixLibrary *) + { + return true; + } + ImplicitRule(RuleAction result) : Rule(result) + { + } + +public: + virtual QJsonObject toJson(); + static std::shared_ptr create(RuleAction result) + { + return std::shared_ptr(new ImplicitRule(result)); + } +}; diff --git a/logic/OneSixUpdate.cpp b/logic/OneSixUpdate.cpp new file mode 100644 index 00000000..f51b6c23 --- /dev/null +++ b/logic/OneSixUpdate.cpp @@ -0,0 +1,372 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "MultiMC.h" +#include "OneSixUpdate.h" + +#include + +#include +#include +#include +#include + +#include "BaseInstance.h" +#include "lists/MinecraftVersionList.h" +#include "OneSixVersion.h" +#include "OneSixLibrary.h" +#include "OneSixInstance.h" +#include "net/ForgeMirrors.h" +#include "net/URLConstants.h" +#include "assets/AssetsUtils.h" + +#include "pathutils.h" +#include + +OneSixUpdate::OneSixUpdate(BaseInstance *inst, bool only_prepare, QObject *parent) + : Task(parent), m_inst(inst), m_only_prepare(only_prepare) +{ +} + +void OneSixUpdate::executeTask() +{ + QString intendedVersion = m_inst->intendedVersionId(); + + // Make directories + QDir mcDir(m_inst->minecraftRoot()); + if (!mcDir.exists() && !mcDir.mkpath(".")) + { + emitFailed("Failed to create bin folder."); + return; + } + + if (m_only_prepare) + { + prepareForLaunch(); + return; + } + + if (m_inst->shouldUpdate()) + { + // Get a pointer to the version object that corresponds to the instance's version. + targetVersion = std::dynamic_pointer_cast( + MMC->minecraftlist()->findVersion(intendedVersion)); + if (targetVersion == nullptr) + { + // don't do anything if it was invalid + emitFailed("The specified Minecraft version is invalid. Choose a different one."); + return; + } + versionFileStart(); + } + else + { + jarlibStart(); + } +} + +void OneSixUpdate::versionFileStart() +{ + QLOG_INFO() << m_inst->name() << ": getting version file."; + setStatus(tr("Getting the version files from Mojang...")); + + QString urlstr = "http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + + targetVersion->descriptor() + "/" + targetVersion->descriptor() + ".json"; + auto job = new NetJob("Version index"); + job->addNetAction(ByteArrayDownload::make(QUrl(urlstr))); + specificVersionDownloadJob.reset(job); + connect(specificVersionDownloadJob.get(), SIGNAL(succeeded()), SLOT(versionFileFinished())); + connect(specificVersionDownloadJob.get(), SIGNAL(failed()), SLOT(versionFileFailed())); + connect(specificVersionDownloadJob.get(), SIGNAL(progress(qint64, qint64)), + SIGNAL(progress(qint64, qint64))); + specificVersionDownloadJob->start(); +} + +void OneSixUpdate::versionFileFinished() +{ + NetActionPtr DlJob = specificVersionDownloadJob->first(); + OneSixInstance *inst = (OneSixInstance *)m_inst; + + QString version_id = targetVersion->descriptor(); + QString inst_dir = m_inst->instanceRoot(); + // save the version file in $instanceId/version.json + { + QString version1 = PathCombine(inst_dir, "/version.json"); + ensureFilePathExists(version1); + // FIXME: detect errors here, download to a temp file, swap + QSaveFile vfile1(version1); + if (!vfile1.open(QIODevice::Truncate | QIODevice::WriteOnly)) + { + emitFailed("Can't open " + version1 + " for writing."); + return; + } + auto data = std::dynamic_pointer_cast(DlJob)->m_data; + qint64 actual = 0; + if ((actual = vfile1.write(data)) != data.size()) + { + emitFailed("Failed to write into " + version1 + ". Written " + actual + " out of " + + data.size() + '.'); + return; + } + if (!vfile1.commit()) + { + emitFailed("Can't commit changes to " + version1); + return; + } + } + + // the version is downloaded safely. update is 'done' at this point + m_inst->setShouldUpdate(false); + + // delete any custom version inside the instance (it's no longer relevant, we did an update) + QString custom = PathCombine(inst_dir, "/custom.json"); + QFile finfo(custom); + if (finfo.exists()) + { + finfo.remove(); + } + inst->reloadFullVersion(); + + jarlibStart(); +} + +void OneSixUpdate::versionFileFailed() +{ + emitFailed("Failed to download the version description. Try again."); +} + +void OneSixUpdate::assetIndexStart() +{ + setStatus(tr("Updating assets index...")); + OneSixInstance *inst = (OneSixInstance *)m_inst; + std::shared_ptr version = inst->getFullVersion(); + QString assetName = version->assets; + QUrl indexUrl = "http://" + URLConstants::AWS_DOWNLOAD_INDEXES + assetName + ".json"; + QString localPath = assetName + ".json"; + auto job = new NetJob("Asset index for " + inst->name()); + + auto metacache = MMC->metacache(); + auto entry = metacache->resolveEntry("asset_indexes", localPath); + job->addNetAction(CacheDownload::make(indexUrl, entry)); + jarlibDownloadJob.reset(job); + + connect(jarlibDownloadJob.get(), SIGNAL(succeeded()), SLOT(assetIndexFinished())); + connect(jarlibDownloadJob.get(), SIGNAL(failed()), SLOT(assetIndexFailed())); + connect(jarlibDownloadJob.get(), SIGNAL(progress(qint64, qint64)), + SIGNAL(progress(qint64, qint64))); + + jarlibDownloadJob->start(); +} + +void OneSixUpdate::assetIndexFinished() +{ + AssetsIndex index; + + OneSixInstance *inst = (OneSixInstance *)m_inst; + std::shared_ptr version = inst->getFullVersion(); + QString assetName = version->assets; + + QString asset_fname = "assets/indexes/" + assetName + ".json"; + if (!AssetsUtils::loadAssetsIndexJson(asset_fname, &index)) + { + emitFailed("Failed to read the assets index!"); + } + + QList dls; + for (auto object : index.objects.values()) + { + QString objectName = object.hash.left(2) + "/" + object.hash; + QFileInfo objectFile("assets/objects/" + objectName); + if ((!objectFile.isFile()) || (objectFile.size() != object.size)) + { + auto objectDL = MD5EtagDownload::make( + QUrl("http://" + URLConstants::RESOURCE_BASE + objectName), + objectFile.filePath()); + objectDL->m_total_progress = object.size; + dls.append(objectDL); + } + } + if (dls.size()) + { + setStatus(tr("Getting the assets files from Mojang...")); + auto job = new NetJob("Assets for " + inst->name()); + for (auto dl : dls) + job->addNetAction(dl); + jarlibDownloadJob.reset(job); + connect(jarlibDownloadJob.get(), SIGNAL(succeeded()), SLOT(assetsFinished())); + connect(jarlibDownloadJob.get(), SIGNAL(failed()), SLOT(assetsFailed())); + connect(jarlibDownloadJob.get(), SIGNAL(progress(qint64, qint64)), + SIGNAL(progress(qint64, qint64))); + jarlibDownloadJob->start(); + return; + } + assetsFinished(); +} + +void OneSixUpdate::assetIndexFailed() +{ + emitFailed("Failed to download the assets index!"); +} + +void OneSixUpdate::assetsFinished() +{ + prepareForLaunch(); +} + +void OneSixUpdate::assetsFailed() +{ + emitFailed("Failed to download assets!"); +} + +void OneSixUpdate::jarlibStart() +{ + setStatus(tr("Getting the library files from Mojang...")); + QLOG_INFO() << m_inst->name() << ": downloading libraries"; + OneSixInstance *inst = (OneSixInstance *)m_inst; + bool successful = inst->reloadFullVersion(); + if (!successful) + { + emitFailed("Failed to load the version description file. It might be " + "corrupted, missing or simply too new."); + return; + } + + // Build a list of URLs that will need to be downloaded. + std::shared_ptr version = inst->getFullVersion(); + // minecraft.jar for this version + { + QString version_id = version->id; + QString localPath = version_id + "/" + version_id + ".jar"; + QString urlstr = "http://" + URLConstants::AWS_DOWNLOAD_VERSIONS + localPath; + + auto job = new NetJob("Libraries for instance " + inst->name()); + + auto metacache = MMC->metacache(); + auto entry = metacache->resolveEntry("versions", localPath); + job->addNetAction(CacheDownload::make(QUrl(urlstr), entry)); + + jarlibDownloadJob.reset(job); + } + + auto libs = version->getActiveNativeLibs(); + libs.append(version->getActiveNormalLibs()); + + auto metacache = MMC->metacache(); + QList ForgeLibs; + for (auto lib : libs) + { + if (lib->hint() == "local") + continue; + + QString raw_storage = lib->storagePath(); + QString raw_dl = lib->downloadUrl(); + + auto f = [&](QString storage, QString dl) + { + auto entry = metacache->resolveEntry("libraries", storage); + if (entry->stale) + { + if (lib->hint() == "forge-pack-xz") + { + ForgeLibs.append(ForgeXzDownload::make(storage, entry)); + } + else + { + jarlibDownloadJob->addNetAction(CacheDownload::make(dl, entry)); + } + } + }; + if (raw_storage.contains("${arch}")) + { + QString cooked_storage = raw_storage; + QString cooked_dl = raw_dl; + f(cooked_storage.replace("${arch}", "32"), cooked_dl.replace("${arch}", "32")); + cooked_storage = raw_storage; + cooked_dl = raw_dl; + f(cooked_storage.replace("${arch}", "64"), cooked_dl.replace("${arch}", "64")); + } + else + { + f(raw_storage, raw_dl); + } + } + // TODO: think about how to propagate this from the original json file... or IF AT ALL + QString forgeMirrorList = "http://files.minecraftforge.net/mirror-brand.list"; + if (!ForgeLibs.empty()) + { + jarlibDownloadJob->addNetAction( + ForgeMirrors::make(ForgeLibs, jarlibDownloadJob, forgeMirrorList)); + } + + connect(jarlibDownloadJob.get(), SIGNAL(succeeded()), SLOT(jarlibFinished())); + connect(jarlibDownloadJob.get(), SIGNAL(failed()), SLOT(jarlibFailed())); + connect(jarlibDownloadJob.get(), SIGNAL(progress(qint64, qint64)), + SIGNAL(progress(qint64, qint64))); + + jarlibDownloadJob->start(); +} + +void OneSixUpdate::jarlibFinished() +{ + assetIndexStart(); +} + +void OneSixUpdate::jarlibFailed() +{ + QStringList failed = jarlibDownloadJob->getFailedFiles(); + QString failed_all = failed.join("\n"); + emitFailed("Failed to download the following files:\n" + failed_all + + "\n\nPlease try again."); +} + +void OneSixUpdate::prepareForLaunch() +{ + setStatus(tr("Preparing for launch...")); + QLOG_INFO() << m_inst->name() << ": preparing for launch"; + auto OneSix_inst = (OneSixInstance *)m_inst; + + // delete any leftovers, if they are present. + OneSix_inst->cleanupAfterRun(); + + QString natives_dir_raw = PathCombine(OneSix_inst->instanceRoot(), "natives/"); + auto version = OneSix_inst->getFullVersion(); + if (!version) + { + emitFailed("The version information for this instance is not complete. Try re-creating " + "it or changing the version."); + return; + } + /* + for (auto lib : version->getActiveNativeLibs()) + { + if (!lib->filesExist()) + { + emitFailed("Native library is missing some files:\n" + lib->storagePath() + + "\n\nRun the instance at least once in online mode to get all the " + "required files."); + return; + } + if (!lib->extractTo(natives_dir_raw)) + { + emitFailed("Could not extract the native library:\n" + lib->storagePath() + " to " + + natives_dir_raw + + "\n\nMake sure MultiMC has appropriate permissions and there is enough " + "space on the storage device."); + return; + } + } +*/ + emitSucceeded(); +} diff --git a/logic/OneSixUpdate.h b/logic/OneSixUpdate.h new file mode 100644 index 00000000..bc717a94 --- /dev/null +++ b/logic/OneSixUpdate.h @@ -0,0 +1,63 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include + +#include "logic/net/NetJob.h" +#include "logic/tasks/Task.h" + +class MinecraftVersion; +class BaseInstance; + +class OneSixUpdate : public Task +{ + Q_OBJECT +public: + explicit OneSixUpdate(BaseInstance *inst, bool prepare_for_launch, QObject *parent = 0); + virtual void executeTask(); + +private +slots: + void versionFileStart(); + void versionFileFinished(); + void versionFileFailed(); + + void jarlibStart(); + void jarlibFinished(); + void jarlibFailed(); + + void assetIndexStart(); + void assetIndexFinished(); + void assetIndexFailed(); + + void assetsFinished(); + void assetsFailed(); + + // extract the appropriate libraries + void prepareForLaunch(); + +private: + NetJobPtr specificVersionDownloadJob; + NetJobPtr jarlibDownloadJob; + + // target version, determined during this task + std::shared_ptr targetVersion; + BaseInstance *m_inst = nullptr; + bool m_only_prepare = false; +}; diff --git a/logic/OneSixVersion.cpp b/logic/OneSixVersion.cpp index 3571be9b..3db3bd77 100644 --- a/logic/OneSixVersion.cpp +++ b/logic/OneSixVersion.cpp @@ -13,228 +13,60 @@ * limitations under the License. */ -#include "logic/DerpVersion.h" -#include "logic/DerpLibrary.h" -#include "logic/DerpRule.h" +#include "OneSixVersion.h" -#include "logger/QsLog.h" +#include -std::shared_ptr fromJsonV4(QJsonObject root, - std::shared_ptr fullVersion) -{ - fullVersion->id = root.value("id").toString(); - - fullVersion->mainClass = root.value("mainClass").toString(); - auto procArgsValue = root.value("processArguments"); - if (procArgsValue.isString()) - { - fullVersion->processArguments = procArgsValue.toString(); - QString toCompare = fullVersion->processArguments.toLower(); - if (toCompare == "legacy") - { - fullVersion->minecraftArguments = " ${auth_player_name} ${auth_session}"; - } - else if (toCompare == "username_session") - { - fullVersion->minecraftArguments = - "--username ${auth_player_name} --session ${auth_session}"; - } - else if (toCompare == "username_session_version") - { - fullVersion->minecraftArguments = "--username ${auth_player_name} " - "--session ${auth_session} " - "--version ${profile_name}"; - } - } - - auto minecraftArgsValue = root.value("minecraftArguments"); - if (minecraftArgsValue.isString()) - { - fullVersion->minecraftArguments = minecraftArgsValue.toString(); - } - - auto minecraftTypeValue = root.value("type"); - if (minecraftTypeValue.isString()) - { - fullVersion->type = minecraftTypeValue.toString(); - } - - fullVersion->releaseTime = root.value("releaseTime").toString(); - fullVersion->time = root.value("time").toString(); - - auto assetsID = root.value("assets"); - if (assetsID.isString()) - { - fullVersion->assets = assetsID.toString(); - } - else - { - fullVersion->assets = "legacy"; - } - - QLOG_DEBUG() << "Assets version:" << fullVersion->assets; - - // Iterate through the list, if it's a list. - auto librariesValue = root.value("libraries"); - if (!librariesValue.isArray()) - return fullVersion; - - QJsonArray libList = root.value("libraries").toArray(); - for (auto libVal : libList) - { - if (!libVal.isObject()) - { - continue; - } - - QJsonObject libObj = libVal.toObject(); - - // Library name - auto nameVal = libObj.value("name"); - if (!nameVal.isString()) - continue; - std::shared_ptr library(new DerpLibrary(nameVal.toString())); - - auto urlVal = libObj.value("url"); - if (urlVal.isString()) - { - library->setBaseUrl(urlVal.toString()); - } - auto hintVal = libObj.value("MMC-hint"); - if (hintVal.isString()) - { - library->setHint(hintVal.toString()); - } - auto urlAbsVal = libObj.value("MMC-absoluteUrl"); - auto urlAbsuVal = libObj.value("MMC-absulute_url"); // compatibility - if (urlAbsVal.isString()) - { - library->setAbsoluteUrl(urlAbsVal.toString()); - } - else if (urlAbsuVal.isString()) - { - library->setAbsoluteUrl(urlAbsuVal.toString()); - } - // Extract excludes (if any) - auto extractVal = libObj.value("extract"); - if (extractVal.isObject()) - { - QStringList excludes; - auto extractObj = extractVal.toObject(); - auto excludesVal = extractObj.value("exclude"); - if (excludesVal.isArray()) - { - auto excludesList = excludesVal.toArray(); - for (auto excludeVal : excludesList) - { - if (excludeVal.isString()) - excludes.append(excludeVal.toString()); - } - library->extract_excludes = excludes; - } - } +#include "OneSixVersionBuilder.h" - auto nativesVal = libObj.value("natives"); - if (nativesVal.isObject()) - { - library->setIsNative(); - auto nativesObj = nativesVal.toObject(); - auto iter = nativesObj.begin(); - while (iter != nativesObj.end()) - { - auto osType = OpSys_fromString(iter.key()); - if (osType == Os_Other) - continue; - if (!iter.value().isString()) - continue; - library->addNative(osType, iter.value().toString()); - iter++; - } - } - library->setRules(rulesFromJsonV4(libObj)); - library->finalize(); - fullVersion->libraries.append(library); - } - return fullVersion; +OneSixVersion::OneSixVersion(OneSixInstance *instance, QObject *parent) + : QAbstractListModel(parent), m_instance(instance) +{ + clear(); } -std::shared_ptr DerpVersion::fromJson(QJsonObject root) +bool OneSixVersion::reload(QWidget *widgetParent) { - std::shared_ptr readVersion(new DerpVersion()); - int launcher_ver = readVersion->minimumLauncherVersion = - root.value("minimumLauncherVersion").toDouble(); - - // ADD MORE HERE :D - if (launcher_ver > 0 && launcher_ver <= 13) - return fromJsonV4(root, readVersion); - else - { - return std::shared_ptr(); - } + return OneSixVersionBuilder::build(this, m_instance, widgetParent); } -std::shared_ptr DerpVersion::fromFile(QString filepath) +void OneSixVersion::clear() { - QFile file(filepath); - if (!file.open(QIODevice::ReadOnly)) - { - return std::shared_ptr(); - } - - auto data = file.readAll(); - QJsonParseError jsonError; - QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); - - if (jsonError.error != QJsonParseError::NoError) - { - return std::shared_ptr(); - } - - if (!jsonDoc.isObject()) - { - return std::shared_ptr(); - } - QJsonObject root = jsonDoc.object(); - auto version = fromJson(root); - if (version) - version->original_file = filepath; - return version; + id.clear(); + time.clear(); + releaseTime.clear(); + type.clear(); + assets.clear(); + processArguments.clear(); + minecraftArguments.clear(); + minimumLauncherVersion = 0xDEADBEAF; + mainClass.clear(); + libraries.clear(); } -bool DerpVersion::toOriginalFile() +void OneSixVersion::dump() const { - if (original_file.isEmpty()) - return false; - QSaveFile file(original_file); - if (!file.open(QIODevice::WriteOnly)) - { - return false; - } - // serialize base attributes (those we care about anyway) - QJsonObject root; - root.insert("minecraftArguments", minecraftArguments); - root.insert("mainClass", mainClass); - root.insert("minimumLauncherVersion", minimumLauncherVersion); - root.insert("time", time); - root.insert("id", id); - root.insert("type", type); - // screw processArguments - root.insert("releaseTime", releaseTime); - QJsonArray libarray; - for (const auto &lib : libraries) + qDebug().nospace() << "OneSixVersion(" + << "\n\tid=" << id + << "\n\ttime=" << time + << "\n\treleaseTime=" << releaseTime + << "\n\ttype=" << type + << "\n\tassets=" << assets + << "\n\tprocessArguments=" << processArguments + << "\n\tminecraftArguments=" << minecraftArguments + << "\n\tminimumLauncherVersion=" << minimumLauncherVersion + << "\n\tmainClass=" << mainClass + << "\n\tlibraries="; + for (auto lib : libraries) { - libarray.append(lib->toJson()); + qDebug().nospace() << "\n\t\t" << lib.get(); } - if (libarray.count()) - root.insert("libraries", libarray); - QJsonDocument doc(root); - file.write(doc.toJson()); - return file.commit(); + qDebug().nospace() << "\n)"; } -QList> DerpVersion::getActiveNormalLibs() +QList > OneSixVersion::getActiveNormalLibs() { - QList> output; + QList > output; for (auto lib : libraries) { if (lib->isActive() && !lib->isNative()) @@ -245,9 +77,9 @@ QList> DerpVersion::getActiveNormalLibs() return output; } -QList> DerpVersion::getActiveNativeLibs() +QList > OneSixVersion::getActiveNativeLibs() { - QList> output; + QList > output; for (auto lib : libraries) { if (lib->isActive() && lib->isNative()) @@ -258,17 +90,17 @@ QList> DerpVersion::getActiveNativeLibs() return output; } -void DerpVersion::externalUpdateStart() -{ - beginResetModel(); -} - -void DerpVersion::externalUpdateFinish() +std::shared_ptr OneSixVersion::fromJson(const QJsonObject &obj) { - endResetModel(); + std::shared_ptr version(new OneSixVersion(0)); + if (OneSixVersionBuilder::read(version.get(), obj)) + { + return version; + } + return 0; } -QVariant DerpVersion::data(const QModelIndex &index, int role) const +QVariant OneSixVersion::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); @@ -296,7 +128,7 @@ QVariant DerpVersion::data(const QModelIndex &index, int role) const return QVariant(); } -Qt::ItemFlags DerpVersion::flags(const QModelIndex &index) const +Qt::ItemFlags OneSixVersion::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; @@ -312,7 +144,7 @@ Qt::ItemFlags DerpVersion::flags(const QModelIndex &index) const // return QAbstractListModel::flags(index); } -QVariant DerpVersion::headerData(int section, Qt::Orientation orientation, int role) const +QVariant OneSixVersion::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole || orientation != Qt::Horizontal) return QVariant(); @@ -329,12 +161,34 @@ QVariant DerpVersion::headerData(int section, Qt::Orientation orientation, int r } } -int DerpVersion::rowCount(const QModelIndex &parent) const +int OneSixVersion::rowCount(const QModelIndex &parent) const { return libraries.size(); } -int DerpVersion::columnCount(const QModelIndex &parent) const +int OneSixVersion::columnCount(const QModelIndex &parent) const { return 3; } + +QDebug operator<<(QDebug &dbg, const OneSixVersion *version) +{ + version->dump(); + return dbg.maybeSpace(); +} +QDebug operator<<(QDebug &dbg, const OneSixLibrary *library) +{ + dbg.nospace() << "OneSixLibrary(" + << "\n\t\t\trawName=" << library->rawName() + << "\n\t\t\tname=" << library->name() + << "\n\t\t\tversion=" << library->version() + << "\n\t\t\ttype=" << library->type() + << "\n\t\t\tisActive=" << library->isActive() + << "\n\t\t\tisNative=" << library->isNative() + << "\n\t\t\tdownloadUrl=" << library->downloadUrl() + << "\n\t\t\tstoragePath=" << library->storagePath() + << "\n\t\t\tabsolutePath=" << library->absoluteUrl() + << "\n\t\t\thint=" << library->hint(); + dbg.nospace() << "\n\t\t)"; + return dbg.maybeSpace(); +} diff --git a/logic/OneSixVersion.h b/logic/OneSixVersion.h index e8f744aa..00afd010 100644 --- a/logic/OneSixVersion.h +++ b/logic/OneSixVersion.h @@ -14,15 +14,23 @@ */ #pragma once -#include + +#include + +#include +#include #include -class DerpLibrary; +#include "OneSixLibrary.h" + +class OneSixInstance; -class DerpVersion : public QAbstractListModel +class OneSixVersion : public QAbstractListModel { - // Things required to implement the Qt list model + Q_OBJECT public: + explicit OneSixVersion(OneSixInstance *instance, QObject *parent = 0); + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; virtual QVariant headerData(int section, Qt::Orientation orientation, @@ -30,24 +38,19 @@ public: virtual int columnCount(const QModelIndex &parent) const; virtual Qt::ItemFlags flags(const QModelIndex &index) const; - // serialization/deserialization -public: - bool toOriginalFile(); - static std::shared_ptr fromJson(QJsonObject root); - static std::shared_ptr fromFile(QString filepath); + bool reload(QWidget *widgetParent); + void clear(); + + void dump() const; public: - QList> getActiveNormalLibs(); - QList> getActiveNativeLibs(); - // called when something starts/stops messing with the object - // FIXME: these are ugly in every possible way. - void externalUpdateStart(); - void externalUpdateFinish(); + QList> getActiveNormalLibs(); + QList> getActiveNativeLibs(); + + static std::shared_ptr fromJson(const QJsonObject &obj); // data members public: - /// file this was read from. blank, if none - QString original_file; /// the ID - determines which jar to use! ACTUALLY IMPORTANT! QString id; /// Last updated time - as a string @@ -81,7 +84,7 @@ public: QString mainClass; /// the list of libs - both active and inactive, native and java - QList> libraries; + QList> libraries; /* FIXME: add support for those rules here? Looks like a pile of quick hacks to me though. @@ -103,4 +106,10 @@ public: } */ // QList rules; + +private: + OneSixInstance *m_instance; }; + +QDebug operator<<(QDebug &dbg, const OneSixVersion *version); +QDebug operator<<(QDebug &dbg, const OneSixLibrary *library); diff --git a/logic/OneSixVersionBuilder.cpp b/logic/OneSixVersionBuilder.cpp new file mode 100644 index 00000000..85f55a52 --- /dev/null +++ b/logic/OneSixVersionBuilder.cpp @@ -0,0 +1,446 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "OneSixVersionBuilder.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "OneSixVersion.h" +#include "OneSixInstance.h" +#include "OneSixRule.h" +#include "logger/QsLog.h" + +OneSixVersionBuilder::OneSixVersionBuilder() +{ + +} + +bool OneSixVersionBuilder::build(OneSixVersion *version, OneSixInstance *instance, QWidget *widgetParent) +{ + OneSixVersionBuilder builder; + builder.m_version = version; + builder.m_instance = instance; + builder.m_widgetParent = widgetParent; + return builder.build(); +} + +bool OneSixVersionBuilder::read(OneSixVersion *version, const QJsonObject &obj) +{ + OneSixVersionBuilder builder; + builder.m_version = version; + builder.m_instance = 0; + builder.m_widgetParent = 0; + return builder.read(obj); +} + +bool OneSixVersionBuilder::build() +{ + m_version->clear(); + + QDir root(m_instance->instanceRoot()); + QDir patches(root.absoluteFilePath("patches/")); + + // version.json -> patches/*.json -> custom.json + + // version.json + { + QLOG_INFO() << "Reading version.json"; + QJsonObject obj; + if (!read(QFileInfo(root.absoluteFilePath("version.json")), &obj)) + { + return false; + } + if (!apply(obj)) + { + return false; + } + } + + // patches/ + { + // load all, put into map for ordering, apply in the right order + + QMap objects; + for (auto info : patches.entryInfoList(QStringList() << "*.json", QDir::Files)) + { + QLOG_INFO() << "Reading" << info.fileName(); + QJsonObject obj; + if (!read(info, &obj)) + { + return false; + } + if (!obj.contains("order") || !obj.value("order").isDouble()) + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Missing or invalid 'order' in %1").arg(info.absoluteFilePath())); + return false; + } + objects.insert(obj.value("order").toDouble(), obj); + } + for (auto object : objects.values()) + { + qDebug() << "Applying object with order" << objects.key(object); + if (!apply(object)) + { + return false; + } + } + } + + // custom.json + { + if (QFile::exists(root.absoluteFilePath("custom.json"))) + { + QLOG_INFO() << "Reading custom.json"; + QJsonObject obj; + if (!read(QFileInfo(root.absoluteFilePath("custom.json")), &obj)) + { + return false; + } + if (!apply(obj)) + { + return false; + } + } + } + + return true; +} + +bool OneSixVersionBuilder::read(const QJsonObject &obj) +{ + m_version->clear(); + + return apply(obj); +} + +void applyString(const QJsonObject &obj, const QString &key, QString &out, const bool onlyOverride = true) +{ + if (obj.contains(key) && obj.value(key).isString()) + { + out = obj.value(key).toString(); + } + else if (!onlyOverride) + { + if (obj.contains("+" + key) && obj.value("+" + key).isString()) + { + out += obj.value("+" + key).toString(); + } + else if (obj.contains("-" + key) && obj.value("-" + key).isString()) + { + out.remove(obj.value("-" + key).toString()); + } + } +} +void applyString(const QJsonObject &obj, const QString &key, std::shared_ptr lib, void(OneSixLibrary::*func)(const QString &val)) +{ + if (obj.contains(key) && obj.value(key).isString()) + { + (lib.get()->*func)(obj.value(key).toString()); + } +} +bool OneSixVersionBuilder::apply(const QJsonObject &object) +{ + applyString(object, "id", m_version->id); + applyString(object, "mainClass", m_version->mainClass); + applyString(object, "minecraftArguments", m_version->minecraftArguments, false); + applyString(object, "processArguments", m_version->processArguments, false); + if (m_version->minecraftArguments.isEmpty()) + { + const QString toCompare = m_version->processArguments.toLower(); + if (toCompare == "legacy") + { + m_version->minecraftArguments = " ${auth_player_name} ${auth_session}"; + } + else if (toCompare == "username_session") + { + m_version->minecraftArguments = "--username ${auth_player_name} --session ${auth_session}"; + } + else if (toCompare == "username_session_version") + { + m_version->minecraftArguments = "--username ${auth_player_name} --session ${auth_session} --version ${profile_name}"; + } + } + applyString(object, "type", m_version->type); + applyString(object, "releaseTime", m_version->releaseTime); + applyString(object, "time", m_version->time); + applyString(object, "assets", m_version->assets); + { + if (m_version->assets.isEmpty()) + { + m_version->assets = "legacy"; + } + } + if (object.contains("minimumLauncherVersion")) + { + auto minLauncherVersionVal = object.value("minimumLauncherVersion"); + if (minLauncherVersionVal.isDouble()) + { + m_version->minimumLauncherVersion = minLauncherVersionVal.toDouble(); + } + } + + // libraries + if (object.contains("libraries")) + { + m_version->libraries.clear(); + auto librariesValue = object.value("libraries"); + if (!librariesValue.isArray()) + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("One json files contains a libraries field, but it's not an array")); + return false; + } + auto array = librariesValue.toArray(); + for (auto libVal : array) + { + if (libVal.isObject()) + { + if (!applyLibrary(libVal.toObject(), Override)) + { + return false; + } + } + + } + } + + // +libraries + if (object.contains("+libraries")) + { + auto librariesValue = object.value("+libraries"); + if (!librariesValue.isArray()) + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("One json files contains a libraries field, but it's not an array")); + return false; + } + for (auto libVal : librariesValue.toArray()) + { + if (libVal.isObject()) + { + applyLibrary(libVal.toObject(), Add); + } + + } + } + + // -libraries + if (object.contains("-libraries")) + { + auto librariesValue = object.value("-libraries"); + if (!librariesValue.isArray()) + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("One json files contains a libraries field, but it's not an array")); + return false; + } + for (auto libVal : librariesValue.toArray()) + { + if (libVal.isObject()) + { + applyLibrary(libVal.toObject(), Remove); + } + + } + } + + return true; +} + +int findLibrary(QList > haystack, const QString &needle) +{ + for (int i = 0; i < haystack.size(); ++i) + { + if (QRegExp(needle, Qt::CaseSensitive, QRegExp::WildcardUnix).indexIn(haystack.at(i)->rawName()) != -1) + { + return i; + } + } + return -1; +} + +bool OneSixVersionBuilder::applyLibrary(const QJsonObject &lib, const OneSixVersionBuilder::Type type) +{ + // Library name + auto nameVal = lib.value("name"); + if (!nameVal.isString()) + { + return false; + } + auto name = nameVal.toString(); + + if (type == Remove) + { + int index = findLibrary(m_version->libraries, name); + if (index >= 0) + { + m_version->libraries.removeAt(index); + } + return true; + } + + if (type == Add && !lib.contains("insert")) + { + return false; + } + + std::shared_ptr library; + + if (lib.value("insert").toString() != "apply" && type == Add) + { + QMutableListIterator > it(m_version->libraries); + while (it.hasNext()) + { + if (it.next()->rawName() == name) + { + it.remove(); + } + } + } + + if (lib.value("insert").toString() == "apply" && type == Add) + { + library = m_version->libraries[findLibrary(m_version->libraries, name)]; + } + else + { + library.reset(new OneSixLibrary(nameVal.toString())); + } + + applyString(lib, "url", library, &OneSixLibrary::setBaseUrl); + applyString(lib, "MMC-hint", library, &OneSixLibrary::setHint); + applyString(lib, "MMC-absulute_url", library, &OneSixLibrary::setAbsoluteUrl); + applyString(lib, "MMC-absoluteUrl", library, &OneSixLibrary::setAbsoluteUrl); + + auto extractVal = lib.value("extract"); + if (extractVal.isObject()) + { + QStringList excludes; + auto extractObj = extractVal.toObject(); + auto excludesVal = extractObj.value("exclude"); + if (excludesVal.isArray()) + { + auto excludesList = excludesVal.toArray(); + for (auto excludeVal : excludesList) + { + if (excludeVal.isString()) + { + excludes.append(excludeVal.toString()); + } + } + library->extract_excludes = excludes; + } + } + + auto nativesVal = lib.value("natives"); + if (nativesVal.isObject()) + { + library->setIsNative(); + auto nativesObj = nativesVal.toObject(); + for (auto it = nativesObj.begin(); it != nativesObj.end(); ++it) + { + auto osType = OpSys_fromString(it.key()); + if (osType == Os_Other) + { + continue; + } + if (!it.value().isString()) + { + continue; + } + library->addNative(osType, it.value().toString()); + } + } + + if (lib.contains("rules")) + { + library->setRules(rulesFromJsonV4(lib)); + } + library->finalize(); + if (type == Override) + { + m_version->libraries.append(library); + } + else if (lib.value("insert").toString() != "apply") + { + if (lib.value("insert").toString() == "append") + { + m_version->libraries.append(library); + } + else if (lib.value("insert").toString() == "prepend") + { + m_version->libraries.prepend(library); + } + else if (lib.value("insert").isObject()) + { + QJsonObject insertObj = lib.value("insert").toObject(); + if (insertObj.isEmpty()) + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("'insert' object empty")); + return false; + } + const QString key = insertObj.keys().first(); + const QString value = insertObj.value(key).toString(); + const int index = findLibrary(m_version->libraries, value); + if (index >= 0) + { + if (key == "before") + { + m_version->libraries.insert(index, library); + } + else if (key == "after") + { + m_version->libraries.insert(index + 1, library); + } + else + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Invalid value for 'insert': %1").arg(lib.value("insert").toString())); + return false; + } + } + } + else + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Invalid value for 'insert': %1").arg(lib.value("insert").toString())); + return false; + } + } + return true; +} + +bool OneSixVersionBuilder::read(const QFileInfo &fileInfo, QJsonObject *out) +{ + QFile file(fileInfo.absoluteFilePath()); + if (!file.open(QFile::ReadOnly)) + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Unable to open %1: %2").arg(file.fileName(), file.errorString())); + return false; + } + QJsonParseError error; + QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error); + if (error.error != QJsonParseError::NoError) + { + QMessageBox::critical(m_widgetParent, QObject::tr("Error"), QObject::tr("Unable to parse %1: %2 at %3").arg(file.fileName(), error.errorString()).arg(error.offset)); + return false; + } + *out = doc.object(); + return true; +} diff --git a/logic/OneSixVersionBuilder.h b/logic/OneSixVersionBuilder.h new file mode 100644 index 00000000..a3ba331c --- /dev/null +++ b/logic/OneSixVersionBuilder.h @@ -0,0 +1,53 @@ +/* Copyright 2013 MultiMC Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +class OneSixVersion; +class OneSixInstance; +class QWidget; +class QJsonObject; +class QFileInfo; + +class OneSixVersionBuilder +{ + OneSixVersionBuilder(); +public: + static bool build(OneSixVersion *version, OneSixInstance *instance, QWidget *widgetParent); + static bool read(OneSixVersion *version, const QJsonObject &obj); + +private: + OneSixVersion *m_version; + OneSixInstance *m_instance; + QWidget *m_widgetParent; + + enum Type + { + Override, + Add, + Remove + }; + + bool build(); + bool read(const QJsonObject &obj); + + void clear(); + bool apply(const QJsonObject &object); + bool applyLibrary(const QJsonObject &lib, const Type type); + + bool read(const QFileInfo &fileInfo, QJsonObject *out); +}; diff --git a/logic/lists/MinecraftVersionList.cpp b/logic/lists/MinecraftVersionList.cpp index 29894b5a..91f86df0 100644 --- a/logic/lists/MinecraftVersionList.cpp +++ b/logic/lists/MinecraftVersionList.cpp @@ -234,18 +234,18 @@ void MCVListLoadTask::list_downloaded() } // Parse the type. MinecraftVersion::VersionType versionType; - // Derp or Legacy. use filter to determine type + // OneSix or Legacy. use filter to determine type if (versionTypeStr == "release") { versionType = legacyWhitelist.contains(versionID) ? MinecraftVersion::Legacy - : MinecraftVersion::Derp; + : MinecraftVersion::OneSix; is_latest = (versionID == latestReleaseID); is_snapshot = false; } else if (versionTypeStr == "snapshot") // It's a snapshot... yay { versionType = legacyWhitelist.contains(versionID) ? MinecraftVersion::Legacy - : MinecraftVersion::Derp; + : MinecraftVersion::OneSix; is_latest = (versionID == latestSnapshotID); is_snapshot = true; } -- cgit v1.2.3