Compare commits

..

1 Commits

Author SHA1 Message Date
janrupf
3bdf63b0ee GH-2065 Strip non ASCII chars 2019-06-22 01:35:07 +02:00
106 changed files with 2218 additions and 4237 deletions

View File

@@ -32,7 +32,7 @@ set(CMAKE_C_STANDARD_REQUIRED true)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_C_STANDARD 11)
include(GenerateExportHeader)
set(CMAKE_CXX_FLAGS " -Wall -pedantic -Werror -Wno-deprecated-declarations -D_GLIBCXX_USE_CXX11_ABI=0 -fstack-protector-strong --param=ssp-buffer-size=4 -O3 -D_FORTIFY_SOURCE=2 ${CMAKE_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS " -Wall -pedantic -Werror -D_GLIBCXX_USE_CXX11_ABI=0 -fstack-protector-strong --param=ssp-buffer-size=4 -O3 -D_FORTIFY_SOURCE=2 ${CMAKE_CXX_FLAGS}")
if(UNIX AND APPLE)
set(CMAKE_CXX_FLAGS " -stdlib=libc++ ${CMAKE_CXX_FLAGS}")
endif()
@@ -46,7 +46,7 @@ set(MultiMC_NEWS_RSS_URL "https://multimc.org/rss.xml" CACHE STRING "URL to fetc
######## Set version numbers ########
set(MultiMC_VERSION_MAJOR 0)
set(MultiMC_VERSION_MINOR 6)
set(MultiMC_VERSION_HOTFIX 7)
set(MultiMC_VERSION_HOTFIX 5)
# Build number
set(MultiMC_VERSION_BUILD -1 CACHE STRING "Build number. -1 for no build number.")

View File

@@ -27,7 +27,7 @@ We use [Clang Format](http://clang.llvm.org/docs/ClangFormat.html) to format the
## Translations
Translations can be done either directly in the [translations repository](https://github.com/MultiMC/MultiMC5-translate). For more details, see: [Translating-MultiMC](https://github.com/MultiMC/MultiMC5/wiki/Translating-MultiMC).
Translations can be done either directly in the [translations repository](https://github.com/MultiMC/MultiMC5). For more details, see: [Translating-MultiMC](https://github.com/MultiMC/MultiMC5/wiki/Translating-MultiMC).
## Forking/Redistributing
We keep MultiMC open source because we think it's important to be able to see the source code for a project like this, and we do so using the Apache license.

View File

@@ -213,10 +213,8 @@ set(MINECRAFT_SOURCES
minecraft/auth/flows/RefreshTask.cpp
minecraft/auth/flows/ValidateTask.h
minecraft/auth/flows/ValidateTask.cpp
minecraft/gameoptions/GameOptions.h
minecraft/gameoptions/GameOptions.cpp
minecraft/update/AssetUpdateTask.h
minecraft/update/AssetUpdateTask.cpp
minecraft/update/FMLLibrariesTask.cpp
@@ -225,7 +223,6 @@ set(MINECRAFT_SOURCES
minecraft/update/FoldersTask.h
minecraft/update/LibrariesTask.cpp
minecraft/update/LibrariesTask.h
minecraft/launch/ClaimAccount.cpp
minecraft/launch/ClaimAccount.h
minecraft/launch/CreateServerResourcePacksFolder.cpp
@@ -242,16 +239,12 @@ set(MINECRAFT_SOURCES
minecraft/launch/PrintInstanceInfo.h
minecraft/launch/ReconstructAssets.cpp
minecraft/launch/ReconstructAssets.h
minecraft/launch/ScanModFolders.cpp
minecraft/launch/ScanModFolders.h
minecraft/legacy/LegacyModList.h
minecraft/legacy/LegacyModList.cpp
minecraft/legacy/LegacyInstance.h
minecraft/legacy/LegacyInstance.cpp
minecraft/legacy/LegacyUpgradeTask.h
minecraft/legacy/LegacyUpgradeTask.cpp
minecraft/GradleSpecifier.h
minecraft/MinecraftInstance.cpp
minecraft/MinecraftInstance.h
@@ -286,21 +279,15 @@ set(MINECRAFT_SOURCES
minecraft/VersionFile.h
minecraft/VersionFilterData.h
minecraft/VersionFilterData.cpp
minecraft/Mod.h
minecraft/Mod.cpp
minecraft/SimpleModList.h
minecraft/SimpleModList.cpp
minecraft/World.h
minecraft/World.cpp
minecraft/WorldList.h
minecraft/WorldList.cpp
minecraft/mod/Mod.h
minecraft/mod/Mod.cpp
minecraft/mod/ModDetails.h
minecraft/mod/ModFolderModel.h
minecraft/mod/ModFolderModel.cpp
minecraft/mod/ModFolderLoadTask.h
minecraft/mod/ModFolderLoadTask.cpp
minecraft/mod/LocalModParseTask.h
minecraft/mod/LocalModParseTask.cpp
# Assets
minecraft/AssetsUtils.h
minecraft/AssetsUtils.cpp
@@ -331,8 +318,8 @@ add_unit_test(Library
)
# FIXME: shares data with FileSystem test
add_unit_test(ModFolderModel
SOURCES minecraft/mod/ModFolderModel_test.cpp
add_unit_test(SimpleModList
SOURCES minecraft/SimpleModList_test.cpp
DATA testdata
LIBS MultiMC_logic
)
@@ -456,8 +443,6 @@ set(FLAME_SOURCES
modplatform/flame/PackManifest.cpp
modplatform/flame/FileResolvingTask.h
modplatform/flame/FileResolvingTask.cpp
modplatform/flame/UrlResolvingTask.h
modplatform/flame/UrlResolvingTask.cpp
)
add_unit_test(Index
@@ -492,6 +477,8 @@ set(LOGIC_SOURCES
${FLAME_SOURCES}
)
message(STATUS "FOO! ${LOGIC_SOURCES}")
add_library(MultiMC_logic SHARED ${LOGIC_SOURCES})
set_target_properties(MultiMC_logic PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN 1)

View File

@@ -174,11 +174,6 @@ bool copy::operator()(const QString &offset)
bool deletePath(QString path)
{
bool OK = true;
QFileInfo finfo(path);
if(finfo.isFile()) {
return QFile::remove(path);
}
QDir dir(path);
if (!dir.exists())
@@ -309,6 +304,10 @@ QString RemoveInvalidFilenameChars(QString string, QChar replaceWith)
{
string[i] = replaceWith;
}
else if(string[i] > 127) // non ASCII
{
string[i] = replaceWith;
}
}
return string;
}

View File

@@ -100,10 +100,6 @@ QVariant InstanceList::data(const QModelIndex &index, int role) const
{
return pdata->name();
}
case Qt::AccessibleTextRole:
{
return tr("%1 Instance").arg(pdata->name());
}
case Qt::ToolTipRole:
{
return pdata->instanceRoot();
@@ -238,7 +234,7 @@ void InstanceList::deleteInstance(const InstanceId& id)
auto inst = getInstanceById(id);
if(!inst)
{
qDebug() << "Cannot delete instance" << id << ". No such instance is present (deleted externally?).";
qDebug() << "Cannot delete instance" << id << " No such instance is present.";
return;
}
@@ -823,7 +819,6 @@ bool InstanceList::commitStagedInstance(const QString& path, const QString& inst
instanceSet.insert(instID);
m_groups.insert(groupName);
emit instancesChanged();
emit instanceSelectRequest(instID);
}
saveGroupList();
return true;

View File

@@ -129,7 +129,6 @@ public:
signals:
void dataIsInvalid();
void instancesChanged();
void instanceSelectRequest(QString instanceId);
void groupsChanged(QSet<QString> groups);
public slots:

View File

@@ -18,7 +18,7 @@
#include <QString>
#include <QFileInfo>
#include <QSet>
#include "minecraft/mod/Mod.h"
#include "minecraft/Mod.h"
#include <functional>
#include "multimc_logic_export.h"

View File

@@ -43,8 +43,6 @@ ComponentList::ComponentList(MinecraftInstance * instance)
d->m_instance = instance;
d->m_saveTimer.setSingleShot(true);
d->m_saveTimer.setInterval(5000);
d->interactionDisabled = instance->isRunning();
connect(d->m_instance, &BaseInstance::runningStatusChanged, this, &ComponentList::disableInteraction);
connect(&d->m_saveTimer, &QTimer::timeout, this, &ComponentList::save_internal);
}
@@ -637,9 +635,6 @@ void ComponentList::componentDataChanged()
qWarning() << "ComponentList got dataChenged signal from a non-Component!";
return;
}
if(objPtr->getID() == "net.minecraft") {
emit minecraftChanged();
}
// figure out which one is it... in a seriously dumb way.
int index = 0;
for (auto component: d->components)
@@ -767,9 +762,8 @@ QVariant ComponentList::data(const QModelIndex &index, int role) const
{
switch (column)
{
case NameColumn: {
return patch->isEnabled() ? Qt::Checked : Qt::Unchecked;
}
case NameColumn:
return d->components.at(row)->isEnabled() ? Qt::Checked : Qt::Unchecked;
default:
return QVariant();
}
@@ -779,7 +773,7 @@ QVariant ComponentList::data(const QModelIndex &index, int role) const
switch (column)
{
case NameColumn:
return patch->getName();
return d->components.at(row)->getName();
case VersionColumn:
{
if(patch->isCustom())
@@ -859,25 +853,21 @@ QVariant ComponentList::headerData(int section, Qt::Orientation orientation, int
}
return QVariant();
}
// FIXME: zero precision mess
Qt::ItemFlags ComponentList::flags(const QModelIndex &index) const
{
if (!index.isValid()) {
if (!index.isValid())
return Qt::NoItemFlags;
}
Qt::ItemFlags outFlags = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
int row = index.row();
if (row < 0 || row >= d->components.size()) {
if (row < 0 || row >= d->components.size())
return Qt::NoItemFlags;
}
auto patch = d->components.at(row);
// TODO: this will need fine-tuning later...
if(patch->canBeDisabled() && !d->interactionDisabled)
if(patch->canBeDisabled())
{
outFlags |= Qt::ItemIsUserCheckable;
}
@@ -1212,14 +1202,3 @@ QString ComponentList::getComponentVersion(const QString& uid) const
}
return QString();
}
void ComponentList::disableInteraction(bool disable)
{
if(d->interactionDisabled != disable) {
d->interactionDisabled = disable;
auto size = d->components.size();
if(size) {
emit dataChanged(index(0), index(size - 1));
}
}
}

View File

@@ -104,9 +104,6 @@ public:
/// if there is a save scheduled, do it now.
void saveNow();
signals:
void minecraftChanged();
public:
/// get the profile component by id
Component * getComponent(const QString &id);
@@ -134,7 +131,6 @@ private slots:
void updateSucceeded();
void updateFailed(const QString & error);
void componentDataChanged();
void disableInteraction(bool disable);
private:
bool load();

View File

@@ -38,6 +38,5 @@ struct ComponentListData
QTimer m_saveTimer;
shared_qobject_ptr<Task> m_updateTask;
bool loaded = false;
bool interactionDisabled = true;
};

View File

@@ -21,13 +21,12 @@
#include "minecraft/launch/ModMinecraftJar.h"
#include "minecraft/launch/ClaimAccount.h"
#include "minecraft/launch/ReconstructAssets.h"
#include "minecraft/launch/ScanModFolders.h"
#include "java/launch/CheckJava.h"
#include "java/JavaUtils.h"
#include "meta/Index.h"
#include "meta/VersionList.h"
#include "mod/ModFolderModel.h"
#include "SimpleModList.h"
#include "WorldList.h"
#include "icons/IIconList.h"
@@ -551,38 +550,37 @@ QStringList MinecraftInstance::verboseDescription(AuthSessionPtr session)
out << "";
}
auto printModList = [&](const QString & label, ModFolderModel & model) {
if(model.size())
if(loaderModList()->size())
{
out << "Mods:";
for(auto & mod: loaderModList()->allMods())
{
out << QString("%1:").arg(label);
auto modList = model.allMods();
std::sort(modList.begin(), modList.end(), [](Mod &a, Mod &b) {
auto aName = a.filename().completeBaseName();
auto bName = b.filename().completeBaseName();
return aName.localeAwareCompare(bName) < 0;
});
for(auto & mod: modList)
{
if(mod.type() == Mod::MOD_FOLDER)
{
out << u8" [📁] " + mod.filename().completeBaseName() + " (folder)";
continue;
}
if(!mod.enabled())
continue;
if(mod.type() == Mod::MOD_FOLDER)
continue;
// TODO: proper implementation would need to descend into folders.
if(mod.enabled()) {
out << u8" [✔️] " + mod.filename().completeBaseName();
}
else {
out << u8" [❌] " + mod.filename().completeBaseName() + " (disabled)";
}
}
out << "";
out << " " + mod.filename().completeBaseName();
}
};
out << "";
}
printModList("Mods", *(loaderModList().get()));
printModList("Core Mods", *(coreModList().get()));
if(coreModList()->size())
{
out << "Core Mods:";
for(auto & coremod: coreModList()->allMods())
{
if(!coremod.enabled())
continue;
if(coremod.type() == Mod::MOD_FOLDER)
continue;
// TODO: proper implementation would need to descend into folders.
out << " " + coremod.filename().completeBaseName();
}
out << "";
}
auto & jarMods = profile->getJarMods();
if(jarMods.size())
@@ -650,7 +648,8 @@ QMap<QString, QString> MinecraftInstance::createCensorFilterFromSession(AuthSess
auto i = sessionRef.u.properties.begin();
while (i != sessionRef.u.properties.end())
{
if(i.value().length() <= 3) {
if(i.key() == "preferredLanguage")
{
++i;
continue;
}
@@ -829,11 +828,6 @@ shared_qobject_ptr<LaunchTask> MinecraftInstance::createLaunchTask(AuthSessionPt
process->appendStep(new ModMinecraftJar(pptr));
}
// if there are any jar mods
{
process->appendStep(new ScanModFolders(pptr));
}
// print some instance info here...
{
process->appendStep(new PrintInstanceInfo(pptr, session));
@@ -899,47 +893,43 @@ JavaVersion MinecraftInstance::getJavaVersion() const
return JavaVersion(settings()->get("JavaVersion").toString());
}
std::shared_ptr<ModFolderModel> MinecraftInstance::loaderModList() const
std::shared_ptr<SimpleModList> MinecraftInstance::loaderModList() const
{
if (!m_loader_mod_list)
{
m_loader_mod_list.reset(new ModFolderModel(loaderModsDir()));
m_loader_mod_list->disableInteraction(isRunning());
connect(this, &BaseInstance::runningStatusChanged, m_loader_mod_list.get(), &ModFolderModel::disableInteraction);
m_loader_mod_list.reset(new SimpleModList(loaderModsDir()));
}
m_loader_mod_list->update();
return m_loader_mod_list;
}
std::shared_ptr<ModFolderModel> MinecraftInstance::coreModList() const
std::shared_ptr<SimpleModList> MinecraftInstance::coreModList() const
{
if (!m_core_mod_list)
{
m_core_mod_list.reset(new ModFolderModel(coreModsDir()));
m_core_mod_list->disableInteraction(isRunning());
connect(this, &BaseInstance::runningStatusChanged, m_core_mod_list.get(), &ModFolderModel::disableInteraction);
m_core_mod_list.reset(new SimpleModList(coreModsDir()));
}
m_core_mod_list->update();
return m_core_mod_list;
}
std::shared_ptr<ModFolderModel> MinecraftInstance::resourcePackList() const
std::shared_ptr<SimpleModList> MinecraftInstance::resourcePackList() const
{
if (!m_resource_pack_list)
{
m_resource_pack_list.reset(new ModFolderModel(resourcePacksDir()));
m_resource_pack_list->disableInteraction(isRunning());
connect(this, &BaseInstance::runningStatusChanged, m_resource_pack_list.get(), &ModFolderModel::disableInteraction);
m_resource_pack_list.reset(new SimpleModList(resourcePacksDir()));
}
m_resource_pack_list->update();
return m_resource_pack_list;
}
std::shared_ptr<ModFolderModel> MinecraftInstance::texturePackList() const
std::shared_ptr<SimpleModList> MinecraftInstance::texturePackList() const
{
if (!m_texture_pack_list)
{
m_texture_pack_list.reset(new ModFolderModel(texturePacksDir()));
m_texture_pack_list->disableInteraction(isRunning());
connect(this, &BaseInstance::runningStatusChanged, m_texture_pack_list.get(), &ModFolderModel::disableInteraction);
m_texture_pack_list.reset(new SimpleModList(texturePacksDir()));
}
m_texture_pack_list->update();
return m_texture_pack_list;
}

View File

@@ -1,12 +1,13 @@
#pragma once
#include "BaseInstance.h"
#include <java/JavaVersion.h>
#include "minecraft/mod/Mod.h"
#include "minecraft/Mod.h"
#include <QProcess>
#include <QDir>
#include "multimc_logic_export.h"
class ModFolderModel;
class ModsModel;
class SimpleModList;
class WorldList;
class GameOptions;
class LaunchStep;
@@ -67,10 +68,11 @@ public:
std::shared_ptr<ComponentList> getComponentList() const;
////// Mod Lists //////
std::shared_ptr<ModFolderModel> loaderModList() const;
std::shared_ptr<ModFolderModel> coreModList() const;
std::shared_ptr<ModFolderModel> resourcePackList() const;
std::shared_ptr<ModFolderModel> texturePackList() const;
std::shared_ptr<ModsModel> modsModel() const;
std::shared_ptr<SimpleModList> loaderModList() const;
std::shared_ptr<SimpleModList> coreModList() const;
std::shared_ptr<SimpleModList> resourcePackList() const;
std::shared_ptr<SimpleModList> texturePackList() const;
std::shared_ptr<WorldList> worldList() const;
std::shared_ptr<GameOptions> gameOptionsModel() const;
@@ -111,6 +113,9 @@ public:
virtual JavaVersion getJavaVersion() const;
signals:
void versionReloaded();
protected:
QMap<QString, QString> createCensorFilterFromSession(AuthSessionPtr session);
QStringList validLaunchMethods();
@@ -121,10 +126,11 @@ private:
protected: // data
std::shared_ptr<ComponentList> m_components;
mutable std::shared_ptr<ModFolderModel> m_loader_mod_list;
mutable std::shared_ptr<ModFolderModel> m_core_mod_list;
mutable std::shared_ptr<ModFolderModel> m_resource_pack_list;
mutable std::shared_ptr<ModFolderModel> m_texture_pack_list;
mutable std::shared_ptr<ModsModel> m_mods_model;
mutable std::shared_ptr<SimpleModList> m_loader_mod_list;
mutable std::shared_ptr<SimpleModList> m_core_mod_list;
mutable std::shared_ptr<SimpleModList> m_resource_pack_list;
mutable std::shared_ptr<SimpleModList> m_texture_pack_list;
mutable std::shared_ptr<WorldList> m_world_list;
mutable std::shared_ptr<GameOptions> m_game_options;
};

433
api/logic/minecraft/Mod.cpp Normal file
View File

@@ -0,0 +1,433 @@
/* Copyright 2013-2019 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 <QDir>
#include <QString>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <quazip.h>
#include <quazipfile.h>
#include "Mod.h"
#include "settings/INIFile.h"
#include <FileSystem.h>
#include <QDebug>
Mod::Mod(const QFileInfo &file)
{
repath(file);
m_changedDateTime = file.lastModified();
}
void Mod::repath(const QFileInfo &file)
{
m_file = file;
QString name_base = file.fileName();
m_type = Mod::MOD_UNKNOWN;
if (m_file.isDir())
{
m_type = MOD_FOLDER;
m_name = name_base;
m_mmc_id = name_base;
}
else if (m_file.isFile())
{
if (name_base.endsWith(".disabled"))
{
m_enabled = false;
name_base.chop(9);
}
else
{
m_enabled = true;
}
m_mmc_id = name_base;
if (name_base.endsWith(".zip") || name_base.endsWith(".jar"))
{
m_type = MOD_ZIPFILE;
name_base.chop(4);
}
else if (name_base.endsWith(".litemod"))
{
m_type = MOD_LITEMOD;
name_base.chop(8);
}
else
{
m_type = MOD_SINGLEFILE;
}
m_name = name_base;
}
if (m_type == MOD_ZIPFILE)
{
QuaZip zip(m_file.filePath());
if (!zip.open(QuaZip::mdUnzip))
return;
QuaZipFile file(&zip);
if (zip.setCurrentFile("mcmod.info"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
ReadMCModInfo(file.readAll());
file.close();
zip.close();
return;
}
else if (zip.setCurrentFile("fabric.mod.json"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
ReadFabricModInfo(file.readAll());
file.close();
zip.close();
return;
}
else if (zip.setCurrentFile("forgeversion.properties"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
ReadForgeInfo(file.readAll());
file.close();
zip.close();
return;
}
zip.close();
}
else if (m_type == MOD_FOLDER)
{
QFileInfo mcmod_info(FS::PathCombine(m_file.filePath(), "mcmod.info"));
if (mcmod_info.isFile())
{
QFile mcmod(mcmod_info.filePath());
if (!mcmod.open(QIODevice::ReadOnly))
return;
auto data = mcmod.readAll();
if (data.isEmpty() || data.isNull())
return;
ReadMCModInfo(data);
}
}
else if (m_type == MOD_LITEMOD)
{
QuaZip zip(m_file.filePath());
if (!zip.open(QuaZip::mdUnzip))
return;
QuaZipFile file(&zip);
if (zip.setCurrentFile("litemod.json"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
ReadLiteModInfo(file.readAll());
file.close();
}
zip.close();
}
}
// NEW format
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/6f62b37cea040daf350dc253eae6326dd9c822c3
// OLD format:
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc
void Mod::ReadMCModInfo(QByteArray contents)
{
auto getInfoFromArray = [&](QJsonArray arr)->void
{
if (!arr.at(0).isObject())
return;
auto firstObj = arr.at(0).toObject();
m_mod_id = firstObj.value("modid").toString();
m_name = firstObj.value("name").toString();
m_version = firstObj.value("version").toString();
m_homeurl = firstObj.value("url").toString();
m_updateurl = firstObj.value("updateUrl").toString();
m_homeurl = m_homeurl.trimmed();
if(!m_homeurl.isEmpty())
{
// fix up url.
if (!m_homeurl.startsWith("http://") && !m_homeurl.startsWith("https://") &&
!m_homeurl.startsWith("ftp://"))
{
m_homeurl.prepend("http://");
}
}
m_description = firstObj.value("description").toString();
QJsonArray authors = firstObj.value("authorList").toArray();
if (authors.size() == 0)
authors = firstObj.value("authors").toArray();
if (authors.size() == 0)
m_authors = "";
else if (authors.size() >= 1)
{
m_authors = authors.at(0).toString();
for (int i = 1; i < authors.size(); i++)
{
m_authors += ", " + authors.at(i).toString();
}
}
m_credits = firstObj.value("credits").toString();
return;
}
;
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
// this is the very old format that had just the array
if (jsonDoc.isArray())
{
getInfoFromArray(jsonDoc.array());
}
else if (jsonDoc.isObject())
{
auto val = jsonDoc.object().value("modinfoversion");
if(val.isUndefined())
val = jsonDoc.object().value("modListVersion");
int version = val.toDouble();
if (version != 2)
{
qCritical() << "BAD stuff happened to mod json:";
qCritical() << contents;
return;
}
auto arrVal = jsonDoc.object().value("modlist");
if(arrVal.isUndefined())
arrVal = jsonDoc.object().value("modList");
if (arrVal.isArray())
{
getInfoFromArray(arrVal.toArray());
}
}
}
// https://fabricmc.net/wiki/documentation:fabric_mod_json
void Mod::ReadFabricModInfo(QByteArray contents)
{
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
auto object = jsonDoc.object();
auto schemaVersion = object.contains("schemaVersion") ? object.value("schemaVersion").toInt(0) : 0;
m_mod_id = object.value("id").toString();
m_version = object.value("version").toString();
m_name = object.contains("name") ? object.value("name").toString() : m_mod_id;
m_description = object.value("description").toString();
if (schemaVersion >= 1)
{
QJsonArray authors = object.value("authors").toArray();
m_authors = "";
for (int i = 0; i < authors.size(); i++)
{
QString author_name = authors.at(i).isObject()
? authors.at(i).toObject().value("name").toString()
: authors.at(i).toString();
if (i > 0)
m_authors += ", " + author_name;
else {
m_authors += author_name;
}
}
if (object.contains("contact"))
{
QJsonObject contact = object.value("contact").toObject();
if (contact.contains("homepage"))
m_homeurl = contact.value("homepage").toString();
}
}
}
void Mod::ReadForgeInfo(QByteArray contents)
{
// Read the data
m_name = "Minecraft Forge";
m_mod_id = "Forge";
m_homeurl = "http://www.minecraftforge.net/forum/";
INIFile ini;
if (!ini.loadFile(contents))
return;
QString major = ini.get("forge.major.number", "0").toString();
QString minor = ini.get("forge.minor.number", "0").toString();
QString revision = ini.get("forge.revision.number", "0").toString();
QString build = ini.get("forge.build.number", "0").toString();
m_version = major + "." + minor + "." + revision + "." + build;
}
void Mod::ReadLiteModInfo(QByteArray contents)
{
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
auto object = jsonDoc.object();
if (object.contains("name"))
{
m_mod_id = m_name = object.value("name").toString();
}
if (object.contains("version"))
{
m_version = object.value("version").toString("");
}
else
{
m_version = object.value("revision").toString("");
}
m_mcversion = object.value("mcversion").toString();
m_authors = object.value("author").toString();
m_description = object.value("description").toString();
m_homeurl = object.value("url").toString();
}
bool Mod::replace(Mod &with)
{
if (!destroy())
return false;
bool success = false;
auto t = with.type();
if (t == MOD_ZIPFILE || t == MOD_SINGLEFILE || t == MOD_LITEMOD)
{
qDebug() << "Copy: " << with.m_file.filePath() << " to " << m_file.filePath();
success = QFile::copy(with.m_file.filePath(), m_file.filePath());
}
if (t == MOD_FOLDER)
{
success = FS::copy(with.m_file.filePath(), m_file.path())();
}
if (success)
{
m_name = with.m_name;
m_mmc_id = with.m_mmc_id;
m_mod_id = with.m_mod_id;
m_version = with.m_version;
m_mcversion = with.m_mcversion;
m_description = with.m_description;
m_authors = with.m_authors;
m_credits = with.m_credits;
m_homeurl = with.m_homeurl;
m_type = with.m_type;
m_file.refresh();
}
return success;
}
bool Mod::destroy()
{
if (m_type == MOD_FOLDER)
{
QDir d(m_file.filePath());
if (d.removeRecursively())
{
m_type = MOD_UNKNOWN;
return true;
}
return false;
}
else if (m_type == MOD_SINGLEFILE || m_type == MOD_ZIPFILE || m_type == MOD_LITEMOD)
{
QFile f(m_file.filePath());
if (f.remove())
{
m_type = MOD_UNKNOWN;
return true;
}
return false;
}
return true;
}
QString Mod::version() const
{
switch (type())
{
case MOD_ZIPFILE:
case MOD_LITEMOD:
return m_version;
case MOD_FOLDER:
return "Folder";
case MOD_SINGLEFILE:
return "File";
default:
return "VOID";
}
}
bool Mod::enable(bool value)
{
if (m_type == Mod::MOD_UNKNOWN || m_type == Mod::MOD_FOLDER)
return false;
if (m_enabled == value)
return false;
QString path = m_file.absoluteFilePath();
if (value)
{
QFile foo(path);
if (!path.endsWith(".disabled"))
return false;
path.chop(9);
if (!foo.rename(path))
return false;
}
else
{
QFile foo(path);
path += ".disabled";
if (!foo.rename(path))
return false;
}
m_file = QFileInfo(path);
m_enabled = value;
return true;
}
bool Mod::operator==(const Mod &other) const
{
return mmc_id() == other.mmc_id();
}
bool Mod::strongCompare(const Mod &other) const
{
return mmc_id() == other.mmc_id() && version() == other.version() && type() == other.type();
}

View File

@@ -16,16 +16,8 @@
#pragma once
#include <QFileInfo>
#include <QDateTime>
#include <QList>
#include <memory>
#include "multimc_logic_export.h"
#include "ModDetails.h"
class MULTIMC_LOGIC_EXPORT Mod
class Mod
{
public:
enum ModType
@@ -37,7 +29,6 @@ public:
MOD_LITEMOD, //!< The mod is a litemod
};
Mod() = default;
Mod(const QFileInfo &file);
QFileInfo filename() const
@@ -48,14 +39,54 @@ public:
{
return m_mmc_id;
}
QString mod_id() const
{
return m_mod_id;
}
ModType type() const
{
return m_type;
}
QString mcversion() const
{
return m_mcversion;
}
;
bool valid()
{
return m_type != MOD_UNKNOWN;
}
QString name() const
{
QString name = m_name.trimmed();
if(name.isEmpty() || name == "Example Mod")
{
return m_mmc_id;
}
return m_name;
}
QString version() const;
QString homeurl() const
{
return m_homeurl;
}
QString description() const
{
return m_description;
}
QString authors() const
{
return m_authors;
}
QString credits() const
{
return m_credits;
}
QDateTime dateTimeChanged() const
{
@@ -67,51 +98,46 @@ public:
return m_enabled;
}
const ModDetails &details() const;
QString name() const;
QString version() const;
QString homeurl() const;
QString description() const;
QStringList authors() const;
bool enable(bool value);
// delete all the files of this mod
bool destroy();
// replace this mod with a copy of the other
bool replace(Mod &with);
// change the mod's filesystem path (used by mod lists for *MAGIC* purposes)
void repath(const QFileInfo &file);
bool shouldResolve() {
return !m_resolving && !m_resolved;
}
bool isResolving() {
return m_resolving;
}
int resolutionTicket()
{
return m_resolutionTicket;
}
void setResolving(bool resolving, int resolutionTicket) {
m_resolving = resolving;
m_resolutionTicket = resolutionTicket;
}
void finishResolvingWithDetails(std::shared_ptr<ModDetails> details){
m_resolving = false;
m_resolved = true;
m_localDetails = details;
}
// WEAK compare operator - used for replacing mods
bool operator==(const Mod &other) const;
bool strongCompare(const Mod &other) const;
private:
void ReadMCModInfo(QByteArray contents);
void ReadFabricModInfo(QByteArray contents);
void ReadForgeInfo(QByteArray contents);
void ReadLiteModInfo(QByteArray contents);
protected:
// FIXME: what do do with those? HMM...
/*
void ReadModInfoData(QString info);
void ReadForgeInfoData(QString infoFileData);
*/
QFileInfo m_file;
QDateTime m_changedDateTime;
QString m_mmc_id;
QString m_name;
QString m_mod_id;
bool m_enabled = true;
bool m_resolving = false;
bool m_resolved = false;
int m_resolutionTicket = 0;
ModType m_type = MOD_UNKNOWN;
std::shared_ptr<ModDetails> m_localDetails;
QString m_name;
QString m_version;
QString m_mcversion;
QString m_homeurl;
QString m_updateurl;
QString m_description;
QString m_authors;
QString m_credits;
ModType m_type;
};

View File

@@ -33,7 +33,7 @@ slots:
auto time_parsed = timeFromS3Time(timestamp);
auto time_serialized = timeToS3Time(time_parsed);
QCOMPARE(time_serialized, timestamp);
}

View File

@@ -13,7 +13,7 @@
* limitations under the License.
*/
#include "ModFolderModel.h"
#include "SimpleModList.h"
#include <FileSystem.h>
#include <QMimeData>
#include <QUrl>
@@ -21,21 +21,18 @@
#include <QString>
#include <QFileSystemWatcher>
#include <QDebug>
#include "ModFolderLoadTask.h"
#include <QThreadPool>
#include <algorithm>
#include "LocalModParseTask.h"
ModFolderModel::ModFolderModel(const QString &dir) : QAbstractListModel(), m_dir(dir)
SimpleModList::SimpleModList(const QString &dir) : QAbstractListModel(), m_dir(dir)
{
FS::ensureFolderPathExists(m_dir.absolutePath());
m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs | QDir::NoSymLinks);
m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs |
QDir::NoSymLinks);
m_dir.setSorting(QDir::Name | QDir::IgnoreCase | QDir::LocaleAware);
m_watcher = new QFileSystemWatcher(this);
connect(m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(directoryChanged(QString)));
}
void ModFolderModel::startWatching()
void SimpleModList::startWatching()
{
if(is_watching)
return;
@@ -53,7 +50,7 @@ void ModFolderModel::startWatching()
}
}
void ModFolderModel::stopWatching()
void SimpleModList::stopWatching()
{
if(!is_watching)
return;
@@ -69,164 +66,39 @@ void ModFolderModel::stopWatching()
}
}
bool ModFolderModel::update()
bool SimpleModList::update()
{
if (!isValid()) {
if (!isValid())
return false;
}
if(m_update) {
scheduled_update = true;
return true;
QList<Mod> newMods;
m_dir.refresh();
for (auto entry : m_dir.entryInfoList())
{
newMods.append(Mod(entry));
}
auto task = new ModFolderLoadTask(m_dir);
m_update = task->result();
QThreadPool *threadPool = QThreadPool::globalInstance();
connect(task, &ModFolderLoadTask::succeeded, this, &ModFolderModel::finishUpdate);
threadPool->start(task);
beginResetModel();
mods.swap(newMods);
endResetModel();
emit changed();
return true;
}
void ModFolderModel::finishUpdate()
{
QSet<QString> currentSet = modsIndex.keys().toSet();
auto & newMods = m_update->mods;
QSet<QString> newSet = newMods.keys().toSet();
// see if the kept mods changed in some way
{
QSet<QString> kept = currentSet;
kept.intersect(newSet);
for(auto & keptMod: kept) {
auto & newMod = newMods[keptMod];
auto row = modsIndex[keptMod];
auto & currentMod = mods[row];
if(newMod.dateTimeChanged() == currentMod.dateTimeChanged()) {
// no significant change, ignore...
continue;
}
auto & oldMod = mods[row];
if(oldMod.isResolving()) {
activeTickets.remove(oldMod.resolutionTicket());
}
oldMod = newMod;
resolveMod(mods[row]);
emit dataChanged(index(row, 0), index(row, columnCount(QModelIndex()) - 1));
}
}
// remove mods no longer present
{
QSet<QString> removed = currentSet;
QList<int> removedRows;
removed.subtract(newSet);
for(auto & removedMod: removed) {
removedRows.append(modsIndex[removedMod]);
}
std::sort(removedRows.begin(), removedRows.end(), std::greater<int>());
for(auto iter = removedRows.begin(); iter != removedRows.end(); iter++) {
int removedIndex = *iter;
beginRemoveRows(QModelIndex(), removedIndex, removedIndex);
auto removedIter = mods.begin() + removedIndex;
if(removedIter->isResolving()) {
activeTickets.remove(removedIter->resolutionTicket());
}
mods.erase(removedIter);
endRemoveRows();
}
}
// add new mods to the end
{
QSet<QString> added = newSet;
added.subtract(currentSet);
beginInsertRows(QModelIndex(), mods.size(), mods.size() + added.size() - 1);
for(auto & addedMod: added) {
mods.append(newMods[addedMod]);
resolveMod(mods.last());
}
endInsertRows();
}
// update index
{
modsIndex.clear();
int idx = 0;
for(auto & mod: mods) {
modsIndex[mod.mmc_id()] = idx;
idx++;
}
}
m_update.reset();
emit updateFinished();
if(scheduled_update) {
scheduled_update = false;
update();
}
}
void ModFolderModel::resolveMod(Mod& m)
{
if(!m.shouldResolve()) {
return;
}
auto task = new LocalModParseTask(nextResolutionTicket, m.type(), m.filename());
auto result = task->result();
result->id = m.mmc_id();
activeTickets.insert(nextResolutionTicket, result);
m.setResolving(true, nextResolutionTicket);
nextResolutionTicket++;
QThreadPool *threadPool = QThreadPool::globalInstance();
connect(task, &LocalModParseTask::finished, this, &ModFolderModel::finishModParse);
threadPool->start(task);
}
void ModFolderModel::finishModParse(int token)
{
auto iter = activeTickets.find(token);
if(iter == activeTickets.end()) {
return;
}
auto result = *iter;
activeTickets.remove(token);
int row = modsIndex[result->id];
auto & mod = mods[row];
mod.finishResolvingWithDetails(result->details);
emit dataChanged(index(row), index(row, columnCount(QModelIndex()) - 1));
}
void ModFolderModel::disableInteraction(bool disabled)
{
if (interaction_disabled == disabled) {
return;
}
interaction_disabled = disabled;
if(size()) {
emit dataChanged(index(0), index(size() - 1));
}
}
void ModFolderModel::directoryChanged(QString path)
void SimpleModList::directoryChanged(QString path)
{
update();
}
bool ModFolderModel::isValid()
bool SimpleModList::isValid()
{
return m_dir.exists() && m_dir.isReadable();
}
// FIXME: this does not take disabled mod (with extra .disable extension) into account...
bool ModFolderModel::installMod(const QString &filename)
bool SimpleModList::installMod(const QString &filename)
{
if(interaction_disabled) {
return false;
}
// NOTE: fix for GH-1178: remove trailing slash to avoid issues with using the empty result of QFileInfo::fileName
auto originalPath = FS::NormalizePath(filename);
QFileInfo fileinfo(originalPath);
@@ -303,31 +175,23 @@ bool ModFolderModel::installMod(const QString &filename)
return false;
}
bool ModFolderModel::setModStatus(const QModelIndexList& indexes, ModStatusAction enable)
bool SimpleModList::enableMods(const QModelIndexList& indexes, bool enable)
{
if(interaction_disabled) {
return false;
}
if(indexes.isEmpty())
return true;
for (auto index: indexes)
for (auto i: indexes)
{
if(index.column() != 0) {
continue;
}
setModStatus(index.row(), enable);
Mod &m = mods[i.row()];
m.enable(enable);
emit dataChanged(i, i);
}
emit changed();
return true;
}
bool ModFolderModel::deleteMods(const QModelIndexList& indexes)
bool SimpleModList::deleteMods(const QModelIndexList& indexes)
{
if(interaction_disabled) {
return false;
}
if(indexes.isEmpty())
return true;
@@ -336,15 +200,16 @@ bool ModFolderModel::deleteMods(const QModelIndexList& indexes)
Mod &m = mods[i.row()];
m.destroy();
}
emit changed();
return true;
}
int ModFolderModel::columnCount(const QModelIndex &parent) const
int SimpleModList::columnCount(const QModelIndex &parent) const
{
return NUM_COLUMNS;
}
QVariant ModFolderModel::data(const QModelIndex &index, int role) const
QVariant SimpleModList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
@@ -362,17 +227,8 @@ QVariant ModFolderModel::data(const QModelIndex &index, int role) const
{
case NameColumn:
return mods[row].name();
case VersionColumn: {
switch(mods[row].type()) {
case Mod::MOD_FOLDER:
return tr("Folder");
case Mod::MOD_SINGLEFILE:
return tr("File");
default:
break;
}
case VersionColumn:
return mods[row].version();
}
case DateColumn:
return mods[row].dateTimeChanged();
@@ -396,7 +252,7 @@ QVariant ModFolderModel::data(const QModelIndex &index, int role) const
}
}
bool ModFolderModel::setData(const QModelIndex &index, const QVariant &value, int role)
bool SimpleModList::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.row() < 0 || index.row() >= rowCount(index) || !index.isValid())
{
@@ -405,53 +261,17 @@ bool ModFolderModel::setData(const QModelIndex &index, const QVariant &value, in
if (role == Qt::CheckStateRole)
{
return setModStatus(index.row(), Toggle);
auto &mod = mods[index.row()];
if (mod.enable(!mod.enabled()))
{
emit dataChanged(index, index);
return true;
}
}
return false;
}
bool ModFolderModel::setModStatus(int row, ModFolderModel::ModStatusAction action)
{
if(row < 0 || row >= mods.size()) {
return false;
}
auto &mod = mods[row];
bool desiredStatus;
switch(action) {
case Enable:
desiredStatus = true;
break;
case Disable:
desiredStatus = false;
break;
case Toggle:
default:
desiredStatus = !mod.enabled();
break;
}
if(desiredStatus == mod.enabled()) {
return true;
}
// preserve the row, but change its ID
auto oldId = mod.mmc_id();
if(!mod.enable(!mod.enabled())) {
return false;
}
auto newId = mod.mmc_id();
if(modsIndex.contains(newId)) {
// NOTE: this could handle a corner case, where we are overwriting a file, because the same 'mod' exists both enabled and disabled
// But is it necessary?
}
modsIndex.remove(oldId);
modsIndex[newId] = row;
emit dataChanged(index(row, 0), index(row, columnCount(QModelIndex()) - 1));
return true;
}
QVariant ModFolderModel::headerData(int section, Qt::Orientation orientation, int role) const
QVariant SimpleModList::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role)
{
@@ -490,37 +310,30 @@ QVariant ModFolderModel::headerData(int section, Qt::Orientation orientation, in
return QVariant();
}
Qt::ItemFlags ModFolderModel::flags(const QModelIndex &index) const
Qt::ItemFlags SimpleModList::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);
auto flags = defaultFlags;
if(interaction_disabled) {
flags &= ~Qt::ItemIsDropEnabled;
}
if (index.isValid())
return Qt::ItemIsUserCheckable | Qt::ItemIsDropEnabled |
defaultFlags;
else
{
flags |= Qt::ItemIsDropEnabled;
if(index.isValid()) {
flags |= Qt::ItemIsUserCheckable;
}
}
return flags;
return Qt::ItemIsDropEnabled | defaultFlags;
}
Qt::DropActions ModFolderModel::supportedDropActions() const
Qt::DropActions SimpleModList::supportedDropActions() const
{
// copy from outside, move from within and other mod lists
return Qt::CopyAction | Qt::MoveAction;
}
QStringList ModFolderModel::mimeTypes() const
QStringList SimpleModList::mimeTypes() const
{
QStringList types;
types << "text/uri-list";
return types;
}
bool ModFolderModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int, int, const QModelIndex&)
bool SimpleModList::dropMimeData(const QMimeData* data, Qt::DropAction action, int, int, const QModelIndex&)
{
if (action == Qt::IgnoreAction)
{

View File

@@ -16,17 +16,13 @@
#pragma once
#include <QList>
#include <QMap>
#include <QSet>
#include <QString>
#include <QDir>
#include <QAbstractListModel>
#include "Mod.h"
#include "minecraft/Mod.h"
#include "multimc_logic_export.h"
#include "ModFolderLoadTask.h"
#include "LocalModParseTask.h"
class LegacyInstance;
class BaseInstance;
@@ -36,7 +32,7 @@ class QFileSystemWatcher;
* A legacy mod list.
* Backed by a folder.
*/
class MULTIMC_LOGIC_EXPORT ModFolderModel : public QAbstractListModel
class MULTIMC_LOGIC_EXPORT SimpleModList : public QAbstractListModel
{
Q_OBJECT
public:
@@ -44,16 +40,11 @@ public:
{
ActiveColumn = 0,
NameColumn,
VersionColumn,
DateColumn,
VersionColumn,
NUM_COLUMNS
};
enum ModStatusAction {
Disable,
Enable,
Toggle
};
ModFolderModel(const QString &dir);
SimpleModList(const QString &dir);
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
@@ -87,7 +78,7 @@ public:
}
/// Reloads the mod list and returns true if the list changed.
bool update();
virtual bool update();
/**
* Adds the given mod to the list at the given index - if the list supports custom ordering
@@ -95,15 +86,15 @@ public:
bool installMod(const QString& filename);
/// Deletes all the selected mods
bool deleteMods(const QModelIndexList &indexes);
virtual bool deleteMods(const QModelIndexList &indexes);
/// Enable or disable listed mods
bool setModStatus(const QModelIndexList &indexes, ModStatusAction action);
virtual bool enableMods(const QModelIndexList &indexes, bool enable = true);
void startWatching();
void stopWatching();
bool isValid();
virtual bool isValid();
QDir dir()
{
@@ -115,31 +106,16 @@ public:
return mods;
}
public slots:
void disableInteraction(bool disabled);
private
slots:
void directoryChanged(QString path);
void finishUpdate();
void finishModParse(int token);
signals:
void updateFinished();
private:
void resolveMod(Mod& m);
bool setModStatus(int index, ModStatusAction action);
void changed();
protected:
QFileSystemWatcher *m_watcher;
bool is_watching = false;
ModFolderLoadTask::ResultPtr m_update;
bool scheduled_update = false;
bool interaction_disabled = false;
QDir m_dir;
QMap<QString, int> modsIndex;
QMap<int, LocalModParseTask::ResultPtr> activeTickets;
int nextResolutionTicket = 0;
QList<Mod> mods;
};

View File

@@ -4,9 +4,9 @@
#include "TestUtil.h"
#include "FileSystem.h"
#include "minecraft/mod/ModFolderModel.h"
#include "minecraft/SimpleModList.h"
class ModFolderModelTest : public QObject
class SimpleModListTest : public QObject
{
Q_OBJECT
@@ -32,7 +32,7 @@ slots:
{
QString folder = source;
QTemporaryDir tempDir;
ModFolderModel m(tempDir.path());
SimpleModList m(tempDir.path());
m.installMod(folder);
verify(tempDir.path());
}
@@ -41,13 +41,13 @@ slots:
{
QString folder = source + '/';
QTemporaryDir tempDir;
ModFolderModel m(tempDir.path());
SimpleModList m(tempDir.path());
m.installMod(folder);
verify(tempDir.path());
}
}
};
QTEST_GUILESS_MAIN(ModFolderModelTest)
QTEST_GUILESS_MAIN(SimpleModListTest)
#include "ModFolderModel_test.moc"
#include "SimpleModList_test.moc"

View File

@@ -429,3 +429,7 @@ bool World::operator==(const World &other) const
{
return is_valid == other.is_valid && folderName() == other.folderName();
}
bool World::strongCompare(const World &other) const
{
return is_valid == other.is_valid && folderName() == other.folderName();
}

View File

@@ -76,6 +76,7 @@ public:
// WEAK compare operator - used for replacing worlds
bool operator==(const World &other) const;
bool strongCompare(const World &other) const;
private:
void readFromZip(const QFileInfo &file);

View File

@@ -1,54 +0,0 @@
/* Copyright 2013-2019 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 "ScanModFolders.h"
#include "launch/LaunchTask.h"
#include "MMCZip.h"
#include "minecraft/OpSys.h"
#include "FileSystem.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/mod/ModFolderModel.h"
void ScanModFolders::executeTask()
{
auto m_inst = std::dynamic_pointer_cast<MinecraftInstance>(m_parent->instance());
auto loaders = m_inst->loaderModList();
connect(loaders.get(), &ModFolderModel::updateFinished, this, &ScanModFolders::modsDone);
loaders->update();
auto cores = m_inst->coreModList();
connect(cores.get(), &ModFolderModel::updateFinished, this, &ScanModFolders::coreModsDone);
cores->update();
}
void ScanModFolders::modsDone()
{
m_modsDone = true;
checkDone();
}
void ScanModFolders::coreModsDone()
{
m_coreModsDone = true;
checkDone();
}
void ScanModFolders::checkDone()
{
if(m_modsDone && m_coreModsDone) {
emitSucceeded();
}
}

View File

@@ -1,42 +0,0 @@
/* Copyright 2013-2019 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 <launch/LaunchStep.h>
#include <memory>
class ScanModFolders: public LaunchStep
{
Q_OBJECT
public:
explicit ScanModFolders(LaunchTask *parent) : LaunchStep(parent) {};
virtual ~ScanModFolders(){};
virtual void executeTask() override;
virtual bool canAbort() const override
{
return false;
}
private slots:
void coreModsDone();
void modsDone();
private:
void checkDone();
private: // DATA
bool m_modsDone = false;
bool m_coreModsDone = false;
};

View File

@@ -21,6 +21,7 @@
#include "LegacyInstance.h"
#include "minecraft/legacy/LegacyModList.h"
#include "minecraft/SimpleModList.h"
#include "minecraft/WorldList.h"
#include <MMCZip.h>
#include <FileSystem.h>
@@ -106,6 +107,11 @@ std::shared_ptr<LegacyModList> LegacyInstance::jarModList() const
return jar_mod_list;
}
QList<Mod> LegacyInstance::getJarMods() const
{
return jarModList()->allMods();
}
QString LegacyInstance::gameRoot() const
{
QFileInfo mcDir(FS::PathCombine(instanceRoot(), "minecraft"));

View File

@@ -16,11 +16,12 @@
#pragma once
#include "BaseInstance.h"
#include "minecraft/Mod.h"
#include "launch/LaunchTask.h"
#include "multimc_logic_export.h"
class ModFolderModel;
class SimpleModList;
class LegacyModList;
class WorldList;
class Task;
@@ -77,6 +78,7 @@ public:
QString customBaseJar() const;
std::shared_ptr<LegacyModList> jarModList() const;
QList<Mod> getJarMods() const;
std::shared_ptr<WorldList> worldList() const;
/*!

View File

@@ -22,7 +22,8 @@ LegacyModList::LegacyModList(const QString &dir, const QString &list_file)
: m_dir(dir), m_list_file(list_file)
{
FS::ensureFolderPathExists(m_dir.absolutePath());
m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs | QDir::NoSymLinks);
m_dir.setFilter(QDir::Readable | QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs |
QDir::NoSymLinks);
m_dir.setSorting(QDir::Name | QDir::IgnoreCase | QDir::LocaleAware);
}
@@ -33,11 +34,15 @@ LegacyModList::LegacyModList(const QString &dir, const QString &list_file)
};
typedef QList<OrderItem> OrderList;
static void internalSort(QList<LegacyModList::Mod> &what)
static void internalSort(QList<Mod> &what)
{
auto predicate = [](const LegacyModList::Mod &left, const LegacyModList::Mod &right)
auto predicate = [](const Mod &left, const Mod &right)
{
return left.fileName().localeAwareCompare(right.fileName()) < 0;
if (left.name() == right.name())
{
return left.mmc_id().localeAwareCompare(right.mmc_id()) < 0;
}
return left.name().localeAwareCompare(right.name()) < 0;
};
std::sort(what.begin(), what.end(), predicate);
}
@@ -85,6 +90,7 @@ bool LegacyModList::update()
QList<Mod> newMods;
m_dir.refresh();
auto folderContents = m_dir.entryInfoList();
bool orderOrStateChanged = false;
// first, process the ordered items (if any)
OrderList listOrder = readListFile(m_list_file);
@@ -118,19 +124,48 @@ bool LegacyModList::update()
// remove from the actual folder contents list
folderContents.takeAt(idx);
// append the new mod
orderedMods.append(info);
orderedMods.append(Mod(info));
if (isEnabled != item.enabled)
orderOrStateChanged = true;
}
else
{
orderOrStateChanged = true;
}
}
// if there are any untracked files... append them sorted at the end
// if there are any untracked files...
if (folderContents.size())
{
// the order surely changed!
for (auto entry : folderContents)
{
newMods.append(entry);
newMods.append(Mod(entry));
}
internalSort(newMods);
orderedMods.append(newMods);
orderOrStateChanged = true;
}
// otherwise, if we were already tracking some mods
else if (mods.size())
{
// if the number doesn't match, order changed.
if (mods.size() != orderedMods.size())
orderOrStateChanged = true;
// if it does match, compare the mods themselves
else
for (int i = 0; i < mods.size(); i++)
{
if (!mods[i].strongCompare(orderedMods[i]))
{
orderOrStateChanged = true;
break;
}
}
}
mods.swap(orderedMods);
if (orderOrStateChanged && !m_list_file.isEmpty())
{
qDebug() << "Mod list " << m_list_file << " changed!";
}
return true;
}

View File

@@ -19,14 +19,21 @@
#include <QString>
#include <QDir>
#include "minecraft/Mod.h"
#include "multimc_logic_export.h"
class LegacyInstance;
class BaseInstance;
/**
* A legacy mod list.
* Backed by a folder.
*/
class MULTIMC_LOGIC_EXPORT LegacyModList
{
public:
using Mod = QFileInfo;
LegacyModList(const QString &dir, const QString &list_file = QString());
/// Reloads the mod list and returns true if the list changed.

View File

@@ -7,7 +7,6 @@
#include "LegacyInstance.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/ComponentList.h"
#include "LegacyModList.h"
#include "classparser.h"
LegacyUpgradeTask::LegacyUpgradeTask(InstancePtr origInstance)
@@ -97,10 +96,10 @@ void LegacyUpgradeTask::copyFinished()
components->installCustomJar(jarPath);
}
auto jarMods = legacyInst->jarModList()->allMods();
auto jarMods = legacyInst->getJarMods();
for(auto & jarMod: jarMods)
{
QString modPath = jarMod.absoluteFilePath();
QString modPath = jarMod.filename().absoluteFilePath();
qDebug() << "jarMod: " << modPath;
components->installJarMods({modPath});
}

View File

@@ -1,298 +0,0 @@
#include "LocalModParseTask.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <quazip.h>
#include <quazipfile.h>
#include "settings/INIFile.h"
#include "FileSystem.h"
namespace {
// NEW format
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/6f62b37cea040daf350dc253eae6326dd9c822c3
// OLD format:
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc
std::shared_ptr<ModDetails> ReadMCModInfo(QByteArray contents)
{
auto getInfoFromArray = [&](QJsonArray arr)->std::shared_ptr<ModDetails>
{
if (!arr.at(0).isObject()) {
return nullptr;
}
std::shared_ptr<ModDetails> details = std::make_shared<ModDetails>();
auto firstObj = arr.at(0).toObject();
details->mod_id = firstObj.value("modid").toString();
auto name = firstObj.value("name").toString();
// NOTE: ignore stupid example mods copies where the author didn't even bother to change the name
if(name != "Example Mod") {
details->name = name;
}
details->version = firstObj.value("version").toString();
details->updateurl = firstObj.value("updateUrl").toString();
auto homeurl = firstObj.value("url").toString().trimmed();
if(!homeurl.isEmpty())
{
// fix up url.
if (!homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://"))
{
homeurl.prepend("http://");
}
}
details->homeurl = homeurl;
details->description = firstObj.value("description").toString();
QJsonArray authors = firstObj.value("authorList").toArray();
if (authors.size() == 0) {
// FIXME: what is the format of this? is there any?
authors = firstObj.value("authors").toArray();
}
for (auto author: authors)
{
details->authors.append(author.toString());
}
details->credits = firstObj.value("credits").toString();
return details;
};
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
// this is the very old format that had just the array
if (jsonDoc.isArray())
{
return getInfoFromArray(jsonDoc.array());
}
else if (jsonDoc.isObject())
{
auto val = jsonDoc.object().value("modinfoversion");
if(val.isUndefined()) {
val = jsonDoc.object().value("modListVersion");
}
int version = val.toDouble();
if (version != 2)
{
qCritical() << "BAD stuff happened to mod json:";
qCritical() << contents;
return nullptr;
}
auto arrVal = jsonDoc.object().value("modlist");
if(arrVal.isUndefined()) {
arrVal = jsonDoc.object().value("modList");
}
if (arrVal.isArray())
{
return getInfoFromArray(arrVal.toArray());
}
}
return nullptr;
}
// https://fabricmc.net/wiki/documentation:fabric_mod_json
std::shared_ptr<ModDetails> ReadFabricModInfo(QByteArray contents)
{
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
auto object = jsonDoc.object();
auto schemaVersion = object.contains("schemaVersion") ? object.value("schemaVersion").toInt(0) : 0;
std::shared_ptr<ModDetails> details = std::make_shared<ModDetails>();
details->mod_id = object.value("id").toString();
details->version = object.value("version").toString();
details->name = object.contains("name") ? object.value("name").toString() : details->mod_id;
details->description = object.value("description").toString();
if (schemaVersion >= 1)
{
QJsonArray authors = object.value("authors").toArray();
for (auto author: authors)
{
if(author.isObject()) {
details->authors.append(author.toObject().value("name").toString());
}
else {
details->authors.append(author.toString());
}
}
if (object.contains("contact"))
{
QJsonObject contact = object.value("contact").toObject();
if (contact.contains("homepage"))
{
details->homeurl = contact.value("homepage").toString();
}
}
}
return details;
}
std::shared_ptr<ModDetails> ReadForgeInfo(QByteArray contents)
{
std::shared_ptr<ModDetails> details = std::make_shared<ModDetails>();
// Read the data
details->name = "Minecraft Forge";
details->mod_id = "Forge";
details->homeurl = "http://www.minecraftforge.net/forum/";
INIFile ini;
if (!ini.loadFile(contents))
return details;
QString major = ini.get("forge.major.number", "0").toString();
QString minor = ini.get("forge.minor.number", "0").toString();
QString revision = ini.get("forge.revision.number", "0").toString();
QString build = ini.get("forge.build.number", "0").toString();
details->version = major + "." + minor + "." + revision + "." + build;
return details;
}
std::shared_ptr<ModDetails> ReadLiteModInfo(QByteArray contents)
{
std::shared_ptr<ModDetails> details = std::make_shared<ModDetails>();
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
auto object = jsonDoc.object();
if (object.contains("name"))
{
details->mod_id = details->name = object.value("name").toString();
}
if (object.contains("version"))
{
details->version = object.value("version").toString("");
}
else
{
details->version = object.value("revision").toString("");
}
details->mcversion = object.value("mcversion").toString();
auto author = object.value("author").toString();
if(!author.isEmpty()) {
details->authors.append(author);
}
details->description = object.value("description").toString();
details->homeurl = object.value("url").toString();
return details;
}
}
LocalModParseTask::LocalModParseTask(int token, Mod::ModType type, const QFileInfo& modFile):
m_token(token),
m_type(type),
m_modFile(modFile),
m_result(new Result())
{
}
void LocalModParseTask::processAsZip()
{
QuaZip zip(m_modFile.filePath());
if (!zip.open(QuaZip::mdUnzip))
return;
QuaZipFile file(&zip);
if (zip.setCurrentFile("mcmod.info"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
m_result->details = ReadMCModInfo(file.readAll());
file.close();
zip.close();
return;
}
else if (zip.setCurrentFile("fabric.mod.json"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
m_result->details = ReadFabricModInfo(file.readAll());
file.close();
zip.close();
return;
}
else if (zip.setCurrentFile("forgeversion.properties"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
m_result->details = ReadForgeInfo(file.readAll());
file.close();
zip.close();
return;
}
zip.close();
}
void LocalModParseTask::processAsFolder()
{
QFileInfo mcmod_info(FS::PathCombine(m_modFile.filePath(), "mcmod.info"));
if (mcmod_info.isFile())
{
QFile mcmod(mcmod_info.filePath());
if (!mcmod.open(QIODevice::ReadOnly))
return;
auto data = mcmod.readAll();
if (data.isEmpty() || data.isNull())
return;
m_result->details = ReadMCModInfo(data);
}
}
void LocalModParseTask::processAsLitemod()
{
QuaZip zip(m_modFile.filePath());
if (!zip.open(QuaZip::mdUnzip))
return;
QuaZipFile file(&zip);
if (zip.setCurrentFile("litemod.json"))
{
if (!file.open(QIODevice::ReadOnly))
{
zip.close();
return;
}
m_result->details = ReadLiteModInfo(file.readAll());
file.close();
}
zip.close();
}
void LocalModParseTask::run()
{
switch(m_type)
{
case Mod::MOD_ZIPFILE:
processAsZip();
break;
case Mod::MOD_FOLDER:
processAsFolder();
break;
case Mod::MOD_LITEMOD:
processAsLitemod();
break;
default:
break;
}
emit finished(m_token);
}

View File

@@ -1,37 +0,0 @@
#pragma once
#include <QRunnable>
#include <QDebug>
#include <QObject>
#include "Mod.h"
#include "ModDetails.h"
class LocalModParseTask : public QObject, public QRunnable
{
Q_OBJECT
public:
struct Result {
QString id;
std::shared_ptr<ModDetails> details;
};
using ResultPtr = std::shared_ptr<Result>;
ResultPtr result() const {
return m_result;
}
LocalModParseTask(int token, Mod::ModType type, const QFileInfo & modFile);
void run();
signals:
void finished(int token);
private:
void processAsZip();
void processAsFolder();
void processAsLitemod();
private:
int m_token;
Mod::ModType m_type;
QFileInfo m_modFile;
ResultPtr m_result;
};

View File

@@ -1,151 +0,0 @@
/* Copyright 2013-2019 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 <QDir>
#include <QString>
#include "Mod.h"
#include <QDebug>
#include <FileSystem.h>
namespace {
ModDetails invalidDetails;
}
Mod::Mod(const QFileInfo &file)
{
repath(file);
m_changedDateTime = file.lastModified();
}
void Mod::repath(const QFileInfo &file)
{
m_file = file;
QString name_base = file.fileName();
m_type = Mod::MOD_UNKNOWN;
m_mmc_id = name_base;
if (m_file.isDir())
{
m_type = MOD_FOLDER;
m_name = name_base;
}
else if (m_file.isFile())
{
if (name_base.endsWith(".disabled"))
{
m_enabled = false;
name_base.chop(9);
}
else
{
m_enabled = true;
}
if (name_base.endsWith(".zip") || name_base.endsWith(".jar"))
{
m_type = MOD_ZIPFILE;
name_base.chop(4);
}
else if (name_base.endsWith(".litemod"))
{
m_type = MOD_LITEMOD;
name_base.chop(8);
}
else
{
m_type = MOD_SINGLEFILE;
}
m_name = name_base;
}
}
bool Mod::enable(bool value)
{
if (m_type == Mod::MOD_UNKNOWN || m_type == Mod::MOD_FOLDER)
return false;
if (m_enabled == value)
return false;
QString path = m_file.absoluteFilePath();
if (value)
{
QFile foo(path);
if (!path.endsWith(".disabled"))
return false;
path.chop(9);
if (!foo.rename(path))
return false;
}
else
{
QFile foo(path);
path += ".disabled";
if (!foo.rename(path))
return false;
}
repath(QFileInfo(path));
m_enabled = value;
return true;
}
bool Mod::destroy()
{
m_type = MOD_UNKNOWN;
return FS::deletePath(m_file.filePath());
}
const ModDetails & Mod::details() const
{
if(!m_localDetails)
return invalidDetails;
return *m_localDetails;
}
QString Mod::version() const
{
return details().version;
}
QString Mod::name() const
{
auto & d = details();
if(!d.name.isEmpty()) {
return d.name;
}
return m_name;
}
QString Mod::homeurl() const
{
return details().homeurl;
}
QString Mod::description() const
{
return details().description;
}
QStringList Mod::authors() const
{
return details().authors;
}

View File

@@ -1,17 +0,0 @@
#pragma once
#include <QString>
#include <QStringList>
struct ModDetails
{
QString mod_id;
QString name;
QString version;
QString mcversion;
QString homeurl;
QString updateurl;
QString description;
QStringList authors;
QString credits;
};

View File

@@ -1,18 +0,0 @@
#include "ModFolderLoadTask.h"
#include <QDebug>
ModFolderLoadTask::ModFolderLoadTask(QDir dir) :
m_dir(dir), m_result(new Result())
{
}
void ModFolderLoadTask::run()
{
m_dir.refresh();
for (auto entry : m_dir.entryInfoList())
{
Mod m(entry);
m_result->mods[m.mmc_id()] = m;
}
emit succeeded();
}

View File

@@ -1,29 +0,0 @@
#pragma once
#include <QRunnable>
#include <QObject>
#include <QDir>
#include <QMap>
#include "Mod.h"
#include <memory>
class ModFolderLoadTask : public QObject, public QRunnable
{
Q_OBJECT
public:
struct Result {
QMap<QString, Mod> mods;
};
using ResultPtr = std::shared_ptr<Result>;
ResultPtr result() const {
return m_result;
}
public:
ModFolderLoadTask(QDir dir);
void run();
signals:
void succeeded();
private:
QDir m_dir;
ResultPtr m_result;
};

View File

@@ -1,9 +1,7 @@
#include "FileResolvingTask.h"
#include "Json.h"
namespace {
const char * metabase = "https://cursemeta.dries007.net";
}
const char * metabase = "https://cursemeta.dries007.net";
Flame::FileResolvingTask::FileResolvingTask(Flame::Manifest& toProcess)
: m_toProcess(toProcess)
@@ -36,14 +34,70 @@ void Flame::FileResolvingTask::netJobFinished()
int index = 0;
for(auto & bytes: results)
{
auto & out = m_toProcess.files[index];
try
{
failed &= (!out.parseFromBytes(bytes));
auto doc = Json::requireDocument(bytes);
auto obj = Json::requireObject(doc);
auto & out = m_toProcess.files[index];
// result code signifies true failure.
if(obj.contains("code"))
{
qCritical() << "Resolving of" << out.projectId << out.fileId << "failed because of a negative result:";
qCritical() << bytes;
failed = true;
continue;
}
out.fileName = Json::requireString(obj, "FileNameOnDisk");
QString rawUrl = Json::requireString(obj, "DownloadURL");
out.url = QUrl(rawUrl, QUrl::TolerantMode);
if(!out.url.isValid())
{
throw JSONValidationError(QString("Invalid URL: %1").arg(rawUrl));
}
// This is a piece of a Flame project JSON pulled out into the file metadata (here) for convenience
// It is also optional
QJsonObject projObj = Json::ensureObject(obj, "_Project", {});
if(!projObj.isEmpty())
{
QString strType = Json::ensureString(projObj, "PackageType", "mod").toLower();
if(strType == "singlefile")
{
out.type = File::Type::SingleFile;
}
else if(strType == "ctoc")
{
out.type = File::Type::Ctoc;
}
else if(strType == "cmod2")
{
out.type = File::Type::Cmod2;
}
else if(strType == "mod")
{
out.type = File::Type::Mod;
}
else if(strType == "folder")
{
out.type = File::Type::Folder;
}
else if(strType == "modpack")
{
out.type = File::Type::Modpack;
}
else
{
qCritical() << "Resolving of" << out.projectId << out.fileId << "failed because of unknown file type:" << strType;
out.type = File::Type::Unknown;
failed = true;
continue;
}
out.targetFolder = Json::ensureString(projObj, "Path", "mods");
}
out.resolved = true;
}
catch (const JSONValidationError &e)
{
auto & out = m_toProcess.files[index];
qCritical() << "Resolving of" << out.projectId << out.fileId << "failed because of a parsing error:";
qCritical() << e.cause();
qCritical() << "JSON:";

View File

@@ -64,63 +64,3 @@ void Flame::loadManifest(Flame::Manifest & m, const QString &filepath)
}
loadManifestV1(m, obj);
}
bool Flame::File::parseFromBytes(const QByteArray& bytes)
{
auto doc = Json::requireDocument(bytes);
auto obj = Json::requireObject(doc);
// result code signifies true failure.
if(obj.contains("code"))
{
qCritical() << "Resolving of" << projectId << fileId << "failed because of a negative result:";
qCritical() << bytes;
return false;
}
fileName = Json::requireString(obj, "FileNameOnDisk");
QString rawUrl = Json::requireString(obj, "DownloadURL");
url = QUrl(rawUrl, QUrl::TolerantMode);
if(!url.isValid())
{
throw JSONValidationError(QString("Invalid URL: %1").arg(rawUrl));
}
// This is a piece of a Flame project JSON pulled out into the file metadata (here) for convenience
// It is also optional
QJsonObject projObj = Json::ensureObject(obj, "_Project", {});
if(!projObj.isEmpty())
{
QString strType = Json::ensureString(projObj, "PackageType", "mod").toLower();
if(strType == "singlefile")
{
type = File::Type::SingleFile;
}
else if(strType == "ctoc")
{
type = File::Type::Ctoc;
}
else if(strType == "cmod2")
{
type = File::Type::Cmod2;
}
else if(strType == "mod")
{
type = File::Type::Mod;
}
else if(strType == "folder")
{
type = File::Type::Folder;
}
else if(strType == "modpack")
{
type = File::Type::Modpack;
}
else
{
qCritical() << "Resolving of" << projectId << fileId << "failed because of unknown file type:" << strType;
type = File::Type::Unknown;
return false;
}
targetFolder = Json::ensureString(projObj, "Path", "mods");
}
resolved = true;
return true;
}

View File

@@ -8,9 +8,6 @@ namespace Flame
{
struct File
{
// NOTE: throws JSONValidationError
bool parseFromBytes(const QByteArray &bytes);
int projectId = 0;
int fileId = 0;
// NOTE: the opposite to 'optional'. This is at the time of writing unused.

View File

@@ -1,175 +0,0 @@
#include "UrlResolvingTask.h"
#include <QtXml>
#include <Json.h>
namespace {
const char * metabase = "https://cursemeta.dries007.net";
}
Flame::UrlResolvingTask::UrlResolvingTask(const QString& toProcess)
: m_url(toProcess)
{
}
void Flame::UrlResolvingTask::executeTask()
{
resolveUrl();
}
void Flame::UrlResolvingTask::resolveUrl()
{
setStatus(tr("Resolving URL..."));
setProgress(0, 1);
QUrl actualUrl(m_url);
if(actualUrl.host() != "www.curseforge.com") {
emitFailed(tr("Not a Twitch URL."));
return;
}
m_dljob.reset(new NetJob("URL resolver"));
bool weAreDigging = false;
needle = QString();
if(m_url.startsWith("https://")) {
if(m_url.endsWith("?client=y")) {
// https://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download?client=y
// https://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download/2697088?client=y
m_url.chop(9);
// https://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download
// https://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download/2697088
}
if(m_url.endsWith("/download")) {
// https://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download -> need to dig inside html...
weAreDigging = true;
needle = m_url;
needle.replace("https://", "twitch://");
needle.replace("/download", "/download-client/");
m_url.append("?client=y");
} else if (m_url.contains("/download/")) {
// https://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download/2697088
m_url.replace("/download/", "/download-client/");
}
}
else if(m_url.startsWith("twitch://")) {
// twitch://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download-client/2697088
m_url.replace(0, 9, "https://");
// https://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download-client/2697088
}
auto dl = Net::Download::makeByteArray(QUrl(m_url), &results);
m_dljob->addNetAction(dl);
if(weAreDigging) {
connect(m_dljob.get(), &NetJob::finished, this, &Flame::UrlResolvingTask::processHTML);
} else {
connect(m_dljob.get(), &NetJob::finished, this, &Flame::UrlResolvingTask::processCCIP);
}
m_dljob->start();
}
void Flame::UrlResolvingTask::processHTML()
{
QString htmlDoc = QString::fromUtf8(results);
auto index = htmlDoc.indexOf(needle);
if(index < 0) {
emitFailed(tr("Couldn't find the needle in the haystack..."));
return;
}
auto indexStart = index;
int indexEnd = -1;
while((index + 1) < htmlDoc.size() && htmlDoc[index] != '"') {
index ++;
if(htmlDoc[index] == '"') {
indexEnd = index;
break;
}
}
if(indexEnd > 0) {
QString found = htmlDoc.mid(indexStart, indexEnd - indexStart);
qDebug() << "Found needle: " << found;
// twitch://www.curseforge.com/minecraft/modpacks/ftb-sky-odyssey/download-client/2697088
m_url = found;
resolveUrl();
return;
}
emitFailed(tr("Couldn't find the end of the needle in the haystack..."));
return;
}
void Flame::UrlResolvingTask::processCCIP()
{
QDomDocument doc;
if (!doc.setContent(results)) {
qDebug() << results;
emitFailed(tr("Resolving failed."));
return;
}
auto packageNode = doc.namedItem("package");
if(!packageNode.isElement()) {
emitFailed(tr("Resolving failed: missing package root element."));
return;
}
auto projectNode = packageNode.namedItem("project");
if(!projectNode.isElement()) {
emitFailed(tr("Resolving failed: missing project element."));
return;
}
auto attribs = projectNode.attributes();
auto projectIdNode = attribs.namedItem("id");
if(!projectIdNode.isAttr()) {
emitFailed(tr("Resolving failed: missing id attribute."));
return;
}
auto fileIdNode = attribs.namedItem("file");
if(!fileIdNode.isAttr()) {
emitFailed(tr("Resolving failed: missing file attribute."));
return;
}
auto projectId = projectIdNode.nodeValue();
auto fileId = fileIdNode.nodeValue();
bool success = true;
m_result.projectId = projectId.toInt(&success);
if(!success) {
emitFailed(tr("Failed to resove projectId as a number."));
return;
}
m_result.fileId = fileId.toInt(&success);
if(!success) {
emitFailed(tr("Failed to resove fileId as a number."));
return;
}
qDebug() << "Resolved" << m_url << "as" << m_result.projectId << "/" << m_result.fileId;
resolveIDs();
}
void Flame::UrlResolvingTask::resolveIDs()
{
setStatus(tr("Resolving mod IDs..."));
m_dljob.reset(new NetJob("Mod id resolver"));
auto projectIdStr = QString::number(m_result.projectId);
auto fileIdStr = QString::number(m_result.fileId);
QString metaurl = QString("%1/%2/%3.json").arg(metabase, projectIdStr, fileIdStr);
auto dl = Net::Download::makeByteArray(QUrl(metaurl), &results);
m_dljob->addNetAction(dl);
connect(m_dljob.get(), &NetJob::finished, this, &Flame::UrlResolvingTask::processCursemeta);
m_dljob->start();
}
void Flame::UrlResolvingTask::processCursemeta()
{
try {
if(m_result.parseFromBytes(results)) {
emitSucceeded();
qDebug() << results;
return;
}
} catch (const JSONValidationError &e) {
qCritical() << "Resolving of" << m_result.projectId << m_result.fileId << "failed because of a parsing error:";
qCritical() << e.cause();
qCritical() << "JSON:";
qCritical() << results;
}
emitFailed(tr("Failed to resolve the modpack file."));
}

View File

@@ -1,43 +0,0 @@
#pragma once
#include "tasks/Task.h"
#include "net/NetJob.h"
#include "PackManifest.h"
#include "multimc_logic_export.h"
namespace Flame
{
class MULTIMC_LOGIC_EXPORT UrlResolvingTask : public Task
{
Q_OBJECT
public:
explicit UrlResolvingTask(const QString &toProcess);
virtual ~UrlResolvingTask() {};
const Flame::File &getResults() const
{
return m_result;
}
protected:
virtual void executeTask() override;
protected slots:
void processCCIP();
void processHTML();
void processCursemeta();
private:
void resolveUrl();
void resolveIDs();
private: /* data */
QString m_url;
QString needle;
Flame::File m_result;
QByteArray results;
NetJobPtr m_dljob;
};
}

View File

@@ -36,10 +36,8 @@ QString INIFile::unescape(QString orig)
{
if(c == 'n')
out += '\n';
else if(c == 't')
else if (c == 't')
out += '\t';
else if(c == '#')
out += '#';
else
out += c;
prev = 0;
@@ -69,8 +67,6 @@ QString INIFile::escape(QString orig)
out += "\\t";
else if(c == '\\')
out += "\\\\";
else if(c == '#')
out += "\\#";
else
out += c;
}
@@ -124,15 +120,7 @@ bool INIFile::loadFile(QByteArray file)
{
QString &lineRaw = lines[i];
// Ignore comments.
int commentIndex = 0;
QString line = lineRaw;
// Search for comments until no more escaped # are available
while((commentIndex = line.indexOf('#', commentIndex + 1)) != -1) {
if(commentIndex > 0 && line.at(commentIndex - 1) == '\\') {
continue;
}
line = line.left(lineRaw.indexOf('#')).trimmed();
}
QString line = lineRaw.left(lineRaw.indexOf('#')).trimmed();
int eqPos = line.indexOf('=');
if (eqPos == -1)

View File

@@ -26,7 +26,6 @@ slots:
QTest::newRow("Plain text") << "Lorem ipsum dolor sit amet.";
QTest::newRow("Escape sequences") << "Lorem\n\t\n\\n\\tAAZ\nipsum dolor\n\nsit amet.";
QTest::newRow("Escape sequences 2") << "\"\n\n\"";
QTest::newRow("Hashtags") << "some data#something";
}
void test_Escape()
{
@@ -41,7 +40,7 @@ slots:
void test_SaveLoad()
{
QString a = "a";
QString b = "a\nb\t\n\\\\\\C:\\Program files\\terrible\\name\\of something\\#thisIsNotAComment";
QString b = "a\nb\t\n\\\\\\C:\\Program files\\terrible\\name\\of something\\";
QString filename = "test_SaveLoad.ini";
// save

View File

@@ -131,14 +131,7 @@ void DownloadTask::processDownloadedVersionInfo()
QObject::connect(netJob.get(), &NetJob::progress, this, &DownloadTask::fileDownloadProgressChanged);
QObject::connect(netJob.get(), &NetJob::failed, this, &DownloadTask::fileDownloadFailed);
if(netJob->size() == 1) // Translation issues... see https://github.com/MultiMC/MultiMC5/issues/1701
{
setStatus(tr("Downloading one update file."));
}
else
{
setStatus(tr("Downloading %1 update files.").arg(QString::number(netJob->size())));
}
setStatus(tr("Downloading %1 update files.").arg(QString::number(netJob->size())));
qDebug() << "Begin downloading update files to" << m_updateFilesDir.path();
m_filesNetJob = netJob;
m_filesNetJob->start();

View File

@@ -159,6 +159,8 @@ SET(MULTIMC_SOURCES
dialogs/IconPickerDialog.h
dialogs/LoginDialog.cpp
dialogs/LoginDialog.h
dialogs/ModEditDialogCommon.cpp
dialogs/ModEditDialogCommon.h
dialogs/NewComponentDialog.cpp
dialogs/NewComponentDialog.h
dialogs/NewInstanceDialog.cpp
@@ -211,15 +213,10 @@ SET(MULTIMC_SOURCES
widgets/VersionSelectWidget.h
widgets/ProgressWidget.h
widgets/ProgressWidget.cpp
widgets/WideBar.h
widgets/WideBar.cpp
# GUI - instance group view
groupview/GroupedProxyModel.cpp
groupview/GroupedProxyModel.h
groupview/AccessibleGroupView.cpp
groupview/AccessibleGroupView.h
groupview/AccessibleGroupView_p.h
groupview/GroupView.cpp
groupview/GroupView.h
groupview/InstanceDelegate.cpp

View File

@@ -45,7 +45,7 @@ public:
values.append(new ResourcePackPage(onesix.get()));
values.append(new TexturePackPage(onesix.get()));
values.append(new NotesPage(onesix.get()));
values.append(new WorldListPage(onesix.get(), onesix->worldList()));
values.append(new WorldListPage(onesix.get(), onesix->worldList(), "worlds", "worlds", tr("Worlds"), "Worlds"));
values.append(new ServersPage(onesix.get()));
// values.append(new GameOptionsPage(onesix.get()));
values.append(new ScreenshotsPage(FS::PathCombine(onesix->gameRoot(), "screenshots")));
@@ -56,7 +56,7 @@ public:
{
values.append(new LegacyUpgradePage(legacy));
values.append(new NotesPage(legacy.get()));
values.append(new WorldListPage(legacy.get(), legacy->worldList()));
values.append(new WorldListPage(legacy.get(), legacy->worldList(), "worlds", "worlds", tr("Worlds"), "Worlds"));
values.append(new ScreenshotsPage(FS::PathCombine(legacy->gameRoot(), "screenshots")));
}
auto logMatcher = inst->getLogFileMatcher();

View File

@@ -50,7 +50,6 @@ InstanceWindow::InstanceWindow(InstancePtr instance, QWidget *parent)
m_container = new PageContainer(provider.get(), "console", this);
m_container->setParentContainer(this);
setCentralWidget(m_container);
setContentsMargins(0, 0, 0, 0);
}
// Add custom buttons to the page container layout.
@@ -150,13 +149,10 @@ void InstanceWindow::on_InstanceLaunchTask_changed(shared_qobject_ptr<LaunchTask
m_proc = proc;
}
void InstanceWindow::on_RunningState_changed(bool running)
void InstanceWindow::on_RunningState_changed(bool)
{
updateLaunchButtons();
m_container->refreshContainer();
if(running) {
selectPage("log");
}
}
void InstanceWindow::on_closeButton_clicked()

View File

@@ -288,7 +288,6 @@ public:
foldersMenuButton->setPopupMode(QToolButton::InstantPopup);
foldersMenuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
foldersMenuButton->setIcon(MMC->getThemedIcon("viewfolder"));
foldersMenuButton->setFocusPolicy(Qt::NoFocus);
all_toolbuttons.append(&foldersMenuButton);
QWidgetAction* foldersButtonAction = new QWidgetAction(MainWindow);
foldersButtonAction->setDefaultWidget(foldersMenuButton);
@@ -346,7 +345,6 @@ public:
helpMenuButton->setPopupMode(QToolButton::InstantPopup);
helpMenuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
helpMenuButton->setIcon(MMC->getThemedIcon("help"));
helpMenuButton->setFocusPolicy(Qt::NoFocus);
all_toolbuttons.append(&helpMenuButton);
QWidgetAction* helpButtonAction = new QWidgetAction(MainWindow);
helpButtonAction->setDefaultWidget(helpMenuButton);
@@ -585,6 +583,7 @@ public:
centralWidget->setObjectName(QStringLiteral("centralWidget"));
horizontalLayout = new QHBoxLayout(centralWidget);
horizontalLayout->setSpacing(0);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalLayout->setSizeConstraint(QLayout::SetDefaultConstraint);
horizontalLayout->setContentsMargins(0, 0, 0, 0);
@@ -653,7 +652,6 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
newsLabel->setIcon(MMC->getThemedIcon("news"));
newsLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
newsLabel->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
newsLabel->setFocusPolicy(Qt::NoFocus);
ui->newsToolBar->insertWidget(ui->actionMoreNews, newsLabel);
QObject::connect(newsLabel, &QAbstractButton::clicked, this, &MainWindow::newsButtonClicked);
QObject::connect(m_newsChecker.get(), &NewsChecker::newsLoaded, this, &MainWindow::updateNewsLabel);
@@ -704,9 +702,6 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
// model reset -> selection is invalid. All the instance pointers are wrong.
connect(MMC->instances().get(), &InstanceList::dataIsInvalid, this, &MainWindow::selectionBad);
// handle newly added instances
connect(MMC->instances().get(), &InstanceList::instanceSelectRequest, this, &MainWindow::instanceSelectRequest);
// When the global settings page closes, we want to know about it and update our state
connect(MMC, &MultiMC::globalSettingsClosed, this, &MainWindow::globalSettingsClosed);
@@ -830,13 +825,6 @@ MainWindow::~MainWindow()
{
}
QMenu * MainWindow::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction( ui->mainToolBar->toggleViewAction() );
return filteredMenu;
}
void MainWindow::konamiTriggered()
{
// ENV.enableFeature("NewModsPage");
@@ -1663,13 +1651,19 @@ void MainWindow::on_actionAbout_triggered()
dialog.exec();
}
void MainWindow::on_mainToolBar_visibilityChanged(bool)
{
// Don't allow hiding the main toolbar.
// This is the only way I could find to prevent it... :/
ui->mainToolBar->setVisible(true);
}
void MainWindow::on_actionDeleteInstance_triggered()
{
if (!m_selectedInstance)
{
return;
}
auto id = m_selectedInstance->id();
auto response = CustomMessageBox::selectable(
this,
tr("CAREFUL!"),
@@ -1680,7 +1674,7 @@ void MainWindow::on_actionDeleteInstance_triggered()
)->exec();
if (response == QMessageBox::Yes)
{
MMC->instances()->deleteInstance(id);
MMC->instances()->deleteInstance(m_selectedInstance->id());
}
}
@@ -1842,11 +1836,6 @@ void MainWindow::instanceChanged(const QModelIndex &current, const QModelIndex &
}
}
void MainWindow::instanceSelectRequest(QString id)
{
setSelectedInstanceById(id);
}
void MainWindow::instanceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
auto current = view->selectionModel()->currentIndex();
@@ -1896,7 +1885,7 @@ void MainWindow::checkInstancePathForProblems()
warning.setDefaultButton(QMessageBox::Ok);
warning.exec();
}
else if (pathfoldername.startsWith(QDir::tempPath()) || pathfoldername.contains("/TempState/"))
else if (pathfoldername.contains(QDir::tempPath()))
{
QMessageBox warning(this);
warning.setText(tr("Your instance folder is in a temporary folder: \'%1\'!").arg(QDir::tempPath()));

View File

@@ -60,9 +60,6 @@ public:
signals:
void isClosing();
protected:
QMenu * createPopupMenu() override;
private slots:
void onCatToggled(bool);
@@ -112,6 +109,8 @@ private slots:
void newsButtonClicked();
void on_mainToolBar_visibilityChanged(bool);
void on_actionLaunchInstance_triggered();
void on_actionLaunchInstanceOffline_triggered();
@@ -153,8 +152,6 @@ private slots:
void instanceChanged(const QModelIndex &current, const QModelIndex &previous);
void instanceSelectRequest(QString id);
void instanceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
void selectionBad();

View File

@@ -2,10 +2,6 @@
#include "BuildConfig.h"
#include "MainWindow.h"
#include "InstanceWindow.h"
#include "groupview/AccessibleGroupView.h"
#include <QAccessible>
#include "pages/BasePageProvider.h"
#include "pages/global/MultiMCPage.h"
#include "pages/global/MinecraftPage.h"
@@ -535,8 +531,6 @@ MultiMC::MultiMC(int &argc, char **argv) : QApplication(argc, argv)
qDebug() << "<> Settings loaded.";
}
QAccessible::installFactory(groupViewAccessibleFactory);
// load translations
{
m_translations.reset(new TranslationsModel("translations"));

View File

@@ -0,0 +1,40 @@
#include "ModEditDialogCommon.h"
#include "CustomMessageBox.h"
#include <QUrl>
bool lastfirst(QModelIndexList &list, int &first, int &last)
{
if (list.isEmpty())
return false;
first = last = list[0].row();
for (auto item : list)
{
int row = item.row();
if (row < first)
first = row;
if (row > last)
last = row;
}
return true;
}
void showWebsiteForMod(QWidget *parentDlg, Mod &m)
{
QString url = m.homeurl();
if (url.size())
{
// catch the cases where the protocol is missing
if (!url.startsWith("http"))
{
url = "http://" + url;
}
DesktopServices::openUrl(url);
}
else
{
CustomMessageBox::selectable(
parentDlg, QObject::tr("How sad!"),
QObject::tr("The mod author didn't provide a website link for this mod."),
QMessageBox::Warning);
}
}

View File

@@ -0,0 +1,9 @@
#pragma once
#include <QModelIndex>
#include <DesktopServices.h>
#include <QWidget>
#include <minecraft/Mod.h>
bool lastfirst(QModelIndexList &list, int &first, int &last);
void showWebsiteForMod(QWidget *parentDlg, Mod &m);

View File

@@ -39,8 +39,6 @@
#include <pages/modplatform/ImportPage.h>
#include <pages/modplatform/TechnicPage.h>
NewInstanceDialog::NewInstanceDialog(const QString & initialGroup, const QString & url, QWidget *parent)
: QDialog(parent), ui(new Ui::NewInstanceDialog)
{
@@ -96,15 +94,8 @@ NewInstanceDialog::NewInstanceDialog(const QString & initialGroup, const QString
if(!url.isEmpty())
{
QUrl actualUrl(url);
if(actualUrl.host() == "www.curseforge.com") {
m_container->selectPage("twitch");
twitchPage->setUrl(url);
}
else {
m_container->selectPage("import");
importPage->setUrl(url);
}
m_container->selectPage("import");
importPage->setUrl(url);
}
updateDialogState();
@@ -128,13 +119,13 @@ void NewInstanceDialog::accept()
QList<BasePage *> NewInstanceDialog::getPages()
{
importPage = new ImportPage(this);
twitchPage = new TwitchPage(this);
return
{
new VanillaPage(this),
new FTBPage(this),
importPage,
twitchPage,
new FTBPage(this)
new TwitchPage(this),
new TechnicPage(this)
};
}

View File

@@ -29,7 +29,6 @@ class NewInstanceDialog;
class PageContainer;
class QDialogButtonBox;
class ImportPage;
class TwitchPage;
class NewInstanceDialog : public QDialog, public BasePageProvider
{
@@ -68,7 +67,6 @@ private:
QString InstIconKey;
ImportPage *importPage = nullptr;
TwitchPage *twitchPage = nullptr;
std::unique_ptr<InstanceTask> creationTask;
bool importIcon = false;

View File

@@ -1,774 +0,0 @@
#include "GroupView.h"
#include "AccessibleGroupView.h"
#include "AccessibleGroupView_p.h"
#include <qvariant.h>
#include <qaccessible.h>
#include <qheaderview.h>
QAccessibleInterface *groupViewAccessibleFactory(const QString &classname, QObject *object)
{
QAccessibleInterface *iface = 0;
if (!object || !object->isWidgetType())
return iface;
QWidget *widget = static_cast<QWidget*>(object);
if (classname == QLatin1String("GroupView")) {
iface = new AccessibleGroupView((GroupView *)widget);
}
return iface;
}
QAbstractItemView *AccessibleGroupView::view() const
{
return qobject_cast<QAbstractItemView*>(object());
}
int AccessibleGroupView::logicalIndex(const QModelIndex &index) const
{
if (!view()->model() || !index.isValid())
return -1;
return index.row() * (index.model()->columnCount()) + index.column();
}
AccessibleGroupView::AccessibleGroupView(QWidget *w)
: QAccessibleObject(w)
{
Q_ASSERT(view());
}
bool AccessibleGroupView::isValid() const
{
return view();
}
AccessibleGroupView::~AccessibleGroupView()
{
for (QAccessible::Id id : childToId) {
QAccessible::deleteAccessibleInterface(id);
}
}
QAccessibleInterface *AccessibleGroupView::cellAt(int row, int column) const
{
if (!view()->model()) {
return 0;
}
QModelIndex index = view()->model()->index(row, column, view()->rootIndex());
if (Q_UNLIKELY(!index.isValid())) {
qWarning() << "AccessibleGroupView::cellAt: invalid index: " << index << " for " << view();
return 0;
}
return child(logicalIndex(index));
}
QAccessibleInterface *AccessibleGroupView::caption() const
{
return 0;
}
QString AccessibleGroupView::columnDescription(int column) const
{
if (!view()->model())
return QString();
return view()->model()->headerData(column, Qt::Horizontal).toString();
}
int AccessibleGroupView::columnCount() const
{
if (!view()->model())
return 0;
return 1;
}
int AccessibleGroupView::rowCount() const
{
if (!view()->model())
return 0;
return view()->model()->rowCount();
}
int AccessibleGroupView::selectedCellCount() const
{
if (!view()->selectionModel())
return 0;
return view()->selectionModel()->selectedIndexes().count();
}
int AccessibleGroupView::selectedColumnCount() const
{
if (!view()->selectionModel())
return 0;
return view()->selectionModel()->selectedColumns().count();
}
int AccessibleGroupView::selectedRowCount() const
{
if (!view()->selectionModel())
return 0;
return view()->selectionModel()->selectedRows().count();
}
QString AccessibleGroupView::rowDescription(int row) const
{
if (!view()->model())
return QString();
return view()->model()->headerData(row, Qt::Vertical).toString();
}
QList<QAccessibleInterface *> AccessibleGroupView::selectedCells() const
{
QList<QAccessibleInterface*> cells;
if (!view()->selectionModel())
return cells;
const QModelIndexList selectedIndexes = view()->selectionModel()->selectedIndexes();
cells.reserve(selectedIndexes.size());
for (const QModelIndex &index : selectedIndexes)
cells.append(child(logicalIndex(index)));
return cells;
}
QList<int> AccessibleGroupView::selectedColumns() const
{
if (!view()->selectionModel()) {
return QList<int>();
}
const QModelIndexList selectedColumns = view()->selectionModel()->selectedColumns();
QList<int> columns;
columns.reserve(selectedColumns.size());
for (const QModelIndex &index : selectedColumns) {
columns.append(index.column());
}
return columns;
}
QList<int> AccessibleGroupView::selectedRows() const
{
if (!view()->selectionModel()) {
return QList<int>();
}
QList<int> rows;
const QModelIndexList selectedRows = view()->selectionModel()->selectedRows();
rows.reserve(selectedRows.size());
for (const QModelIndex &index : selectedRows) {
rows.append(index.row());
}
return rows;
}
QAccessibleInterface *AccessibleGroupView::summary() const
{
return 0;
}
bool AccessibleGroupView::isColumnSelected(int column) const
{
if (!view()->selectionModel()) {
return false;
}
return view()->selectionModel()->isColumnSelected(column, QModelIndex());
}
bool AccessibleGroupView::isRowSelected(int row) const
{
if (!view()->selectionModel()) {
return false;
}
return view()->selectionModel()->isRowSelected(row, QModelIndex());
}
bool AccessibleGroupView::selectRow(int row)
{
if (!view()->model() || !view()->selectionModel()) {
return false;
}
QModelIndex index = view()->model()->index(row, 0, view()->rootIndex());
if (!index.isValid() || view()->selectionBehavior() == QAbstractItemView::SelectColumns) {
return false;
}
switch (view()->selectionMode()) {
case QAbstractItemView::NoSelection: {
return false;
}
case QAbstractItemView::SingleSelection: {
if (view()->selectionBehavior() != QAbstractItemView::SelectRows && columnCount() > 1 )
return false;
view()->clearSelection();
break;
}
case QAbstractItemView::ContiguousSelection: {
if ((!row || !view()->selectionModel()->isRowSelected(row - 1, view()->rootIndex())) && !view()->selectionModel()->isRowSelected(row + 1, view()->rootIndex())) {
view()->clearSelection();
}
break;
}
default: {
break;
}
}
view()->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows);
return true;
}
bool AccessibleGroupView::selectColumn(int column)
{
if (!view()->model() || !view()->selectionModel()) {
return false;
}
QModelIndex index = view()->model()->index(0, column, view()->rootIndex());
if (!index.isValid() || view()->selectionBehavior() == QAbstractItemView::SelectRows) {
return false;
}
switch (view()->selectionMode()) {
case QAbstractItemView::NoSelection: {
return false;
}
case QAbstractItemView::SingleSelection: {
if (view()->selectionBehavior() != QAbstractItemView::SelectColumns && rowCount() > 1) {
return false;
}
// fallthrough intentional
}
case QAbstractItemView::ContiguousSelection: {
if ((!column || !view()->selectionModel()->isColumnSelected(column - 1, view()->rootIndex())) && !view()->selectionModel()->isColumnSelected(column + 1, view()->rootIndex())) {
view()->clearSelection();
}
break;
}
default: {
break;
}
}
view()->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Columns);
return true;
}
bool AccessibleGroupView::unselectRow(int row)
{
if (!view()->model() || !view()->selectionModel()) {
return false;
}
QModelIndex index = view()->model()->index(row, 0, view()->rootIndex());
if (!index.isValid()) {
return false;
}
QItemSelection selection(index, index);
auto selectionModel = view()->selectionModel();
switch (view()->selectionMode()) {
case QAbstractItemView::SingleSelection:
// no unselect
if (selectedRowCount() == 1) {
return false;
}
break;
case QAbstractItemView::ContiguousSelection: {
// no unselect
if (selectedRowCount() == 1) {
return false;
}
if ((!row || selectionModel->isRowSelected(row - 1, view()->rootIndex())) && selectionModel->isRowSelected(row + 1, view()->rootIndex())) {
//If there are rows selected both up the current row and down the current rown,
//the ones which are down the current row will be deselected
selection = QItemSelection(index, view()->model()->index(rowCount() - 1, 0, view()->rootIndex()));
}
}
default: {
break;
}
}
selectionModel->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Rows);
return true;
}
bool AccessibleGroupView::unselectColumn(int column)
{
auto model = view()->model();
if (!model || !view()->selectionModel()) {
return false;
}
QModelIndex index = model->index(0, column, view()->rootIndex());
if (!index.isValid()) {
return false;
}
QItemSelection selection(index, index);
switch (view()->selectionMode()) {
case QAbstractItemView::SingleSelection: {
//In SingleSelection and ContiguousSelection once an item
//is selected, there's no way for the user to unselect all items
if (selectedColumnCount() == 1) {
return false;
}
break;
}
case QAbstractItemView::ContiguousSelection:
if (selectedColumnCount() == 1) {
return false;
}
if ((!column || view()->selectionModel()->isColumnSelected(column - 1, view()->rootIndex()))
&& view()->selectionModel()->isColumnSelected(column + 1, view()->rootIndex())) {
//If there are columns selected both at the left of the current row and at the right
//of the current row, the ones which are at the right will be deselected
selection = QItemSelection(index, model->index(0, columnCount() - 1, view()->rootIndex()));
}
default:
break;
}
view()->selectionModel()->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Columns);
return true;
}
QAccessible::Role AccessibleGroupView::role() const
{
return QAccessible::List;
}
QAccessible::State AccessibleGroupView::state() const
{
return QAccessible::State();
}
QAccessibleInterface *AccessibleGroupView::childAt(int x, int y) const
{
QPoint viewportOffset = view()->viewport()->mapTo(view(), QPoint(0,0));
QPoint indexPosition = view()->mapFromGlobal(QPoint(x, y) - viewportOffset);
// FIXME: if indexPosition < 0 in one coordinate, return header
QModelIndex index = view()->indexAt(indexPosition);
if (index.isValid()) {
return child(logicalIndex(index));
}
return 0;
}
int AccessibleGroupView::childCount() const
{
if (!view()->model()) {
return 0;
}
return (view()->model()->rowCount()) * (view()->model()->columnCount());
}
int AccessibleGroupView::indexOfChild(const QAccessibleInterface *iface) const
{
if (!view()->model())
return -1;
QAccessibleInterface *parent = iface->parent();
if (parent->object() != view())
return -1;
Q_ASSERT(iface->role() != QAccessible::TreeItem); // should be handled by tree class
if (iface->role() == QAccessible::Cell || iface->role() == QAccessible::ListItem) {
const AccessibleGroupViewItem* cell = static_cast<const AccessibleGroupViewItem*>(iface);
return logicalIndex(cell->m_index);
} else if (iface->role() == QAccessible::Pane) {
return 0; // corner button
} else {
qWarning() << "AccessibleGroupView::indexOfChild has a child with unknown role..." << iface->role() << iface->text(QAccessible::Name);
}
// FIXME: we are in denial of our children. this should stop.
return -1;
}
QString AccessibleGroupView::text(QAccessible::Text t) const
{
if (t == QAccessible::Description)
return view()->accessibleDescription();
return view()->accessibleName();
}
QRect AccessibleGroupView::rect() const
{
if (!view()->isVisible())
return QRect();
QPoint pos = view()->mapToGlobal(QPoint(0, 0));
return QRect(pos.x(), pos.y(), view()->width(), view()->height());
}
QAccessibleInterface *AccessibleGroupView::parent() const
{
if (view() && view()->parent()) {
if (qstrcmp("QComboBoxPrivateContainer", view()->parent()->metaObject()->className()) == 0) {
return QAccessible::queryAccessibleInterface(view()->parent()->parent());
}
return QAccessible::queryAccessibleInterface(view()->parent());
}
return 0;
}
QAccessibleInterface *AccessibleGroupView::child(int logicalIndex) const
{
if (!view()->model())
return 0;
auto id = childToId.constFind(logicalIndex);
if (id != childToId.constEnd())
return QAccessible::accessibleInterface(id.value());
int columns = view()->model()->columnCount();
int row = logicalIndex / columns;
int column = logicalIndex % columns;
QAccessibleInterface *iface = 0;
QModelIndex index = view()->model()->index(row, column, view()->rootIndex());
if (Q_UNLIKELY(!index.isValid())) {
qWarning("AccessibleGroupView::child: Invalid index at: %d %d", row, column);
return 0;
}
iface = new AccessibleGroupViewItem(view(), index);
QAccessible::registerAccessibleInterface(iface);
childToId.insert(logicalIndex, QAccessible::uniqueId(iface));
return iface;
}
void *AccessibleGroupView::interface_cast(QAccessible::InterfaceType t)
{
if (t == QAccessible::TableInterface)
return static_cast<QAccessibleTableInterface*>(this);
return 0;
}
void AccessibleGroupView::modelChange(QAccessibleTableModelChangeEvent *event)
{
// if there is no cache yet, we don't update anything
if (childToId.isEmpty())
return;
switch (event->modelChangeType()) {
case QAccessibleTableModelChangeEvent::ModelReset:
for (QAccessible::Id id : childToId)
QAccessible::deleteAccessibleInterface(id);
childToId.clear();
break;
// rows are inserted: move every row after that
case QAccessibleTableModelChangeEvent::RowsInserted:
case QAccessibleTableModelChangeEvent::ColumnsInserted: {
ChildCache newCache;
ChildCache::ConstIterator iter = childToId.constBegin();
while (iter != childToId.constEnd()) {
QAccessible::Id id = iter.value();
QAccessibleInterface *iface = QAccessible::accessibleInterface(id);
Q_ASSERT(iface);
if (indexOfChild(iface) >= 0) {
newCache.insert(indexOfChild(iface), id);
} else {
// ### This should really not happen,
// but it might if the view has a root index set.
// This needs to be fixed.
QAccessible::deleteAccessibleInterface(id);
}
++iter;
}
childToId = newCache;
break;
}
case QAccessibleTableModelChangeEvent::ColumnsRemoved:
case QAccessibleTableModelChangeEvent::RowsRemoved: {
ChildCache newCache;
ChildCache::ConstIterator iter = childToId.constBegin();
while (iter != childToId.constEnd()) {
QAccessible::Id id = iter.value();
QAccessibleInterface *iface = QAccessible::accessibleInterface(id);
Q_ASSERT(iface);
if (iface->role() == QAccessible::Cell || iface->role() == QAccessible::ListItem) {
Q_ASSERT(iface->tableCellInterface());
AccessibleGroupViewItem *cell = static_cast<AccessibleGroupViewItem*>(iface->tableCellInterface());
// Since it is a QPersistentModelIndex, we only need to check if it is valid
if (cell->m_index.isValid())
newCache.insert(indexOfChild(cell), id);
else
QAccessible::deleteAccessibleInterface(id);
}
++iter;
}
childToId = newCache;
break;
}
case QAccessibleTableModelChangeEvent::DataChanged:
// nothing to do in this case
break;
}
}
// TABLE CELL
AccessibleGroupViewItem::AccessibleGroupViewItem(QAbstractItemView *view_, const QModelIndex &index_)
: view(view_), m_index(index_)
{
if (Q_UNLIKELY(!index_.isValid()))
qWarning() << "AccessibleGroupViewItem::AccessibleGroupViewItem with invalid index: " << index_;
}
void *AccessibleGroupViewItem::interface_cast(QAccessible::InterfaceType t)
{
if (t == QAccessible::TableCellInterface)
return static_cast<QAccessibleTableCellInterface*>(this);
if (t == QAccessible::ActionInterface)
return static_cast<QAccessibleActionInterface*>(this);
return 0;
}
int AccessibleGroupViewItem::columnExtent() const { return 1; }
int AccessibleGroupViewItem::rowExtent() const { return 1; }
QList<QAccessibleInterface*> AccessibleGroupViewItem::rowHeaderCells() const
{
return {};
}
QList<QAccessibleInterface*> AccessibleGroupViewItem::columnHeaderCells() const
{
return {};
}
int AccessibleGroupViewItem::columnIndex() const
{
if (!isValid()) {
return -1;
}
return m_index.column();
}
int AccessibleGroupViewItem::rowIndex() const
{
if (!isValid()) {
return -1;
}
return m_index.row();
}
bool AccessibleGroupViewItem::isSelected() const
{
if (!isValid()) {
return false;
}
return view->selectionModel()->isSelected(m_index);
}
QStringList AccessibleGroupViewItem::actionNames() const
{
QStringList names;
names << toggleAction();
return names;
}
void AccessibleGroupViewItem::doAction(const QString& actionName)
{
if (actionName == toggleAction()) {
if (isSelected()) {
unselectCell();
}
else {
selectCell();
}
}
}
QStringList AccessibleGroupViewItem::keyBindingsForAction(const QString &) const
{
return QStringList();
}
void AccessibleGroupViewItem::selectCell()
{
if (!isValid()) {
return;
}
QAbstractItemView::SelectionMode selectionMode = view->selectionMode();
if (selectionMode == QAbstractItemView::NoSelection) {
return;
}
Q_ASSERT(table());
QAccessibleTableInterface *cellTable = table()->tableInterface();
switch (view->selectionBehavior()) {
case QAbstractItemView::SelectItems:
break;
case QAbstractItemView::SelectColumns:
if (cellTable)
cellTable->selectColumn(m_index.column());
return;
case QAbstractItemView::SelectRows:
if (cellTable)
cellTable->selectRow(m_index.row());
return;
}
if (selectionMode == QAbstractItemView::SingleSelection) {
view->clearSelection();
}
view->selectionModel()->select(m_index, QItemSelectionModel::Select);
}
void AccessibleGroupViewItem::unselectCell()
{
if (!isValid())
return;
QAbstractItemView::SelectionMode selectionMode = view->selectionMode();
if (selectionMode == QAbstractItemView::NoSelection)
return;
QAccessibleTableInterface *cellTable = table()->tableInterface();
switch (view->selectionBehavior()) {
case QAbstractItemView::SelectItems:
break;
case QAbstractItemView::SelectColumns:
if (cellTable)
cellTable->unselectColumn(m_index.column());
return;
case QAbstractItemView::SelectRows:
if (cellTable)
cellTable->unselectRow(m_index.row());
return;
}
//If the mode is not MultiSelection or ExtendedSelection and only
//one cell is selected it cannot be unselected by the user
if ((selectionMode != QAbstractItemView::MultiSelection) && (selectionMode != QAbstractItemView::ExtendedSelection) && (view->selectionModel()->selectedIndexes().count() <= 1))
return;
view->selectionModel()->select(m_index, QItemSelectionModel::Deselect);
}
QAccessibleInterface *AccessibleGroupViewItem::table() const
{
return QAccessible::queryAccessibleInterface(view);
}
QAccessible::Role AccessibleGroupViewItem::role() const
{
return QAccessible::ListItem;
}
QAccessible::State AccessibleGroupViewItem::state() const
{
QAccessible::State st;
if (!isValid())
return st;
QRect globalRect = view->rect();
globalRect.translate(view->mapToGlobal(QPoint(0,0)));
if (!globalRect.intersects(rect()))
st.invisible = true;
if (view->selectionModel()->isSelected(m_index))
st.selected = true;
if (view->selectionModel()->currentIndex() == m_index)
st.focused = true;
if (m_index.model()->data(m_index, Qt::CheckStateRole).toInt() == Qt::Checked)
st.checked = true;
Qt::ItemFlags flags = m_index.flags();
if (flags & Qt::ItemIsSelectable) {
st.selectable = true;
st.focusable = true;
if (view->selectionMode() == QAbstractItemView::MultiSelection)
st.multiSelectable = true;
if (view->selectionMode() == QAbstractItemView::ExtendedSelection)
st.extSelectable = true;
}
return st;
}
QRect AccessibleGroupViewItem::rect() const
{
QRect r;
if (!isValid())
return r;
r = view->visualRect(m_index);
if (!r.isNull()) {
r.translate(view->viewport()->mapTo(view, QPoint(0,0)));
r.translate(view->mapToGlobal(QPoint(0, 0)));
}
return r;
}
QString AccessibleGroupViewItem::text(QAccessible::Text t) const
{
QString value;
if (!isValid())
return value;
QAbstractItemModel *model = view->model();
switch (t) {
case QAccessible::Name:
value = model->data(m_index, Qt::AccessibleTextRole).toString();
if (value.isEmpty())
value = model->data(m_index, Qt::DisplayRole).toString();
break;
case QAccessible::Description:
value = model->data(m_index, Qt::AccessibleDescriptionRole).toString();
break;
default:
break;
}
return value;
}
void AccessibleGroupViewItem::setText(QAccessible::Text /*t*/, const QString &text)
{
if (!isValid() || !(m_index.flags() & Qt::ItemIsEditable))
return;
view->model()->setData(m_index, text);
}
bool AccessibleGroupViewItem::isValid() const
{
return view && view->model() && m_index.isValid();
}
QAccessibleInterface *AccessibleGroupViewItem::parent() const
{
return QAccessible::queryAccessibleInterface(view);
}
QAccessibleInterface *AccessibleGroupViewItem::child(int) const
{
return 0;
}

View File

@@ -1,6 +0,0 @@
#pragma once
#include <QString>
class QAccessibleInterface;
QAccessibleInterface *groupViewAccessibleFactory(const QString &classname, QObject *object);

View File

@@ -1,116 +0,0 @@
#pragma once
#include "GroupView.h"
#include "QtCore/qpointer.h"
#include <QtGui/qaccessible.h>
#include <QAccessibleWidget>
#include <QAbstractItemView>
// #include <QHeaderView>
class QAccessibleTableCell;
class QAccessibleTableHeaderCell;
class AccessibleGroupView :public QAccessibleTableInterface, public QAccessibleObject
{
public:
explicit AccessibleGroupView(QWidget *w);
bool isValid() const override;
QAccessible::Role role() const override;
QAccessible::State state() const override;
QString text(QAccessible::Text t) const override;
QRect rect() const override;
QAccessibleInterface *childAt(int x, int y) const override;
int childCount() const override;
int indexOfChild(const QAccessibleInterface *) const override;
QAccessibleInterface *parent() const override;
QAccessibleInterface *child(int index) const override;
void *interface_cast(QAccessible::InterfaceType t) override;
// table interface
QAccessibleInterface *cellAt(int row, int column) const override;
QAccessibleInterface *caption() const override;
QAccessibleInterface *summary() const override;
QString columnDescription(int column) const override;
QString rowDescription(int row) const override;
int columnCount() const override;
int rowCount() const override;
// selection
int selectedCellCount() const override;
int selectedColumnCount() const override;
int selectedRowCount() const override;
QList<QAccessibleInterface*> selectedCells() const override;
QList<int> selectedColumns() const override;
QList<int> selectedRows() const override;
bool isColumnSelected(int column) const override;
bool isRowSelected(int row) const override;
bool selectRow(int row) override;
bool selectColumn(int column) override;
bool unselectRow(int row) override;
bool unselectColumn(int column) override;
QAbstractItemView *view() const;
void modelChange(QAccessibleTableModelChangeEvent *event) override;
protected:
// maybe vector
typedef QHash<int, QAccessible::Id> ChildCache;
mutable ChildCache childToId;
virtual ~AccessibleGroupView();
private:
inline int logicalIndex(const QModelIndex &index) const;
};
class AccessibleGroupViewItem: public QAccessibleInterface, public QAccessibleTableCellInterface, public QAccessibleActionInterface
{
public:
AccessibleGroupViewItem(QAbstractItemView *view, const QModelIndex &m_index);
void *interface_cast(QAccessible::InterfaceType t) override;
QObject *object() const override { return nullptr; }
QAccessible::Role role() const override;
QAccessible::State state() const override;
QRect rect() const override;
bool isValid() const override;
QAccessibleInterface *childAt(int, int) const override { return nullptr; }
int childCount() const override { return 0; }
int indexOfChild(const QAccessibleInterface *) const override { return -1; }
QString text(QAccessible::Text t) const override;
void setText(QAccessible::Text t, const QString &text) override;
QAccessibleInterface *parent() const override;
QAccessibleInterface *child(int) const override;
// cell interface
int columnExtent() const override;
QList<QAccessibleInterface*> columnHeaderCells() const override;
int columnIndex() const override;
int rowExtent() const override;
QList<QAccessibleInterface*> rowHeaderCells() const override;
int rowIndex() const override;
bool isSelected() const override;
QAccessibleInterface* table() const override;
//action interface
QStringList actionNames() const override;
void doAction(const QString &actionName) override;
QStringList keyBindingsForAction(const QString &actionName) const override;
private:
QPointer<QAbstractItemView > view;
QPersistentModelIndex m_index;
void selectCell();
void unselectCell();
friend class AccessibleGroupView;
};

View File

@@ -25,7 +25,6 @@
#include <QMimeData>
#include <QCache>
#include <QScrollBar>
#include <QAccessible>
#include "VisualGroup.h"
#include <QDebug>
@@ -89,18 +88,6 @@ void GroupView::rowsRemoved()
scheduleDelayedItemsLayout();
}
void GroupView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
QAbstractItemView::currentChanged(current, previous);
// TODO: for accessibility support, implement+register a factory, steal QAccessibleTable from Qt and return an instance of it for GroupView.
if (QAccessible::isActive() && current.isValid()) {
QAccessibleEvent event(this, QAccessible::Focus);
event.setChild(current.row());
QAccessible::updateAccessibility(&event);
}
}
class LocaleString : public QString
{
public:
@@ -233,8 +220,6 @@ VisualGroup *GroupView::categoryAt(const QPoint &pos, VisualGroup::HitResults &
QString GroupView::groupNameAt(const QPoint &point)
{
executeDelayedItemsLayout();
VisualGroup::HitResults hitresult;
auto group = categoryAt(point + offset(), hitresult);
if(group && (hitresult & (VisualGroup::HeaderHit | VisualGroup::BodyHit)))
@@ -261,7 +246,7 @@ int GroupView::itemWidth() const
void GroupView::mousePressEvent(QMouseEvent *event)
{
executeDelayedItemsLayout();
// endCategoryEditor();
QPoint visualPos = event->pos();
QPoint geometryPos = event->pos() + offset();
@@ -310,8 +295,6 @@ void GroupView::mousePressEvent(QMouseEvent *event)
void GroupView::mouseMoveEvent(QMouseEvent *event)
{
executeDelayedItemsLayout();
QPoint topLeft;
QPoint visualPos = event->pos();
QPoint geometryPos = event->pos() + offset();
@@ -368,8 +351,6 @@ void GroupView::mouseMoveEvent(QMouseEvent *event)
void GroupView::mouseReleaseEvent(QMouseEvent *event)
{
executeDelayedItemsLayout();
QPoint visualPos = event->pos();
QPoint geometryPos = event->pos() + offset();
QPersistentModelIndex index = indexAt(visualPos);
@@ -424,8 +405,6 @@ void GroupView::mouseReleaseEvent(QMouseEvent *event)
void GroupView::mouseDoubleClickEvent(QMouseEvent *event)
{
executeDelayedItemsLayout();
QModelIndex index = indexAt(event->pos());
if (!index.isValid() || !(index.flags() & Qt::ItemIsEnabled) || (m_pressedIndex != index))
{
@@ -549,8 +528,6 @@ void GroupView::resizeEvent(QResizeEvent *event)
void GroupView::dragEnterEvent(QDragEnterEvent *event)
{
executeDelayedItemsLayout();
if (!isDragEventAccepted(event))
{
return;
@@ -562,8 +539,6 @@ void GroupView::dragEnterEvent(QDragEnterEvent *event)
void GroupView::dragMoveEvent(QDragMoveEvent *event)
{
executeDelayedItemsLayout();
if (!isDragEventAccepted(event))
{
return;
@@ -575,16 +550,12 @@ void GroupView::dragMoveEvent(QDragMoveEvent *event)
void GroupView::dragLeaveEvent(QDragLeaveEvent *event)
{
executeDelayedItemsLayout();
m_lastDragPosition = QPoint();
viewport()->update();
}
void GroupView::dropEvent(QDropEvent *event)
{
executeDelayedItemsLayout();
m_lastDragPosition = QPoint();
stopAutoScroll();
@@ -635,8 +606,6 @@ void GroupView::dropEvent(QDropEvent *event)
void GroupView::startDrag(Qt::DropActions supportedActions)
{
executeDelayedItemsLayout();
QModelIndexList indexes = selectionModel()->selectedIndexes();
if(indexes.count() == 0)
return;
@@ -682,15 +651,11 @@ void GroupView::startDrag(Qt::DropActions supportedActions)
QRect GroupView::visualRect(const QModelIndex &index) const
{
const_cast<GroupView*>(this)->executeDelayedItemsLayout();
return geometryRect(index).translated(-offset());
}
QRect GroupView::geometryRect(const QModelIndex &index) const
{
const_cast<GroupView*>(this)->executeDelayedItemsLayout();
if (!index.isValid() || isIndexHidden(index) || index.column() > 0)
{
return QRect();
@@ -730,10 +695,9 @@ QModelIndex GroupView::indexAt(const QPoint &point) const
return QModelIndex();
}
void GroupView::setSelection(const QRect &rect, const QItemSelectionModel::SelectionFlags commands)
void GroupView::setSelection(const QRect &rect,
const QItemSelectionModel::SelectionFlags commands)
{
executeDelayedItemsLayout();
for (int i = 0; i < model()->rowCount(); ++i)
{
QModelIndex index = model()->index(i, 0);
@@ -768,7 +732,8 @@ QPixmap GroupView::renderToPixmap(const QModelIndexList &indices, QRect *r) cons
return pixmap;
}
QList<QPair<QRect, QModelIndex>> GroupView::draggablePaintPairs(const QModelIndexList &indices, QRect *r) const
QList<QPair<QRect, QModelIndex>> GroupView::draggablePaintPairs(const QModelIndexList &indices,
QRect *r) const
{
Q_ASSERT(r);
QRect &rect = *r;

View File

@@ -76,7 +76,6 @@ protected slots:
virtual void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override;
void modelReset();
void rowsRemoved();
void currentChanged(const QModelIndex &current, const QModelIndex &previous) override;
signals:
void droppedURLs(QList<QUrl> urls);

View File

@@ -205,8 +205,6 @@ void ListViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti
{
// FIXME: unused
// QSize textSize = viewItemTextSize ( &opt );
drawSelectionRect(painter, opt, textHighlightRect);
/*
QPalette::ColorGroup cg;
QStyleOptionViewItem opt2(opt);
@@ -221,13 +219,10 @@ void ListViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti
{
cg = QPalette::Disabled;
}
*/
/*
opt2.palette.setCurrentColorGroup(cg);
// fill in background, if any
if (opt.backgroundBrush.style() != Qt::NoBrush)
{
QPointF oldBO = painter->brushOrigin();
@@ -237,7 +232,6 @@ void ListViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti
}
drawSelectionRect(painter, opt2, textHighlightRect);
*/
/*
if (opt.showDecorationSelected)

View File

@@ -29,8 +29,7 @@ int main(int argc, char *argv[])
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
// initialize Qt

View File

@@ -1,11 +1,11 @@
Package: multimc
Version: 1.3-1
Version: 1.2-1
Architecture: all
Maintainer: Petr Mrázek <peterix@gmail.com>
Section: games
Priority: optional
Installed-Size: 75
Depends: zenity, desktop-file-utils, qt5-default
Depends: zenity, desktop-file-utils
Recommends: openjdk-8-jre
Homepage: http://multimc.org
Description: A local install wrapper for MultiMC

View File

@@ -4,9 +4,9 @@ A simple ubuntu package for MultiMC that wraps the contains a script that downlo
It contains a `.desktop` file, an icon, and a simple script that does the heavy lifting.
# How to build this?
You need dpkg utils. Rename the `multimc` folder to `multimc_1.3-1` and then run:
You need dpkg utils. Rename the `multimc` folder to `multimc_1.2-1` and then run:
```
fakeroot dpkg-deb --build multimc_1.3-1
fakeroot dpkg-deb --build multimc_1.2-1
```
Replace the version with whatever is appropriate.

View File

@@ -39,7 +39,6 @@ PageDialog::PageDialog(BasePageProvider *pageProvider, QString defaultId, QWidge
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Help | QDialogButtonBox::Close);
buttons->button(QDialogButtonBox::Close)->setDefault(true);
buttons->setContentsMargins(6, 0, 6, 0);
m_container->addButtons(buttons);
connect(buttons->button(QDialogButtonBox::Close), SIGNAL(clicked()), this, SLOT(close()));

View File

@@ -17,7 +17,6 @@
#include "ui_AccountListPage.h"
#include <QItemSelectionModel>
#include <QMenu>
#include <QDebug>
@@ -35,31 +34,24 @@
#include "MultiMC.h"
AccountListPage::AccountListPage(QWidget *parent)
: QMainWindow(parent), ui(new Ui::AccountListPage)
: QWidget(parent), ui(new Ui::AccountListPage)
{
ui->setupUi(this);
ui->listView->setEmptyString(tr(
"Welcome!\n"
"If you're new here, you can click the \"Add\" button to add your Mojang or Minecraft account."
));
ui->listView->setEmptyMode(VersionListView::String);
ui->listView->setContextMenuPolicy(Qt::CustomContextMenu);
ui->tabWidget->tabBar()->hide();
m_accounts = MMC->accounts();
ui->listView->setModel(m_accounts.get());
ui->listView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
ui->listView->setSelectionMode(QAbstractItemView::SingleSelection);
// Expand the account column
ui->listView->header()->setSectionResizeMode(1, QHeaderView::Stretch);
QItemSelectionModel *selectionModel = ui->listView->selectionModel();
connect(selectionModel, &QItemSelectionModel::selectionChanged, [this](const QItemSelection &sel, const QItemSelection &dsel) {
updateButtonStates();
});
connect(ui->listView, &VersionListView::customContextMenuRequested, this, &AccountListPage::ShowContextMenu);
connect(selectionModel, &QItemSelectionModel::selectionChanged,
[this](const QItemSelection &sel, const QItemSelection &dsel)
{ updateButtonStates(); });
connect(m_accounts.get(), SIGNAL(listChanged()), SLOT(listChanged()));
connect(m_accounts.get(), SIGNAL(activeAccountChanged()), SLOT(listChanged()));
@@ -72,42 +64,18 @@ AccountListPage::~AccountListPage()
delete ui;
}
void AccountListPage::ShowContextMenu(const QPoint& pos)
{
auto menu = ui->toolBar->createContextMenu(this, tr("Context menu"));
menu->exec(ui->listView->mapToGlobal(pos));
delete menu;
}
void AccountListPage::changeEvent(QEvent* event)
{
if (event->type() == QEvent::LanguageChange)
{
ui->retranslateUi(this);
}
QMainWindow::changeEvent(event);
}
QMenu * AccountListPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction(ui->toolBar->toggleViewAction() );
return filteredMenu;
}
void AccountListPage::listChanged()
{
updateButtonStates();
}
void AccountListPage::on_actionAdd_triggered()
void AccountListPage::on_addAccountBtn_clicked()
{
addAccount(tr("Please enter your Mojang or Minecraft account username and password to add "
"your account."));
}
void AccountListPage::on_actionRemove_triggered()
void AccountListPage::on_rmAccountBtn_clicked()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0)
@@ -117,7 +85,7 @@ void AccountListPage::on_actionRemove_triggered()
}
}
void AccountListPage::on_actionSetDefault_triggered()
void AccountListPage::on_setDefaultBtn_clicked()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0)
@@ -129,7 +97,7 @@ void AccountListPage::on_actionSetDefault_triggered()
}
}
void AccountListPage::on_actionNoDefault_triggered()
void AccountListPage::on_noDefaultBtn_clicked()
{
m_accounts->setActiveAccount("");
}
@@ -139,19 +107,11 @@ void AccountListPage::updateButtonStates()
// If there is no selection, disable buttons that require something selected.
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
ui->actionRemove->setEnabled(selection.size() > 0);
ui->actionSetDefault->setEnabled(selection.size() > 0);
ui->actionUploadSkin->setEnabled(selection.size() > 0);
if(m_accounts->activeAccount().get() == nullptr) {
ui->actionNoDefault->setEnabled(false);
ui->actionNoDefault->setChecked(true);
}
else {
ui->actionNoDefault->setEnabled(true);
ui->actionNoDefault->setChecked(false);
}
ui->rmAccountBtn->setEnabled(selection.size() > 0);
ui->setDefaultBtn->setEnabled(selection.size() > 0);
ui->uploadSkinBtn->setEnabled(selection.size() > 0);
ui->noDefaultBtn->setDown(m_accounts->activeAccount().get() == nullptr);
}
void AccountListPage::addAccount(const QString &errMsg)
@@ -180,7 +140,7 @@ void AccountListPage::addAccount(const QString &errMsg)
}
}
void AccountListPage::on_actionUploadSkin_triggered()
void AccountListPage::on_uploadSkinBtn_clicked()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0)

View File

@@ -15,7 +15,7 @@
#pragma once
#include <QMainWindow>
#include <QDialog>
#include <memory>
#include "pages/BasePage.h"
@@ -30,7 +30,7 @@ class AccountListPage;
class AuthenticateTask;
class AccountListPage : public QMainWindow, public BasePage
class AccountListPage : public QWidget, public BasePage
{
Q_OBJECT
public:
@@ -59,21 +59,17 @@ public:
return "Getting-Started#adding-an-account";
}
private:
void changeEvent(QEvent * event) override;
QMenu * createPopupMenu() override;
public
slots:
void on_actionAdd_triggered();
void on_addAccountBtn_clicked();
void on_actionRemove_triggered();
void on_rmAccountBtn_clicked();
void on_actionSetDefault_triggered();
void on_setDefaultBtn_clicked();
void on_actionNoDefault_triggered();
void on_noDefaultBtn_clicked();
void on_actionUploadSkin_triggered();
void on_uploadSkinBtn_clicked();
void listChanged();
@@ -85,7 +81,6 @@ protected:
protected
slots:
void ShowContextMenu(const QPoint &pos);
void addAccount(const QString& errMsg="");
private:

View File

@@ -1,94 +1,122 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AccountListPage</class>
<widget class="QMainWindow" name="AccountListPage">
<widget class="QWidget" name="AccountListPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
<width>694</width>
<height>609</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="VersionListView" name="listView"/>
</item>
</layout>
</widget>
<widget class="WideBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="leftMargin">
<number>0</number>
</property>
<attribute name="toolBarArea">
<enum>RightToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionAdd"/>
<addaction name="actionRemove"/>
<addaction name="actionSetDefault"/>
<addaction name="actionNoDefault"/>
<addaction name="actionUploadSkin"/>
</widget>
<action name="actionAdd">
<property name="text">
<string>Add</string>
<property name="topMargin">
<number>0</number>
</property>
</action>
<action name="actionRemove">
<property name="text">
<string>Remove</string>
<property name="rightMargin">
<number>0</number>
</property>
</action>
<action name="actionSetDefault">
<property name="text">
<string>Set Default</string>
<property name="bottomMargin">
<number>0</number>
</property>
</action>
<action name="actionNoDefault">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>No Default</string>
</property>
</action>
<action name="actionUploadSkin">
<property name="text">
<string>Upload Skin</string>
</property>
</action>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="welcomeLabel">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Welcome! If you're new here, you can click the &amp;quot;Add&amp;quot; button to add your Mojang or Minecraft account.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QTreeView" name="listView"/>
</item>
<item>
<layout class="QVBoxLayout" name="manageAcctsBtnBox">
<item>
<widget class="QPushButton" name="addAccountBtn">
<property name="text">
<string>&amp;Add</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="rmAccountBtn">
<property name="text">
<string>&amp;Remove</string>
</property>
</widget>
</item>
<item>
<spacer name="buttonSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="setDefaultBtn">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Set the currently selected account as the active account. The active account is the account that is used to log in (unless it is overridden in an instance-specific setting).&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="text">
<string>&amp;Set Default</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="noDefaultBtn">
<property name="toolTip">
<string>Set no default account. This will cause MultiMC to prompt you to select an account every time you launch an instance that doesn't have its own default set.</string>
</property>
<property name="text">
<string>&amp;No Default</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="uploadSkinBtn">
<property name="toolTip">
<string>Opens a dialog to select and upload a skin image to the selected account.</string>
</property>
<property name="text">
<string>&amp;Upload Skin</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>VersionListView</class>
<extends>QTreeView</extends>
<header>widgets/VersionListView.h</header>
</customwidget>
<customwidget>
<class>WideBar</class>
<extends>QToolBar</extends>
<header>widgets/WideBar.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@@ -13,7 +13,6 @@ CustomCommandsPage::CustomCommandsPage(QWidget* parent): QWidget(parent)
auto tabWidget = new QTabWidget(this);
tabWidget->setObjectName(QStringLiteral("tabWidget"));
commands = new CustomCommands(this);
commands->setContentsMargins(6, 6, 6, 6);
tabWidget->addTab(commands, "Foo");
tabWidget->tabBar()->hide();
verticalLayout->addWidget(tabWidget);

View File

@@ -78,6 +78,7 @@ MultiMCPage::MultiMCPage(QWidget *parent) : QWidget(parent), ui(new Ui::MultiMCP
}
connect(ui->fontSizeBox, SIGNAL(valueChanged(int)), SLOT(refreshFontPreview()));
connect(ui->consoleFont, SIGNAL(currentFontChanged(QFont)), SLOT(refreshFontPreview()));
connect(ui->languageBox, SIGNAL(currentIndexChanged(int)), SLOT(languageIndexChanged(int)));
}
MultiMCPage::~MultiMCPage()
@@ -146,6 +147,19 @@ void MultiMCPage::on_modsDirBrowseBtn_clicked()
}
}
void MultiMCPage::languageIndexChanged(int index)
{
auto languageCode = ui->languageBox->itemData(ui->languageBox->currentIndex()).toString();
if(languageCode.isEmpty())
{
qWarning() << "Unknown language at index" << index;
return;
}
auto translations = MMC->translations();
translations->selectLanguage(languageCode);
translations->updateLanguage(languageCode);
}
void MultiMCPage::refreshUpdateChannelList()
{
// Stop listening for selection changes. It's going to change a lot while we update it and
@@ -222,6 +236,10 @@ void MultiMCPage::applySettings()
{
auto s = MMC->settings();
// Language
auto langCode = ui->languageBox->itemData(ui->languageBox->currentIndex()).toString();
s->set("Language", langCode.isEmpty() ? "en" : langCode);
if (ui->resetNotificationsBtn->isChecked())
{
s->set("ShownNotifications", QString());
@@ -314,6 +332,12 @@ void MultiMCPage::applySettings()
void MultiMCPage::loadSettings()
{
auto s = MMC->settings();
// Language
{
ui->languageBox->setModel(m_languageModel.get());
ui->languageBox->setCurrentIndex(ui->languageBox->findData(s->get("Language").toString()));
}
// Updates
ui->autoUpdateCheckBox->setChecked(s->get("AutoUpdate").toBool());
m_currentUpdateChannel = s->get("UpdateChannel").toString();

View File

@@ -68,6 +68,8 @@ slots:
void on_modsDirBrowseBtn_clicked();
void on_iconsDirBrowseBtn_clicked();
void languageIndexChanged(int index);
/*!
* Updates the list of update channels in the combo box.
*/

View File

@@ -6,7 +6,7 @@
<rect>
<x>0</x>
<y>0</y>
<width>514</width>
<width>467</width>
<height>629</height>
</rect>
</property>
@@ -228,6 +228,18 @@
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>Language:</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QComboBox" name="languageBox"/>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="themeBox">
<property name="title">
@@ -558,6 +570,7 @@
<tabstop>resetNotificationsBtn</tabstop>
<tabstop>sortLastLaunchedBtn</tabstop>
<tabstop>sortByNameBtn</tabstop>
<tabstop>languageBox</tabstop>
<tabstop>themeComboBox</tabstop>
<tabstop>themeComboBoxColors</tabstop>
<tabstop>showConsoleCheck</tabstop>

View File

@@ -20,7 +20,6 @@
#include "settings/SettingsObject.h"
#include "MultiMC.h"
#include "Env.h"
ProxyPage::ProxyPage(QWidget *parent) : QWidget(parent), ui(new Ui::ProxyPage)
{
@@ -76,9 +75,6 @@ void ProxyPage::applySettings()
s->set("ProxyPort", ui->proxyPortEdit->value());
s->set("ProxyUser", ui->proxyUserEdit->text());
s->set("ProxyPass", ui->proxyPassEdit->text());
ENV.updateProxySettings(proxyType, ui->proxyAddrEdit->text(), ui->proxyPortEdit->value(),
ui->proxyUserEdit->text(), ui->proxyPassEdit->text());
}
void ProxyPage::loadSettings()
{

View File

@@ -11,18 +11,6 @@
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QCommandLinkButton" name="openGlobalJavaSettingsButton">
<property name="text">

View File

@@ -20,115 +20,32 @@
#include <QEvent>
#include <QKeyEvent>
#include <QAbstractItemModel>
#include <QMenu>
#include "MultiMC.h"
#include "dialogs/CustomMessageBox.h"
#include "dialogs/ModEditDialogCommon.h"
#include <GuiUtil.h>
#include "minecraft/mod/ModFolderModel.h"
#include "minecraft/mod/Mod.h"
#include "minecraft/SimpleModList.h"
#include "minecraft/Mod.h"
#include "minecraft/VersionFilterData.h"
#include "minecraft/ComponentList.h"
#include <DesktopServices.h>
#include <QSortFilterProxyModel>
#include "Version.h"
namespace {
// FIXME: wasteful
void RemoveThePrefix(QString & string) {
QRegularExpression regex(QStringLiteral("^(([Tt][Hh][eE])|([Tt][eE][Hh])) +"));
string.remove(regex);
string = string.trimmed();
}
}
class ModSortProxy : public QSortFilterProxyModel
{
public:
explicit ModSortProxy(QObject *parent = 0) : QSortFilterProxyModel(parent)
{
}
protected:
bool lessThan(const QModelIndex & source_left, const QModelIndex & source_right) const override
{
ModFolderModel *model = qobject_cast<ModFolderModel *>(sourceModel());
if(
!model ||
!source_left.isValid() ||
!source_right.isValid() ||
source_left.column() != source_right.column()
) {
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
// we are now guaranteed to have two valid indexes in the same column... we love the provided invariants unconditionally and proceed.
auto column = (ModFolderModel::Columns) source_left.column();
bool invert = false;
switch(column) {
// GH-2550 - sort by enabled/disabled
case ModFolderModel::ActiveColumn: {
auto dataL = source_left.data(Qt::CheckStateRole).toBool();
auto dataR = source_right.data(Qt::CheckStateRole).toBool();
if(dataL != dataR) {
return dataL > dataR;
}
// fallthrough
invert = sortOrder() == Qt::DescendingOrder;
}
// GH-2722 - sort mod names in a way that discards "The" prefixes
case ModFolderModel::NameColumn: {
auto dataL = model->data(model->index(source_left.row(), ModFolderModel::NameColumn)).toString();
RemoveThePrefix(dataL);
auto dataR = model->data(model->index(source_right.row(), ModFolderModel::NameColumn)).toString();
RemoveThePrefix(dataR);
auto less = dataL.compare(dataR, sortCaseSensitivity());
if(less != 0) {
return invert ? (less > 0) : (less < 0);
}
// fallthrough
invert = sortOrder() == Qt::DescendingOrder;
}
// GH-2762 - sort versions by parsing them as versions
case ModFolderModel::VersionColumn: {
auto dataL = Version(model->data(model->index(source_left.row(), ModFolderModel::VersionColumn)).toString());
auto dataR = Version(model->data(model->index(source_right.row(), ModFolderModel::VersionColumn)).toString());
return invert ? (dataL > dataR) : (dataL < dataR);
}
default: {
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
}
}
};
ModFolderPage::ModFolderPage(
BaseInstance *inst,
std::shared_ptr<ModFolderModel> mods,
QString id,
QString iconName,
QString displayName,
QString helpPage,
QWidget *parent
) :
QMainWindow(parent),
ui(new Ui::ModFolderPage)
ModFolderPage::ModFolderPage(BaseInstance *inst, std::shared_ptr<SimpleModList> mods, QString id,
QString iconName, QString displayName, QString helpPage,
QWidget *parent)
: QWidget(parent), ui(new Ui::ModFolderPage)
{
ui->setupUi(this);
ui->actionsToolbar->insertSpacer(ui->actionView_configs);
ui->tabWidget->tabBar()->hide();
m_inst = inst;
on_RunningState_changed(m_inst && m_inst->isRunning());
m_mods = mods;
m_id = id;
m_displayName = displayName;
m_iconName = iconName;
m_helpName = helpPage;
m_fileSelectionFilter = "%1 (*.zip *.jar)";
m_filterModel = new ModSortProxy(this);
m_filterModel = new QSortFilterProxyModel(this);
m_filterModel->setDynamicSortFilter(true);
m_filterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_filterModel->setSortCaseSensitivity(Qt::CaseInsensitive);
@@ -137,37 +54,9 @@ ModFolderPage::ModFolderPage(
ui->modTreeView->setModel(m_filterModel);
ui->modTreeView->installEventFilter(this);
ui->modTreeView->sortByColumn(1, Qt::AscendingOrder);
ui->modTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->modTreeView, &ModListView::customContextMenuRequested, this, &ModFolderPage::ShowContextMenu);
connect(ui->modTreeView, &ModListView::activated, this, &ModFolderPage::modItemActivated);
auto smodel = ui->modTreeView->selectionModel();
connect(smodel, &QItemSelectionModel::currentChanged, this, &ModFolderPage::modCurrent);
connect(ui->filterEdit, &QLineEdit::textChanged, this, &ModFolderPage::on_filterTextChanged );
connect(m_inst, &BaseInstance::runningStatusChanged, this, &ModFolderPage::on_RunningState_changed);
}
void ModFolderPage::modItemActivated(const QModelIndex&)
{
if(!m_controlsEnabled) {
return;
}
auto selection = m_filterModel->mapSelectionToSource(ui->modTreeView->selectionModel()->selection());
m_mods->setModStatus(selection.indexes(), ModFolderModel::Toggle);
}
QMenu * ModFolderPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction(ui->actionsToolbar->toggleViewAction() );
return filteredMenu;
}
void ModFolderPage::ShowContextMenu(const QPoint& pos)
{
auto menu = ui->actionsToolbar->createContextMenu(this, tr("Context menu"));
menu->exec(ui->modTreeView->mapToGlobal(pos));
delete menu;
}
void ModFolderPage::openedImpl()
@@ -187,7 +76,7 @@ void ModFolderPage::on_filterTextChanged(const QString& newContents)
}
CoreModFolderPage::CoreModFolderPage(BaseInstance *inst, std::shared_ptr<ModFolderModel> mods,
CoreModFolderPage::CoreModFolderPage(BaseInstance *inst, std::shared_ptr<SimpleModList> mods,
QString id, QString iconName, QString displayName,
QString helpPage, QWidget *parent)
: ModFolderPage(inst, mods, id, iconName, displayName, helpPage, parent)
@@ -200,20 +89,10 @@ ModFolderPage::~ModFolderPage()
delete ui;
}
void ModFolderPage::on_RunningState_changed(bool running)
{
if(m_controlsEnabled == !running) {
return;
}
m_controlsEnabled = !running;
ui->actionAdd->setEnabled(m_controlsEnabled);
ui->actionDisable->setEnabled(m_controlsEnabled);
ui->actionEnable->setEnabled(m_controlsEnabled);
ui->actionRemove->setEnabled(m_controlsEnabled);
}
bool ModFolderPage::shouldDisplay() const
{
if (m_inst)
return !m_inst->isRunning();
return true;
}
@@ -248,10 +127,10 @@ bool ModFolderPage::modListFilter(QKeyEvent *keyEvent)
switch (keyEvent->key())
{
case Qt::Key_Delete:
on_actionRemove_triggered();
on_rmModBtn_clicked();
return true;
case Qt::Key_Plus:
on_actionAdd_triggered();
on_addModBtn_clicked();
return true;
default:
break;
@@ -271,11 +150,8 @@ bool ModFolderPage::eventFilter(QObject *obj, QEvent *ev)
return QWidget::eventFilter(obj, ev);
}
void ModFolderPage::on_actionAdd_triggered()
void ModFolderPage::on_addModBtn_clicked()
{
if(!m_controlsEnabled) {
return;
}
auto list = GuiUtil::BrowseForFiles(
m_helpName,
tr("Select %1",
@@ -292,39 +168,30 @@ void ModFolderPage::on_actionAdd_triggered()
}
}
void ModFolderPage::on_actionEnable_triggered()
void ModFolderPage::on_enableModBtn_clicked()
{
if(!m_controlsEnabled) {
return;
}
auto selection = m_filterModel->mapSelectionToSource(ui->modTreeView->selectionModel()->selection());
m_mods->setModStatus(selection.indexes(), ModFolderModel::Enable);
m_mods->enableMods(selection.indexes(), true);
}
void ModFolderPage::on_actionDisable_triggered()
void ModFolderPage::on_disableModBtn_clicked()
{
if(!m_controlsEnabled) {
return;
}
auto selection = m_filterModel->mapSelectionToSource(ui->modTreeView->selectionModel()->selection());
m_mods->setModStatus(selection.indexes(), ModFolderModel::Disable);
m_mods->enableMods(selection.indexes(), false);
}
void ModFolderPage::on_actionRemove_triggered()
void ModFolderPage::on_rmModBtn_clicked()
{
if(!m_controlsEnabled) {
return;
}
auto selection = m_filterModel->mapSelectionToSource(ui->modTreeView->selectionModel()->selection());
m_mods->deleteMods(selection.indexes());
}
void ModFolderPage::on_actionView_configs_triggered()
void ModFolderPage::on_configFolderBtn_clicked()
{
DesktopServices::openDirectory(m_inst->instanceConfigFolder(), true);
}
void ModFolderPage::on_actionView_Folder_triggered()
void ModFolderPage::on_viewModBtn_clicked()
{
DesktopServices::openDirectory(m_mods->dir().absolutePath(), true);
}

View File

@@ -15,32 +15,26 @@
#pragma once
#include <QMainWindow>
#include <QWidget>
#include "minecraft/MinecraftInstance.h"
#include "pages/BasePage.h"
#include <MultiMC.h>
class ModFolderModel;
class SimpleModList;
namespace Ui
{
class ModFolderPage;
}
class ModFolderPage : public QMainWindow, public BasePage
class ModFolderPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit ModFolderPage(
BaseInstance *inst,
std::shared_ptr<ModFolderModel> mods,
QString id,
QString iconName,
QString displayName,
QString helpPage = "",
QWidget *parent = 0
);
explicit ModFolderPage(BaseInstance *inst, std::shared_ptr<SimpleModList> mods, QString id,
QString iconName, QString displayName, QString helpPage = "",
QWidget *parent = 0);
virtual ~ModFolderPage();
void setFilter(const QString & filter)
@@ -71,22 +65,20 @@ public:
protected:
bool eventFilter(QObject *obj, QEvent *ev) override;
bool modListFilter(QKeyEvent *ev);
QMenu * createPopupMenu() override;
protected:
BaseInstance *m_inst = nullptr;
BaseInstance *m_inst;
protected:
Ui::ModFolderPage *ui = nullptr;
std::shared_ptr<ModFolderModel> m_mods;
QSortFilterProxyModel *m_filterModel = nullptr;
Ui::ModFolderPage *ui;
std::shared_ptr<SimpleModList> m_mods;
QSortFilterProxyModel *m_filterModel;
QString m_iconName;
QString m_id;
QString m_displayName;
QString m_helpName;
QString m_fileSelectionFilter;
QString m_viewFilter;
bool m_controlsEnabled = true;
public
slots:
@@ -94,22 +86,19 @@ slots:
private
slots:
void modItemActivated(const QModelIndex &index);
void on_filterTextChanged(const QString & newContents);
void on_RunningState_changed(bool running);
void on_actionAdd_triggered();
void on_actionRemove_triggered();
void on_actionEnable_triggered();
void on_actionDisable_triggered();
void on_actionView_Folder_triggered();
void on_actionView_configs_triggered();
void ShowContextMenu(const QPoint &pos);
void on_addModBtn_clicked();
void on_rmModBtn_clicked();
void on_viewModBtn_clicked();
void on_enableModBtn_clicked();
void on_disableModBtn_clicked();
void on_configFolderBtn_clicked();
};
class CoreModFolderPage : public ModFolderPage
{
public:
explicit CoreModFolderPage(BaseInstance *inst, std::shared_ptr<ModFolderModel> mods, QString id,
explicit CoreModFolderPage(BaseInstance *inst, std::shared_ptr<SimpleModList> mods, QString id,
QString iconName, QString displayName, QString helpPage = "",
QWidget *parent = 0);
virtual ~CoreModFolderPage()

View File

@@ -1,144 +1,155 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ModFolderPage</class>
<widget class="QMainWindow" name="ModFolderPage">
<widget class="QWidget" name="ModFolderPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1042</width>
<height>501</height>
<width>723</width>
<height>532</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item row="4" column="1" colspan="3">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="1">
<widget class="QLineEdit" name="filterEdit">
<property name="clearButtonEnabled">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="filterLabel">
<property name="text">
<string>Filter:</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="2" column="1" colspan="3">
<widget class="MCModInfoFrame" name="frame">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QGridLayout" name="gridLayout" columnstretch="0,1,0">
<item row="0" column="2">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QPushButton" name="addModBtn">
<property name="text">
<string>&amp;Add</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="rmModBtn">
<property name="text">
<string>&amp;Remove</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="enableModBtn">
<property name="text">
<string>Enable</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="disableModBtn">
<property name="text">
<string>Disable</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="configFolderBtn">
<property name="toolTip">
<string>Open the 'config' folder in the system file manager.</string>
</property>
<property name="text">
<string>View configs</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="viewModBtn">
<property name="text">
<string>&amp;View Folder</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0" colspan="3">
<widget class="MCModInfoFrame" name="frame">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="0" column="0" colspan="2">
<layout class="QGridLayout" name="gridLayout_2">
<item row="1" column="1">
<widget class="QLineEdit" name="filterEdit">
<property name="clearButtonEnabled">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="filterLabel">
<property name="text">
<string>Filter:</string>
</property>
</widget>
</item>
<item row="0" column="0" colspan="3">
<widget class="ModListView" name="modTreeView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::DropOnly</enum>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item row="1" column="1" colspan="3">
<widget class="ModListView" name="modTreeView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::DropOnly</enum>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="WideBar" name="actionsToolbar">
<property name="windowTitle">
<string>Actions</string>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextOnly</enum>
</property>
<attribute name="toolBarArea">
<enum>RightToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionAdd"/>
<addaction name="separator"/>
<addaction name="actionRemove"/>
<addaction name="actionEnable"/>
<addaction name="actionDisable"/>
<addaction name="actionView_configs"/>
<addaction name="actionView_Folder"/>
</widget>
<action name="actionAdd">
<property name="text">
<string>&amp;Add</string>
</property>
<property name="toolTip">
<string>Add mods</string>
</property>
</action>
<action name="actionRemove">
<property name="text">
<string>&amp;Remove</string>
</property>
<property name="toolTip">
<string>Remove selected mods</string>
</property>
</action>
<action name="actionEnable">
<property name="text">
<string>&amp;Enable</string>
</property>
<property name="toolTip">
<string>Enable selected mods</string>
</property>
</action>
<action name="actionDisable">
<property name="text">
<string>&amp;Disable</string>
</property>
<property name="toolTip">
<string>Disable selected mods</string>
</property>
</action>
<action name="actionView_configs">
<property name="text">
<string>View &amp;Configs</string>
</property>
<property name="toolTip">
<string>Open the 'config' folder in the system file manager.</string>
</property>
</action>
<action name="actionView_Folder">
<property name="text">
<string>View &amp;Folder</string>
</property>
</action>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
@@ -152,15 +163,17 @@
<header>widgets/MCModInfoFrame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WideBar</class>
<extends>QToolBar</extends>
<header>widgets/WideBar.h</header>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>modTreeView</tabstop>
<tabstop>filterEdit</tabstop>
<tabstop>addModBtn</tabstop>
<tabstop>rmModBtn</tabstop>
<tabstop>enableModBtn</tabstop>
<tabstop>disableModBtn</tabstop>
<tabstop>configFolderBtn</tabstop>
<tabstop>viewModBtn</tabstop>
</tabstops>
<resources/>
<connections/>

View File

@@ -6,6 +6,7 @@ NotesPage::NotesPage(BaseInstance *inst, QWidget *parent)
: QWidget(parent), ui(new Ui::NotesPage), m_inst(inst)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();
ui->noteEditor->setText(m_inst->notes());
}

View File

@@ -10,7 +10,7 @@
<height>538</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="leftMargin">
<number>0</number>
</property>
@@ -24,26 +24,34 @@
<number>0</number>
</property>
<item>
<widget class="QTextEdit" name="noteEditor">
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="tabChangesFocus">
<bool>true</bool>
</property>
<property name="acceptRichText">
<bool>false</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextEditable|Qt::TextEditorInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTextEdit" name="noteEditor">
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="acceptRichText">
<bool>false</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextEditable|Qt::TextEditorInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>noteEditor</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@@ -10,7 +10,7 @@ public:
: ModFolderPage(instance, instance->resourcePackList(), "resourcepacks",
"resourcepacks", tr("Resource packs"), "Resource-packs", parent)
{
ui->actionView_configs->setVisible(false);
ui->configFolderBtn->setHidden(true);
}
virtual ~ResourcePackPage() {}

View File

@@ -13,7 +13,6 @@
#include <QPainter>
#include <QClipboard>
#include <QKeyEvent>
#include <QMenu>
#include <MultiMC.h>
@@ -210,7 +209,7 @@ public:
};
ScreenshotsPage::ScreenshotsPage(QString path, QWidget *parent)
: QMainWindow(parent), ui(new Ui::ScreenshotsPage)
: QWidget(parent), ui(new Ui::ScreenshotsPage)
{
m_model.reset(new QFileSystemModel());
m_filterModel.reset(new FilterModel());
@@ -223,8 +222,7 @@ ScreenshotsPage::ScreenshotsPage(QString path, QWidget *parent)
m_valid = FS::ensureFolderPathExists(m_folder);
ui->setupUi(this);
ui->toolBar->insertSpacer(ui->actionView_Folder);
ui->tabWidget->tabBar()->hide();
ui->listView->setIconSize(QSize(128, 128));
ui->listView->setGridSize(QSize(192, 160));
ui->listView->setSpacing(9);
@@ -235,8 +233,6 @@ ScreenshotsPage::ScreenshotsPage(QString path, QWidget *parent)
ui->listView->installEventFilter(this);
ui->listView->setEditTriggers(0);
ui->listView->setItemDelegate(new CenteredEditingDelegate(this));
ui->listView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->listView, &QListView::customContextMenuRequested, this, &ScreenshotsPage::ShowContextMenu);
connect(ui->listView, SIGNAL(activated(QModelIndex)), SLOT(onItemActivated(QModelIndex)));
}
@@ -252,10 +248,10 @@ bool ScreenshotsPage::eventFilter(QObject *obj, QEvent *evt)
switch (keyEvent->key())
{
case Qt::Key_Delete:
on_actionDelete_triggered();
on_deleteBtn_clicked();
return true;
case Qt::Key_F2:
on_actionRename_triggered();
on_renameBtn_clicked();
return true;
default:
break;
@@ -268,20 +264,6 @@ ScreenshotsPage::~ScreenshotsPage()
delete ui;
}
void ScreenshotsPage::ShowContextMenu(const QPoint& pos)
{
auto menu = ui->toolBar->createContextMenu(this, tr("Context menu"));
menu->exec(ui->listView->mapToGlobal(pos));
delete menu;
}
QMenu * ScreenshotsPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction( ui->toolBar->toggleViewAction() );
return filteredMenu;
}
void ScreenshotsPage::onItemActivated(QModelIndex index)
{
if (!index.isValid())
@@ -291,12 +273,12 @@ void ScreenshotsPage::onItemActivated(QModelIndex index)
DesktopServices::openFile(info.absoluteFilePath());
}
void ScreenshotsPage::on_actionView_Folder_triggered()
void ScreenshotsPage::on_viewFolderBtn_clicked()
{
DesktopServices::openDirectory(m_folder, true);
}
void ScreenshotsPage::on_actionUpload_triggered()
void ScreenshotsPage::on_uploadBtn_clicked()
{
auto selection = ui->listView->selectionModel()->selectedRows();
if (selection.isEmpty())
@@ -304,38 +286,6 @@ void ScreenshotsPage::on_actionUpload_triggered()
QList<ScreenshotPtr> uploaded;
auto job = NetJobPtr(new NetJob("Screenshot Upload"));
if(selection.size() < 2)
{
auto item = selection.at(0);
auto info = m_model->fileInfo(item);
auto screenshot = std::make_shared<ScreenShot>(info);
job->addNetAction(ImgurUpload::make(screenshot));
m_uploadActive = true;
ProgressDialog dialog(this);
if(dialog.execWithTask(job.get()) != QDialog::Accepted)
{
CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"),
tr("Unknown error"), QMessageBox::Warning)->exec();
}
else
{
auto link = screenshot->m_url;
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(link);
CustomMessageBox::selectable(
this,
tr("Upload finished"),
tr("The <a href=\"%1\">link to the uploaded screenshot</a> has been placed in your clipboard.")
.arg(link),
QMessageBox::Information
)->exec();
}
m_uploadActive = false;
return;
}
for (auto item : selection)
{
auto info = m_model->fileInfo(item);
@@ -371,7 +321,7 @@ void ScreenshotsPage::on_actionUpload_triggered()
m_uploadActive = false;
}
void ScreenshotsPage::on_actionDelete_triggered()
void ScreenshotsPage::on_deleteBtn_clicked()
{
auto mbox = CustomMessageBox::selectable(
this, tr("Are you sure?"), tr("This will delete all selected screenshots."),
@@ -388,7 +338,7 @@ void ScreenshotsPage::on_actionDelete_triggered()
}
}
void ScreenshotsPage::on_actionRename_triggered()
void ScreenshotsPage::on_renameBtn_clicked()
{
auto selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.isEmpty())

View File

@@ -15,7 +15,7 @@
#pragma once
#include <QMainWindow>
#include <QWidget>
#include "pages/BasePage.h"
#include <MultiMC.h>
@@ -31,7 +31,7 @@ struct ScreenShot;
class ScreenshotList;
class ImgurAlbumCreation;
class ScreenshotsPage : public QMainWindow, public BasePage
class ScreenshotsPage : public QWidget, public BasePage
{
Q_OBJECT
@@ -67,17 +67,12 @@ public:
{
return !m_uploadActive;
}
protected:
QMenu * createPopupMenu() override;
private slots:
void on_actionUpload_triggered();
void on_actionDelete_triggered();
void on_actionRename_triggered();
void on_actionView_Folder_triggered();
void on_uploadBtn_clicked();
void on_deleteBtn_clicked();
void on_renameBtn_clicked();
void on_viewFolderBtn_clicked();
void onItemActivated(QModelIndex);
void ShowContextMenu(const QPoint &pos);
private:
Ui::ScreenshotsPage *ui;

View File

@@ -1,90 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ScreenshotsPage</class>
<widget class="QMainWindow" name="ScreenshotsPage">
<widget class="QWidget" name="ScreenshotsPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
<width>723</width>
<height>532</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QListView" name="listView">
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QListView" name="listView">
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
</widget>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QPushButton" name="uploadBtn">
<property name="text">
<string>&amp;Upload</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="deleteBtn">
<property name="text">
<string>&amp;Delete</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="renameBtn">
<property name="text">
<string>&amp;Rename</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="viewFolderBtn">
<property name="text">
<string>&amp;View Folder</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="WideBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextOnly</enum>
</property>
<attribute name="toolBarArea">
<enum>RightToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionUpload"/>
<addaction name="actionDelete"/>
<addaction name="actionRename"/>
<addaction name="actionView_Folder"/>
</widget>
<action name="actionUpload">
<property name="text">
<string>Upload</string>
</property>
</action>
<action name="actionDelete">
<property name="text">
<string>Delete</string>
</property>
</action>
<action name="actionRename">
<property name="text">
<string>Rename</string>
</property>
</action>
<action name="actionView_Folder">
<property name="text">
<string>View Folder</string>
</property>
</action>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>WideBar</class>
<extends>QToolBar</extends>
<header>widgets/WideBar.h</header>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>listView</tabstop>
<tabstop>uploadBtn</tabstop>
<tabstop>deleteBtn</tabstop>
<tabstop>renameBtn</tabstop>
<tabstop>viewFolderBtn</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@@ -11,7 +11,6 @@
#include <minecraft/MinecraftInstance.h>
#include <QFileSystemWatcher>
#include <QMenu>
static const int COLUMN_COUNT = 2; // 3 , TBD: latency and other nice things.
@@ -557,16 +556,14 @@ private:
};
ServersPage::ServersPage(MinecraftInstance * inst, QWidget* parent)
: QMainWindow(parent), ui(new Ui::ServersPage)
: QWidget(parent), ui(new Ui::ServersPage)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();
m_inst = inst;
m_model = new ServersModel(inst->gameRoot(), this);
ui->serversView->setIconSize(QSize(64,64));
ui->serversView->setModel(m_model);
ui->serversView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->serversView, &QTreeView::customContextMenuRequested, this, &ServersPage::ShowContextMenu);
auto head = ui->serversView->header();
if(head->count())
{
@@ -599,20 +596,6 @@ ServersPage::~ServersPage()
m_model->saveNow();
}
void ServersPage::ShowContextMenu(const QPoint& pos)
{
auto menu = ui->toolBar->createContextMenu(this, tr("Context menu"));
menu->exec(ui->serversView->mapToGlobal(pos));
delete menu;
}
QMenu * ServersPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction( ui->toolBar->toggleViewAction() );
return filteredMenu;
}
void ServersPage::on_RunningState_changed(bool running)
{
if(m_locked == running)
@@ -691,9 +674,9 @@ void ServersPage::updateState()
ui->addressLine->setEnabled(serverEditEnabled);
ui->nameLine->setEnabled(serverEditEnabled);
ui->resourceComboBox->setEnabled(serverEditEnabled);
ui->actionMove_Down->setEnabled(serverEditEnabled);
ui->actionMove_Up->setEnabled(serverEditEnabled);
ui->actionRemove->setEnabled(serverEditEnabled);
ui->moveDownBtn->setEnabled(serverEditEnabled);
ui->moveUpBtn->setEnabled(serverEditEnabled);
ui->removeBtn->setEnabled(serverEditEnabled);
if(server)
{
@@ -708,7 +691,7 @@ void ServersPage::updateState()
ui->resourceComboBox->setCurrentIndex(0);
}
ui->actionAdd->setDisabled(m_locked);
ui->addBtn->setDisabled(m_locked);
}
void ServersPage::openedImpl()
@@ -721,7 +704,7 @@ void ServersPage::closedImpl()
m_model->unobserve();
}
void ServersPage::on_actionAdd_triggered()
void ServersPage::on_addBtn_clicked()
{
int position = m_model->addEmptyRow(currentServer + 1);
if(position < 0)
@@ -736,12 +719,12 @@ void ServersPage::on_actionAdd_triggered()
currentServer = position;
}
void ServersPage::on_actionRemove_triggered()
void ServersPage::on_removeBtn_clicked()
{
m_model->removeRow(currentServer);
}
void ServersPage::on_actionMove_Up_triggered()
void ServersPage::on_moveUpBtn_clicked()
{
if(m_model->moveUp(currentServer))
{
@@ -749,7 +732,7 @@ void ServersPage::on_actionMove_Up_triggered()
}
}
void ServersPage::on_actionMove_Down_triggered()
void ServersPage::on_moveDownBtn_clicked()
{
if(m_model->moveDown(currentServer))
{

View File

@@ -15,7 +15,7 @@
#pragma once
#include <QMainWindow>
#include <QWidget>
#include <QString>
#include "pages/BasePage.h"
@@ -30,7 +30,7 @@ struct Server;
class ServersModel;
class MinecraftInstance;
class ServersPage : public QMainWindow, public BasePage
class ServersPage : public QWidget, public BasePage
{
Q_OBJECT
@@ -57,10 +57,6 @@ public:
{
return "Servers-management";
}
protected:
QMenu * createPopupMenu() override;
private:
void updateState();
void scheduleSave();
@@ -70,18 +66,15 @@ private slots:
void currentChanged(const QModelIndex &current, const QModelIndex &previous);
void rowsRemoved(const QModelIndex &parent, int first, int last);
void on_actionAdd_triggered();
void on_actionRemove_triggered();
void on_actionMove_Up_triggered();
void on_actionMove_Down_triggered();
void on_addBtn_clicked();
void on_removeBtn_clicked();
void on_moveUpBtn_clicked();
void on_moveDownBtn_clicked();
void on_RunningState_changed(bool running);
void nameEdited(const QString & name);
void addressEdited(const QString & address);
void resourceIndexChanged(int index);\
void ShowContextMenu(const QPoint &pos);
void resourceIndexChanged(int index);
private: // data
int currentServer = -1;

View File

@@ -1,190 +1,198 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ServersPage</class>
<widget class="QMainWindow" name="ServersPage">
<widget class="QWidget" name="ServersPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1318</width>
<height>879</height>
<width>706</width>
<height>575</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTreeView" name="serversView">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="iconSize">
<size>
<width>64</width>
<height>64</height>
</size>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="3" column="1">
<widget class="QComboBox" name="resourceComboBox">
<item>
<property name="text">
<string>Ask to download</string>
</property>
</item>
<item>
<property name="text">
<string>Always download</string>
</property>
</item>
<item>
<property name="text">
<string>Never download</string>
</property>
</item>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="resourcesLabel">
<property name="text">
<string>Reso&amp;urces</string>
</property>
<property name="buddy">
<cstring>resourceComboBox</cstring>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="addressLine"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="nameLabel">
<property name="text">
<string>&amp;Name</string>
</property>
<property name="buddy">
<cstring>nameLine</cstring>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="nameLine"/>
</item>
<item row="2" column="0">
<widget class="QLabel" name="addressLabel">
<property name="text">
<string>Address</string>
</property>
<property name="buddy">
<cstring>addressLine</cstring>
</property>
</widget>
</item>
<item row="0" column="0" colspan="2">
<widget class="QTreeView" name="serversView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="iconSize">
<size>
<width>64</width>
<height>64</height>
</size>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
</attribute>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QPushButton" name="addBtn">
<property name="text">
<string>&amp;Add</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="removeBtn">
<property name="text">
<string>&amp;Remove</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="moveUpBtn">
<property name="text">
<string>Move Up</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="moveDownBtn">
<property name="text">
<string>Move Down</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout_2">
<property name="leftMargin">
<number>6</number>
</property>
<property name="rightMargin">
<number>6</number>
</property>
<item row="0" column="0">
<widget class="QLabel" name="nameLabel">
<property name="text">
<string>&amp;Name</string>
</property>
<property name="buddy">
<cstring>nameLine</cstring>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="nameLine"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="addressLabel">
<property name="text">
<string>Address</string>
</property>
<property name="buddy">
<cstring>addressLine</cstring>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="addressLine"/>
</item>
<item row="2" column="0">
<widget class="QLabel" name="resourcesLabel">
<property name="text">
<string>Reso&amp;urces</string>
</property>
<property name="buddy">
<cstring>resourceComboBox</cstring>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QComboBox" name="resourceComboBox">
<item>
<property name="text">
<string>Ask to download</string>
</property>
</item>
<item>
<property name="text">
<string>Always download</string>
</property>
</item>
<item>
<property name="text">
<string>Never download</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="WideBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
</property>
<property name="allowedAreas">
<set>Qt::LeftToolBarArea|Qt::RightToolBarArea</set>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextOnly</enum>
</property>
<property name="floatable">
<bool>false</bool>
</property>
<attribute name="toolBarArea">
<enum>RightToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionAdd"/>
<addaction name="actionRemove"/>
<addaction name="actionMove_Up"/>
<addaction name="actionMove_Down"/>
</widget>
<action name="actionAdd">
<property name="text">
<string>Add</string>
</property>
</action>
<action name="actionRemove">
<property name="text">
<string>Remove</string>
</property>
</action>
<action name="actionMove_Up">
<property name="text">
<string>Move Up</string>
</property>
</action>
<action name="actionMove_Down">
<property name="text">
<string>Move Down</string>
</property>
</action>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>WideBar</class>
<extends>QToolBar</extends>
<header>widgets/WideBar.h</header>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>serversView</tabstop>
<tabstop>nameLine</tabstop>
<tabstop>addressLine</tabstop>
<tabstop>resourceComboBox</tabstop>
<tabstop>addBtn</tabstop>
<tabstop>removeBtn</tabstop>
<tabstop>moveUpBtn</tabstop>
<tabstop>moveDownBtn</tabstop>
</tabstops>
<resources/>
<connections/>

View File

@@ -10,7 +10,7 @@ public:
: ModFolderPage(instance, instance->texturePackList(), "texturepacks", "resourcepacks",
tr("Texture packs"), "Texture-packs", parent)
{
ui->actionView_configs->setVisible(false);
ui->configFolderBtn->setHidden(true);
}
virtual ~TexturePackPage() {}
virtual bool shouldDisplay() const override

View File

@@ -16,10 +16,8 @@
#include "MultiMC.h"
#include <QMessageBox>
#include <QLabel>
#include <QEvent>
#include <QKeyEvent>
#include <QMenu>
#include "VersionPage.h"
#include "ui_VersionPage.h"
@@ -27,6 +25,7 @@
#include "dialogs/CustomMessageBox.h"
#include "dialogs/VersionSelectDialog.h"
#include "dialogs/NewComponentDialog.h"
#include "dialogs/ModEditDialogCommon.h"
#include "dialogs/ProgressDialog.h"
#include <GuiUtil.h>
@@ -39,10 +38,11 @@
#include "minecraft/ComponentList.h"
#include "minecraft/auth/MojangAccountList.h"
#include "minecraft/mod/Mod.h"
#include "minecraft/Mod.h"
#include "icons/IconList.h"
#include "Exception.h"
#include "Version.h"
#include "MultiMC.h"
#include <meta/Index.h>
#include <meta/VersionList.h>
@@ -96,44 +96,38 @@ QIcon VersionPage::icon() const
}
bool VersionPage::shouldDisplay() const
{
return true;
}
QMenu * VersionPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction( ui->toolBar->toggleViewAction() );
return filteredMenu;
return !m_inst->isRunning();
}
VersionPage::VersionPage(MinecraftInstance *inst, QWidget *parent)
: QMainWindow(parent), ui(new Ui::VersionPage), m_inst(inst)
: QWidget(parent), ui(new Ui::VersionPage), m_inst(inst)
{
ui->setupUi(this);
ui->toolBar->insertSpacer(ui->actionReload);
ui->tabWidget->tabBar()->hide();
m_profile = m_inst->getComponentList();
reloadComponentList();
auto proxy = new IconProxy(ui->packageView);
proxy->setSourceModel(m_profile.get());
ui->packageView->setModel(proxy);
ui->packageView->installEventFilter(this);
ui->packageView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->packageView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->packageView->selectionModel(), &QItemSelectionModel::currentChanged, this, &VersionPage::versionCurrent);
auto smodel = ui->packageView->selectionModel();
connect(smodel, &QItemSelectionModel::currentChanged, this, &VersionPage::packageCurrent);
connect(m_profile.get(), &ComponentList::minecraftChanged, this, &VersionPage::updateVersionControls);
controlsEnabled = !m_inst->isRunning();
updateVersionControls();
preselect(0);
connect(m_inst, &BaseInstance::runningStatusChanged, this, &VersionPage::updateRunningStatus);
connect(ui->packageView, &ModListView::customContextMenuRequested, this, &VersionPage::ShowContextMenu);
if (m_profile)
{
auto proxy = new IconProxy(ui->packageView);
proxy->setSourceModel(m_profile.get());
ui->packageView->setModel(proxy);
ui->packageView->installEventFilter(this);
ui->packageView->setSelectionMode(QAbstractItemView::SingleSelection);
connect(ui->packageView->selectionModel(), &QItemSelectionModel::currentChanged, this, &VersionPage::versionCurrent);
auto smodel = ui->packageView->selectionModel();
connect(smodel, &QItemSelectionModel::currentChanged, this, &VersionPage::packageCurrent);
updateVersionControls();
// select first item.
preselect(0);
}
else
{
disableVersionControls();
}
connect(m_inst, &MinecraftInstance::versionReloaded, this,
&VersionPage::updateVersionControls);
}
VersionPage::~VersionPage()
@@ -141,13 +135,6 @@ VersionPage::~VersionPage()
delete ui;
}
void VersionPage::ShowContextMenu(const QPoint& pos)
{
auto menu = ui->toolBar->createContextMenu(this, tr("Context menu"));
menu->exec(ui->packageView->mapToGlobal(pos));
delete menu;
}
void VersionPage::packageCurrent(const QModelIndex &current, const QModelIndex &previous)
{
if (!current.isValid())
@@ -190,45 +177,22 @@ void VersionPage::packageCurrent(const QModelIndex &current, const QModelIndex &
ui->frame->setModDescription(problemOut);
}
void VersionPage::updateRunningStatus(bool running)
{
if(controlsEnabled == running) {
controlsEnabled = !running;
updateVersionControls();
}
}
void VersionPage::updateVersionControls()
{
// FIXME: this is a dirty hack
auto minecraftVersion = Version(m_profile->getComponentVersion("net.minecraft"));
bool newCraft = controlsEnabled && (minecraftVersion >= Version("1.14"));
bool oldCraft = controlsEnabled && (minecraftVersion <= Version("1.12.2"));
ui->actionInstall_Fabric->setEnabled(newCraft);
ui->actionInstall_Forge->setEnabled(oldCraft);
ui->actionInstall_LiteLoader->setEnabled(oldCraft);
ui->actionReload->setEnabled(true);
ui->fabricBtn->setEnabled(true);
ui->forgeBtn->setEnabled(true);
ui->liteloaderBtn->setEnabled(true);
updateButtons();
}
void VersionPage::updateButtons(int row)
void VersionPage::disableVersionControls()
{
if(row == -1)
row = currentRow();
auto patch = m_profile->getComponent(row);
ui->actionRemove->setEnabled(controlsEnabled && patch && patch->isRemovable());
ui->actionMove_down->setEnabled(controlsEnabled && patch && patch->isMoveable());
ui->actionMove_up->setEnabled(controlsEnabled && patch && patch->isMoveable());
ui->actionChange_version->setEnabled(controlsEnabled && patch && patch->isVersionChangeable());
ui->actionEdit->setEnabled(controlsEnabled && patch && patch->isCustom());
ui->actionCustomize->setEnabled(controlsEnabled && patch && patch->isCustomizable());
ui->actionRevert->setEnabled(controlsEnabled && patch && patch->isRevertible());
ui->actionDownload_All->setEnabled(controlsEnabled);
ui->actionAdd_Empty->setEnabled(controlsEnabled);
ui->actionReload->setEnabled(controlsEnabled);
ui->actionInstall_mods->setEnabled(controlsEnabled);
ui->actionReplace_Minecraft_jar->setEnabled(controlsEnabled);
ui->actionAdd_to_Minecraft_jar->setEnabled(controlsEnabled);
ui->fabricBtn->setEnabled(false);
ui->forgeBtn->setEnabled(false);
ui->liteloaderBtn->setEnabled(false);
ui->reloadBtn->setEnabled(false);
updateButtons();
}
bool VersionPage::reloadComponentList()
@@ -252,13 +216,13 @@ bool VersionPage::reloadComponentList()
}
}
void VersionPage::on_actionReload_triggered()
void VersionPage::on_reloadBtn_clicked()
{
reloadComponentList();
m_container->refreshContainer();
}
void VersionPage::on_actionRemove_triggered()
void VersionPage::on_removeBtn_clicked()
{
if (ui->packageView->currentIndex().isValid())
{
@@ -273,7 +237,7 @@ void VersionPage::on_actionRemove_triggered()
m_container->refreshContainer();
}
void VersionPage::on_actionInstall_mods_triggered()
void VersionPage::on_modBtn_clicked()
{
if(m_container)
{
@@ -281,7 +245,7 @@ void VersionPage::on_actionInstall_mods_triggered()
}
}
void VersionPage::on_actionAdd_to_Minecraft_jar_triggered()
void VersionPage::on_jarmodBtn_clicked()
{
auto list = GuiUtil::BrowseForFiles("jarmod", tr("Select jar mods"), tr("Minecraft.jar mods (*.zip *.jar)"), MMC->settings()->get("CentralModsDir").toString(), this->parentWidget());
if(!list.empty())
@@ -291,7 +255,7 @@ void VersionPage::on_actionAdd_to_Minecraft_jar_triggered()
updateButtons();
}
void VersionPage::on_actionReplace_Minecraft_jar_triggered()
void VersionPage::on_jarBtn_clicked()
{
auto jarPath = GuiUtil::BrowseForFile("jar", tr("Select jar"), tr("Minecraft.jar replacement (*.jar)"), MMC->settings()->get("CentralModsDir").toString(), this->parentWidget());
if(!jarPath.isEmpty())
@@ -301,7 +265,7 @@ void VersionPage::on_actionReplace_Minecraft_jar_triggered()
updateButtons();
}
void VersionPage::on_actionMove_up_triggered()
void VersionPage::on_moveUpBtn_clicked()
{
try
{
@@ -314,7 +278,7 @@ void VersionPage::on_actionMove_up_triggered()
updateButtons();
}
void VersionPage::on_actionMove_down_triggered()
void VersionPage::on_moveDownBtn_clicked()
{
try
{
@@ -327,7 +291,7 @@ void VersionPage::on_actionMove_down_triggered()
updateButtons();
}
void VersionPage::on_actionChange_version_triggered()
void VersionPage::on_changeVersionBtn_clicked()
{
auto versionRow = currentRow();
if(versionRow == -1)
@@ -345,12 +309,12 @@ void VersionPage::on_actionChange_version_triggered()
// FIXME: this is a horrible HACK. Get version filtering information from the actual metadata...
if(uid == "net.minecraftforge")
{
on_actionInstall_Forge_triggered();
on_forgeBtn_clicked();
return;
}
else if (uid == "com.mumfrey.liteloader")
{
on_actionInstall_LiteLoader_triggered();
on_liteloaderBtn_clicked();
return;
}
VersionSelectDialog vselect(list.get(), tr("Change %1 version").arg(name), this);
@@ -379,7 +343,7 @@ void VersionPage::on_actionChange_version_triggered()
m_container->refreshContainer();
}
void VersionPage::on_actionDownload_triggered()
void VersionPage::on_downloadBtn_clicked()
{
if (!MMC->accounts()->anyAccountIsValid())
{
@@ -404,7 +368,7 @@ void VersionPage::on_actionDownload_triggered()
m_container->refreshContainer();
}
void VersionPage::on_actionInstall_Forge_triggered()
void VersionPage::on_forgeBtn_clicked()
{
auto vlist = ENV.metadataIndex()->get("net.minecraftforge");
if(!vlist)
@@ -433,7 +397,7 @@ void VersionPage::on_actionInstall_Forge_triggered()
}
}
void VersionPage::on_actionInstall_Fabric_triggered()
void VersionPage::on_fabricBtn_clicked()
{
auto vlist = ENV.metadataIndex()->get("net.fabricmc.fabric-loader");
if(!vlist)
@@ -460,7 +424,7 @@ void VersionPage::on_actionInstall_Fabric_triggered()
}
}
void VersionPage::on_actionAdd_Empty_triggered()
void VersionPage::on_addEmptyBtn_clicked()
{
NewComponentDialog compdialog(QString(), QString(), this);
QStringList blacklist;
@@ -478,7 +442,7 @@ void VersionPage::on_actionAdd_Empty_triggered()
}
}
void VersionPage::on_actionInstall_LiteLoader_triggered()
void VersionPage::on_liteloaderBtn_clicked()
{
auto vlist = ENV.metadataIndex()->get("com.mumfrey.liteloader");
if(!vlist)
@@ -532,9 +496,37 @@ void VersionPage::preselect(int row)
updateButtons(row);
}
void VersionPage::updateButtons(int row)
{
if(row == -1)
row = currentRow();
auto patch = m_profile->getComponent(row);
if (!patch)
{
ui->removeBtn->setDisabled(true);
ui->moveDownBtn->setDisabled(true);
ui->moveUpBtn->setDisabled(true);
ui->changeVersionBtn->setDisabled(true);
ui->editBtn->setDisabled(true);
ui->customizeBtn->setDisabled(true);
ui->revertBtn->setDisabled(true);
}
else
{
ui->removeBtn->setEnabled(patch->isRemovable());
ui->moveDownBtn->setEnabled(patch->isMoveable());
ui->moveUpBtn->setEnabled(patch->isMoveable());
ui->changeVersionBtn->setEnabled(patch->isVersionChangeable());
ui->editBtn->setEnabled(patch->isCustom());
ui->customizeBtn->setEnabled(patch->isCustomizable());
ui->revertBtn->setEnabled(patch->isRevertible());
}
}
void VersionPage::onGameUpdateError(QString error)
{
CustomMessageBox::selectable(this, tr("Error updating instance"), error, QMessageBox::Warning)->show();
CustomMessageBox::selectable(this, tr("Error updating instance"), error,
QMessageBox::Warning)->show();
}
Component * VersionPage::current()
@@ -556,7 +548,7 @@ int VersionPage::currentRow()
return ui->packageView->selectionModel()->selectedRows().first().row();
}
void VersionPage::on_actionCustomize_triggered()
void VersionPage::on_customizeBtn_clicked()
{
auto version = currentRow();
if(version == -1)
@@ -577,7 +569,7 @@ void VersionPage::on_actionCustomize_triggered()
preselect(currentIdx);
}
void VersionPage::on_actionEdit_triggered()
void VersionPage::on_editBtn_clicked()
{
auto version = current();
if(!version)
@@ -593,7 +585,7 @@ void VersionPage::on_actionEdit_triggered()
MMC->openJsonEditor(filename);
}
void VersionPage::on_actionRevert_triggered()
void VersionPage::on_revertBtn_clicked()
{
auto version = currentRow();
if(version == -1)

View File

@@ -15,7 +15,7 @@
#pragma once
#include <QMainWindow>
#include <QWidget>
#include "minecraft/MinecraftInstance.h"
#include "minecraft/ComponentList.h"
@@ -26,7 +26,7 @@ namespace Ui
class VersionPage;
}
class VersionPage : public QMainWindow, public BasePage
class VersionPage : public QWidget, public BasePage
{
Q_OBJECT
@@ -49,24 +49,25 @@ public:
virtual bool shouldDisplay() const override;
private slots:
void on_actionChange_version_triggered();
void on_actionInstall_Forge_triggered();
void on_actionInstall_Fabric_triggered();
void on_actionAdd_Empty_triggered();
void on_actionInstall_LiteLoader_triggered();
void on_actionReload_triggered();
void on_actionRemove_triggered();
void on_actionMove_up_triggered();
void on_actionMove_down_triggered();
void on_actionAdd_to_Minecraft_jar_triggered();
void on_actionReplace_Minecraft_jar_triggered();
void on_actionRevert_triggered();
void on_actionEdit_triggered();
void on_actionInstall_mods_triggered();
void on_actionCustomize_triggered();
void on_actionDownload_triggered();
void on_fabricBtn_clicked();
void on_forgeBtn_clicked();
void on_addEmptyBtn_clicked();
void on_liteloaderBtn_clicked();
void on_reloadBtn_clicked();
void on_removeBtn_clicked();
void on_moveUpBtn_clicked();
void on_moveDownBtn_clicked();
void on_jarmodBtn_clicked();
void on_jarBtn_clicked();
void on_revertBtn_clicked();
void on_editBtn_clicked();
void on_modBtn_clicked();
void on_customizeBtn_clicked();
void on_downloadBtn_clicked();
void updateVersionControls();
void disableVersionControls();
void on_changeVersionBtn_clicked();
private:
Component * current();
@@ -76,8 +77,6 @@ private:
int doUpdate();
protected:
QMenu * createPopupMenu() override;
/// FIXME: this shouldn't be necessary!
bool reloadComponentList();
@@ -86,14 +85,12 @@ private:
std::shared_ptr<ComponentList> m_profile;
MinecraftInstance *m_inst;
int currentIdx = 0;
bool controlsEnabled = false;
public slots:
void versionCurrent(const QModelIndex &current, const QModelIndex &previous);
private slots:
void updateRunningStatus(bool running);
void onGameUpdateError(QString error);
void packageCurrent(const QModelIndex &current, const QModelIndex &previous);
void ShowContextMenu(const QPoint &pos);
};

View File

@@ -1,231 +1,292 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>VersionPage</class>
<widget class="QMainWindow" name="VersionPage">
<widget class="QWidget" name="VersionPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>961</width>
<height>1091</height>
<width>870</width>
<height>1008</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="ModListView" name="packageView">
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="sortingEnabled">
<bool>false</bool>
</property>
<property name="headerHidden">
<bool>false</bool>
</property>
<attribute name="headerVisible">
<bool>true</bool>
</attribute>
</widget>
</item>
<item>
<widget class="MCModInfoFrame" name="frame">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="WideBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="allowedAreas">
<set>Qt::LeftToolBarArea|Qt::RightToolBarArea</set>
<property name="topMargin">
<number>0</number>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextOnly</enum>
<property name="rightMargin">
<number>0</number>
</property>
<property name="floatable">
<bool>false</bool>
<property name="bottomMargin">
<number>0</number>
</property>
<attribute name="toolBarArea">
<enum>RightToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionChange_version"/>
<addaction name="actionMove_up"/>
<addaction name="actionMove_down"/>
<addaction name="actionRemove"/>
<addaction name="separator"/>
<addaction name="actionCustomize"/>
<addaction name="actionEdit"/>
<addaction name="actionRevert"/>
<addaction name="separator"/>
<addaction name="actionInstall_Forge"/>
<addaction name="actionInstall_Fabric"/>
<addaction name="actionInstall_LiteLoader"/>
<addaction name="actionInstall_mods"/>
<addaction name="separator"/>
<addaction name="actionAdd_to_Minecraft_jar"/>
<addaction name="actionReplace_Minecraft_jar"/>
<addaction name="actionAdd_Empty"/>
<addaction name="actionReload"/>
<addaction name="actionDownload_All"/>
</widget>
<action name="actionChange_version">
<property name="text">
<string>Change version</string>
</property>
<property name="toolTip">
<string>Change version of the selected package.</string>
</property>
</action>
<action name="actionMove_up">
<property name="text">
<string>Move up</string>
</property>
<property name="toolTip">
<string>Make the selected package apply sooner.</string>
</property>
</action>
<action name="actionMove_down">
<property name="text">
<string>Move down</string>
</property>
<property name="toolTip">
<string>Make the selected package apply later.</string>
</property>
</action>
<action name="actionRemove">
<property name="text">
<string>Remove</string>
</property>
<property name="toolTip">
<string>Remove selected package from the instance.</string>
</property>
</action>
<action name="actionCustomize">
<property name="text">
<string>Customize</string>
</property>
<property name="toolTip">
<string>Customize selected package.</string>
</property>
</action>
<action name="actionEdit">
<property name="text">
<string>Edit</string>
</property>
<property name="toolTip">
<string>Edit selected package.</string>
</property>
</action>
<action name="actionRevert">
<property name="text">
<string>Revert</string>
</property>
<property name="toolTip">
<string>Revert the selected package to default.</string>
</property>
</action>
<action name="actionInstall_Forge">
<property name="text">
<string>Install Forge</string>
</property>
<property name="toolTip">
<string>Install the Minecraft Forge package.</string>
</property>
</action>
<action name="actionInstall_Fabric">
<property name="text">
<string>Install Fabric</string>
</property>
<property name="toolTip">
<string>Install the Fabric Loader package.</string>
</property>
</action>
<action name="actionInstall_LiteLoader">
<property name="text">
<string>Install LiteLoader</string>
</property>
<property name="toolTip">
<string>Install the LiteLoader package.</string>
</property>
</action>
<action name="actionInstall_mods">
<property name="text">
<string>Install mods</string>
</property>
<property name="toolTip">
<string>Install normal mods.</string>
</property>
</action>
<action name="actionAdd_to_Minecraft_jar">
<property name="text">
<string>Add to Minecraft.jar</string>
</property>
<property name="toolTip">
<string>Add a mod into the Minecraft jar file.</string>
</property>
</action>
<action name="actionReplace_Minecraft_jar">
<property name="text">
<string>Replace Minecraft.jar</string>
</property>
</action>
<action name="actionAdd_Empty">
<property name="text">
<string>Add Empty</string>
</property>
<property name="toolTip">
<string>Add an empty custom package.</string>
</property>
</action>
<action name="actionReload">
<property name="text">
<string>Reload</string>
</property>
<property name="toolTip">
<string>Reload all packages.</string>
</property>
</action>
<action name="actionDownload_All">
<property name="text">
<string>Download All</string>
</property>
<property name="toolTip">
<string>Download the files needed to launch the instance now.</string>
</property>
</action>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="ModListView" name="packageView">
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOn</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="sortingEnabled">
<bool>false</bool>
</property>
<property name="headerHidden">
<bool>false</bool>
</property>
<attribute name="headerVisible">
<bool>true</bool>
</attribute>
</widget>
</item>
<item row="0" column="1">
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Selection</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="changeVersionBtn">
<property name="toolTip">
<string>Change version of the selected package.</string>
</property>
<property name="text">
<string>Change version</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="moveUpBtn">
<property name="toolTip">
<string>Make the selected package apply sooner.</string>
</property>
<property name="text">
<string>Move up</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="moveDownBtn">
<property name="toolTip">
<string>Make the selected package apply later.</string>
</property>
<property name="text">
<string>Move down</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="removeBtn">
<property name="toolTip">
<string>Remove selected package from the instance.</string>
</property>
<property name="text">
<string>Remove</string>
</property>
</widget>
</item>
<item>
<widget class="LineSeparator" name="separator_4" native="true"/>
</item>
<item>
<widget class="QLabel" name="label_10">
<property name="text">
<string>Edit</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="customizeBtn">
<property name="toolTip">
<string>Customize selected package.</string>
</property>
<property name="text">
<string>Customize</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="editBtn">
<property name="toolTip">
<string>Edit selected package.</string>
</property>
<property name="text">
<string>Edit</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="revertBtn">
<property name="toolTip">
<string>Revert the selected package to default.</string>
</property>
<property name="text">
<string>Revert</string>
</property>
</widget>
</item>
<item>
<widget class="LineSeparator" name="separator" native="true"/>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Install</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="forgeBtn">
<property name="toolTip">
<string>Install the Minecraft Forge package.</string>
</property>
<property name="text">
<string>Install Forge</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="fabricBtn">
<property name="toolTip">
<string>Install the Fabric Loader package.</string>
</property>
<property name="text">
<string>Install Fabric</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="liteloaderBtn">
<property name="toolTip">
<string>Install the LiteLoader package.</string>
</property>
<property name="text">
<string>Install LiteLoader</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="modBtn">
<property name="toolTip">
<string>Install normal mods.</string>
</property>
<property name="text">
<string>Install mods</string>
</property>
</widget>
</item>
<item>
<widget class="LineSeparator" name="widget" native="true"/>
</item>
<item>
<widget class="QLabel" name="label_5">
<property name="text">
<string>Advanced</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="jarmodBtn">
<property name="toolTip">
<string>Add a mod into the Minecraft jar file.</string>
</property>
<property name="text">
<string>Add to Minecraft.jar</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="jarBtn">
<property name="text">
<string>Replace Minecraft.jar</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="addEmptyBtn">
<property name="text">
<string>Add Empty</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="reloadBtn">
<property name="toolTip">
<string>Reload all packages.</string>
</property>
<property name="text">
<string>Reload</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="downloadBtn">
<property name="toolTip">
<string>Download the files needed to launch the instance now.</string>
</property>
<property name="text">
<string>Download All</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer_7">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>111</width>
<height>13</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="1" column="0" colspan="2">
<widget class="MCModInfoFrame" name="frame">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
@@ -233,18 +294,39 @@
<extends>QTreeView</extends>
<header>widgets/ModListView.h</header>
</customwidget>
<customwidget>
<class>LineSeparator</class>
<extends>QWidget</extends>
<header>widgets/LineSeparator.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>MCModInfoFrame</class>
<extends>QFrame</extends>
<header>widgets/MCModInfoFrame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>WideBar</class>
<extends>QToolBar</extends>
<header>widgets/WideBar.h</header>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>packageView</tabstop>
<tabstop>changeVersionBtn</tabstop>
<tabstop>moveUpBtn</tabstop>
<tabstop>moveDownBtn</tabstop>
<tabstop>removeBtn</tabstop>
<tabstop>customizeBtn</tabstop>
<tabstop>editBtn</tabstop>
<tabstop>revertBtn</tabstop>
<tabstop>forgeBtn</tabstop>
<tabstop>fabricBtn</tabstop>
<tabstop>liteloaderBtn</tabstop>
<tabstop>modBtn</tabstop>
<tabstop>jarmodBtn</tabstop>
<tabstop>jarBtn</tabstop>
<tabstop>addEmptyBtn</tabstop>
<tabstop>reloadBtn</tabstop>
<tabstop>downloadBtn</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@@ -17,8 +17,8 @@
#include "ui_WorldListPage.h"
#include "minecraft/WorldList.h"
#include <DesktopServices.h>
#include "dialogs/ModEditDialogCommon.h"
#include <QEvent>
#include <QMenu>
#include <QKeyEvent>
#include <QClipboard>
#include <QMessageBox>
@@ -31,27 +31,27 @@
#include <QProcess>
#include <FileSystem.h>
WorldListPage::WorldListPage(BaseInstance *inst, std::shared_ptr<WorldList> worlds, QWidget *parent)
: QMainWindow(parent), m_inst(inst), ui(new Ui::WorldListPage), m_worlds(worlds)
WorldListPage::WorldListPage(BaseInstance *inst, std::shared_ptr<WorldList> worlds, QString id,
QString iconName, QString displayName, QString helpPage,
QWidget *parent)
: QWidget(parent), m_inst(inst), ui(new Ui::WorldListPage), m_worlds(worlds), m_iconName(iconName), m_id(id), m_displayName(displayName), m_helpName(helpPage)
{
ui->setupUi(this);
ui->toolBar->insertSpacer(ui->actionRefresh);
ui->tabWidget->tabBar()->hide();
QSortFilterProxyModel * proxy = new QSortFilterProxyModel(this);
proxy->setSortCaseSensitivity(Qt::CaseInsensitive);
proxy->setSourceModel(m_worlds.get());
ui->worldTreeView->setSortingEnabled(true);
ui->worldTreeView->setModel(proxy);
ui->worldTreeView->installEventFilter(this);
ui->worldTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->worldTreeView, &QTreeView::customContextMenuRequested, this, &WorldListPage::ShowContextMenu);
auto head = ui->worldTreeView->header();
head->setSectionResizeMode(0, QHeaderView::Stretch);
head->setSectionResizeMode(1, QHeaderView::ResizeToContents);
connect(ui->worldTreeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &WorldListPage::worldChanged);
connect(ui->worldTreeView->selectionModel(),
SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this,
SLOT(worldChanged(const QModelIndex &, const QModelIndex &)));
worldChanged(QModelIndex(), QModelIndex());
}
@@ -71,20 +71,6 @@ WorldListPage::~WorldListPage()
delete ui;
}
void WorldListPage::ShowContextMenu(const QPoint& pos)
{
auto menu = ui->toolBar->createContextMenu(this, tr("Context menu"));
menu->exec(ui->worldTreeView->mapToGlobal(pos));
delete menu;
}
QMenu * WorldListPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction( ui->toolBar->toggleViewAction() );
return filteredMenu;
}
bool WorldListPage::shouldDisplay() const
{
return true;
@@ -95,7 +81,7 @@ bool WorldListPage::worldListFilter(QKeyEvent *keyEvent)
switch (keyEvent->key())
{
case Qt::Key_Delete:
on_actionRemove_triggered();
on_rmWorldBtn_clicked();
return true;
default:
break;
@@ -115,7 +101,7 @@ bool WorldListPage::eventFilter(QObject *obj, QEvent *ev)
return QWidget::eventFilter(obj, ev);
}
void WorldListPage::on_actionRemove_triggered()
void WorldListPage::on_rmWorldBtn_clicked()
{
auto proxiedIndex = getSelectedWorld();
@@ -137,7 +123,7 @@ void WorldListPage::on_actionRemove_triggered()
m_worlds->startWatching();
}
void WorldListPage::on_actionView_Folder_triggered()
void WorldListPage::on_viewFolderBtn_clicked()
{
DesktopServices::openDirectory(m_worlds->dir().absolutePath(), true);
}
@@ -150,7 +136,7 @@ QModelIndex WorldListPage::getSelectedWorld()
return proxy->mapToSource(index);
}
void WorldListPage::on_actionCopy_Seed_triggered()
void WorldListPage::on_copySeedBtn_clicked()
{
QModelIndex index = getSelectedWorld();
@@ -162,7 +148,7 @@ void WorldListPage::on_actionCopy_Seed_triggered()
MMC->clipboard()->setText(QString::number(seed));
}
void WorldListPage::on_actionMCEdit_triggered()
void WorldListPage::on_mcEditBtn_clicked()
{
if(m_mceditStarting)
return;
@@ -250,17 +236,17 @@ void WorldListPage::worldChanged(const QModelIndex &current, const QModelIndex &
{
QModelIndex index = getSelectedWorld();
bool enable = index.isValid();
ui->actionCopy_Seed->setEnabled(enable);
ui->actionMCEdit->setEnabled(enable);
ui->actionRemove->setEnabled(enable);
ui->actionCopy->setEnabled(enable);
ui->actionRename->setEnabled(enable);
ui->copySeedBtn->setEnabled(enable);
ui->mcEditBtn->setEnabled(enable);
ui->rmWorldBtn->setEnabled(enable);
ui->copyBtn->setEnabled(enable);
ui->renameBtn->setEnabled(enable);
}
void WorldListPage::on_actionAdd_triggered()
void WorldListPage::on_addBtn_clicked()
{
auto list = GuiUtil::BrowseForFiles(
displayName(),
m_helpName,
tr("Select a Minecraft world zip"),
tr("Minecraft World Zip File (*.zip)"), QString(), this->parentWidget());
if (!list.empty())
@@ -293,7 +279,7 @@ bool WorldListPage::worldSafetyNagQuestion()
}
void WorldListPage::on_actionCopy_triggered()
void WorldListPage::on_copyBtn_clicked()
{
QModelIndex index = getSelectedWorld();
if (!index.isValid())
@@ -315,7 +301,7 @@ void WorldListPage::on_actionCopy_triggered()
}
}
void WorldListPage::on_actionRename_triggered()
void WorldListPage::on_renameBtn_clicked()
{
QModelIndex index = getSelectedWorld();
if (!index.isValid())
@@ -338,7 +324,7 @@ void WorldListPage::on_actionRename_triggered()
}
}
void WorldListPage::on_actionRefresh_triggered()
void WorldListPage::on_refreshBtn_clicked()
{
m_worlds->update();
}

View File

@@ -15,7 +15,7 @@
#pragma once
#include <QMainWindow>
#include <QWidget>
#include "minecraft/MinecraftInstance.h"
#include "pages/BasePage.h"
@@ -28,33 +28,31 @@ namespace Ui
class WorldListPage;
}
class WorldListPage : public QMainWindow, public BasePage
class WorldListPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit WorldListPage(
BaseInstance *inst,
std::shared_ptr<WorldList> worlds,
QWidget *parent = 0
);
explicit WorldListPage(BaseInstance *inst, std::shared_ptr<WorldList> worlds, QString id,
QString iconName, QString displayName, QString helpPage = "",
QWidget *parent = 0);
virtual ~WorldListPage();
virtual QString displayName() const override
{
return tr("Worlds");
return m_displayName;
}
virtual QIcon icon() const override
{
return MMC->getThemedIcon("worlds");
return MMC->getThemedIcon(m_iconName);
}
virtual QString id() const override
{
return "worlds";
return m_id;
}
virtual QString helpPage() const override
{
return "Worlds";
return m_helpName;
}
virtual bool shouldDisplay() const override;
@@ -64,7 +62,6 @@ public:
protected:
bool eventFilter(QObject *obj, QEvent *ev) override;
bool worldListFilter(QKeyEvent *ev);
QMenu * createPopupMenu() override;
protected:
BaseInstance *m_inst;
@@ -80,18 +77,20 @@ private:
std::shared_ptr<WorldList> m_worlds;
unique_qobject_ptr<LoggedProcess> m_mceditProcess;
bool m_mceditStarting = false;
QString m_iconName;
QString m_id;
QString m_displayName;
QString m_helpName;
private slots:
void on_actionCopy_Seed_triggered();
void on_actionMCEdit_triggered();
void on_actionRemove_triggered();
void on_actionAdd_triggered();
void on_actionCopy_triggered();
void on_actionRename_triggered();
void on_actionRefresh_triggered();
void on_actionView_Folder_triggered();
void on_copySeedBtn_clicked();
void on_mcEditBtn_clicked();
void on_rmWorldBtn_clicked();
void on_addBtn_clicked();
void on_copyBtn_clicked();
void on_renameBtn_clicked();
void on_refreshBtn_clicked();
void on_viewFolderBtn_clicked();
void worldChanged(const QModelIndex &current, const QModelIndex &previous);
void mceditState(LoggedProcess::State state);
void ShowContextMenu(const QPoint &pos);
};

View File

@@ -1,140 +1,171 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WorldListPage</class>
<widget class="QMainWindow" name="WorldListPage">
<widget class="QWidget" name="WorldListPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
<width>723</width>
<height>532</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTreeView" name="worldTreeView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::DragDrop</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="2">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QPushButton" name="addBtn">
<property name="text">
<string>Add</string>
</property>
</widget>
</item>
<item>
<widget class="LineSeparator" name="separator" native="true"/>
</item>
<item>
<widget class="QPushButton" name="renameBtn">
<property name="text">
<string>Rename</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="copyBtn">
<property name="text">
<string>Copy</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="rmWorldBtn">
<property name="text">
<string>&amp;Remove</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="mcEditBtn">
<property name="text">
<string notr="true">MCEdit</string>
</property>
</widget>
</item>
<item>
<widget class="LineSeparator" name="separator_2" native="true"/>
</item>
<item>
<widget class="QPushButton" name="copySeedBtn">
<property name="text">
<string>Copy Seed</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="refreshBtn">
<property name="text">
<string>Refresh</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="viewFolderBtn">
<property name="text">
<string>&amp;View Folder</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="0" column="1">
<widget class="QTreeView" name="worldTreeView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="dragDropMode">
<enum>QAbstractItemView::DragDrop</enum>
</property>
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
</attribute>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="WideBar" name="toolBar">
<property name="windowTitle">
<string>toolBar</string>
</property>
<property name="allowedAreas">
<set>Qt::LeftToolBarArea|Qt::RightToolBarArea</set>
</property>
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextOnly</enum>
</property>
<property name="floatable">
<bool>false</bool>
</property>
<attribute name="toolBarArea">
<enum>RightToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionAdd"/>
<addaction name="separator"/>
<addaction name="actionRename"/>
<addaction name="actionCopy"/>
<addaction name="actionRemove"/>
<addaction name="actionMCEdit"/>
<addaction name="separator"/>
<addaction name="actionCopy_Seed"/>
<addaction name="actionRefresh"/>
<addaction name="actionView_Folder"/>
</widget>
<action name="actionAdd">
<property name="text">
<string>Add</string>
</property>
</action>
<action name="actionRename">
<property name="text">
<string>Rename</string>
</property>
</action>
<action name="actionCopy">
<property name="text">
<string>Copy</string>
</property>
</action>
<action name="actionRemove">
<property name="text">
<string>Remove</string>
</property>
</action>
<action name="actionMCEdit">
<property name="text">
<string>MCEdit</string>
</property>
</action>
<action name="actionCopy_Seed">
<property name="text">
<string>Copy Seed</string>
</property>
</action>
<action name="actionRefresh">
<property name="text">
<string>Refresh</string>
</property>
</action>
<action name="actionView_Folder">
<property name="text">
<string>View Folder</string>
</property>
</action>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>WideBar</class>
<extends>QToolBar</extends>
<header>widgets/WideBar.h</header>
<class>LineSeparator</class>
<extends>QWidget</extends>
<header>widgets/LineSeparator.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>worldTreeView</tabstop>
<tabstop>addBtn</tabstop>
<tabstop>renameBtn</tabstop>
<tabstop>copyBtn</tabstop>
<tabstop>rmWorldBtn</tabstop>
<tabstop>mcEditBtn</tabstop>
<tabstop>copySeedBtn</tabstop>
<tabstop>refreshBtn</tabstop>
<tabstop>viewFolderBtn</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@@ -75,11 +75,6 @@ void ImportPage::updateState()
}
else
{
if(input.endsWith("?client=y")) {
input.chop(9);
input.append("/file");
url = QUrl::fromUserInput(input);
}
// hook, line and sinker.
QFileInfo fi(url.fileName());
dialog->setSuggestedPack(fi.completeBaseName(), new InstanceImportTask(url));

View File

@@ -3,13 +3,11 @@
#include "MultiMC.h"
#include "dialogs/NewInstanceDialog.h"
#include <InstanceImportTask.h>
TwitchPage::TwitchPage(NewInstanceDialog* dialog, QWidget *parent)
: QWidget(parent), ui(new Ui::TwitchPage), dialog(dialog)
{
ui->setupUi(this);
connect(ui->checkButton, &QPushButton::clicked, this, &TwitchPage::triggerCheck);
}
TwitchPage::~TwitchPage()
@@ -19,42 +17,10 @@ TwitchPage::~TwitchPage()
bool TwitchPage::shouldDisplay() const
{
return true;
return false;
}
void TwitchPage::openedImpl()
{
dialog->setSuggestedPack();
}
void TwitchPage::triggerCheck(bool)
{
if(m_modIdResolver) {
return;
}
auto task = new Flame::UrlResolvingTask(ui->lineEdit->text());
connect(task, &Task::finished, this, &TwitchPage::checkDone);
m_modIdResolver.reset(task);
task->start();
}
void TwitchPage::setUrl(const QString& url)
{
ui->lineEdit->setText(url);
triggerCheck(true);
}
void TwitchPage::checkDone()
{
auto result = m_modIdResolver->getResults();
auto formatted = QString("Project %1, File %2").arg(result.projectId).arg(result.fileId);
if(result.resolved && result.type == Flame::File::Type::Modpack) {
ui->twitchLabel->setText(formatted);
QFileInfo fi(result.fileName);
dialog->setSuggestedPack(fi.completeBaseName(), new InstanceImportTask(result.url));
} else {
ui->twitchLabel->setPixmap(QPixmap(QString::fromUtf8(":/assets/deadglitch")));
dialog->setSuggestedPack();
}
m_modIdResolver.reset();
}

View File

@@ -20,7 +20,6 @@
#include "pages/BasePage.h"
#include <MultiMC.h>
#include "tasks/Task.h"
#include "modplatform/flame/UrlResolvingTask.h"
namespace Ui
{
@@ -38,7 +37,7 @@ public:
virtual ~TwitchPage();
virtual QString displayName() const override
{
return tr("Twitch URL");
return tr("Twitch");
}
virtual QIcon icon() const override
{
@@ -56,14 +55,7 @@ public:
void openedImpl() override;
void setUrl(const QString & url);
private slots:
void triggerCheck(bool checked);
void checkDone();
private:
Ui::TwitchPage *ui = nullptr;
NewInstanceDialog* dialog = nullptr;
shared_qobject_ptr<Flame::UrlResolvingTask> m_modIdResolver;
};

View File

@@ -10,25 +10,9 @@
<height>405</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="1">
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Twitch URL:</string>
</property>
</widget>
</item>
<item row="1" column="0" colspan="3">
<widget class="QLabel" name="twitchLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label_3">
<property name="font">
<font>
<pointsize>40</pointsize>
@@ -42,19 +26,8 @@
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QPushButton" name="checkButton">
<property name="text">
<string>Check</string>
</property>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>lineEdit</tabstop>
<tabstop>checkButton</tabstop>
</tabstops>
<resources>
<include location="../../resources/assets/assets.qrc"/>
</resources>

View File

@@ -23,7 +23,6 @@ VanillaPage::VanillaPage(NewInstanceDialog *dialog, QWidget *parent)
connect(ui->snapshotFilter, &QCheckBox::stateChanged, this, &VanillaPage::filterChanged);
connect(ui->oldSnapshotFilter, &QCheckBox::stateChanged, this, &VanillaPage::filterChanged);
connect(ui->releaseFilter, &QCheckBox::stateChanged, this, &VanillaPage::filterChanged);
connect(ui->experimentsFilter, &QCheckBox::stateChanged, this, &VanillaPage::filterChanged);
connect(ui->refreshBtn, &QPushButton::clicked, this, &VanillaPage::refresh);
}
@@ -59,8 +58,6 @@ void VanillaPage::filterChanged()
out << "(old_snapshot)";
if(ui->releaseFilter->isChecked())
out << "(release)";
if(ui->experimentsFilter->isChecked())
out << "(experiment)";
auto regexp = out.join('|');
ui->versionList->setFilter(BaseVersionList::TypeRole, new RegexpFilter(regexp, false));
}

View File

@@ -98,16 +98,6 @@
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="experimentsFilter">
<property name="text">
<string>Experiments</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
@@ -154,16 +144,6 @@
<container>1</container>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>releaseFilter</tabstop>
<tabstop>snapshotFilter</tabstop>
<tabstop>oldSnapshotFilter</tabstop>
<tabstop>betaFilter</tabstop>
<tabstop>alphaFilter</tabstop>
<tabstop>experimentsFilter</tabstop>
<tabstop>refreshBtn</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@@ -14,18 +14,6 @@
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QGroupBox" name="customCommandsGroupBox">
<property name="enabled">

View File

@@ -36,7 +36,6 @@ LanguageSelectionWidget::LanguageSelectionWidget(QWidget *parent) :
languageView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
languageView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
connect(languageView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &LanguageSelectionWidget::languageRowChanged);
verticalLayout->setContentsMargins(0,0,0,0);
}
QString LanguageSelectionWidget::getSelectedLanguageKey() const
@@ -50,7 +49,7 @@ void LanguageSelectionWidget::retranslate()
QString text =
tr("Don't see your language or the quality is poor?") +
"<br/>" +
QString("<a href=\"https://github.com/MultiMC/MultiMC5/wiki/Translating-MultiMC\">%1</a>").arg(tr("Help us with translations!"));
QString("<a href=\"https://github.com/MultiMC/MultiMC5/wiki/Translating-MultiMC\">%1</a>").arg("Help us with translations!");
helpUsLabel->setText(text);
}

View File

@@ -40,7 +40,7 @@ void MCModInfoFrame::updateWithMod(Mod &m)
else
text = "<a href=\"" + m.homeurl() + "\">" + name + "</a>";
if (!m.authors().isEmpty())
text += " by " + m.authors().join(", ");
text += " by " + m.authors();
setModText(text);

View File

@@ -16,7 +16,7 @@
#pragma once
#include <QFrame>
#include "minecraft/mod/Mod.h"
#include "minecraft/Mod.h"
namespace Ui
{

View File

@@ -16,6 +16,8 @@
#pragma once
#include <QTreeView>
class Mod;
class ModListView: public QTreeView
{
Q_OBJECT

Some files were not shown because too many files have changed in this diff Show More