NOISSUE Some happy little refactors

This commit is contained in:
Petr Mrázek 2021-11-20 16:22:22 +01:00
parent eafeb64dec
commit 0c861db7a2
142 changed files with 812 additions and 694 deletions

View File

@ -1,4 +1,4 @@
#include "Launcher.h"
#include "Application.h"
#include "BuildConfig.h"
#include "MainWindow.h"
#include "InstanceWindow.h"
@ -23,7 +23,7 @@
#include "themes/BrightTheme.h"
#include "themes/CustomTheme.h"
#include "LauncherMessage.h"
#include "ApplicationMessage.h"
#include "setupwizard/SetupWizard.h"
#include "setupwizard/LanguageWizardPage.h"
@ -72,6 +72,7 @@
#include <sys.h>
#include "pagedialog/PageDialog.h"
#include <Secrets.h>
#if defined Q_OS_WIN32
@ -99,7 +100,7 @@ void appDebugOutput(QtMsgType type, const QMessageLogContext &context, const QSt
const char *levels = "DWCFIS";
const QString format("%1 %2 %3\n");
qint64 msecstotal = LAUNCHER->timeSinceStart();
qint64 msecstotal = APPLICATION->timeSinceStart();
qint64 seconds = msecstotal / 1000;
qint64 msecs = msecstotal % 1000;
QString foo;
@ -108,8 +109,8 @@ void appDebugOutput(QtMsgType type, const QMessageLogContext &context, const QSt
QString out = format.arg(buf).arg(levels[type]).arg(msg);
LAUNCHER->logFile->write(out.toUtf8());
LAUNCHER->logFile->flush();
APPLICATION->logFile->write(out.toUtf8());
APPLICATION->logFile->flush();
QTextStream(stderr) << out.toLocal8Bit();
fflush(stderr);
}
@ -155,7 +156,7 @@ QString getIdealPlatform(QString currentPlatform) {
}
Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
Application::Application(int &argc, char **argv) : QApplication(argc, argv)
{
#if defined Q_OS_WIN32
// attach the parent console
@ -261,7 +262,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
if(argc > 0)
std::cerr << "Try '" << argv[0] << " -h' to get help on command line parameters."
<< std::endl;
m_status = Launcher::Failed;
m_status = Application::Failed;
return;
}
@ -269,7 +270,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
if (args["help"].toBool())
{
std::cout << qPrintable(parser.compileHelp(arguments()[0]));
m_status = Launcher::Succeeded;
m_status = Application::Succeeded;
return;
}
@ -278,7 +279,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
{
std::cout << "Version " << BuildConfig.printableVersionString().toStdString() << std::endl;
std::cout << "Git " << BuildConfig.GIT_COMMIT.toStdString() << std::endl;
m_status = Launcher::Succeeded;
m_status = Application::Succeeded;
return;
}
}
@ -347,14 +348,14 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
if(m_instanceIdToLaunch.isEmpty() && !m_serverToJoin.isEmpty())
{
std::cerr << "--server can only be used in combination with --launch!" << std::endl;
m_status = Launcher::Failed;
m_status = Application::Failed;
return;
}
if(m_instanceIdToLaunch.isEmpty() && !m_profileToUse.isEmpty())
{
std::cerr << "--account can only be used in combination with --launch!" << std::endl;
m_status = Launcher::Failed;
m_status = Application::Failed;
return;
}
@ -430,19 +431,19 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
{
// FIXME: you can run the same binaries with multiple data dirs and they won't clash. This could cause issues for updates.
m_peerInstance = new LocalPeer(this, appID);
connect(m_peerInstance, &LocalPeer::messageReceived, this, &Launcher::messageReceived);
connect(m_peerInstance, &LocalPeer::messageReceived, this, &Application::messageReceived);
if(m_peerInstance->isClient()) {
int timeout = 2000;
if(m_instanceIdToLaunch.isEmpty())
{
LauncherMessage activate;
ApplicationMessage activate;
activate.command = "activate";
m_peerInstance->sendMessage(activate.serialize(), timeout);
if(!m_zipToImport.isEmpty())
{
LauncherMessage import;
ApplicationMessage import;
import.command = "import";
import.args.insert("path", m_zipToImport.toString());
m_peerInstance->sendMessage(import.serialize(), timeout);
@ -450,7 +451,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
}
else
{
LauncherMessage launch;
ApplicationMessage launch;
launch.command = "launch";
launch.args["id"] = m_instanceIdToLaunch;
@ -464,7 +465,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
}
m_peerInstance->sendMessage(launch.serialize(), timeout);
}
m_status = Launcher::Succeeded;
m_status = Application::Succeeded;
return;
}
}
@ -520,7 +521,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
#endif
#ifdef MULTIMC_JARS_LOCATION
ENV.setJarsPath( TOSTRING(MULTIMC_JARS_LOCATION) );
ENV->setJarsPath( TOSTRING(MULTIMC_JARS_LOCATION) );
#endif
qDebug() << BuildConfig.LAUNCHER_DISPLAYNAME << ", (c) 2013-2021 " << BuildConfig.LAUNCHER_COPYRIGHT;
@ -750,7 +751,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
// Instance icons
{
auto setting = LAUNCHER->settings()->getSetting("IconsDir");
auto setting = APPLICATION->settings()->getSetting("IconsDir");
QStringList instFolders =
{
":/icons/multimc/32x32/instances/",
@ -763,7 +764,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
{
m_icons->directoryChanged(value.toString());
});
ENV.registerIconList(m_icons);
ENV->registerIconList(m_icons);
qDebug() << "<> Instance icons intialized.";
}
@ -820,7 +821,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
// init the http meta cache
{
ENV.initHttpMetaCache();
ENV->initHttpMetaCache();
qDebug() << "<> Cache initialized.";
}
@ -831,7 +832,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
int port = settings()->get("ProxyPort").value<qint16>();
QString user = settings()->get("ProxyUser").toString();
QString pass = settings()->get("ProxyPass").toString();
ENV.updateProxySettings(proxyTypeStr, addr, port, user, pass);
ENV->updateProxySettings(proxyTypeStr, addr, port, user, pass);
qDebug() << "<> Proxy settings done.";
}
@ -851,7 +852,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
m_mcedit.reset(new MCEditTool(m_settings));
}
connect(this, &Launcher::aboutToQuit, [this](){
connect(this, &Application::aboutToQuit, [this](){
if(m_instances)
{
// save any remaining instance state
@ -881,7 +882,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
}
auto analyticsSetting = m_settings->getSetting("Analytics");
connect(analyticsSetting.get(), &Setting::SettingChanged, this, &Launcher::analyticsSettingChanged);
connect(analyticsSetting.get(), &Setting::SettingChanged, this, &Application::analyticsSettingChanged);
QString clientID = m_settings->get("AnalyticsClientID").toString();
if(clientID.isEmpty())
{
@ -893,7 +894,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
m_analytics = new GAnalytics(BuildConfig.ANALYTICS_ID, clientID, analyticsVersion, this);
m_analytics->setLogLevel(GAnalytics::Debug);
m_analytics->setAnonymizeIPs(true);
m_analytics->setNetworkAccessManager(&ENV.network());
m_analytics->setNetworkAccessManager(&ENV->network());
if(m_settings->get("AnalyticsSeen").toInt() < m_analytics->version())
{
@ -917,7 +918,7 @@ Launcher::Launcher(int &argc, char **argv) : QApplication(argc, argv)
performMainStartupAction();
}
bool Launcher::createSetupWizard()
bool Application::createSetupWizard()
{
bool javaRequired = [&]()
{
@ -975,22 +976,22 @@ bool Launcher::createSetupWizard()
{
m_setupWizard->addPage(new AnalyticsWizardPage(m_setupWizard));
}
connect(m_setupWizard, &QDialog::finished, this, &Launcher::setupWizardFinished);
connect(m_setupWizard, &QDialog::finished, this, &Application::setupWizardFinished);
m_setupWizard->show();
return true;
}
return false;
}
void Launcher::setupWizardFinished(int status)
void Application::setupWizardFinished(int status)
{
qDebug() << "Wizard result =" << status;
performMainStartupAction();
}
void Launcher::performMainStartupAction()
void Application::performMainStartupAction()
{
m_status = Launcher::Initialized;
m_status = Application::Initialized;
if(!m_instanceIdToLaunch.isEmpty())
{
auto inst = instances()->getInstanceById(m_instanceIdToLaunch);
@ -1033,14 +1034,14 @@ void Launcher::performMainStartupAction()
}
}
void Launcher::showFatalErrorMessage(const QString& title, const QString& content)
void Application::showFatalErrorMessage(const QString& title, const QString& content)
{
m_status = Launcher::Failed;
m_status = Application::Failed;
auto dialog = CustomMessageBox::selectable(nullptr, title, content, QMessageBox::Critical);
dialog->exec();
}
Launcher::~Launcher()
Application::~Application()
{
// kill the other globals.
Env::dispose();
@ -1060,7 +1061,7 @@ Launcher::~Launcher()
#endif
}
void Launcher::messageReceived(const QByteArray& message)
void Application::messageReceived(const QByteArray& message)
{
if(status() != Initialized)
{
@ -1068,7 +1069,7 @@ void Launcher::messageReceived(const QByteArray& message)
return;
}
LauncherMessage received;
ApplicationMessage received;
received.parse(message);
auto & command = received.command;
@ -1134,7 +1135,7 @@ void Launcher::messageReceived(const QByteArray& message)
}
}
void Launcher::analyticsSettingChanged(const Setting&, QVariant value)
void Application::analyticsSettingChanged(const Setting&, QVariant value)
{
if(!m_analytics)
return;
@ -1150,12 +1151,12 @@ void Launcher::analyticsSettingChanged(const Setting&, QVariant value)
m_analytics->enable(enabled);
}
std::shared_ptr<TranslationsModel> Launcher::translations()
std::shared_ptr<TranslationsModel> Application::translations()
{
return m_translations;
}
std::shared_ptr<JavaInstallList> Launcher::javalist()
std::shared_ptr<JavaInstallList> Application::javalist()
{
if (!m_javalist)
{
@ -1164,7 +1165,7 @@ std::shared_ptr<JavaInstallList> Launcher::javalist()
return m_javalist;
}
std::vector<ITheme *> Launcher::getValidApplicationThemes()
std::vector<ITheme *> Application::getValidApplicationThemes()
{
std::vector<ITheme *> ret;
auto iter = m_themes.cbegin();
@ -1176,7 +1177,7 @@ std::vector<ITheme *> Launcher::getValidApplicationThemes()
return ret;
}
void Launcher::setApplicationTheme(const QString& name, bool initial)
void Application::setApplicationTheme(const QString& name, bool initial)
{
auto systemPalette = qApp->palette();
auto themeIter = m_themes.find(name);
@ -1191,12 +1192,12 @@ void Launcher::setApplicationTheme(const QString& name, bool initial)
}
}
void Launcher::setIconTheme(const QString& name)
void Application::setIconTheme(const QString& name)
{
XdgIcon::setThemeName(name);
}
QIcon Launcher::getThemedIcon(const QString& name)
QIcon Application::getThemedIcon(const QString& name)
{
if(name == "logo") {
return QIcon(":/logo.svg");
@ -1204,7 +1205,7 @@ QIcon Launcher::getThemedIcon(const QString& name)
return XdgIcon::fromTheme(name);
}
bool Launcher::openJsonEditor(const QString &filename)
bool Application::openJsonEditor(const QString &filename)
{
const QString file = QDir::current().absoluteFilePath(filename);
if (m_settings->get("JsonEditor").toString().isEmpty())
@ -1218,7 +1219,7 @@ bool Launcher::openJsonEditor(const QString &filename)
}
}
bool Launcher::launch(
bool Application::launch(
InstancePtr instance,
bool online,
BaseProfilerFactory *profiler,
@ -1255,8 +1256,8 @@ bool Launcher::launch(
{
controller->setParentWidget(m_mainWindow);
}
connect(controller.get(), &LaunchController::succeeded, this, &Launcher::controllerSucceeded);
connect(controller.get(), &LaunchController::failed, this, &Launcher::controllerFailed);
connect(controller.get(), &LaunchController::succeeded, this, &Application::controllerSucceeded);
connect(controller.get(), &LaunchController::failed, this, &Application::controllerFailed);
addRunningInstance();
controller->start();
return true;
@ -1274,7 +1275,7 @@ bool Launcher::launch(
return false;
}
bool Launcher::kill(InstancePtr instance)
bool Application::kill(InstancePtr instance)
{
if (!instance->isRunning())
{
@ -1291,7 +1292,7 @@ bool Launcher::kill(InstancePtr instance)
return true;
}
void Launcher::addRunningInstance()
void Application::addRunningInstance()
{
m_runningInstances ++;
if(m_runningInstances == 1)
@ -1300,7 +1301,7 @@ void Launcher::addRunningInstance()
}
}
void Launcher::subRunningInstance()
void Application::subRunningInstance()
{
if(m_runningInstances == 0)
{
@ -1314,23 +1315,23 @@ void Launcher::subRunningInstance()
}
}
bool Launcher::shouldExitNow() const
bool Application::shouldExitNow() const
{
return m_runningInstances == 0 && m_openWindows == 0;
}
bool Launcher::updatesAreAllowed()
bool Application::updatesAreAllowed()
{
return m_runningInstances == 0;
}
void Launcher::updateIsRunning(bool running)
void Application::updateIsRunning(bool running)
{
m_updateRunning = running;
}
void Launcher::controllerSucceeded()
void Application::controllerSucceeded()
{
auto controller = qobject_cast<LaunchController *>(QObject::sender());
if(!controller)
@ -1357,7 +1358,7 @@ void Launcher::controllerSucceeded()
}
}
void Launcher::controllerFailed(const QString& error)
void Application::controllerFailed(const QString& error)
{
Q_UNUSED(error);
auto controller = qobject_cast<LaunchController *>(QObject::sender());
@ -1378,21 +1379,21 @@ void Launcher::controllerFailed(const QString& error)
}
}
void Launcher::ShowGlobalSettings(class QWidget* parent, QString open_page)
void Application::ShowGlobalSettings(class QWidget* parent, QString open_page)
{
if(!m_globalSettingsProvider) {
return;
}
emit globalSettingsAboutToOpen();
{
SettingsObject::Lock lock(LAUNCHER->settings());
SettingsObject::Lock lock(APPLICATION->settings());
PageDialog dlg(m_globalSettingsProvider.get(), open_page, parent);
dlg.exec();
}
emit globalSettingsClosed();
}
MainWindow* Launcher::showMainWindow(bool minimized)
MainWindow* Application::showMainWindow(bool minimized)
{
if(m_mainWindow)
{
@ -1403,8 +1404,8 @@ MainWindow* Launcher::showMainWindow(bool minimized)
else
{
m_mainWindow = new MainWindow();
m_mainWindow->restoreState(QByteArray::fromBase64(LAUNCHER->settings()->get("MainWindowState").toByteArray()));
m_mainWindow->restoreGeometry(QByteArray::fromBase64(LAUNCHER->settings()->get("MainWindowGeometry").toByteArray()));
m_mainWindow->restoreState(QByteArray::fromBase64(APPLICATION->settings()->get("MainWindowState").toByteArray()));
m_mainWindow->restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("MainWindowGeometry").toByteArray()));
if(minimized)
{
m_mainWindow->showMinimized();
@ -1415,8 +1416,8 @@ MainWindow* Launcher::showMainWindow(bool minimized)
}
m_mainWindow->checkInstancePathForProblems();
connect(this, &Launcher::updateAllowedChanged, m_mainWindow, &MainWindow::updatesAllowedChanged);
connect(m_mainWindow, &MainWindow::isClosing, this, &Launcher::on_windowClose);
connect(this, &Application::updateAllowedChanged, m_mainWindow, &MainWindow::updatesAllowedChanged);
connect(m_mainWindow, &MainWindow::isClosing, this, &Application::on_windowClose);
m_openWindows++;
}
// FIXME: move this somewhere else...
@ -1476,7 +1477,7 @@ MainWindow* Launcher::showMainWindow(bool minimized)
return m_mainWindow;
}
InstanceWindow *Launcher::showInstanceWindow(InstancePtr instance, QString page)
InstanceWindow *Application::showInstanceWindow(InstancePtr instance, QString page)
{
if(!instance)
return nullptr;
@ -1493,7 +1494,7 @@ InstanceWindow *Launcher::showInstanceWindow(InstancePtr instance, QString page)
{
window = new InstanceWindow(instance);
m_openWindows ++;
connect(window, &InstanceWindow::isClosing, this, &Launcher::on_windowClose);
connect(window, &InstanceWindow::isClosing, this, &Application::on_windowClose);
}
if(!page.isEmpty())
{
@ -1506,7 +1507,7 @@ InstanceWindow *Launcher::showInstanceWindow(InstancePtr instance, QString page)
return window;
}
void Launcher::on_windowClose()
void Application::on_windowClose()
{
m_openWindows--;
auto instWindow = qobject_cast<InstanceWindow *>(QObject::sender());
@ -1530,3 +1531,7 @@ void Launcher::on_windowClose()
exit(0);
}
}
QString Application::msaClientId() const {
return Secrets::getMSAClientID('-');
}

View File

@ -36,12 +36,12 @@ class ITheme;
class MCEditTool;
class GAnalytics;
#if defined(LAUNCHER)
#undef LAUNCHER
#if defined(APPLICATION)
#undef APPLICATION
#endif
#define LAUNCHER (static_cast<Launcher *>(QCoreApplication::instance()))
#define APPLICATION (static_cast<Application *>(QCoreApplication::instance()))
class Launcher : public QApplication
class Application : public QApplication
{
// friends for the purpose of limiting access to deprecated stuff
Q_OBJECT
@ -55,8 +55,8 @@ public:
};
public:
Launcher(int &argc, char **argv);
virtual ~Launcher();
Application(int &argc, char **argv);
virtual ~Application();
GAnalytics *analytics() const
{
@ -111,11 +111,13 @@ public:
return m_mcedit.get();
}
std::shared_ptr<AccountList> accounts() const
shared_qobject_ptr<AccountList> accounts() const
{
return m_accounts;
}
QString msaClientId() const;
Status status() const
{
return m_status;
@ -189,7 +191,7 @@ private:
FolderInstanceProvider * m_instanceFolder = nullptr;
std::shared_ptr<IconList> m_icons;
std::shared_ptr<UpdateChecker> m_updateChecker;
std::shared_ptr<AccountList> m_accounts;
shared_qobject_ptr<AccountList> m_accounts;
std::shared_ptr<JavaInstallList> m_javalist;
std::shared_ptr<TranslationsModel> m_translations;
std::shared_ptr<GenericPageProvider> m_globalSettingsProvider;
@ -199,7 +201,7 @@ private:
QMap<QString, std::shared_ptr<BaseProfilerFactory>> m_profilers;
QString m_rootPath;
Status m_status = Launcher::StartingUp;
Status m_status = Application::StartingUp;
#if defined Q_OS_WIN32
// used on Windows to attach the standard IO streams

View File

@ -1,9 +1,9 @@
#include "LauncherMessage.h"
#include "ApplicationMessage.h"
#include <QJsonDocument>
#include <QJsonObject>
void LauncherMessage::parse(const QByteArray & input) {
void ApplicationMessage::parse(const QByteArray & input) {
auto doc = QJsonDocument::fromBinaryData(input);
auto root = doc.object();
@ -16,7 +16,7 @@ void LauncherMessage::parse(const QByteArray & input) {
}
}
QByteArray LauncherMessage::serialize() {
QByteArray ApplicationMessage::serialize() {
QJsonObject root;
root.insert("command", command);
QJsonObject outArgs;

View File

@ -4,7 +4,7 @@
#include <QMap>
#include <QByteArray>
struct LauncherMessage {
struct ApplicationMessage {
QString command;
QMap<QString, QString> args;

View File

@ -564,12 +564,12 @@ set(LOGIC_SOURCES
SET(LAUNCHER_SOURCES
# Application base
Launcher.h
Launcher.cpp
Application.h
Application.cpp
UpdateController.cpp
UpdateController.h
LauncherMessage.h
LauncherMessage.cpp
ApplicationMessage.h
ApplicationMessage.cpp
# GUI - general utilities
DesktopServices.h

View File

@ -39,13 +39,13 @@ Env::~Env()
delete d;
}
Env& Env::Env::getInstance()
Env* Env::Env::getInstance()
{
if(!instance)
{
instance = new Env();
}
return *instance;
return instance;
}
void Env::dispose()

View File

@ -25,14 +25,14 @@ class Index;
class Env
{
friend class Launcher;
friend class Application;
private:
struct Private;
Env();
~Env();
static void dispose();
public:
static Env& getInstance();
static Env* getInstance();
QNetworkAccessManager &network() const;

View File

@ -8,7 +8,7 @@
#include "net/PasteUpload.h"
#include "dialogs/CustomMessageBox.h"
#include "Launcher.h"
#include "Application.h"
#include <settings/SettingsObject.h>
#include <DesktopServices.h>
#include <BuildConfig.h>
@ -16,7 +16,7 @@
QString GuiUtil::uploadPaste(const QString &text, QWidget *parentWidget)
{
ProgressDialog dialog(parentWidget);
auto APIKeySetting = LAUNCHER->settings()->get("PasteEEAPIKey").toString();
auto APIKeySetting = APPLICATION->settings()->get("PasteEEAPIKey").toString();
if(APIKeySetting == "multimc")
{
APIKeySetting = BuildConfig.PASTE_EE_KEY;

View File

@ -51,7 +51,7 @@ void InstanceImportTask::executeTask()
m_downloadRequired = true;
const QString path = m_sourceUrl.host() + '/' + m_sourceUrl.path();
auto entry = ENV.metacache()->resolveEntry("general", path);
auto entry = ENV->metacache()->resolveEntry("general", path);
entry->setStale(true);
m_filesNetJob.reset(new NetJob(tr("Modpack download")));
m_filesNetJob->addNetAction(Net::Download::makeCached(m_sourceUrl, entry));
@ -444,7 +444,7 @@ void InstanceImportTask::processMultiMC()
if (!importIconPath.isNull() && QFile::exists(importIconPath))
{
// import icon
auto iconList = ENV.icons();
auto iconList = ENV->icons();
if (iconList->iconFileExists(m_instIcon))
{
iconList->deleteIcon(m_instIcon);

View File

@ -14,7 +14,7 @@
*/
#include "InstanceWindow.h"
#include "Launcher.h"
#include "Application.h"
#include <QScrollBar>
#include <QMessageBox>
@ -35,7 +35,7 @@ InstanceWindow::InstanceWindow(InstancePtr instance, QWidget *parent)
{
setAttribute(Qt::WA_DeleteOnClose);
auto icon = LAUNCHER->icons()->getIcon(m_instance->iconKey());
auto icon = APPLICATION->icons()->getIcon(m_instance->iconKey());
QString windowTitle = tr("Console window for ") + m_instance->name();
// Set window properties
@ -87,9 +87,9 @@ InstanceWindow::InstanceWindow(InstancePtr instance, QWidget *parent)
// restore window state
{
auto base64State = LAUNCHER->settings()->get("ConsoleWindowState").toByteArray();
auto base64State = APPLICATION->settings()->get("ConsoleWindowState").toByteArray();
restoreState(QByteArray::fromBase64(base64State));
auto base64Geometry = LAUNCHER->settings()->get("ConsoleWindowGeometry").toByteArray();
auto base64Geometry = APPLICATION->settings()->get("ConsoleWindowGeometry").toByteArray();
restoreGeometry(QByteArray::fromBase64(base64Geometry));
}
@ -148,7 +148,7 @@ void InstanceWindow::updateLaunchButtons()
void InstanceWindow::on_btnLaunchMinecraftOffline_clicked()
{
LAUNCHER->launch(m_instance, false, nullptr);
APPLICATION->launch(m_instance, false, nullptr);
}
void InstanceWindow::on_InstanceLaunchTask_changed(shared_qobject_ptr<LaunchTask> proc)
@ -183,8 +183,8 @@ void InstanceWindow::closeEvent(QCloseEvent *event)
return;
}
LAUNCHER->settings()->set("ConsoleWindowState", saveState().toBase64());
LAUNCHER->settings()->set("ConsoleWindowGeometry", saveGeometry().toBase64());
APPLICATION->settings()->set("ConsoleWindowState", saveState().toBase64());
APPLICATION->settings()->set("ConsoleWindowGeometry", saveGeometry().toBase64());
emit isClosing();
event->accept();
}
@ -198,11 +198,11 @@ void InstanceWindow::on_btnKillMinecraft_clicked()
{
if(m_instance->isRunning())
{
LAUNCHER->kill(m_instance);
APPLICATION->kill(m_instance);
}
else
{
LAUNCHER->launch(m_instance, true, nullptr);
APPLICATION->launch(m_instance, true, nullptr);
}
}

View File

@ -1,7 +1,7 @@
#include "LaunchController.h"
#include "MainWindow.h"
#include <minecraft/auth/AccountList.h>
#include "Launcher.h"
#include "Application.h"
#include "dialogs/CustomMessageBox.h"
#include "dialogs/ProfileSelectDialog.h"
#include "dialogs/ProgressDialog.h"
@ -42,7 +42,7 @@ void LaunchController::decideAccount()
}
// Find an account to use.
std::shared_ptr<AccountList> accounts = LAUNCHER->accounts();
auto accounts = APPLICATION->accounts();
if (accounts->count() <= 0)
{
// Tell the user they need to log in at least one account in order to play.
@ -59,12 +59,12 @@ void LaunchController::decideAccount()
if (reply == QMessageBox::Yes)
{
// Open the account manager.
LAUNCHER->ShowGlobalSettings(m_parentWidget, "accounts");
APPLICATION->ShowGlobalSettings(m_parentWidget, "accounts");
}
}
m_accountToUse = accounts->activeAccount();
if (m_accountToUse == nullptr)
m_accountToUse = accounts->defaultAccount();
if (!m_accountToUse)
{
// If no default account is set, ask the user which one to use.
ProfileSelectDialog selectDialog(
@ -80,7 +80,7 @@ void LaunchController::decideAccount()
// If the user said to use the account as default, do that.
if (selectDialog.useAsGlobalDefault() && m_accountToUse) {
accounts->setActiveAccount(m_accountToUse);
accounts->setDefaultAccount(m_accountToUse);
}
}
}
@ -110,7 +110,7 @@ void LaunchController::login() {
{
m_session = std::make_shared<AuthSession>();
m_session->wants_online = m_online;
std::shared_ptr<AccountTask> task;
shared_qobject_ptr<AccountTask> task;
if(!password.isNull()) {
task = m_accountToUse->login(m_session, password);
}
@ -294,7 +294,7 @@ void LaunchController::launchInstance()
auto showConsole = m_instance->settings()->get("ShowConsole").toBool();
if(!console && showConsole)
{
LAUNCHER->showInstanceWindow(m_instance);
APPLICATION->showInstanceWindow(m_instance);
}
connect(m_launcher.get(), &LaunchTask::readyForLaunch, this, &LaunchController::readyForLaunch);
connect(m_launcher.get(), &LaunchTask::succeeded, this, &LaunchController::onSucceeded);
@ -400,7 +400,7 @@ void LaunchController::onFailed(QString reason)
{
if(m_instance->settings()->get("ShowConsoleOnError").toBool())
{
LAUNCHER->showInstanceWindow(m_instance, "console");
APPLICATION->showInstanceWindow(m_instance, "console");
}
emitFailed(reason);
}

View File

@ -16,7 +16,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Launcher.h"
#include "Application.h"
#include "BuildConfig.h"
#include "MainWindow.h"
@ -278,7 +278,7 @@ public:
actionAddInstance = TranslatedAction(MainWindow);
actionAddInstance->setObjectName(QStringLiteral("actionAddInstance"));
actionAddInstance->setIcon(LAUNCHER->getThemedIcon("new"));
actionAddInstance->setIcon(APPLICATION->getThemedIcon("new"));
actionAddInstance.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Add Instance"));
actionAddInstance.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Add a new instance."));
all_actions.append(&actionAddInstance);
@ -291,7 +291,7 @@ public:
actionViewInstanceFolder = TranslatedAction(MainWindow);
actionViewInstanceFolder->setObjectName(QStringLiteral("actionViewInstanceFolder"));
actionViewInstanceFolder->setIcon(LAUNCHER->getThemedIcon("viewfolder"));
actionViewInstanceFolder->setIcon(APPLICATION->getThemedIcon("viewfolder"));
actionViewInstanceFolder.setTextId(QT_TRANSLATE_NOOP("MainWindow", "View Instance Folder"));
actionViewInstanceFolder.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Open the instance folder in a file browser."));
all_actions.append(&actionViewInstanceFolder);
@ -299,7 +299,7 @@ public:
actionViewCentralModsFolder = TranslatedAction(MainWindow);
actionViewCentralModsFolder->setObjectName(QStringLiteral("actionViewCentralModsFolder"));
actionViewCentralModsFolder->setIcon(LAUNCHER->getThemedIcon("centralmods"));
actionViewCentralModsFolder->setIcon(APPLICATION->getThemedIcon("centralmods"));
actionViewCentralModsFolder.setTextId(QT_TRANSLATE_NOOP("MainWindow", "View Central Mods Folder"));
actionViewCentralModsFolder.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Open the central mods folder in a file browser."));
all_actions.append(&actionViewCentralModsFolder);
@ -311,7 +311,7 @@ public:
foldersMenuButton->setMenu(foldersMenu);
foldersMenuButton->setPopupMode(QToolButton::InstantPopup);
foldersMenuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
foldersMenuButton->setIcon(LAUNCHER->getThemedIcon("viewfolder"));
foldersMenuButton->setIcon(APPLICATION->getThemedIcon("viewfolder"));
foldersMenuButton->setFocusPolicy(Qt::NoFocus);
all_toolbuttons.append(&foldersMenuButton);
QWidgetAction* foldersButtonAction = new QWidgetAction(MainWindow);
@ -320,7 +320,7 @@ public:
actionSettings = TranslatedAction(MainWindow);
actionSettings->setObjectName(QStringLiteral("actionSettings"));
actionSettings->setIcon(LAUNCHER->getThemedIcon("settings"));
actionSettings->setIcon(APPLICATION->getThemedIcon("settings"));
actionSettings->setMenuRole(QAction::PreferencesRole);
actionSettings.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Settings"));
actionSettings.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Change settings."));
@ -333,7 +333,7 @@ public:
if (!BuildConfig.BUG_TRACKER_URL.isEmpty()) {
actionReportBug = TranslatedAction(MainWindow);
actionReportBug->setObjectName(QStringLiteral("actionReportBug"));
actionReportBug->setIcon(LAUNCHER->getThemedIcon("bug"));
actionReportBug->setIcon(APPLICATION->getThemedIcon("bug"));
actionReportBug.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Report a Bug"));
actionReportBug.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Open the bug tracker to report a bug with %1."));
all_actions.append(&actionReportBug);
@ -343,7 +343,7 @@ public:
if (!BuildConfig.DISCORD_URL.isEmpty()) {
actionDISCORD = TranslatedAction(MainWindow);
actionDISCORD->setObjectName(QStringLiteral("actionDISCORD"));
actionDISCORD->setIcon(LAUNCHER->getThemedIcon("discord"));
actionDISCORD->setIcon(APPLICATION->getThemedIcon("discord"));
actionDISCORD.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Discord"));
actionDISCORD.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Open %1 discord voice chat."));
all_actions.append(&actionDISCORD);
@ -353,7 +353,7 @@ public:
if (!BuildConfig.SUBREDDIT_URL.isEmpty()) {
actionREDDIT = TranslatedAction(MainWindow);
actionREDDIT->setObjectName(QStringLiteral("actionREDDIT"));
actionREDDIT->setIcon(LAUNCHER->getThemedIcon("reddit-alien"));
actionREDDIT->setIcon(APPLICATION->getThemedIcon("reddit-alien"));
actionREDDIT.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Reddit"));
actionREDDIT.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Open %1 subreddit."));
all_actions.append(&actionREDDIT);
@ -362,7 +362,7 @@ public:
actionAbout = TranslatedAction(MainWindow);
actionAbout->setObjectName(QStringLiteral("actionAbout"));
actionAbout->setIcon(LAUNCHER->getThemedIcon("about"));
actionAbout->setIcon(APPLICATION->getThemedIcon("about"));
actionAbout->setMenuRole(QAction::AboutRole);
actionAbout.setTextId(QT_TRANSLATE_NOOP("MainWindow", "About %1"));
actionAbout.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "View information about %1."));
@ -375,7 +375,7 @@ public:
helpMenuButton->setMenu(helpMenu);
helpMenuButton->setPopupMode(QToolButton::InstantPopup);
helpMenuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
helpMenuButton->setIcon(LAUNCHER->getThemedIcon("help"));
helpMenuButton->setIcon(APPLICATION->getThemedIcon("help"));
helpMenuButton->setFocusPolicy(Qt::NoFocus);
all_toolbuttons.append(&helpMenuButton);
QWidgetAction* helpButtonAction = new QWidgetAction(MainWindow);
@ -386,7 +386,7 @@ public:
{
actionCheckUpdate = TranslatedAction(MainWindow);
actionCheckUpdate->setObjectName(QStringLiteral("actionCheckUpdate"));
actionCheckUpdate->setIcon(LAUNCHER->getThemedIcon("checkupdate"));
actionCheckUpdate->setIcon(APPLICATION->getThemedIcon("checkupdate"));
actionCheckUpdate.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Update"));
actionCheckUpdate.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Check for new updates for %1."));
all_actions.append(&actionCheckUpdate);
@ -397,7 +397,7 @@ public:
actionPatreon = TranslatedAction(MainWindow);
actionPatreon->setObjectName(QStringLiteral("actionPatreon"));
actionPatreon->setIcon(LAUNCHER->getThemedIcon("patreon"));
actionPatreon->setIcon(APPLICATION->getThemedIcon("patreon"));
actionPatreon.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Support %1"));
actionPatreon.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Open the %1 Patreon page."));
all_actions.append(&actionPatreon);
@ -406,7 +406,7 @@ public:
actionCAT = TranslatedAction(MainWindow);
actionCAT->setObjectName(QStringLiteral("actionCAT"));
actionCAT->setCheckable(true);
actionCAT->setIcon(LAUNCHER->getThemedIcon("cat"));
actionCAT->setIcon(APPLICATION->getThemedIcon("cat"));
actionCAT.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Meow"));
actionCAT.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "It's a fluffy kitty :3"));
actionCAT->setPriority(QAction::LowPriority);
@ -419,7 +419,7 @@ public:
actionManageAccounts.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Manage Accounts"));
// FIXME: no tooltip!
actionManageAccounts->setCheckable(false);
actionManageAccounts->setIcon(LAUNCHER->getThemedIcon("accounts"));
actionManageAccounts->setIcon(APPLICATION->getThemedIcon("accounts"));
all_actions.append(&actionManageAccounts);
all_toolbars.append(&mainToolBar);
@ -446,7 +446,7 @@ public:
actionMoreNews = TranslatedAction(MainWindow);
actionMoreNews->setObjectName(QStringLiteral("actionMoreNews"));
actionMoreNews->setIcon(LAUNCHER->getThemedIcon("news"));
actionMoreNews->setIcon(APPLICATION->getThemedIcon("news"));
actionMoreNews.setTextId(QT_TRANSLATE_NOOP("MainWindow", "More news..."));
actionMoreNews.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Open the development blog to read more news about %1."));
all_actions.append(&actionMoreNews);
@ -478,7 +478,7 @@ public:
changeIconButton = new LabeledToolButton(MainWindow);
changeIconButton->setObjectName(QStringLiteral("changeIconButton"));
changeIconButton->setIcon(LAUNCHER->getThemedIcon("news"));
changeIconButton->setIcon(APPLICATION->getThemedIcon("news"));
changeIconButton->setToolTip(actionChangeInstIcon->toolTip());
changeIconButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
instanceToolBar->addWidget(changeIconButton);
@ -589,7 +589,7 @@ public:
actionCopyInstance = TranslatedAction(MainWindow);
actionCopyInstance->setObjectName(QStringLiteral("actionCopyInstance"));
actionCopyInstance->setIcon(LAUNCHER->getThemedIcon("copy"));
actionCopyInstance->setIcon(APPLICATION->getThemedIcon("copy"));
actionCopyInstance.setTextId(QT_TRANSLATE_NOOP("MainWindow", "Copy Instance"));
actionCopyInstance.setTooltipId(QT_TRANSLATE_NOOP("MainWindow", "Copy the selected instance."));
all_actions.append(&actionCopyInstance);
@ -606,7 +606,7 @@ public:
MainWindow->setObjectName(QStringLiteral("MainWindow"));
}
MainWindow->resize(800, 600);
MainWindow->setWindowIcon(LAUNCHER->getThemedIcon("logo"));
MainWindow->setWindowIcon(APPLICATION->getThemedIcon("logo"));
MainWindow->setWindowTitle(BuildConfig.LAUNCHER_DISPLAYNAME);
#ifndef QT_NO_ACCESSIBILITY
MainWindow->setAccessibleName(BuildConfig.LAUNCHER_NAME);
@ -683,7 +683,7 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
{
m_newsChecker.reset(new NewsChecker(BuildConfig.NEWS_RSS_URL));
newsLabel = new QToolButton();
newsLabel->setIcon(LAUNCHER->getThemedIcon("news"));
newsLabel->setIcon(APPLICATION->getThemedIcon("news"));
newsLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
newsLabel->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
newsLabel->setFocusPolicy(Qt::NoFocus);
@ -710,20 +710,20 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
connect(view, &InstanceView::droppedURLs, this, &MainWindow::droppedURLs, Qt::QueuedConnection);
proxymodel = new InstanceProxyModel(this);
proxymodel->setSourceModel(LAUNCHER->instances().get());
proxymodel->setSourceModel(APPLICATION->instances().get());
proxymodel->sort(0);
connect(proxymodel, &InstanceProxyModel::dataChanged, this, &MainWindow::instanceDataChanged);
view->setModel(proxymodel);
view->setSourceOfGroupCollapseStatus([](const QString & groupName)->bool {
return LAUNCHER->instances()->isGroupCollapsed(groupName);
return APPLICATION->instances()->isGroupCollapsed(groupName);
});
connect(view, &InstanceView::groupStateChanged, LAUNCHER->instances().get(), &InstanceList::on_GroupStateChanged);
connect(view, &InstanceView::groupStateChanged, APPLICATION->instances().get(), &InstanceList::on_GroupStateChanged);
ui->horizontalLayout->addWidget(view);
}
// The cat background
{
bool cat_enable = LAUNCHER->settings()->get("TheCat").toBool();
bool cat_enable = APPLICATION->settings()->get("TheCat").toBool();
ui->actionCAT->setChecked(cat_enable);
// NOTE: calling the operator like that is an ugly hack to appease ancient gcc...
connect(ui->actionCAT.operator->(), SIGNAL(toggled(bool)), SLOT(onCatToggled(bool)));
@ -736,16 +736,16 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
connect(view->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::instanceChanged);
// track icon changes and update the toolbar!
connect(LAUNCHER->icons().get(), &IconList::iconUpdated, this, &MainWindow::iconUpdated);
connect(APPLICATION->icons().get(), &IconList::iconUpdated, this, &MainWindow::iconUpdated);
// model reset -> selection is invalid. All the instance pointers are wrong.
connect(LAUNCHER->instances().get(), &InstanceList::dataIsInvalid, this, &MainWindow::selectionBad);
connect(APPLICATION->instances().get(), &InstanceList::dataIsInvalid, this, &MainWindow::selectionBad);
// handle newly added instances
connect(LAUNCHER->instances().get(), &InstanceList::instanceSelectRequest, this, &MainWindow::instanceSelectRequest);
connect(APPLICATION->instances().get(), &InstanceList::instanceSelectRequest, this, &MainWindow::instanceSelectRequest);
// When the global settings page closes, we want to know about it and update our state
connect(LAUNCHER, &Launcher::globalSettingsClosed, this, &MainWindow::globalSettingsClosed);
connect(APPLICATION, &Application::globalSettingsClosed, this, &MainWindow::globalSettingsClosed);
m_statusLeft = new QLabel(tr("No instance selected"), this);
m_statusCenter = new QLabel(tr("Total playtime: 0s"), this);
@ -765,7 +765,7 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
accountMenuButton->setMenu(accountMenu);
accountMenuButton->setPopupMode(QToolButton::InstantPopup);
accountMenuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
accountMenuButton->setIcon(LAUNCHER->getThemedIcon("noaccount"));
accountMenuButton->setIcon(APPLICATION->getThemedIcon("noaccount"));
QWidgetAction *accountMenuButtonAction = new QWidgetAction(this);
accountMenuButtonAction->setDefaultWidget(accountMenuButton);
@ -776,14 +776,14 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
// Shouldn't have to use lambdas here like this, but if I don't, the compiler throws a fit.
// Template hell sucks...
connect(
LAUNCHER->accounts().get(),
&AccountList::activeAccountChanged,
APPLICATION->accounts().get(),
&AccountList::defaultAccountChanged,
[this] {
activeAccountChanged();
defaultAccountChanged();
}
);
connect(
LAUNCHER->accounts().get(),
APPLICATION->accounts().get(),
&AccountList::listChanged,
[this]
{
@ -792,10 +792,10 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
);
// Show initial account
activeAccountChanged();
defaultAccountChanged();
// TODO: refresh accounts here?
// auto accounts = LAUNCHER->accounts();
// auto accounts = APPLICATION->accounts();
// load the news
{
@ -806,20 +806,20 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
if(BuildConfig.UPDATER_ENABLED)
{
bool updatesAllowed = LAUNCHER->updatesAreAllowed();
bool updatesAllowed = APPLICATION->updatesAreAllowed();
updatesAllowedChanged(updatesAllowed);
// NOTE: calling the operator like that is an ugly hack to appease ancient gcc...
connect(ui->actionCheckUpdate.operator->(), &QAction::triggered, this, &MainWindow::checkForUpdates);
// set up the updater object.
auto updater = LAUNCHER->updateChecker();
auto updater = APPLICATION->updateChecker();
connect(updater.get(), &UpdateChecker::updateAvailable, this, &MainWindow::updateAvailable);
connect(updater.get(), &UpdateChecker::noUpdateFound, this, &MainWindow::updateNotAvailable);
// if automatic update checks are allowed, start one.
if (LAUNCHER->settings()->get("AutoUpdate").toBool() && updatesAllowed)
if (APPLICATION->settings()->get("AutoUpdate").toBool() && updatesAllowed)
{
updater->checkForUpdate(LAUNCHER->settings()->get("UpdateChannel").toString(), false);
updater->checkForUpdate(APPLICATION->settings()->get("UpdateChannel").toString(), false);
}
}
@ -834,7 +834,7 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
checker->checkForNotifications();
}
setSelectedInstanceById(LAUNCHER->settings()->get("SelectedInstance").toString());
setSelectedInstanceById(APPLICATION->settings()->get("SelectedInstance").toString());
// removing this looks stupid
view->setFocus();
@ -844,10 +844,10 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new MainWindow
void MainWindow::retranslateUi()
{
std::shared_ptr<AccountList> accounts = LAUNCHER->accounts();
MinecraftAccountPtr active_account = accounts->activeAccount();
if(active_account) {
auto profileLabel = profileInUseFilter(active_account->profileName(), active_account->isInUse());
auto accounts = APPLICATION->accounts();
MinecraftAccountPtr defaultAccount = accounts->defaultAccount();
if(defaultAccount) {
auto profileLabel = profileInUseFilter(defaultAccount->profileName(), defaultAccount->isInUse());
accountMenuButton->setText(profileLabel);
}
else {
@ -876,7 +876,7 @@ QMenu * MainWindow::createPopupMenu()
void MainWindow::konamiTriggered()
{
// ENV.enableFeature("NewModsPage");
// ENV->enableFeature("NewModsPage");
qDebug() << "Super Secret Mode ACTIVATED!";
}
@ -982,16 +982,16 @@ void MainWindow::updateToolsMenu()
QAction *normalLaunchOffline = launchOfflineMenu->addAction(tr("Launch Offline"));
connect(normalLaunch, &QAction::triggered, [this]()
{
LAUNCHER->launch(m_selectedInstance, true);
APPLICATION->launch(m_selectedInstance, true);
});
connect(normalLaunchOffline, &QAction::triggered, [this]()
{
LAUNCHER->launch(m_selectedInstance, false);
APPLICATION->launch(m_selectedInstance, false);
});
QString profilersTitle = tr("Profilers");
launchMenu->addSeparator()->setText(profilersTitle);
launchOfflineMenu->addSeparator()->setText(profilersTitle);
for (auto profiler : LAUNCHER->profilers().values())
for (auto profiler : APPLICATION->profilers().values())
{
QAction *profilerAction = launchMenu->addAction(profiler->name());
QAction *profilerOfflineAction = launchOfflineMenu->addAction(profiler->name());
@ -1008,11 +1008,11 @@ void MainWindow::updateToolsMenu()
{
connect(profilerAction, &QAction::triggered, [this, profiler]()
{
LAUNCHER->launch(m_selectedInstance, true, profiler.get());
APPLICATION->launch(m_selectedInstance, true, profiler.get());
});
connect(profilerOfflineAction, &QAction::triggered, [this, profiler]()
{
LAUNCHER->launch(m_selectedInstance, false, profiler.get());
APPLICATION->launch(m_selectedInstance, false, profiler.get());
});
}
}
@ -1024,16 +1024,16 @@ void MainWindow::repopulateAccountsMenu()
{
accountMenu->clear();
std::shared_ptr<AccountList> accounts = LAUNCHER->accounts();
MinecraftAccountPtr active_account = accounts->activeAccount();
auto accounts = APPLICATION->accounts();
MinecraftAccountPtr defaultAccount = accounts->defaultAccount();
QString active_profileId = "";
if (active_account != nullptr)
if (defaultAccount)
{
// this can be called before accountMenuButton exists
if (accountMenuButton)
{
auto profileLabel = profileInUseFilter(active_account->profileName(), active_account->isInUse());
auto profileLabel = profileInUseFilter(defaultAccount->profileName(), defaultAccount->isInUse());
accountMenuButton->setText(profileLabel);
}
}
@ -1054,7 +1054,7 @@ void MainWindow::repopulateAccountsMenu()
QAction *action = new QAction(profileLabel, this);
action->setData(i);
action->setCheckable(true);
if (active_account == account)
if (defaultAccount == account)
{
action->setChecked(true);
}
@ -1064,7 +1064,7 @@ void MainWindow::repopulateAccountsMenu()
action->setIcon(face);
}
else {
action->setIcon(LAUNCHER->getThemedIcon("noaccount"));
action->setIcon(APPLICATION->getThemedIcon("noaccount"));
}
accountMenu->addAction(action);
connect(action, SIGNAL(triggered(bool)), SLOT(changeActiveAccount()));
@ -1075,9 +1075,9 @@ void MainWindow::repopulateAccountsMenu()
QAction *action = new QAction(tr("No Default Account"), this);
action->setCheckable(true);
action->setIcon(LAUNCHER->getThemedIcon("noaccount"));
action->setIcon(APPLICATION->getThemedIcon("noaccount"));
action->setData(-1);
if (active_account == nullptr) {
if (!defaultAccount) {
action->setChecked(true);
}
@ -1114,25 +1114,25 @@ void MainWindow::changeActiveAccount()
if(!valid) {
index = -1;
}
std::shared_ptr<AccountList> accounts = LAUNCHER->accounts();
accounts->setActiveAccount(index == -1 ? nullptr : accounts->at(index));
activeAccountChanged();
auto accounts = APPLICATION->accounts();
accounts->setDefaultAccount(index == -1 ? nullptr : accounts->at(index));
defaultAccountChanged();
}
void MainWindow::activeAccountChanged()
void MainWindow::defaultAccountChanged()
{
repopulateAccountsMenu();
MinecraftAccountPtr account = LAUNCHER->accounts()->activeAccount();
MinecraftAccountPtr account = APPLICATION->accounts()->defaultAccount();
// FIXME: this needs adjustment for MSA
if (account != nullptr && account->profileName() != "")
if (account && account->profileName() != "")
{
auto profileLabel = profileInUseFilter(account->profileName(), account->isInUse());
accountMenuButton->setText(profileLabel);
auto face = account->getFace();
if(face.isNull()) {
accountMenuButton->setIcon(LAUNCHER->getThemedIcon("noaccount"));
accountMenuButton->setIcon(APPLICATION->getThemedIcon("noaccount"));
}
else {
accountMenuButton->setIcon(face);
@ -1141,7 +1141,7 @@ void MainWindow::activeAccountChanged()
}
// Set the icon to the "no account" icon.
accountMenuButton->setIcon(LAUNCHER->getThemedIcon("noaccount"));
accountMenuButton->setIcon(APPLICATION->getThemedIcon("noaccount"));
accountMenuButton->setText(tr("Profiles"));
}
@ -1203,7 +1203,7 @@ void MainWindow::updateNewsLabel()
void MainWindow::updateAvailable(GoUpdate::Status status)
{
if(!LAUNCHER->updatesAreAllowed())
if(!APPLICATION->updatesAreAllowed())
{
updateNotAvailable();
return;
@ -1249,7 +1249,7 @@ QString intListToString(const QList<int> &list)
void MainWindow::notificationsChanged()
{
QList<NotificationChecker::NotificationEntry> entries = m_notificationChecker->notificationEntries();
QList<int> shownNotifications = stringToIntList(LAUNCHER->settings()->get("ShownNotifications").toString());
QList<int> shownNotifications = stringToIntList(APPLICATION->settings()->get("ShownNotifications").toString());
for (auto it = entries.begin(); it != entries.end(); ++it)
{
NotificationChecker::NotificationEntry entry = *it;
@ -1262,20 +1262,20 @@ void MainWindow::notificationsChanged()
}
}
}
LAUNCHER->settings()->set("ShownNotifications", intListToString(shownNotifications));
APPLICATION->settings()->set("ShownNotifications", intListToString(shownNotifications));
}
void MainWindow::downloadUpdates(GoUpdate::Status status)
{
if(!LAUNCHER->updatesAreAllowed())
if(!APPLICATION->updatesAreAllowed())
{
return;
}
qDebug() << "Downloading updates.";
ProgressDialog updateDlg(this);
status.rootPath = LAUNCHER->root();
status.rootPath = APPLICATION->root();
auto dlPath = FS::PathCombine(LAUNCHER->root(), "update", "XXXXXX");
auto dlPath = FS::PathCombine(APPLICATION->root(), "update", "XXXXXX");
if (!FS::ensureFilePathExists(dlPath))
{
CustomMessageBox::selectable(this, tr("Error"), tr("Couldn't create folder for update downloads:\n%1").arg(dlPath), QMessageBox::Warning)->show();
@ -1288,10 +1288,10 @@ void MainWindow::downloadUpdates(GoUpdate::Status status)
* NOTE: This disables launching instances until the update either succeeds (and this process exits)
* or the update fails (and the control leaves this scope).
*/
LAUNCHER->updateIsRunning(true);
UpdateController update(this, LAUNCHER->root(), updateTask.updateFilesDir(), updateTask.operations());
APPLICATION->updateIsRunning(true);
UpdateController update(this, APPLICATION->root(), updateTask.updateFilesDir(), updateTask.operations());
update.installUpdates();
LAUNCHER->updateIsRunning(false);
APPLICATION->updateIsRunning(false);
}
else
{
@ -1302,7 +1302,7 @@ void MainWindow::downloadUpdates(GoUpdate::Status status)
void MainWindow::onCatToggled(bool state)
{
setCatBackground(state);
LAUNCHER->settings()->set("TheCat", state);
APPLICATION->settings()->set("TheCat", state);
}
namespace {
@ -1360,7 +1360,7 @@ void MainWindow::runModalTask(Task *task)
void MainWindow::instanceFromInstanceTask(InstanceTask *rawTask)
{
unique_qobject_ptr<Task> task(LAUNCHER->instances()->wrapInstanceTask(rawTask));
unique_qobject_ptr<Task> task(APPLICATION->instances()->wrapInstanceTask(rawTask));
runModalTask(task.get());
}
@ -1377,7 +1377,7 @@ void MainWindow::on_actionCopyInstance_triggered()
copyTask->setName(copyInstDlg.instName());
copyTask->setGroup(copyInstDlg.instGroup());
copyTask->setIcon(copyInstDlg.iconKey());
unique_qobject_ptr<Task> task(LAUNCHER->instances()->wrapInstanceTask(copyTask));
unique_qobject_ptr<Task> task(APPLICATION->instances()->wrapInstanceTask(copyTask));
runModalTask(task.get());
}
@ -1385,7 +1385,7 @@ void MainWindow::finalizeInstance(InstancePtr inst)
{
view->updateGeometries();
setSelectedInstanceById(inst->id());
if (LAUNCHER->accounts()->anyAccountIsValid())
if (APPLICATION->accounts()->anyAccountIsValid())
{
ProgressDialog loadDialog(this);
auto update = inst->createUpdateTask(Net::Mode::Online);
@ -1431,14 +1431,14 @@ void MainWindow::addInstance(QString url)
if(groupName.isEmpty())
{
groupName = LAUNCHER->settings()->get("LastUsedGroupForNewInstance").toString();
groupName = APPLICATION->settings()->get("LastUsedGroupForNewInstance").toString();
}
NewInstanceDialog newInstDlg(groupName, url, this);
if (!newInstDlg.exec())
return;
LAUNCHER->settings()->set("LastUsedGroupForNewInstance", newInstDlg.instGroup());
APPLICATION->settings()->set("LastUsedGroupForNewInstance", newInstDlg.instGroup());
InstanceTask * creationTask = newInstDlg.extractTask();
if(creationTask)
@ -1489,7 +1489,7 @@ void MainWindow::on_actionChangeInstIcon_triggered()
if (dlg.result() == QDialog::Accepted)
{
m_selectedInstance->setIconKey(dlg.selectedIconKey);
auto icon = LAUNCHER->icons()->getIcon(dlg.selectedIconKey);
auto icon = APPLICATION->icons()->getIcon(dlg.selectedIconKey);
ui->actionChangeInstIcon->setIcon(icon);
ui->changeIconButton->setIcon(icon);
}
@ -1499,7 +1499,7 @@ void MainWindow::iconUpdated(QString icon)
{
if (icon == m_currentInstIcon)
{
auto icon = LAUNCHER->icons()->getIcon(m_currentInstIcon);
auto icon = APPLICATION->icons()->getIcon(m_currentInstIcon);
ui->actionChangeInstIcon->setIcon(icon);
ui->changeIconButton->setIcon(icon);
}
@ -1508,7 +1508,7 @@ void MainWindow::iconUpdated(QString icon)
void MainWindow::updateInstanceToolIcon(QString new_icon)
{
m_currentInstIcon = new_icon;
auto icon = LAUNCHER->icons()->getIcon(m_currentInstIcon);
auto icon = APPLICATION->icons()->getIcon(m_currentInstIcon);
ui->actionChangeInstIcon->setIcon(icon);
ui->changeIconButton->setIcon(icon);
}
@ -1517,7 +1517,7 @@ void MainWindow::setSelectedInstanceById(const QString &id)
{
if (id.isNull())
return;
const QModelIndex index = LAUNCHER->instances()->getInstanceIndexById(id);
const QModelIndex index = APPLICATION->instances()->getInstanceIndexById(id);
if (index.isValid())
{
QModelIndex selectionIndex = proxymodel->mapFromSource(index);
@ -1533,8 +1533,8 @@ void MainWindow::on_actionChangeInstGroup_triggered()
bool ok = false;
InstanceId instId = m_selectedInstance->id();
QString name(LAUNCHER->instances()->getInstanceGroup(instId));
auto groups = LAUNCHER->instances()->getGroups();
QString name(APPLICATION->instances()->getInstanceGroup(instId));
auto groups = APPLICATION->instances()->getGroups();
groups.insert(0, "");
groups.sort(Qt::CaseInsensitive);
int foo = groups.indexOf(name);
@ -1543,7 +1543,7 @@ void MainWindow::on_actionChangeInstGroup_triggered()
name = name.simplified();
if (ok)
{
LAUNCHER->instances()->setInstanceGroup(instId, name);
APPLICATION->instances()->setInstanceGroup(instId, name);
}
}
@ -1565,25 +1565,25 @@ void MainWindow::deleteGroup()
.arg(groupName), QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes)
{
LAUNCHER->instances()->deleteGroup(groupName);
APPLICATION->instances()->deleteGroup(groupName);
}
}
}
void MainWindow::on_actionViewInstanceFolder_triggered()
{
QString str = LAUNCHER->settings()->get("InstanceDir").toString();
QString str = APPLICATION->settings()->get("InstanceDir").toString();
DesktopServices::openDirectory(str);
}
void MainWindow::refreshInstances()
{
LAUNCHER->instances()->loadList();
APPLICATION->instances()->loadList();
}
void MainWindow::on_actionViewCentralModsFolder_triggered()
{
DesktopServices::openDirectory(LAUNCHER->settings()->get("CentralModsDir").toString(), true);
DesktopServices::openDirectory(APPLICATION->settings()->get("CentralModsDir").toString(), true);
}
void MainWindow::on_actionConfig_Folder_triggered()
@ -1599,8 +1599,8 @@ void MainWindow::checkForUpdates()
{
if(BuildConfig.UPDATER_ENABLED)
{
auto updater = LAUNCHER->updateChecker();
updater->checkForUpdate(LAUNCHER->settings()->get("UpdateChannel").toString(), true);
auto updater = APPLICATION->updateChecker();
updater->checkForUpdate(APPLICATION->settings()->get("UpdateChannel").toString(), true);
}
else
{
@ -1610,13 +1610,13 @@ void MainWindow::checkForUpdates()
void MainWindow::on_actionSettings_triggered()
{
LAUNCHER->ShowGlobalSettings(this, "global-settings");
APPLICATION->ShowGlobalSettings(this, "global-settings");
}
void MainWindow::globalSettingsClosed()
{
// FIXME: quick HACK to make this work. improve, optimize.
LAUNCHER->instances()->loadList();
APPLICATION->instances()->loadList();
proxymodel->invalidate();
proxymodel->sort(0);
updateToolsMenu();
@ -1626,32 +1626,32 @@ void MainWindow::globalSettingsClosed()
void MainWindow::on_actionInstanceSettings_triggered()
{
LAUNCHER->showInstanceWindow(m_selectedInstance, "settings");
APPLICATION->showInstanceWindow(m_selectedInstance, "settings");
}
void MainWindow::on_actionEditInstNotes_triggered()
{
LAUNCHER->showInstanceWindow(m_selectedInstance, "notes");
APPLICATION->showInstanceWindow(m_selectedInstance, "notes");
}
void MainWindow::on_actionWorlds_triggered()
{
LAUNCHER->showInstanceWindow(m_selectedInstance, "worlds");
APPLICATION->showInstanceWindow(m_selectedInstance, "worlds");
}
void MainWindow::on_actionEditInstance_triggered()
{
LAUNCHER->showInstanceWindow(m_selectedInstance);
APPLICATION->showInstanceWindow(m_selectedInstance);
}
void MainWindow::on_actionScreenshots_triggered()
{
LAUNCHER->showInstanceWindow(m_selectedInstance, "screenshots");
APPLICATION->showInstanceWindow(m_selectedInstance, "screenshots");
}
void MainWindow::on_actionManageAccounts_triggered()
{
LAUNCHER->ShowGlobalSettings(this, "accounts");
APPLICATION->ShowGlobalSettings(this, "accounts");
}
void MainWindow::on_actionReportBug_triggered()
@ -1705,7 +1705,7 @@ void MainWindow::on_actionDeleteInstance_triggered()
)->exec();
if (response == QMessageBox::Yes)
{
LAUNCHER->instances()->deleteInstance(id);
APPLICATION->instances()->deleteInstance(id);
}
}
@ -1753,8 +1753,8 @@ void MainWindow::on_actionViewSelectedMCFolder_triggered()
void MainWindow::closeEvent(QCloseEvent *event)
{
// Save the window state and geometry.
LAUNCHER->settings()->set("MainWindowState", saveState().toBase64());
LAUNCHER->settings()->set("MainWindowGeometry", saveGeometry().toBase64());
APPLICATION->settings()->set("MainWindowState", saveState().toBase64());
APPLICATION->settings()->set("MainWindowGeometry", saveGeometry().toBase64());
event->accept();
emit isClosing();
}
@ -1773,7 +1773,7 @@ void MainWindow::instanceActivated(QModelIndex index)
if (!index.isValid())
return;
QString id = index.data(InstanceList::InstanceIDRole).toString();
InstancePtr inst = LAUNCHER->instances()->getInstanceById(id);
InstancePtr inst = APPLICATION->instances()->getInstanceById(id);
if (!inst)
return;
@ -1788,24 +1788,24 @@ void MainWindow::on_actionLaunchInstance_triggered()
}
if(m_selectedInstance->isRunning())
{
LAUNCHER->kill(m_selectedInstance);
APPLICATION->kill(m_selectedInstance);
}
else
{
LAUNCHER->launch(m_selectedInstance);
APPLICATION->launch(m_selectedInstance);
}
}
void MainWindow::activateInstance(InstancePtr instance)
{
LAUNCHER->launch(instance);
APPLICATION->launch(instance);
}
void MainWindow::on_actionLaunchInstanceOffline_triggered()
{
if (m_selectedInstance)
{
LAUNCHER->launch(m_selectedInstance, false);
APPLICATION->launch(m_selectedInstance, false);
}
}
@ -1829,12 +1829,12 @@ void MainWindow::instanceChanged(const QModelIndex &current, const QModelIndex &
{
if (!current.isValid())
{
LAUNCHER->settings()->set("SelectedInstance", QString());
APPLICATION->settings()->set("SelectedInstance", QString());
selectionBad();
return;
}
QString id = current.data(InstanceList::InstanceIDRole).toString();
m_selectedInstance = LAUNCHER->instances()->getInstanceById(id);
m_selectedInstance = APPLICATION->instances()->getInstanceById(id);
if (m_selectedInstance)
{
ui->instanceToolBar->setEnabled(true);
@ -1857,12 +1857,12 @@ void MainWindow::instanceChanged(const QModelIndex &current, const QModelIndex &
updateToolsMenu();
LAUNCHER->settings()->set("SelectedInstance", m_selectedInstance->id());
APPLICATION->settings()->set("SelectedInstance", m_selectedInstance->id());
}
else
{
ui->instanceToolBar->setEnabled(false);
LAUNCHER->settings()->set("SelectedInstance", QString());
APPLICATION->settings()->set("SelectedInstance", QString());
selectionBad();
return;
}
@ -1894,12 +1894,12 @@ void MainWindow::selectionBad()
updateInstanceToolIcon("grass");
// ...and then see if we can enable the previously selected instance
setSelectedInstanceById(LAUNCHER->settings()->get("SelectedInstance").toString());
setSelectedInstanceById(APPLICATION->settings()->get("SelectedInstance").toString());
}
void MainWindow::checkInstancePathForProblems()
{
QString instanceFolder = LAUNCHER->settings()->get("InstanceDir").toString();
QString instanceFolder = APPLICATION->settings()->get("InstanceDir").toString();
if (FS::checkProblemticPathJava(QDir(instanceFolder)))
{
QMessageBox warning(this);
@ -1938,9 +1938,9 @@ void MainWindow::checkInstancePathForProblems()
void MainWindow::updateStatusCenter()
{
m_statusCenter->setVisible(LAUNCHER->settings()->get("ShowGlobalGameTime").toBool());
m_statusCenter->setVisible(APPLICATION->settings()->get("ShowGlobalGameTime").toBool());
int timePlayed = LAUNCHER->instances()->getTotalPlayTime();
int timePlayed = APPLICATION->instances()->getTotalPlayTime();
if (timePlayed > 0) {
m_statusCenter->setText(tr("Total playtime: %1").arg(Time::prettifyDuration(timePlayed)));
}

View File

@ -166,7 +166,7 @@ private slots:
void notificationsChanged();
void activeAccountChanged();
void defaultAccountChanged();
void changeActiveAccount();

View File

@ -30,7 +30,7 @@ namespace SkinUtils
*/
QPixmap getFaceFromCache(QString username, int height, int width)
{
QFile fskin(ENV.metacache()->resolveEntry("skins", username + ".png")->getFullPath());
QFile fskin(ENV->metacache()->resolveEntry("skins", username + ".png")->getFullPath());
if (fskin.exists())
{

View File

@ -3,6 +3,8 @@
#include <cstddef>
#include <memory>
#include "QObjectPtr.h"
class Usable;
/**
@ -14,11 +16,11 @@ class Usable
{
friend class UseLock;
public:
std::size_t useCount()
std::size_t useCount() const
{
return m_useCount;
}
bool isInUse()
bool isInUse() const
{
return m_useCount > 0;
}
@ -43,7 +45,7 @@ private:
class UseLock
{
public:
UseLock(std::shared_ptr<Usable> usable)
UseLock(shared_qobject_ptr<Usable> usable)
: m_usable(usable)
{
// this doesn't use shared pointer use count, because that wouldn't be correct. this count is separate.
@ -54,5 +56,5 @@ public:
m_usable->decrementUses();
}
private:
std::shared_ptr<Usable> m_usable;
shared_qobject_ptr<Usable> m_usable;
};

View File

@ -1,5 +1,5 @@
#include "VersionProxyModel.h"
#include "Launcher.h"
#include "Application.h"
#include <QSortFilterProxyModel>
#include <QPixmapCache>
#include <Version.h>
@ -194,19 +194,19 @@ QVariant VersionProxyModel::data(const QModelIndex &index, int role) const
auto value = sourceModel()->data(parentIndex, BaseVersionList::RecommendedRole);
if(value.toBool())
{
return LAUNCHER->getThemedIcon("star");
return APPLICATION->getThemedIcon("star");
}
else if(hasLatest)
{
auto value = sourceModel()->data(parentIndex, BaseVersionList::LatestRole);
if(value.toBool())
{
return LAUNCHER->getThemedIcon("bug");
return APPLICATION->getThemedIcon("bug");
}
}
else if(index.row() == 0)
{
return LAUNCHER->getThemedIcon("bug");
return APPLICATION->getThemedIcon("bug");
}
auto pixmap = QPixmapCache::find("placeholder");
if(!pixmap)

View File

@ -16,7 +16,7 @@
#include "AboutDialog.h"
#include "ui_AboutDialog.h"
#include <QIcon>
#include "Launcher.h"
#include "Application.h"
#include "BuildConfig.h"
#include <net/NetJob.h>
@ -88,7 +88,7 @@ AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDia
ui->urlLabel->setOpenExternalLinks(true);
ui->icon->setPixmap(LAUNCHER->getThemedIcon("logo").pixmap(64));
ui->icon->setPixmap(APPLICATION->getThemedIcon("logo").pixmap(64));
ui->title->setText(launcherName);
ui->versionLabel->setText(tr("Version") +": " + BuildConfig.printableVersionString());

View File

@ -16,7 +16,7 @@
#include <QLayout>
#include <QPushButton>
#include "Launcher.h"
#include "Application.h"
#include "CopyInstanceDialog.h"
#include "ui_CopyInstanceDialog.h"
@ -36,16 +36,16 @@ CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent)
layout()->setSizeConstraint(QLayout::SetFixedSize);
InstIconKey = original->iconKey();
ui->iconButton->setIcon(LAUNCHER->icons()->getIcon(InstIconKey));
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
ui->instNameTextBox->setText(original->name());
ui->instNameTextBox->setFocus();
auto groups = LAUNCHER->instances()->getGroups().toSet();
auto groups = APPLICATION->instances()->getGroups().toSet();
auto groupList = QStringList(groups.toList());
groupList.sort(Qt::CaseInsensitive);
groupList.removeOne("");
groupList.push_front("");
ui->groupBox->addItems(groupList);
int index = groupList.indexOf(LAUNCHER->instances()->getInstanceGroup(m_original->id()));
int index = groupList.indexOf(APPLICATION->instances()->getInstanceGroup(m_original->id()));
if(index == -1)
{
index = 0;
@ -99,7 +99,7 @@ void CopyInstanceDialog::on_iconButton_clicked()
if (dlg.result() == QDialog::Accepted)
{
InstIconKey = dlg.selectedIconKey;
ui->iconButton->setIcon(LAUNCHER->icons()->getIcon(InstIconKey));
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
}
}

View File

@ -27,7 +27,7 @@
#include <QSaveFile>
#include "MMCStrings.h"
#include "SeparatorPrefixTree.h"
#include "Launcher.h"
#include "Application.h"
#include <icons/IconList.h>
#include <FileSystem.h>
@ -341,7 +341,7 @@ ExportInstanceDialog::~ExportInstanceDialog()
void SaveIcon(InstancePtr m_instance)
{
auto iconKey = m_instance->iconKey();
auto iconList = LAUNCHER->icons();
auto iconList = APPLICATION->icons();
auto mmcIcon = iconList->icon(iconKey);
if(!mmcIcon || mmcIcon->isBuiltIn()) {
return;

View File

@ -17,7 +17,7 @@
#include <QPushButton>
#include <QFileDialog>
#include "Launcher.h"
#include "Application.h"
#include "IconPickerDialog.h"
#include "ui_IconPickerDialog.h"
@ -59,7 +59,7 @@ IconPickerDialog::IconPickerDialog(QWidget *parent)
contentsWidget->installEventFilter(this);
contentsWidget->setModel(LAUNCHER->icons().get());
contentsWidget->setModel(APPLICATION->icons().get());
// NOTE: ResetRole forces the button to be on the left, while the OK/Cancel ones are on the right. We win.
auto buttonAdd = ui->buttonBox->addButton(tr("Add Icon"), QDialogButtonBox::ResetRole);
@ -106,12 +106,12 @@ void IconPickerDialog::addNewIcon()
//: The type of icon files
auto filter = IconUtils::getIconFilter();
QStringList fileNames = QFileDialog::getOpenFileNames(this, selectIcons, QString(), tr("Icons %1").arg(filter));
LAUNCHER->icons()->installIcons(fileNames);
APPLICATION->icons()->installIcons(fileNames);
}
void IconPickerDialog::removeSelectedIcon()
{
LAUNCHER->icons()->deleteIcon(selectedIconKey);
APPLICATION->icons()->deleteIcon(selectedIconKey);
}
void IconPickerDialog::activated(QModelIndex index)
@ -133,7 +133,7 @@ void IconPickerDialog::selectionChanged(QItemSelection selected, QItemSelection
int IconPickerDialog::execWithSelection(QString selection)
{
auto list = LAUNCHER->icons();
auto list = APPLICATION->icons();
auto contentsWidget = ui->iconView;
selectedIconKey = selection;
@ -159,5 +159,5 @@ IconPickerDialog::~IconPickerDialog()
void IconPickerDialog::openFolder()
{
DesktopServices::openDirectory(LAUNCHER->icons()->getDirectory(), true);
DesktopServices::openDirectory(APPLICATION->icons()->getDirectory(), true);
}

View File

@ -54,5 +54,5 @@ slots:
private:
Ui::LoginDialog *ui;
MinecraftAccountPtr m_account;
std::shared_ptr<Task> m_loginTask;
shared_qobject_ptr<Task> m_loginTask;
};

View File

@ -55,7 +55,7 @@ slots:
private:
Ui::MSALoginDialog *ui;
MinecraftAccountPtr m_account;
std::shared_ptr<AccountTask> m_loginTask;
shared_qobject_ptr<AccountTask> m_loginTask;
QTimer m_externalLoginTimer;
int m_externalLoginElapsed = 0;
int m_externalLoginTimeout = 0;

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
#include "Launcher.h"
#include "Application.h"
#include "NewComponentDialog.h"
#include "ui_NewComponentDialog.h"
@ -46,7 +46,7 @@ NewComponentDialog::NewComponentDialog(const QString & initialName, const QStrin
connect(ui->nameTextBox, &QLineEdit::textChanged, this, &NewComponentDialog::updateDialogState);
connect(ui->uidTextBox, &QLineEdit::textChanged, this, &NewComponentDialog::updateDialogState);
auto groups = LAUNCHER->instances()->getGroups().toSet();
auto groups = APPLICATION->instances()->getGroups().toSet();
ui->nameTextBox->setFocus();
originalPlaceholderText = ui->uidTextBox->placeholderText();

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
#include "Launcher.h"
#include "Application.h"
#include "NewInstanceDialog.h"
#include "ui_NewInstanceDialog.h"
@ -48,12 +48,12 @@ NewInstanceDialog::NewInstanceDialog(const QString & initialGroup, const QString
{
ui->setupUi(this);
setWindowIcon(LAUNCHER->getThemedIcon("new"));
setWindowIcon(APPLICATION->getThemedIcon("new"));
InstIconKey = "default";
ui->iconButton->setIcon(LAUNCHER->icons()->getIcon(InstIconKey));
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
auto groups = LAUNCHER->instances()->getGroups().toSet();
auto groups = APPLICATION->instances()->getGroups().toSet();
auto groupList = QStringList(groups.toList());
groupList.sort(Qt::CaseInsensitive);
groupList.removeOne("");
@ -105,18 +105,18 @@ NewInstanceDialog::NewInstanceDialog(const QString & initialGroup, const QString
updateDialogState();
restoreGeometry(QByteArray::fromBase64(LAUNCHER->settings()->get("NewInstanceGeometry").toByteArray()));
restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("NewInstanceGeometry").toByteArray()));
}
void NewInstanceDialog::reject()
{
LAUNCHER->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
QDialog::reject();
}
void NewInstanceDialog::accept()
{
LAUNCHER->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
importIconNow();
QDialog::accept();
}
@ -155,7 +155,7 @@ void NewInstanceDialog::setSuggestedPack(const QString& name, InstanceTask* task
if(!task)
{
ui->iconButton->setIcon(LAUNCHER->icons()->getIcon("default"));
ui->iconButton->setIcon(APPLICATION->icons()->getIcon("default"));
importIcon = false;
}
@ -175,7 +175,7 @@ void NewInstanceDialog::setSuggestedIconFromFile(const QString &path, const QStr
void NewInstanceDialog::setSuggestedIcon(const QString &key)
{
auto icon = LAUNCHER->icons()->getIcon(key);
auto icon = APPLICATION->icons()->getIcon(key);
importIcon = false;
ui->iconButton->setIcon(icon);
@ -234,7 +234,7 @@ void NewInstanceDialog::on_iconButton_clicked()
if (dlg.result() == QDialog::Accepted)
{
InstIconKey = dlg.selectedIconKey;
ui->iconButton->setIcon(LAUNCHER->icons()->getIcon(InstIconKey));
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
importIcon = false;
}
}
@ -247,9 +247,9 @@ void NewInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1)
void NewInstanceDialog::importIconNow()
{
if(importIcon) {
LAUNCHER->icons()->installIcon(importIconPath, importIconName);
APPLICATION->icons()->installIcon(importIconPath, importIconName);
InstIconKey = importIconName;
importIcon = false;
}
LAUNCHER->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
}

View File

@ -23,14 +23,14 @@
#include <dialogs/ProgressDialog.h>
#include <Launcher.h>
#include <Application.h>
ProfileSelectDialog::ProfileSelectDialog(const QString &message, int flags, QWidget *parent)
: QDialog(parent), ui(new Ui::ProfileSelectDialog)
{
ui->setupUi(this);
m_accounts = LAUNCHER->accounts();
m_accounts = APPLICATION->accounts();
auto view = ui->listView;
//view->setModel(m_accounts.get());
//view->hideColumn(AccountList::ActiveColumn);

View File

@ -80,7 +80,7 @@ slots:
void on_buttonBox_rejected();
protected:
std::shared_ptr<AccountList> m_accounts;
shared_qobject_ptr<AccountList> m_accounts;
//! The account that was selected when the user clicked OK.
MinecraftAccountPtr m_selected;

View File

@ -23,19 +23,21 @@
#include <dialogs/ProgressDialog.h>
#include <Launcher.h>
#include <Application.h>
#include <minecraft/auth/flows/AuthRequest.h>
#include <minecraft/auth/flows/Parsers.h>
#include <QJsonDocument>
ProfileSetupDialog::ProfileSetupDialog(MinecraftAccountPtr accountToSetup, QWidget *parent)
: QDialog(parent), m_accountToSetup(accountToSetup), ui(new Ui::ProfileSetupDialog)
{
ui->setupUi(this);
ui->errorLabel->setVisible(false);
goodIcon = LAUNCHER->getThemedIcon("status-good");
yellowIcon = LAUNCHER->getThemedIcon("status-yellow");
badIcon = LAUNCHER->getThemedIcon("status-bad");
goodIcon = APPLICATION->getThemedIcon("status-good");
yellowIcon = APPLICATION->getThemedIcon("status-yellow");
badIcon = APPLICATION->getThemedIcon("status-bad");
QRegExp permittedNames("[a-zA-Z0-9_]{3,16}");
auto nameEdit = ui->nameEdit;

View File

@ -3,14 +3,15 @@
#include <QPainter>
#include <FileSystem.h>
#include <minecraft/services/SkinUpload.h>
#include <minecraft/services/CapeChange.h>
#include <tasks/SequentialTask.h>
#include "SkinUploadDialog.h"
#include "ui_SkinUploadDialog.h"
#include "ProgressDialog.h"
#include "CustomMessageBox.h"
#include <minecraft/services/CapeChange.h>
void SkinUploadDialog::on_buttonBox_rejected()
{
@ -91,10 +92,10 @@ void SkinUploadDialog::on_buttonBox_accepted()
model = SkinUpload::ALEX;
}
SequentialTask skinUpload;
skinUpload.addTask(std::make_shared<SkinUpload>(this, session, FS::read(fileName), model));
skinUpload.addTask(shared_qobject_ptr<SkinUpload>(new SkinUpload(this, session, FS::read(fileName), model)));
auto selectedCape = ui->capeCombo->currentData().toString();
if(selectedCape != session->m_accountPtr->accountData()->minecraftProfile.currentCape) {
skinUpload.addTask(std::make_shared<CapeChange>(this, session, selectedCape));
if(selectedCape != m_acct->accountData()->minecraftProfile.currentCape) {
skinUpload.addTask(shared_qobject_ptr<CapeChange>(new CapeChange(this, session, selectedCape)));
}
if (prog.execWithTask(&skinUpload) != QDialog::Accepted)
{

View File

@ -1,7 +1,7 @@
#include "UpdateDialog.h"
#include "ui_UpdateDialog.h"
#include <QDebug>
#include "Launcher.h"
#include "Application.h"
#include <settings/SettingsObject.h>
#include <Json.h>
@ -11,7 +11,7 @@
UpdateDialog::UpdateDialog(bool hasUpdate, QWidget *parent) : QDialog(parent), ui(new Ui::UpdateDialog)
{
ui->setupUi(this);
auto channel = LAUNCHER->settings()->get("UpdateChannel").toString();
auto channel = APPLICATION->settings()->get("UpdateChannel").toString();
if(hasUpdate)
{
ui->label->setText(tr("A new %1 update is available!").arg(channel));
@ -24,7 +24,7 @@ UpdateDialog::UpdateDialog(bool hasUpdate, QWidget *parent) : QDialog(parent), u
}
ui->changelogBrowser->setHtml(tr("<center><h1>Loading changelog...</h1></center>"));
loadChangelog();
restoreGeometry(QByteArray::fromBase64(LAUNCHER->settings()->get("UpdateDialogGeometry").toByteArray()));
restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("UpdateDialogGeometry").toByteArray()));
}
UpdateDialog::~UpdateDialog()
@ -33,7 +33,7 @@ UpdateDialog::~UpdateDialog()
void UpdateDialog::loadChangelog()
{
auto channel = LAUNCHER->settings()->get("UpdateChannel").toString();
auto channel = APPLICATION->settings()->get("UpdateChannel").toString();
dljob.reset(new NetJob("Changelog"));
QString url;
if(channel == "stable")
@ -65,7 +65,7 @@ QString reprocessMarkdown(QByteArray markdown)
QString reprocessCommits(QByteArray json)
{
auto channel = LAUNCHER->settings()->get("UpdateChannel").toString();
auto channel = APPLICATION->settings()->get("UpdateChannel").toString();
try
{
QString result;
@ -177,6 +177,6 @@ void UpdateDialog::on_btnUpdateNow_clicked()
void UpdateDialog::closeEvent(QCloseEvent* evt)
{
LAUNCHER->settings()->set("UpdateDialogGeometry", saveGeometry().toBase64());
APPLICATION->settings()->set("UpdateDialogGeometry", saveGeometry().toBase64());
QDialog::closeEvent(evt);
}

View File

@ -28,7 +28,7 @@
#include <BaseVersionList.h>
#include <tasks/Task.h>
#include <QDebug>
#include "Launcher.h"
#include "Application.h"
#include <VersionProxyModel.h>
#include <widgets/VersionSelectWidget.h>

View File

@ -16,7 +16,7 @@
#include "InstanceProxyModel.h"
#include "InstanceView.h"
#include "Launcher.h"
#include "Application.h"
#include <BaseInstance.h>
#include <icons/IconList.h>
@ -34,7 +34,7 @@ QVariant InstanceProxyModel::data(const QModelIndex & index, int role) const
QVariant data = QSortFilterProxyModel::data(index, role);
if(role == Qt::DecorationRole)
{
return QVariant(LAUNCHER->icons()->getIcon(data.toString()));
return QVariant(APPLICATION->icons()->getIcon(data.toString()));
}
return data;
}
@ -59,7 +59,7 @@ bool InstanceProxyModel::subSortLessThan(const QModelIndex &left, const QModelIn
{
BaseInstance *pdataLeft = static_cast<BaseInstance *>(left.internalPointer());
BaseInstance *pdataRight = static_cast<BaseInstance *>(right.internalPointer());
QString sortMode = LAUNCHER->settings()->get("InstSortMode").toString();
QString sortMode = APPLICATION->settings()->get("InstSortMode").toString();
if (sortMode == "LastLaunch")
{
return pdataLeft->lastLaunch() > pdataRight->lastLaunch();

View File

@ -30,7 +30,7 @@
#include "VisualGroup.h"
#include <QDebug>
#include <Launcher.h>
#include <Application.h>
#include <InstanceList.h>
@ -628,7 +628,7 @@ void InstanceView::dropEvent(QDropEvent *event)
return;
}
auto instanceId = QString::fromUtf8(mimedata->data("application/x-instanceid"));
auto instanceList = LAUNCHER->instances().get();
auto instanceList = APPLICATION->instances().get();
instanceList->setInstanceGroup(instanceId, group->text);
event->setDropAction(Qt::MoveAction);
event->accept();

View File

@ -16,7 +16,7 @@ JavaChecker::JavaChecker(QObject *parent) : QObject(parent)
void JavaChecker::performCheck()
{
QString checkerJar = FS::PathCombine(ENV.getJarsPath(), "JavaCheck.jar");
QString checkerJar = FS::PathCombine(ENV->getJarsPath(), "JavaCheck.jar");
QStringList args;

View File

@ -1,4 +1,4 @@
#include "Launcher.h"
#include "Application.h"
#include "MainWindow.h"
#include "LaunchController.h"
#include <InstanceList.h>
@ -34,12 +34,12 @@ int main(int argc, char *argv[])
#endif
// initialize Qt
Launcher app(argc, argv);
Application app(argc, argv);
switch (app.status())
{
case Launcher::StartingUp:
case Launcher::Initialized:
case Application::StartingUp:
case Application::Initialized:
{
Q_INIT_RESOURCE(multimc);
Q_INIT_RESOURCE(backgrounds);
@ -55,9 +55,9 @@ int main(int argc, char *argv[])
Q_INIT_RESOURCE(flat);
return app.exec();
}
case Launcher::Failed:
case Application::Failed:
return 1;
case Launcher::Succeeded:
case Application::Succeeded:
return 0;
}
}

View File

@ -122,7 +122,7 @@ void Meta::BaseEntity::load(Net::Mode loadType)
}
NetJob *job = new NetJob(QObject::tr("Download of meta file %1").arg(localFilename()));
auto url = this->url();
auto entry = ENV.metacache()->resolveEntry("meta", localFilename());
auto entry = ENV->metacache()->resolveEntry("meta", localFilename());
entry->setStale(true);
auto dl = Net::Download::makeCached(url, entry);
/*

View File

@ -12,8 +12,8 @@ private
slots:
void test_isProvidedByEnv()
{
QVERIFY(ENV.metadataIndex());
QCOMPARE(ENV.metadataIndex(), ENV.metadataIndex());
QVERIFY(ENV->metadataIndex());
QCOMPARE(ENV->metadataIndex(), ENV->metadataIndex());
}
void test_hasUid_and_getList()

View File

@ -85,9 +85,9 @@ std::shared_ptr<class VersionFile> Component::getVersionFile() const
std::shared_ptr<class Meta::VersionList> Component::getVersionList() const
{
// FIXME: what if the metadata index isn't loaded yet?
if(ENV.metadataIndex()->hasUid(m_uid))
if(ENV->metadataIndex()->hasUid(m_uid))
{
return ENV.metadataIndex()->get(m_uid);
return ENV->metadataIndex()->get(m_uid);
}
return nullptr;
}
@ -192,7 +192,7 @@ bool Component::isRevertible()
{
if (isCustom())
{
if(ENV.metadataIndex()->hasUid(m_uid))
if(ENV->metadataIndex()->hasUid(m_uid))
{
return true;
}
@ -266,7 +266,7 @@ void Component::setVersion(const QString& version)
// we don't have a file, therefore we are loaded with metadata
m_cachedVersion = version;
// see if the meta version is loaded
auto metaVersion = ENV.metadataIndex()->get(m_uid, version);
auto metaVersion = ENV->metadataIndex()->get(m_uid, version);
if(metaVersion->isLoaded())
{
// if yes, we can continue with that.
@ -350,7 +350,7 @@ bool Component::revert()
m_file.reset();
// check local cache for metadata...
auto version = ENV.metadataIndex()->get(m_uid, m_version);
auto version = ENV->metadataIndex()->get(m_uid, m_version);
if(version->isLoaded())
{
m_metaVersion = version;

View File

@ -102,7 +102,7 @@ static LoadResult loadComponent(ComponentPtr component, shared_qobject_ptr<Task>
}
else
{
auto metaVersion = ENV.metadataIndex()->get(component->m_uid, component->m_version);
auto metaVersion = ENV->metadataIndex()->get(component->m_uid, component->m_version);
component->m_metaVersion = metaVersion;
if(metaVersion->isLoaded())
{
@ -135,7 +135,7 @@ static LoadResult loadPackProfile(ComponentPtr component, shared_qobject_ptr<Tas
}
LoadResult result = LoadResult::Failed;
auto metaList = ENV.metadataIndex()->get(component->m_uid);
auto metaList = ENV->metadataIndex()->get(component->m_uid);
if(metaList->isLoaded())
{
component->m_loaded = true;
@ -154,13 +154,13 @@ static LoadResult loadPackProfile(ComponentPtr component, shared_qobject_ptr<Tas
static LoadResult loadIndex(shared_qobject_ptr<Task>& loadTask, Net::Mode netmode)
{
// FIXME: DECIDE. do we want to run the update task anyway?
if(ENV.metadataIndex()->isLoaded())
if(ENV->metadataIndex()->isLoaded())
{
qDebug() << "Index is already loaded";
return LoadResult::LoadedLocal;
}
ENV.metadataIndex()->load(netmode);
loadTask = ENV.metadataIndex()->getCurrentTask();
ENV->metadataIndex()->load(netmode);
loadTask = ENV->metadataIndex()->getCurrentTask();
if(loadTask)
{
return LoadResult::RequiresRemote;

View File

@ -816,7 +816,7 @@ shared_qobject_ptr<LaunchTask> MinecraftInstance::createLaunchTask(AuthSessionPt
auto process = LaunchTask::create(std::dynamic_pointer_cast<MinecraftInstance>(shared_from_this()));
auto pptr = process.get();
ENV.icons()->saveIcon(iconKey(), FS::PathCombine(gameRoot(), "icon.png"), "PNG");
ENV->icons()->saveIcon(iconKey(), FS::PathCombine(gameRoot(), "icon.png"), "PNG");
// print a header
{

View File

@ -481,7 +481,7 @@ bool PackProfile::migratePreComponentConfig()
}
else if(!intendedVersion.isEmpty())
{
auto metaVersion = ENV.metadataIndex()->get(uid, intendedVersion);
auto metaVersion = ENV->metadataIndex()->get(uid, intendedVersion);
component = new Component(this, metaVersion);
}
else
@ -546,7 +546,7 @@ bool PackProfile::migratePreComponentConfig()
auto patchVersion = d->getOldConfigVersion(uid);
if(!patchVersion.isEmpty() && !loadedComponents.contains(uid))
{
auto patch = new Component(this, ENV.metadataIndex()->get(uid, patchVersion));
auto patch = new Component(this, ENV->metadataIndex()->get(uid, patchVersion));
patch->setOrder(order);
loadedComponents[uid] = patch;
}

View File

@ -37,6 +37,8 @@ enum AccountListVersion {
AccountList::AccountList(QObject *parent) : QAbstractListModel(parent) { }
AccountList::~AccountList() noexcept {}
int AccountList::findAccountByProfileId(const QString& profileId) const {
for (int i = 0; i < count(); i++) {
MinecraftAccountPtr account = at(i);
@ -62,6 +64,18 @@ const MinecraftAccountPtr AccountList::at(int i) const
return MinecraftAccountPtr(m_accounts.at(i));
}
QStringList AccountList::profileNames() const {
QStringList out;
for(auto & account: m_accounts) {
auto profileName = account->profileName();
if(profileName.isEmpty()) {
continue;
}
out.append(profileName);
}
return out;
}
void AccountList::addAccount(const MinecraftAccountPtr account)
{
auto profileId = account->profileId();
@ -71,8 +85,8 @@ void AccountList::addAccount(const MinecraftAccountPtr account)
if(existingAccount != -1) {
MinecraftAccountPtr existingAccountPtr = m_accounts[existingAccount];
m_accounts[existingAccount] = account;
if(m_activeAccount == existingAccountPtr) {
m_activeAccount = account;
if(m_defaultAccount == existingAccountPtr) {
m_defaultAccount = account;
}
emit dataChanged(index(existingAccount), index(existingAccount, columnCount(QModelIndex()) - 1));
onListChanged();
@ -80,10 +94,11 @@ void AccountList::addAccount(const MinecraftAccountPtr account)
}
}
// if we don't have this porfileId yet, add the account to the end
// if we don't have this profileId yet, add the account to the end
int row = m_accounts.count();
beginInsertRows(QModelIndex(), row, row);
connect(account.get(), SIGNAL(changed()), SLOT(accountChanged()));
connect(account.get(), &MinecraftAccount::changed, this, &AccountList::accountChanged);
connect(account.get(), &MinecraftAccount::activityChanged, this, &AccountList::accountActivityChanged);
m_accounts.append(account);
endInsertRows();
onListChanged();
@ -95,10 +110,10 @@ void AccountList::removeAccount(QModelIndex index)
if(index.isValid() && row >= 0 && row < m_accounts.size())
{
auto & account = m_accounts[row];
if(account == m_activeAccount)
if(account == m_defaultAccount)
{
m_activeAccount = nullptr;
onActiveChanged();
m_defaultAccount = nullptr;
onDefaultAccountChanged();
}
beginRemoveRows(QModelIndex(), row, row);
m_accounts.removeAt(index.row());
@ -107,54 +122,54 @@ void AccountList::removeAccount(QModelIndex index)
}
}
MinecraftAccountPtr AccountList::activeAccount() const
MinecraftAccountPtr AccountList::defaultAccount() const
{
return m_activeAccount;
return m_defaultAccount;
}
void AccountList::setActiveAccount(MinecraftAccountPtr newAccount)
void AccountList::setDefaultAccount(MinecraftAccountPtr newAccount)
{
if (!newAccount && m_activeAccount)
if (!newAccount && m_defaultAccount)
{
int idx = 0;
auto prevActiveAcc = m_activeAccount;
m_activeAccount = nullptr;
auto previousDefaultAccount = m_defaultAccount;
m_defaultAccount = nullptr;
for (MinecraftAccountPtr account : m_accounts)
{
if (account == prevActiveAcc)
if (account == previousDefaultAccount)
{
emit dataChanged(index(idx), index(idx));
emit dataChanged(index(idx), index(idx, columnCount(QModelIndex()) - 1));
}
idx ++;
}
onActiveChanged();
onDefaultAccountChanged();
}
else
{
auto currentActiveAccount = m_activeAccount;
int currentActiveAccountIdx = -1;
auto newActiveAccount = m_activeAccount;
int newActiveAccountIdx = -1;
auto currentDefaultAccount = m_defaultAccount;
int currentDefaultAccountIdx = -1;
auto newDefaultAccount = m_defaultAccount;
int newDefaultAccountIdx = -1;
int idx = 0;
for (MinecraftAccountPtr account : m_accounts)
{
if (account == newAccount)
{
newActiveAccount = account;
newActiveAccountIdx = idx;
newDefaultAccount = account;
newDefaultAccountIdx = idx;
}
if(currentActiveAccount == account)
if(currentDefaultAccount == account)
{
currentActiveAccountIdx = idx;
currentDefaultAccountIdx = idx;
}
idx++;
}
if(currentActiveAccount != newActiveAccount)
if(currentDefaultAccount != newDefaultAccount)
{
emit dataChanged(index(currentActiveAccountIdx), index(currentActiveAccountIdx));
emit dataChanged(index(newActiveAccountIdx), index(newActiveAccountIdx));
m_activeAccount = newActiveAccount;
onActiveChanged();
emit dataChanged(index(currentDefaultAccountIdx), index(currentDefaultAccountIdx, columnCount(QModelIndex()) - 1));
emit dataChanged(index(newDefaultAccountIdx), index(newDefaultAccountIdx, columnCount(QModelIndex()) - 1));
m_defaultAccount = newDefaultAccount;
onDefaultAccountChanged();
}
}
}
@ -165,6 +180,23 @@ void AccountList::accountChanged()
onListChanged();
}
void AccountList::accountActivityChanged(bool active)
{
MinecraftAccount *account = qobject_cast<MinecraftAccount *>(sender());
bool found = false;
for (int i = 0; i < count(); i++) {
if (at(i).get() == account) {
emit dataChanged(index(i), index(i, columnCount(QModelIndex()) - 1));
found = true;
break;
}
}
if(found) {
emit listActivityChanged();
}
}
void AccountList::onListChanged()
{
if (m_autosave)
@ -174,12 +206,12 @@ void AccountList::onListChanged()
emit listChanged();
}
void AccountList::onActiveChanged()
void AccountList::onDefaultAccountChanged()
{
if (m_autosave)
saveList();
emit activeAccountChanged();
emit defaultAccountChanged();
}
int AccountList::count() const
@ -211,6 +243,11 @@ QVariant AccountList::data(const QModelIndex &index, int role) const
return typeStr;
}
case StatusColumn: {
auto isActive = account->isActive();
return isActive ? "Working" : "Ready";
}
case ProfileNameColumn: {
return account->profileName();
}
@ -235,13 +272,13 @@ QVariant AccountList::data(const QModelIndex &index, int role) const
return account->accountDisplayString();
case PointerRole:
return qVariantFromValue(account);
return QVariant::fromValue(account);
case Qt::CheckStateRole:
switch (index.column())
{
case NameColumn:
return account == m_activeAccount ? Qt::Checked : Qt::Unchecked;
return account == m_defaultAccount ? Qt::Checked : Qt::Unchecked;
}
default:
@ -260,6 +297,8 @@ QVariant AccountList::headerData(int section, Qt::Orientation orientation, int r
return tr("Account");
case TypeColumn:
return tr("Type");
case StatusColumn:
return tr("Status");
case MigrationColumn:
return tr("Can Migrate?");
case ProfileNameColumn:
@ -275,6 +314,8 @@ QVariant AccountList::headerData(int section, Qt::Orientation orientation, int r
return tr("User name of the account.");
case TypeColumn:
return tr("Type of the account - Mojang or MSA.");
case StatusColumn:
return tr("Current status of the account.");
case MigrationColumn:
return tr("Can this account migrate to Microsoft account?");
case ProfileNameColumn:
@ -309,9 +350,9 @@ Qt::ItemFlags AccountList::flags(const QModelIndex &index) const
return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
bool AccountList::setData(const QModelIndex &index, const QVariant &value, int role)
bool AccountList::setData(const QModelIndex &idx, const QVariant &value, int role)
{
if (index.row() < 0 || index.row() >= rowCount(index) || !index.isValid())
if (idx.row() < 0 || idx.row() >= rowCount(idx) || !idx.isValid())
{
return false;
}
@ -320,12 +361,12 @@ bool AccountList::setData(const QModelIndex &index, const QVariant &value, int r
{
if(value == Qt::Checked)
{
MinecraftAccountPtr account = at(index.row());
setActiveAccount(account);
MinecraftAccountPtr account = at(idx.row());
setDefaultAccount(account);
}
}
emit dataChanged(index, index);
emit dataChanged(idx, index(idx.row(), columnCount(QModelIndex()) - 1));
return true;
}
@ -395,7 +436,7 @@ bool AccountList::loadList()
bool AccountList::loadV2(QJsonObject& root) {
beginResetModel();
auto activeUserName = root.value("activeAccount").toString("");
auto defaultUserName = root.value("activeAccount").toString("");
QJsonArray accounts = root.value("accounts").toArray();
for (QJsonValue accountVal : accounts)
{
@ -411,9 +452,10 @@ bool AccountList::loadV2(QJsonObject& root) {
continue;
}
connect(account.get(), &MinecraftAccount::changed, this, &AccountList::accountChanged);
connect(account.get(), &MinecraftAccount::activityChanged, this, &AccountList::accountActivityChanged);
m_accounts.append(account);
if (activeUserName.size() && account->mojangUserName() == activeUserName) {
m_activeAccount = account;
if (defaultUserName.size() && account->mojangUserName() == defaultUserName) {
m_defaultAccount = account;
}
}
else
@ -441,9 +483,10 @@ bool AccountList::loadV3(QJsonObject& root) {
}
}
connect(account.get(), &MinecraftAccount::changed, this, &AccountList::accountChanged);
connect(account.get(), &MinecraftAccount::activityChanged, this, &AccountList::accountActivityChanged);
m_accounts.append(account);
if(accountObj.value("active").toBool(false)) {
m_activeAccount = account;
m_defaultAccount = account;
}
}
else
@ -490,7 +533,7 @@ bool AccountList::saveList()
for (MinecraftAccountPtr account : m_accounts)
{
QJsonObject accountObj = account->saveToJson();
if(m_activeAccount == account) {
if(m_defaultAccount == account) {
accountObj["active"] = true;
}
accounts.append(accountObj);

View File

@ -42,11 +42,13 @@ public:
ProfileNameColumn,
MigrationColumn,
TypeColumn,
StatusColumn,
NUM_COLUMNS
};
explicit AccountList(QObject *parent = 0);
virtual ~AccountList() noexcept;
const MinecraftAccountPtr at(int i) const;
int count() const;
@ -63,6 +65,7 @@ public:
void removeAccount(QModelIndex index);
int findAccountByProfileId(const QString &profileId) const;
MinecraftAccountPtr getAccountByProfileName(const QString &profileName) const;
QStringList profileNames() const;
/*!
* Sets the path to load/save the list file from/to.
@ -78,13 +81,14 @@ public:
bool loadV3(QJsonObject &root);
bool saveList();
MinecraftAccountPtr activeAccount() const;
void setActiveAccount(MinecraftAccountPtr profileId);
MinecraftAccountPtr defaultAccount() const;
void setDefaultAccount(MinecraftAccountPtr profileId);
bool anyAccountIsValid();
signals:
void listChanged();
void activeAccountChanged();
void listActivityChanged();
void defaultAccountChanged();
public slots:
/**
@ -92,6 +96,11 @@ public slots:
*/
void accountChanged();
/**
* This is called when a (refresh/login) task involving the account starts or ends
*/
void accountActivityChanged(bool active);
protected:
/*!
* Called whenever the list changes.
@ -101,13 +110,13 @@ protected:
/*!
* Called whenever the active account changes.
* Emits the activeAccountChanged() signal and autosaves the list if enabled.
* Emits the defaultAccountChanged() signal and autosaves the list if enabled.
*/
void onActiveChanged();
void onDefaultAccountChanged();
QList<MinecraftAccountPtr> m_accounts;
MinecraftAccountPtr m_activeAccount;
MinecraftAccountPtr m_defaultAccount;
//! Path to the account list file. Empty string if there isn't one.
QString m_listFilePath;

View File

@ -23,10 +23,6 @@
#include <QNetworkReply>
#include <QByteArray>
#include <Env.h>
#include <BuildConfig.h>
#include <QDebug>
AccountTask::AccountTask(AccountData *data, QObject *parent)

View File

@ -3,8 +3,10 @@
#include <QString>
#include <QMultiMap>
#include <memory>
#include "QObjectPtr.h"
class MinecraftAccount;
class QNetworkAccessManager;
struct AuthSession
{
@ -41,7 +43,6 @@ struct AuthSession
bool auth_server_online = false;
// Did the user request online mode?
bool wants_online = true;
std::shared_ptr<MinecraftAccount> m_accountPtr;
};
typedef std::shared_ptr<AuthSession> AuthSessionPtr;

View File

@ -28,11 +28,11 @@
#include <QDebug>
#include <QPainter>
#include <minecraft/auth/flows/MSASilent.h>
#include <minecraft/auth/flows/MSAInteractive.h>
#include "flows/MSASilent.h"
#include "flows/MSAInteractive.h"
#include <minecraft/auth/flows/MojangRefresh.h>
#include <minecraft/auth/flows/MojangLogin.h>
#include "flows/MojangRefresh.h"
#include "flows/MojangLogin.h"
MinecraftAccountPtr MinecraftAccount::loadFromJsonV2(const QJsonObject& json) {
MinecraftAccountPtr account(new MinecraftAccount());
@ -104,7 +104,7 @@ QPixmap MinecraftAccount::getFace() const {
}
std::shared_ptr<AccountTask> MinecraftAccount::login(AuthSessionPtr session, QString password)
shared_qobject_ptr<AccountTask> MinecraftAccount::login(AuthSessionPtr session, QString password)
{
Q_ASSERT(m_currentTask.get() == nullptr);
@ -140,11 +140,12 @@ std::shared_ptr<AccountTask> MinecraftAccount::login(AuthSessionPtr session, QSt
connect(m_currentTask.get(), SIGNAL(succeeded()), SLOT(authSucceeded()));
connect(m_currentTask.get(), SIGNAL(failed(QString)), SLOT(authFailed(QString)));
emit activityChanged(true);
}
return m_currentTask;
}
std::shared_ptr<AccountTask> MinecraftAccount::loginMSA(AuthSessionPtr session) {
shared_qobject_ptr<AccountTask> MinecraftAccount::loginMSA(AuthSessionPtr session) {
Q_ASSERT(m_currentTask.get() == nullptr);
if(accountStatus() == Verified && !session->wants_online)
@ -161,11 +162,12 @@ std::shared_ptr<AccountTask> MinecraftAccount::loginMSA(AuthSessionPtr session)
connect(m_currentTask.get(), SIGNAL(succeeded()), SLOT(authSucceeded()));
connect(m_currentTask.get(), SIGNAL(failed(QString)), SLOT(authFailed(QString)));
emit activityChanged(true);
}
return m_currentTask;
}
std::shared_ptr<AccountTask> MinecraftAccount::refresh(AuthSessionPtr session) {
shared_qobject_ptr<AccountTask> MinecraftAccount::refresh(AuthSessionPtr session) {
Q_ASSERT(m_currentTask.get() == nullptr);
// take care of the true offline status
@ -203,6 +205,7 @@ std::shared_ptr<AccountTask> MinecraftAccount::refresh(AuthSessionPtr session) {
connect(m_currentTask.get(), SIGNAL(succeeded()), SLOT(authSucceeded()));
connect(m_currentTask.get(), SIGNAL(failed(QString)), SLOT(authFailed(QString)));
emit activityChanged(true);
}
return m_currentTask;
}
@ -233,6 +236,7 @@ void MinecraftAccount::authSucceeded()
}
m_currentTask.reset();
emit changed();
emit activityChanged(false);
}
void MinecraftAccount::authFailed(QString reason)
@ -297,6 +301,45 @@ void MinecraftAccount::authFailed(QString reason)
}
}
m_currentTask.reset();
emit activityChanged(false);
}
bool MinecraftAccount::isActive() const {
return m_currentTask;
}
bool MinecraftAccount::shouldRefresh() const {
/*
* Never refresh accounts that are being used by the game, it breaks the game session.
* Always refresh accounts that have not been refreshed yet during this session.
* Don't refresh broken accounts.
* Refresh accounts that would expire in the next 12 hours (fresh token validity is 24 hours).
*/
if(isInUse()) {
return false;
}
switch(data.validity_) {
case Katabasis::Validity::Certain: {
break;
}
case Katabasis::Validity::None: {
return false;
}
case Katabasis::Validity::Assumed: {
return true;
}
}
auto now = QDateTime::currentDateTimeUtc();
auto issuedTimestamp = data.yggdrasilToken.issueInstant;
auto expiresTimestamp = data.yggdrasilToken.notAfter;
if(!expiresTimestamp.isValid()) {
expiresTimestamp = issuedTimestamp.addSecs(24 * 3600);
}
if (now.secsTo(expiresTimestamp) < 12 * 3600) {
return true;
}
return false;
}
void MinecraftAccount::fillSession(AuthSessionPtr session)
@ -322,7 +365,6 @@ void MinecraftAccount::fillSession(AuthSessionPtr session)
{
session->session = "-";
}
session->m_accountPtr = shared_from_this();
}
void MinecraftAccount::decrementUses()

View File

@ -27,12 +27,13 @@
#include "AuthSession.h"
#include "Usable.h"
#include "AccountData.h"
#include "QObjectPtr.h"
class Task;
class AccountTask;
class MinecraftAccount;
typedef std::shared_ptr<MinecraftAccount> MinecraftAccountPtr;
typedef shared_qobject_ptr<MinecraftAccount> MinecraftAccountPtr;
Q_DECLARE_METATYPE(MinecraftAccountPtr)
/**
@ -63,8 +64,7 @@ enum AccountStatus
*/
class MinecraftAccount :
public QObject,
public Usable,
public std::enable_shared_from_this<MinecraftAccount>
public Usable
{
Q_OBJECT
public: /* construction */
@ -90,11 +90,11 @@ public: /* manipulation */
* Attempt to login. Empty password means we use the token.
* If the attempt fails because we already are performing some task, it returns false.
*/
std::shared_ptr<AccountTask> login(AuthSessionPtr session, QString password = QString());
shared_qobject_ptr<AccountTask> login(AuthSessionPtr session, QString password);
std::shared_ptr<AccountTask> loginMSA(AuthSessionPtr session);
shared_qobject_ptr<AccountTask> loginMSA(AuthSessionPtr session);
std::shared_ptr<AccountTask> refresh(AuthSessionPtr session);
shared_qobject_ptr<AccountTask> refresh(AuthSessionPtr session);
public: /* queries */
QString accountDisplayString() const {
@ -117,6 +117,8 @@ public: /* queries */
return data.profileName();
}
bool isActive() const;
bool canMigrate() const {
return data.canMigrateToMSA;
}
@ -153,19 +155,23 @@ public: /* queries */
return &data;
}
bool shouldRefresh() const;
signals:
/**
* This signal is emitted when the account changes
*/
void changed();
void activityChanged(bool active);
// TODO: better signalling for the various possible state changes - especially errors
protected: /* variables */
AccountData data;
// current task we are executing here
std::shared_ptr<AccountTask> m_currentTask;
shared_qobject_ptr<AccountTask> m_currentTask;
protected: /* methods */

View File

@ -4,28 +4,21 @@
#include <QDesktopServices>
#include <QMetaEnum>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUuid>
#include <QUrlQuery>
#include <QPixmap>
#include <QPainter>
#include "AuthContext.h"
#include "katabasis/Globals.h"
#include "AuthRequest.h"
#include "Secrets.h"
#include "Env.h"
#include "Parsers.h"
#include <Application.h>
#include <Env.h>
using OAuth2 = Katabasis::OAuth2;
using Activity = Katabasis::Activity;
@ -58,19 +51,14 @@ void AuthContext::initMSA() {
return;
}
auto clientId = Secrets::getMSAClientID('-');
if(clientId.isEmpty()) {
return;
}
Katabasis::OAuth2::Options opts;
opts.scope = "XboxLive.signin offline_access";
opts.clientIdentifier = clientId;
opts.clientIdentifier = APPLICATION->msaClientId();
opts.authorizationUrl = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode";
opts.accessTokenUrl = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
opts.listenerPorts = {28562, 28563, 28564, 28565, 28566};
m_oauth2 = new OAuth2(opts, m_data->msaToken, this, &ENV.network());
m_oauth2 = new OAuth2(opts, m_data->msaToken, this, &ENV->network());
m_oauth2->setGrantFlow(Katabasis::OAuth2::GrantFlowDevice);
connect(m_oauth2, &OAuth2::linkingFailed, this, &AuthContext::onOAuthLinkingFailed);

View File

@ -7,7 +7,8 @@
#include "AuthRequest.h"
#include "katabasis/Globals.h"
#include "Env.h"
#include <Env.h>
AuthRequest::AuthRequest(QObject *parent): QObject(parent) {
}
@ -17,7 +18,7 @@ AuthRequest::~AuthRequest() {
void AuthRequest::get(const QNetworkRequest &req, int timeout/* = 60*1000*/) {
setup(req, QNetworkAccessManager::GetOperation);
reply_ = ENV.network().get(request_);
reply_ = ENV->network().get(request_);
status_ = Requesting;
timedReplies_.add(new Katabasis::Reply(reply_, timeout));
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)));
@ -29,7 +30,7 @@ void AuthRequest::post(const QNetworkRequest &req, const QByteArray &data, int t
setup(req, QNetworkAccessManager::PostOperation);
data_ = data;
status_ = Requesting;
reply_ = ENV.network().post(request_, data_);
reply_ = ENV->network().post(request_, data_);
timedReplies_.add(new Katabasis::Reply(reply_, timeout));
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)));
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()));
@ -89,7 +90,7 @@ void AuthRequest::onUploadProgress(qint64 uploaded, qint64 total) {
emit uploadProgress(uploaded, total);
}
void AuthRequest::setup(const QNetworkRequest &req, QNetworkAccessManager::Operation operation) {
void AuthRequest::setup(const QNetworkRequest &req, QNetworkAccessManager::Operation operation, const QByteArray &verb) {
request_ = req;
operation_ = operation;
url_ = req.url();
@ -97,6 +98,10 @@ void AuthRequest::setup(const QNetworkRequest &req, QNetworkAccessManager::Opera
QUrl url = url_;
request_.setUrl(url);
if (!verb.isEmpty()) {
request_.setRawHeader(Katabasis::HTTP_HTTP_HEADER, verb);
}
status_ = Requesting;
error_ = QNetworkReply::NoError;
}

View File

@ -5,7 +5,6 @@
#include <QNetworkAccessManager>
#include <QUrl>
#include <QByteArray>
#include <QHttpMultiPart>
#include "katabasis/Reply.h"
@ -48,7 +47,7 @@ protected slots:
void onUploadProgress(qint64 uploaded, qint64 total);
protected:
void setup(const QNetworkRequest &request, QNetworkAccessManager::Operation operation);
void setup(const QNetworkRequest &request, QNetworkAccessManager::Operation operation, const QByteArray &verb = QByteArray());
enum Status {
Idle, Requesting, ReRequesting

View File

@ -1,6 +1,9 @@
#include "MSAInteractive.h"
MSAInteractive::MSAInteractive(AccountData* data, QObject* parent) : AuthContext(data, parent) {}
MSAInteractive::MSAInteractive(
AccountData* data,
QObject* parent
) : AuthContext(data, parent) {}
void MSAInteractive::executeTask() {
m_requestsDone = 0;

View File

@ -5,6 +5,9 @@ class MSAInteractive : public AuthContext
{
Q_OBJECT
public:
explicit MSAInteractive(AccountData * data, QObject *parent = 0);
explicit MSAInteractive(
AccountData *data,
QObject *parent = 0
);
void executeTask() override;
};

View File

@ -5,6 +5,9 @@ class MSASilent : public AuthContext
{
Q_OBJECT
public:
explicit MSASilent(AccountData * data, QObject *parent = 0);
explicit MSASilent(
AccountData * data,
QObject *parent = 0
);
void executeTask() override;
};

View File

@ -1,6 +1,10 @@
#include "MojangLogin.h"
MojangLogin::MojangLogin(AccountData* data, QString password, QObject* parent) : AuthContext(data, parent), m_password(password) {}
MojangLogin::MojangLogin(
AccountData *data,
QString password,
QObject *parent
): AuthContext(data, parent), m_password(password) {}
void MojangLogin::executeTask() {
m_requestsDone = 0;

View File

@ -5,7 +5,11 @@ class MojangLogin : public AuthContext
{
Q_OBJECT
public:
explicit MojangLogin(AccountData * data, QString password, QObject *parent = 0);
explicit MojangLogin(
AccountData *data,
QString password,
QObject *parent = 0
);
void executeTask() override;
private:

View File

@ -1,6 +1,9 @@
#include "MojangRefresh.h"
MojangRefresh::MojangRefresh(AccountData* data, QObject* parent) : AuthContext(data, parent) {}
MojangRefresh::MojangRefresh(
AccountData *data,
QObject *parent
) : AuthContext(data, parent) {}
void MojangRefresh::executeTask() {
m_requestsDone = 0;

View File

@ -5,6 +5,6 @@ class MojangRefresh : public AuthContext
{
Q_OBJECT
public:
explicit MojangRefresh(AccountData * data, QObject *parent = 0);
explicit MojangRefresh(AccountData *data, QObject *parent = 0);
void executeTask() override;
};

View File

@ -1,6 +1,6 @@
#pragma once
#include "minecraft/auth/AccountData.h"
#include "../AccountData.h"
namespace Parsers
{

View File

@ -23,12 +23,10 @@
#include <QNetworkReply>
#include <QByteArray>
#include <Env.h>
#include <BuildConfig.h>
#include <QDebug>
#include <Env.h>
Yggdrasil::Yggdrasil(AccountData *data, QObject *parent)
: AccountTask(data, parent)
{
@ -40,7 +38,7 @@ void Yggdrasil::sendRequest(QUrl endpoint, QByteArray content) {
QNetworkRequest netRequest(endpoint);
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
m_netReply = ENV.network().post(netRequest, content);
m_netReply = ENV->network().post(netRequest, content);
connect(m_netReply, &QNetworkReply::finished, this, &Yggdrasil::processReply);
connect(m_netReply, &QNetworkReply::uploadProgress, this, &Yggdrasil::refreshTimers);
connect(m_netReply, &QNetworkReply::downloadProgress, this, &Yggdrasil::refreshTimers);
@ -86,7 +84,7 @@ void Yggdrasil::refresh() {
req.insert("requestUser", false);
QJsonDocument doc(req);
QUrl reqUrl(BuildConfig.AUTH_BASE + "refresh");
QUrl reqUrl("https://authserver.mojang.com/refresh");
QByteArray requestData = doc.toJson();
sendRequest(reqUrl, requestData);
@ -131,7 +129,7 @@ void Yggdrasil::login(QString password) {
QJsonDocument doc(req);
QUrl reqUrl(BuildConfig.AUTH_BASE + "authenticate");
QUrl reqUrl("https://authserver.mojang.com/authenticate");
QNetworkRequest netRequest(reqUrl);
QByteArray requestData = doc.toJson();
@ -140,20 +138,18 @@ void Yggdrasil::login(QString password) {
void Yggdrasil::refreshTimers(qint64, qint64)
{
void Yggdrasil::refreshTimers(qint64, qint64) {
timeout_keeper.stop();
timeout_keeper.start(timeout_max);
progress(count = 0, timeout_max);
}
void Yggdrasil::heartbeat()
{
void Yggdrasil::heartbeat() {
count += time_step;
progress(count, timeout_max);
}
bool Yggdrasil::abort()
{
bool Yggdrasil::abort() {
progress(timeout_max, timeout_max);
// TODO: actually use this in a meaningful way
m_aborted = Yggdrasil::BY_USER;
@ -161,19 +157,16 @@ bool Yggdrasil::abort()
return true;
}
void Yggdrasil::abortByTimeout()
{
void Yggdrasil::abortByTimeout() {
progress(timeout_max, timeout_max);
// TODO: actually use this in a meaningful way
m_aborted = Yggdrasil::BY_TIMEOUT;
m_netReply->abort();
}
void Yggdrasil::sslErrors(QList<QSslError> errors)
{
void Yggdrasil::sslErrors(QList<QSslError> errors) {
int i = 1;
for (auto error : errors)
{
for (auto error : errors) {
qCritical() << "LOGIN SSL Error #" << i << " : " << error.errorString();
auto cert = error.certificate();
qCritical() << "Certificate in question:\n" << cert.toText();
@ -181,8 +174,7 @@ void Yggdrasil::sslErrors(QList<QSslError> errors)
}
}
void Yggdrasil::processResponse(QJsonObject responseData)
{
void Yggdrasil::processResponse(QJsonObject responseData) {
// Read the response data. We need to get the client token, access token, and the selected
// profile.
qDebug() << "Processing authentication response.";
@ -191,8 +183,7 @@ void Yggdrasil::processResponse(QJsonObject responseData)
// If we already have a client token, make sure the one the server gave us matches our
// existing one.
QString clientToken = responseData.value("clientToken").toString("");
if (clientToken.isEmpty())
{
if (clientToken.isEmpty()) {
// Fail if the server gave us an empty client token
changeState(STATE_FAILED_HARD, tr("Authentication server didn't send a client token."));
return;
@ -208,8 +199,7 @@ void Yggdrasil::processResponse(QJsonObject responseData)
// Now, we set the access token.
qDebug() << "Getting access token.";
QString accessToken = responseData.value("accessToken").toString("");
if (accessToken.isEmpty())
{
if (accessToken.isEmpty()) {
// Fail if the server didn't give us an access token.
changeState(STATE_FAILED_HARD, tr("Authentication server didn't send an access token."));
return;
@ -217,6 +207,7 @@ void Yggdrasil::processResponse(QJsonObject responseData)
// Set the access token.
m_data->yggdrasilToken.token = accessToken;
m_data->yggdrasilToken.validity = Katabasis::Validity::Certain;
m_data->yggdrasilToken.issueInstant = QDateTime::currentDateTimeUtc();
// We've made it through the minefield of possible errors. Return true to indicate that
// we've succeeded.
@ -224,8 +215,7 @@ void Yggdrasil::processResponse(QJsonObject responseData)
changeState(STATE_SUCCEEDED);
}
void Yggdrasil::processReply()
{
void Yggdrasil::processReply() {
changeState(STATE_WORKING);
switch (m_netReply->error())
@ -247,9 +237,9 @@ void Yggdrasil::processReply()
"<li>You use Windows and need to update your root certificates, please install any outstanding updates.</li>"
"<li>Some device on your network is interfering with SSL traffic. In that case, "
"you have bigger worries than Minecraft not starting.</li>"
"<li>Possibly something else. Check the %1 log file for details</li>"
"<li>Possibly something else. Check the log file for details</li>"
"</ul>"
).arg(BuildConfig.LAUNCHER_NAME)
)
);
return;
// used for invalid credentials and similar errors. Fall through.
@ -278,19 +268,16 @@ void Yggdrasil::processReply()
// Check the response code.
int responseCode = m_netReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (responseCode == 200)
{
if (responseCode == 200) {
// If the response code was 200, then there shouldn't be an error. Make sure
// anyways.
// Also, sometimes an empty reply indicates success. If there was no data received,
// pass an empty json object to the processResponse function.
if (jsonError.error == QJsonParseError::NoError || replyData.size() == 0)
{
if (jsonError.error == QJsonParseError::NoError || replyData.size() == 0) {
processResponse(replyData.size() > 0 ? doc.object() : QJsonObject());
return;
}
else
{
else {
changeState(
STATE_FAILED_SOFT,
tr("Failed to parse authentication server response JSON response: %1 at offset %2.").arg(jsonError.errorString()).arg(jsonError.offset)
@ -304,16 +291,14 @@ void Yggdrasil::processReply()
// about the error.
// If we can parse the response, then get information from it. Otherwise just say
// there was an unknown error.
if (jsonError.error == QJsonParseError::NoError)
{
if (jsonError.error == QJsonParseError::NoError) {
// We were able to parse the server's response. Woo!
// Call processError. If a subclass has overridden it then they'll handle their
// stuff there.
qDebug() << "The request failed, but the server gave us an error message. Processing error.";
processError(doc.object());
}
else
{
else {
// The server didn't say anything regarding the error. Give the user an unknown
// error.
qDebug() << "The request failed and the server gave no error message. Unknown error.";
@ -324,14 +309,12 @@ void Yggdrasil::processReply()
}
}
void Yggdrasil::processError(QJsonObject responseData)
{
void Yggdrasil::processError(QJsonObject responseData) {
QJsonValue errorVal = responseData.value("error");
QJsonValue errorMessageValue = responseData.value("errorMessage");
QJsonValue causeVal = responseData.value("cause");
if (errorVal.isString() && errorMessageValue.isString())
{
if (errorVal.isString() && errorMessageValue.isString()) {
m_error = std::shared_ptr<Error>(
new Error {
errorVal.toString(""),
@ -341,8 +324,7 @@ void Yggdrasil::processError(QJsonObject responseData)
);
changeState(STATE_FAILED_HARD, m_error->m_errorMessageVerbose);
}
else
{
else {
// Error is not in standard format. Don't set m_error and return unknown error.
changeState(STATE_FAILED_HARD, tr("An unknown Yggdrasil error occurred."));
}

View File

@ -24,6 +24,7 @@
#include "../MinecraftAccount.h"
class QNetworkAccessManager;
class QNetworkReply;
/**
@ -33,7 +34,10 @@ class Yggdrasil : public AccountTask
{
Q_OBJECT
public:
explicit Yggdrasil(AccountData * data, QObject *parent = 0);
explicit Yggdrasil(
AccountData *data,
QObject *parent = 0
);
virtual ~Yggdrasil() {};
void refresh();

View File

@ -1,11 +1,15 @@
#include "ClaimAccount.h"
#include <launch/LaunchTask.h>
#include "Application.h"
#include "minecraft/auth/AccountList.h"
ClaimAccount::ClaimAccount(LaunchTask* parent, AuthSessionPtr session): LaunchStep(parent)
{
if(session->status == AuthSession::Status::PlayableOnline)
{
m_account = session->m_accountPtr;
auto accounts = APPLICATION->accounts();
m_account = accounts->getAccountByProfileName(session->player_name);
}
}

View File

@ -72,7 +72,7 @@ void LauncherPartLaunch::executeTask()
m_process.setDetachable(true);
auto classPath = minecraftInstance->getClassPath();
classPath.prepend(FS::PathCombine(ENV.getJarsPath(), "NewLaunch.jar"));
classPath.prepend(FS::PathCombine(ENV->getJarsPath(), "NewLaunch.jar"));
auto natPath = minecraftInstance->getNativePath();
#ifdef Q_OS_WIN

View File

@ -12,7 +12,7 @@ void CapeChange::setCape(QString& cape) {
QNetworkRequest request(QUrl("https://api.minecraftservices.com/minecraft/profile/capes/active"));
auto requestString = QString("{\"capeId\":\"%1\"}").arg(m_capeId);
request.setRawHeader("Authorization", QString("Bearer %1").arg(m_session->access_token).toLocal8Bit());
QNetworkReply *rep = ENV.network().put(request, requestString.toUtf8());
QNetworkReply *rep = ENV->network().put(request, requestString.toUtf8());
setStatus(tr("Equipping cape"));
@ -26,7 +26,7 @@ void CapeChange::clearCape() {
QNetworkRequest request(QUrl("https://api.minecraftservices.com/minecraft/profile/capes/active"));
auto requestString = QString("{\"capeId\":\"%1\"}").arg(m_capeId);
request.setRawHeader("Authorization", QString("Bearer %1").arg(m_session->access_token).toLocal8Bit());
QNetworkReply *rep = ENV.network().deleteResource(request);
QNetworkReply *rep = ENV->network().deleteResource(request);
setStatus(tr("Removing cape"));

View File

@ -12,7 +12,7 @@ void SkinDelete::executeTask()
{
QNetworkRequest request(QUrl("https://api.minecraftservices.com/minecraft/profile/skins/active"));
request.setRawHeader("Authorization", QString("Bearer %1").arg(m_session->access_token).toLocal8Bit());
QNetworkReply *rep = ENV.network().deleteResource(request);
QNetworkReply *rep = ENV->network().deleteResource(request);
m_reply = std::shared_ptr<QNetworkReply>(rep);
setStatus(tr("Deleting skin"));

View File

@ -37,7 +37,7 @@ void SkinUpload::executeTask()
multiPart->append(skin);
multiPart->append(model);
QNetworkReply *rep = ENV.network().post(request, multiPart);
QNetworkReply *rep = ENV->network().post(request, multiPart);
m_reply = std::shared_ptr<QNetworkReply>(rep);
setStatus(tr("Uploading skin"));

View File

@ -24,7 +24,7 @@ void AssetUpdateTask::executeTask()
QString localPath = assets->id + ".json";
auto job = new NetJob(tr("Asset index for %1").arg(m_inst->name()));
auto metacache = ENV.metacache();
auto metacache = ENV->metacache();
auto entry = metacache->resolveEntry("asset_indexes", localPath);
entry->setStale(true);
auto hexSha1 = assets->sha1.toLatin1();
@ -62,7 +62,7 @@ void AssetUpdateTask::assetIndexFinished()
// FIXME: this looks like a job for a generic validator based on json schema?
if (!AssetsUtils::loadAssetsIndexJson(assets->id, asset_fname, index))
{
auto metacache = ENV.metacache();
auto metacache = ENV->metacache();
auto entry = metacache->resolveEntry("asset_indexes", assets->id + ".json");
metacache->evictEntry(entry);
emitFailed(tr("Failed to read the assets index!"));

View File

@ -60,7 +60,7 @@ void FMLLibrariesTask::executeTask()
// download missing libs to our place
setStatus(tr("Downloading FML libraries..."));
auto dljob = new NetJob("FML libraries");
auto metacache = ENV.metacache();
auto metacache = ENV->metacache();
for (auto &lib : fmlLibsToProcess)
{
auto entry = metacache->resolveEntry("fmllibs", lib.filename);
@ -87,7 +87,7 @@ void FMLLibrariesTask::fmllibsFinished()
{
setStatus(tr("Copying FML libraries into the instance..."));
MinecraftInstance *inst = (MinecraftInstance *)m_inst;
auto metacache = ENV.metacache();
auto metacache = ENV->metacache();
int index = 0;
for (auto &lib : fmlLibsToProcess)
{

View File

@ -21,7 +21,7 @@ void LibrariesTask::executeTask()
auto job = new NetJob(tr("Libraries for instance %1").arg(inst->name()));
downloadJob.reset(job);
auto metacache = ENV.metacache();
auto metacache = ENV->metacache();
auto processArtifactPool = [&](const QList<LibraryPtr> & pool, QStringList & errors, const QString & localPath)
{

View File

@ -76,7 +76,7 @@ void PackInstallTask::onDownloadSucceeded()
}
m_version = version;
auto vlist = ENV.metadataIndex()->get("net.minecraft");
auto vlist = ENV->metadataIndex()->get("net.minecraft");
if(!vlist)
{
emitFailed(tr("Failed to get local metadata index for %1").arg("net.minecraft"));
@ -157,7 +157,7 @@ QString PackInstallTask::getDirForModType(ModType type, QString raw)
QString PackInstallTask::getVersionForLoader(QString uid)
{
if(m_version.loader.recommended || m_version.loader.latest || m_version.loader.choose) {
auto vlist = ENV.metadataIndex()->get(uid);
auto vlist = ENV->metadataIndex()->get(uid);
if(!vlist)
{
emitFailed(tr("Failed to get local metadata index for %1").arg(uid));
@ -409,7 +409,7 @@ void PackInstallTask::installConfigs()
auto path = QString("Configs/%1/%2.zip").arg(m_pack).arg(m_version_name);
auto url = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "packs/%1/versions/%2/Configs.zip")
.arg(m_pack).arg(m_version_name);
auto entry = ENV.metacache()->resolveEntry("ATLauncherPacks", path);
auto entry = ENV->metacache()->resolveEntry("ATLauncherPacks", path);
entry->setStale(true);
auto dl = Net::Download::makeCached(url, entry);
@ -516,7 +516,7 @@ void PackInstallTask::downloadMods()
auto cacheName = fileName.completeBaseName() + "-" + mod.md5 + "." + fileName.suffix();
if (mod.type == ModType::Extract || mod.type == ModType::TexturePackExtract || mod.type == ModType::ResourcePackExtract) {
auto entry = ENV.metacache()->resolveEntry("ATLauncherPacks", cacheName);
auto entry = ENV->metacache()->resolveEntry("ATLauncherPacks", cacheName);
entry->setStale(true);
modsToExtract.insert(entry->getFullPath(), mod);
@ -528,7 +528,7 @@ void PackInstallTask::downloadMods()
jobPtr->addNetAction(dl);
}
else if(mod.type == ModType::Decomp) {
auto entry = ENV.metacache()->resolveEntry("ATLauncherPacks", cacheName);
auto entry = ENV->metacache()->resolveEntry("ATLauncherPacks", cacheName);
entry->setStale(true);
modsToDecomp.insert(entry->getFullPath(), mod);
@ -543,7 +543,7 @@ void PackInstallTask::downloadMods()
auto relpath = getDirForModType(mod.type, mod.type_raw);
if(relpath == Q_NULLPTR) continue;
auto entry = ENV.metacache()->resolveEntry("ATLauncherPacks", cacheName);
auto entry = ENV->metacache()->resolveEntry("ATLauncherPacks", cacheName);
entry->setStale(true);
auto dl = Net::Download::makeCached(url, entry);
@ -558,7 +558,7 @@ void PackInstallTask::downloadMods()
modsToCopy[entry->getFullPath()] = path;
if(mod.type == ModType::Forge) {
auto vlist = ENV.metadataIndex()->get("net.minecraftforge");
auto vlist = ENV->metadataIndex()->get("net.minecraftforge");
if(vlist)
{
auto ver = vlist->getVersion(mod.version);

View File

@ -31,7 +31,7 @@ void PackInstallTask::downloadPack()
setStatus(tr("Downloading zip for %1").arg(m_pack.name));
auto packoffset = QString("%1/%2/%3").arg(m_pack.dir, m_version.replace(".", "_"), m_pack.file);
auto entry = ENV.metacache()->resolveEntry("FTBPacks", packoffset);
auto entry = ENV->metacache()->resolveEntry("FTBPacks", packoffset);
NetJob *job = new NetJob("Download FTB Pack");
entry->setStale(true);

View File

@ -102,7 +102,7 @@ void PackInstallTask::downloadPack()
QFileInfo fileName(file.name);
auto cacheName = fileName.completeBaseName() + "-" + file.sha1 + "." + fileName.suffix();
auto entry = ENV.metacache()->resolveEntry("ModpacksCHPacks", cacheName);
auto entry = ENV->metacache()->resolveEntry("ModpacksCHPacks", cacheName);
entry->setStale(true);
auto relpath = FS::PathCombine("minecraft", file.path, file.name);

View File

@ -41,7 +41,7 @@ void Technic::SingleZipPackInstallTask::executeTask()
setStatus(tr("Downloading modpack:\n%1").arg(m_sourceUrl.toString()));
const QString path = m_sourceUrl.host() + '/' + m_sourceUrl.path();
auto entry = ENV.metacache()->resolveEntry("general", path);
auto entry = ENV->metacache()->resolveEntry("general", path);
entry->setStale(true);
m_filesNetJob.reset(new NetJob(tr("Modpack download")));
m_filesNetJob->addNetAction(Net::Download::makeCached(m_sourceUrl, entry));

View File

@ -97,7 +97,7 @@ void Download::start()
request.setHeader(QNetworkRequest::UserAgentHeader, BuildConfig.USER_AGENT);
QNetworkReply *rep = ENV.network().get(request);
QNetworkReply *rep = ENV->network().get(request);
m_reply.reset(rep);
connect(rep, SIGNAL(downloadProgress(qint64, qint64)), SLOT(downloadProgress(qint64, qint64)));

View File

@ -53,7 +53,7 @@ JobStatus MetaCacheSink::finalizeCache(QNetworkReply & reply)
}
m_entry->setLocalChangedTimestamp(output_file_info.lastModified().toUTC().toMSecsSinceEpoch());
m_entry->setStale(false);
ENV.metacache()->updateEntry(m_entry);
ENV->metacache()->updateEntry(m_entry);
return Job_Finished;
}

View File

@ -41,7 +41,7 @@ void PasteUpload::executeTask()
request.setRawHeader("Content-Length", QByteArray::number(m_jsonContent.size()));
request.setRawHeader("X-Auth-Token", m_key.toStdString().c_str());
QNetworkReply *rep = ENV.network().post(request, m_jsonContent);
QNetworkReply *rep = ENV->network().post(request, m_jsonContent);
m_reply = std::shared_ptr<QNetworkReply>(rep);
setStatus(tr("Uploading to paste.ee"));

View File

@ -53,7 +53,7 @@ void NotificationChecker::checkForNotifications()
return;
}
m_checkJob.reset(new NetJob("Checking for notifications"));
auto entry = ENV.metacache()->resolveEntry("root", "notifications.json");
auto entry = ENV->metacache()->resolveEntry("root", "notifications.json");
entry->setStale(true);
m_checkJob->addNetAction(m_download = Net::Download::makeCached(m_notificationsUrl, entry));
connect(m_download.get(), &Net::Download::succeeded, this, &NotificationChecker::downloadSucceeded);

View File

@ -20,7 +20,7 @@
#include <QVBoxLayout>
#include <QKeyEvent>
#include "Launcher.h"
#include "Application.h"
#include "settings/SettingsObject.h"
#include "widgets/IconLabel.h"
#include "widgets/PageContainer.h"
@ -45,7 +45,7 @@ PageDialog::PageDialog(BasePageProvider *pageProvider, QString defaultId, QWidge
connect(buttons->button(QDialogButtonBox::Close), SIGNAL(clicked()), this, SLOT(close()));
connect(buttons->button(QDialogButtonBox::Help), SIGNAL(clicked()), m_container, SLOT(help()));
restoreGeometry(QByteArray::fromBase64(LAUNCHER->settings()->get("PagedGeometry").toByteArray()));
restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("PagedGeometry").toByteArray()));
}
void PageDialog::closeEvent(QCloseEvent *event)
@ -54,7 +54,7 @@ void PageDialog::closeEvent(QCloseEvent *event)
if (m_container->prepareToClose())
{
qDebug() << "Paged dialog close approved";
LAUNCHER->settings()->set("PagedGeometry", saveGeometry().toBase64());
APPLICATION->settings()->set("PagedGeometry", saveGeometry().toBase64());
qDebug() << "Paged dialog geometry saved";
QDialog::closeEvent(event);
}

View File

@ -32,7 +32,7 @@
#include "minecraft/auth/AccountTask.h"
#include "minecraft/services/SkinDelete.h"
#include "Launcher.h"
#include "Application.h"
#include "BuildConfig.h"
#include <dialogs/MSALoginDialog.h>
@ -50,7 +50,7 @@ AccountListPage::AccountListPage(QWidget *parent)
ui->listView->setEmptyMode(VersionListView::String);
ui->listView->setContextMenuPolicy(Qt::CustomContextMenu);
m_accounts = LAUNCHER->accounts();
m_accounts = APPLICATION->accounts();
ui->listView->setModel(m_accounts.get());
ui->listView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
@ -68,7 +68,8 @@ AccountListPage::AccountListPage(QWidget *parent)
connect(ui->listView, &VersionListView::customContextMenuRequested, this, &AccountListPage::ShowContextMenu);
connect(m_accounts.get(), &AccountList::listChanged, this, &AccountListPage::listChanged);
connect(m_accounts.get(), &AccountList::activeAccountChanged, this, &AccountListPage::listChanged);
connect(m_accounts.get(), &AccountList::listActivityChanged, this, &AccountListPage::listChanged);
connect(m_accounts.get(), &AccountList::defaultAccountChanged, this, &AccountListPage::listChanged);
updateButtonStates();
@ -117,11 +118,11 @@ void AccountListPage::on_actionAddMojang_triggered()
tr("Please enter your Mojang account email and password to add your account.")
);
if (account != nullptr)
if (account)
{
m_accounts->addAccount(account);
if (m_accounts->count() == 1) {
m_accounts->setActiveAccount(account);
m_accounts->setDefaultAccount(account);
}
}
}
@ -145,11 +146,11 @@ void AccountListPage::on_actionAddMicrosoft_triggered()
tr("Please enter your Mojang account email and password to add your account.")
);
if (account != nullptr)
if (account)
{
m_accounts->addAccount(account);
if (m_accounts->count() == 1) {
m_accounts->setActiveAccount(account);
m_accounts->setDefaultAccount(account);
}
}
}
@ -187,27 +188,34 @@ void AccountListPage::on_actionSetDefault_triggered()
{
QModelIndex selected = selection.first();
MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>();
m_accounts->setActiveAccount(account);
m_accounts->setDefaultAccount(account);
}
}
void AccountListPage::on_actionNoDefault_triggered()
{
m_accounts->setActiveAccount(nullptr);
m_accounts->setDefaultAccount(nullptr);
}
void AccountListPage::updateButtonStates()
{
// If there is no selection, disable buttons that require something selected.
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
bool hasSelection = selection.size() > 0;
bool accountIsReady = false;
if (hasSelection)
{
QModelIndex selected = selection.first();
MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>();
accountIsReady = !account->isActive();
}
ui->actionRemove->setEnabled(accountIsReady);
ui->actionSetDefault->setEnabled(accountIsReady);
ui->actionUploadSkin->setEnabled(accountIsReady);
ui->actionDeleteSkin->setEnabled(accountIsReady);
ui->actionRefresh->setEnabled(accountIsReady);
ui->actionRemove->setEnabled(selection.size() > 0);
ui->actionSetDefault->setEnabled(selection.size() > 0);
ui->actionUploadSkin->setEnabled(selection.size() > 0);
ui->actionDeleteSkin->setEnabled(selection.size() > 0);
ui->actionRefresh->setEnabled(selection.size() > 0);
if(m_accounts->activeAccount().get() == nullptr) {
if(m_accounts->defaultAccount().get() == nullptr) {
ui->actionNoDefault->setEnabled(false);
ui->actionNoDefault->setChecked(true);
}
@ -215,7 +223,6 @@ void AccountListPage::updateButtonStates()
ui->actionNoDefault->setEnabled(true);
ui->actionNoDefault->setChecked(false);
}
}
void AccountListPage::on_actionUploadSkin_triggered()

View File

@ -21,7 +21,7 @@
#include "pages/BasePage.h"
#include "minecraft/auth/AccountList.h"
#include "Launcher.h"
#include "Application.h"
namespace Ui
{
@ -43,10 +43,10 @@ public:
}
QIcon icon() const override
{
auto icon = LAUNCHER->getThemedIcon("accounts");
auto icon = APPLICATION->getThemedIcon("accounts");
if(icon.isNull())
{
icon = LAUNCHER->getThemedIcon("noaccount");
icon = APPLICATION->getThemedIcon("noaccount");
}
return icon;
}
@ -80,6 +80,6 @@ protected slots:
private:
void changeEvent(QEvent * event) override;
QMenu * createPopupMenu() override;
std::shared_ptr<AccountList> m_accounts;
shared_qobject_ptr<AccountList> m_accounts;
Ui::AccountListPage *ui;
};

View File

@ -32,7 +32,7 @@ bool CustomCommandsPage::apply()
void CustomCommandsPage::applySettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
s->set("PreLaunchCommand", commands->prelaunchCommand());
s->set("WrapperCommand", commands->wrapperCommand());
s->set("PostExitCommand", commands->postexitCommand());
@ -40,7 +40,7 @@ void CustomCommandsPage::applySettings()
void CustomCommandsPage::loadSettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
commands->initialize(
false,
true,

View File

@ -19,7 +19,7 @@
#include <QDialog>
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
#include "widgets/CustomCommands.h"
class CustomCommandsPage : public QWidget, public BasePage
@ -36,7 +36,7 @@ public:
}
QIcon icon() const override
{
return LAUNCHER->getThemedIcon("custom-commands");
return APPLICATION->getThemedIcon("custom-commands");
}
QString id() const override
{

View File

@ -24,7 +24,7 @@
#include "settings/SettingsObject.h"
#include "tools/BaseProfiler.h"
#include <FileSystem.h>
#include "Launcher.h"
#include "Application.h"
#include <tools/MCEditTool.h>
ExternalToolsPage::ExternalToolsPage(QWidget *parent) :
@ -51,7 +51,7 @@ ExternalToolsPage::~ExternalToolsPage()
void ExternalToolsPage::loadSettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
ui->jprofilerPathEdit->setText(s->get("JProfilerPath").toString());
ui->jvisualvmPathEdit->setText(s->get("JVisualVMPath").toString());
ui->mceditPathEdit->setText(s->get("MCEditPath").toString());
@ -61,7 +61,7 @@ void ExternalToolsPage::loadSettings()
}
void ExternalToolsPage::applySettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
s->set("JProfilerPath", ui->jprofilerPathEdit->text());
s->set("JVisualVMPath", ui->jvisualvmPathEdit->text());
@ -93,7 +93,7 @@ void ExternalToolsPage::on_jprofilerPathBtn_clicked()
break;
}
QString cooked_dir = FS::NormalizePath(raw_dir);
if (!LAUNCHER->profilers()["jprofiler"]->check(cooked_dir, &error))
if (!APPLICATION->profilers()["jprofiler"]->check(cooked_dir, &error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking JProfiler install:\n%1").arg(error));
continue;
@ -108,7 +108,7 @@ void ExternalToolsPage::on_jprofilerPathBtn_clicked()
void ExternalToolsPage::on_jprofilerCheckBtn_clicked()
{
QString error;
if (!LAUNCHER->profilers()["jprofiler"]->check(ui->jprofilerPathEdit->text(), &error))
if (!APPLICATION->profilers()["jprofiler"]->check(ui->jprofilerPathEdit->text(), &error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking JProfiler install:\n%1").arg(error));
}
@ -130,7 +130,7 @@ void ExternalToolsPage::on_jvisualvmPathBtn_clicked()
break;
}
QString cooked_dir = FS::NormalizePath(raw_dir);
if (!LAUNCHER->profilers()["jvisualvm"]->check(cooked_dir, &error))
if (!APPLICATION->profilers()["jvisualvm"]->check(cooked_dir, &error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking JVisualVM install:\n%1").arg(error));
continue;
@ -145,7 +145,7 @@ void ExternalToolsPage::on_jvisualvmPathBtn_clicked()
void ExternalToolsPage::on_jvisualvmCheckBtn_clicked()
{
QString error;
if (!LAUNCHER->profilers()["jvisualvm"]->check(ui->jvisualvmPathEdit->text(), &error))
if (!APPLICATION->profilers()["jvisualvm"]->check(ui->jvisualvmPathEdit->text(), &error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking JVisualVM install:\n%1").arg(error));
}
@ -171,7 +171,7 @@ void ExternalToolsPage::on_mceditPathBtn_clicked()
break;
}
QString cooked_dir = FS::NormalizePath(raw_dir);
if (!LAUNCHER->mcedit()->check(cooked_dir, error))
if (!APPLICATION->mcedit()->check(cooked_dir, error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking MCEdit install:\n%1").arg(error));
continue;
@ -186,7 +186,7 @@ void ExternalToolsPage::on_mceditPathBtn_clicked()
void ExternalToolsPage::on_mceditCheckBtn_clicked()
{
QString error;
if (!LAUNCHER->mcedit()->check(ui->mceditPathEdit->text(), error))
if (!APPLICATION->mcedit()->check(ui->mceditPathEdit->text(), error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking MCEdit install:\n%1").arg(error));
}

View File

@ -18,7 +18,7 @@
#include <QWidget>
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
namespace Ui {
class ExternalToolsPage;
@ -38,10 +38,10 @@ public:
}
QIcon icon() const override
{
auto icon = LAUNCHER->getThemedIcon("externaltools");
auto icon = APPLICATION->getThemedIcon("externaltools");
if(icon.isNull())
{
icon = LAUNCHER->getThemedIcon("loadermods");
icon = APPLICATION->getThemedIcon("loadermods");
}
return icon;
}

View File

@ -29,7 +29,7 @@
#include "settings/SettingsObject.h"
#include <FileSystem.h>
#include "Launcher.h"
#include "Application.h"
#include <sys.h>
JavaPage::JavaPage(QWidget *parent) : QWidget(parent), ui(new Ui::JavaPage)
@ -55,7 +55,7 @@ bool JavaPage::apply()
void JavaPage::applySettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
// Memory
int min = ui->minMemSpinBox->value();
@ -79,7 +79,7 @@ void JavaPage::applySettings()
}
void JavaPage::loadSettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
// Memory
int min = s->get("MinMemAlloc").toInt();
int max = s->get("MaxMemAlloc").toInt();
@ -104,7 +104,7 @@ void JavaPage::on_javaDetectBtn_clicked()
{
JavaInstallPtr java;
VersionSelectDialog vselect(LAUNCHER->javalist().get(), tr("Select a Java version"), this, true);
VersionSelectDialog vselect(APPLICATION->javalist().get(), tr("Select a Java version"), this, true);
vselect.setResizeOn(2);
vselect.exec();

View File

@ -19,7 +19,7 @@
#include <QDialog>
#include "pages/BasePage.h"
#include "JavaCommon.h"
#include <Launcher.h>
#include <Application.h>
#include <QObjectPtr.h>
class SettingsObject;
@ -43,7 +43,7 @@ public:
}
QIcon icon() const override
{
return LAUNCHER->getThemedIcon("java");
return APPLICATION->getThemedIcon("java");
}
QString id() const override
{

View File

@ -26,7 +26,7 @@ bool LanguagePage::apply()
void LanguagePage::applySettings()
{
auto settings = LAUNCHER->settings();
auto settings = APPLICATION->settings();
QString key = mainWidget->getSelectedLanguageKey();
settings->set("Language", key);
}

View File

@ -17,7 +17,7 @@
#include <memory>
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
#include <QWidget>
class LanguageSelectionWidget;
@ -36,7 +36,7 @@ public:
}
QIcon icon() const override
{
return LAUNCHER->getThemedIcon("language");
return APPLICATION->getThemedIcon("language");
}
QString id() const override
{

View File

@ -25,7 +25,7 @@
#include "settings/SettingsObject.h"
#include <FileSystem.h>
#include "Launcher.h"
#include "Application.h"
#include "BuildConfig.h"
#include "themes/ITheme.h"
@ -53,20 +53,20 @@ LauncherPage::LauncherPage(QWidget *parent) : QWidget(parent), ui(new Ui::Launch
defaultFormat = new QTextCharFormat(ui->fontPreview->currentCharFormat());
m_languageModel = LAUNCHER->translations();
m_languageModel = APPLICATION->translations();
loadSettings();
if(BuildConfig.UPDATER_ENABLED)
{
QObject::connect(LAUNCHER->updateChecker().get(), &UpdateChecker::channelListLoaded, this, &LauncherPage::refreshUpdateChannelList);
QObject::connect(APPLICATION->updateChecker().get(), &UpdateChecker::channelListLoaded, this, &LauncherPage::refreshUpdateChannelList);
if (LAUNCHER->updateChecker()->hasChannels())
if (APPLICATION->updateChecker()->hasChannels())
{
refreshUpdateChannelList();
}
else
{
LAUNCHER->updateChecker()->updateChanList(false);
APPLICATION->updateChecker()->updateChanList(false);
}
}
else
@ -171,7 +171,7 @@ void LauncherPage::refreshUpdateChannelList()
QObject::disconnect(ui->updateChannelComboBox, SIGNAL(currentIndexChanged(int)), this,
SLOT(updateChannelSelectionChanged(int)));
QList<UpdateChecker::ChannelListEntry> channelList = LAUNCHER->updateChecker()->getChannelList();
QList<UpdateChecker::ChannelListEntry> channelList = APPLICATION->updateChecker()->getChannelList();
ui->updateChannelComboBox->clear();
int selection = -1;
for (int i = 0; i < channelList.count(); i++)
@ -216,7 +216,7 @@ void LauncherPage::updateChannelSelectionChanged(int index)
void LauncherPage::refreshUpdateChannelDesc()
{
// Get the channel list.
QList<UpdateChecker::ChannelListEntry> channelList = LAUNCHER->updateChecker()->getChannelList();
QList<UpdateChecker::ChannelListEntry> channelList = APPLICATION->updateChecker()->getChannelList();
int selectedIndex = ui->updateChannelComboBox->currentIndex();
if (selectedIndex < 0)
{
@ -237,7 +237,7 @@ void LauncherPage::refreshUpdateChannelDesc()
void LauncherPage::applySettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
if (ui->resetNotificationsBtn->isChecked())
{
@ -283,7 +283,7 @@ void LauncherPage::applySettings()
if(original != s->get("IconTheme"))
{
LAUNCHER->setIconTheme(s->get("IconTheme").toString());
APPLICATION->setIconTheme(s->get("IconTheme").toString());
}
auto originalAppTheme = s->get("ApplicationTheme").toString();
@ -291,7 +291,7 @@ void LauncherPage::applySettings()
if(originalAppTheme != newAppTheme)
{
s->set("ApplicationTheme", newAppTheme);
LAUNCHER->setApplicationTheme(newAppTheme, false);
APPLICATION->setApplicationTheme(newAppTheme, false);
}
// Console settings
@ -330,7 +330,7 @@ void LauncherPage::applySettings()
}
void LauncherPage::loadSettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
// Updates
ui->autoUpdateCheckBox->setChecked(s->get("AutoUpdate").toBool());
m_currentUpdateChannel = s->get("UpdateChannel").toString();
@ -375,7 +375,7 @@ void LauncherPage::loadSettings()
{
auto currentTheme = s->get("ApplicationTheme").toString();
auto themes = LAUNCHER->getValidApplicationThemes();
auto themes = APPLICATION->getValidApplicationThemes();
int idx = 0;
for(auto &theme: themes)
{
@ -392,12 +392,12 @@ void LauncherPage::loadSettings()
ui->showConsoleCheck->setChecked(s->get("ShowConsole").toBool());
ui->autoCloseConsoleCheck->setChecked(s->get("AutoCloseConsole").toBool());
ui->showConsoleErrorCheck->setChecked(s->get("ShowConsoleOnError").toBool());
QString fontFamily = LAUNCHER->settings()->get("ConsoleFont").toString();
QString fontFamily = APPLICATION->settings()->get("ConsoleFont").toString();
QFont consoleFont(fontFamily);
ui->consoleFont->setCurrentFont(consoleFont);
bool conversionOk = true;
int fontSize = LAUNCHER->settings()->get("ConsoleFontSize").toInt(&conversionOk);
int fontSize = APPLICATION->settings()->get("ConsoleFontSize").toInt(&conversionOk);
if(!conversionOk)
{
fontSize = 11;

View File

@ -20,7 +20,7 @@
#include "java/JavaChecker.h"
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
#include "ColorCache.h"
#include <translations/TranslationsModel.h>
@ -46,7 +46,7 @@ public:
}
QIcon icon() const override
{
return LAUNCHER->getThemedIcon("launcher");
return APPLICATION->getThemedIcon("launcher");
}
QString id() const override
{

View File

@ -21,7 +21,7 @@
#include <QTabBar>
#include "settings/SettingsObject.h"
#include "Launcher.h"
#include "Application.h"
MinecraftPage::MinecraftPage(QWidget *parent) : QWidget(parent), ui(new Ui::MinecraftPage)
{
@ -56,7 +56,7 @@ void MinecraftPage::on_maximizedCheckBox_clicked(bool checked)
void MinecraftPage::applySettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
// Window Size
s->set("LaunchMaximized", ui->maximizedCheckBox->isChecked());
@ -75,7 +75,7 @@ void MinecraftPage::applySettings()
void MinecraftPage::loadSettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
// Window Size
ui->maximizedCheckBox->setChecked(s->get("LaunchMaximized").toBool());

View File

@ -20,7 +20,7 @@
#include "java/JavaChecker.h"
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
class SettingsObject;
@ -43,7 +43,7 @@ public:
}
QIcon icon() const override
{
return LAUNCHER->getThemedIcon("minecraft");
return APPLICATION->getThemedIcon("minecraft");
}
QString id() const override
{

View File

@ -23,7 +23,7 @@
#include "settings/SettingsObject.h"
#include "tools/BaseProfiler.h"
#include "Launcher.h"
#include "Application.h"
PasteEEPage::PasteEEPage(QWidget *parent) :
QWidget(parent),
@ -42,7 +42,7 @@ PasteEEPage::~PasteEEPage()
void PasteEEPage::loadSettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
QString keyToUse = s->get("PasteEEAPIKey").toString();
if(keyToUse == "multimc")
{
@ -57,7 +57,7 @@ void PasteEEPage::loadSettings()
void PasteEEPage::applySettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
QString pasteKeyToUse;
if (ui->customButton->isChecked())

View File

@ -18,7 +18,7 @@
#include <QWidget>
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
namespace Ui {
class PasteEEPage;
@ -38,7 +38,7 @@ public:
}
QIcon icon() const override
{
return LAUNCHER->getThemedIcon("log");
return APPLICATION->getThemedIcon("log");
}
QString id() const override
{

View File

@ -19,7 +19,7 @@
#include <QTabBar>
#include "settings/SettingsObject.h"
#include "Launcher.h"
#include "Application.h"
#include "Env.h"
ProxyPage::ProxyPage(QWidget *parent) : QWidget(parent), ui(new Ui::ProxyPage)
@ -58,7 +58,7 @@ void ProxyPage::proxyChanged(int)
void ProxyPage::applySettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
// Proxy
QString proxyType = "None";
@ -77,12 +77,12 @@ void ProxyPage::applySettings()
s->set("ProxyUser", ui->proxyUserEdit->text());
s->set("ProxyPass", ui->proxyPassEdit->text());
ENV.updateProxySettings(proxyType, ui->proxyAddrEdit->text(), ui->proxyPortEdit->value(),
ENV->updateProxySettings(proxyType, ui->proxyAddrEdit->text(), ui->proxyPortEdit->value(),
ui->proxyUserEdit->text(), ui->proxyPassEdit->text());
}
void ProxyPage::loadSettings()
{
auto s = LAUNCHER->settings();
auto s = APPLICATION->settings();
// Proxy
QString proxyType = s->get("ProxyType").toString();
if (proxyType == "Default")

View File

@ -19,7 +19,7 @@
#include <QDialog>
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
namespace Ui
{
@ -40,7 +40,7 @@ public:
}
QIcon icon() const override
{
return LAUNCHER->getThemedIcon("proxy");
return APPLICATION->getThemedIcon("proxy");
}
QString id() const override
{

View File

@ -19,7 +19,7 @@
#include <QString>
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
namespace Ui
{
@ -46,7 +46,7 @@ public:
}
virtual QIcon icon() const override
{
return LAUNCHER->getThemedIcon("settings");
return APPLICATION->getThemedIcon("settings");
}
virtual QString id() const override
{

View File

@ -7,7 +7,7 @@
#include "dialogs/VersionSelectDialog.h"
#include "JavaCommon.h"
#include "Launcher.h"
#include "Application.h"
#include <java/JavaInstallList.h>
#include <FileSystem.h>
@ -22,8 +22,8 @@ InstanceSettingsPage::InstanceSettingsPage(BaseInstance *inst, QWidget *parent)
auto sysMB = Sys::getSystemRam() / Sys::mebibyte;
ui->maxMemSpinBox->setMaximum(sysMB);
connect(ui->openGlobalJavaSettingsButton, &QCommandLinkButton::clicked, this, &InstanceSettingsPage::globalSettingsButtonClicked);
connect(LAUNCHER, &Launcher::globalSettingsAboutToOpen, this, &InstanceSettingsPage::applySettings);
connect(LAUNCHER, &Launcher::globalSettingsClosed, this, &InstanceSettingsPage::loadSettings);
connect(APPLICATION, &Application::globalSettingsAboutToOpen, this, &InstanceSettingsPage::applySettings);
connect(APPLICATION, &Application::globalSettingsClosed, this, &InstanceSettingsPage::loadSettings);
loadSettings();
}
@ -41,13 +41,13 @@ void InstanceSettingsPage::globalSettingsButtonClicked(bool)
{
switch(ui->settingsTabs->currentIndex()) {
case 0:
LAUNCHER->ShowGlobalSettings(this, "java-settings");
APPLICATION->ShowGlobalSettings(this, "java-settings");
return;
case 1:
LAUNCHER->ShowGlobalSettings(this, "minecraft-settings");
APPLICATION->ShowGlobalSettings(this, "minecraft-settings");
return;
case 2:
LAUNCHER->ShowGlobalSettings(this, "custom-commands");
APPLICATION->ShowGlobalSettings(this, "custom-commands");
return;
}
}
@ -278,7 +278,7 @@ void InstanceSettingsPage::on_javaDetectBtn_clicked()
{
JavaInstallPtr java;
VersionSelectDialog vselect(LAUNCHER->javalist().get(), tr("Select a Java version"), this, true);
VersionSelectDialog vselect(APPLICATION->javalist().get(), tr("Select a Java version"), this, true);
vselect.setResizeOn(2);
vselect.exec();

View File

@ -22,7 +22,7 @@
#include <QObjectPtr.h>
#include "pages/BasePage.h"
#include "JavaCommon.h"
#include "Launcher.h"
#include "Application.h"
class JavaChecker;
namespace Ui
@ -43,7 +43,7 @@ public:
}
virtual QIcon icon() const override
{
return LAUNCHER->getThemedIcon("instance-settings");
return APPLICATION->getThemedIcon("instance-settings");
}
virtual QString id() const override
{

View File

@ -4,7 +4,7 @@
#include "InstanceList.h"
#include "minecraft/legacy/LegacyInstance.h"
#include "minecraft/legacy/LegacyUpgradeTask.h"
#include "Launcher.h"
#include "Application.h"
#include "dialogs/CustomMessageBox.h"
#include "dialogs/ProgressDialog.h"
@ -38,9 +38,9 @@ void LegacyUpgradePage::on_upgradeButton_clicked()
QString newName = tr("%1 (Migrated)").arg(m_inst->name());
auto upgradeTask = new LegacyUpgradeTask(m_inst);
upgradeTask->setName(newName);
upgradeTask->setGroup(LAUNCHER->instances()->getInstanceGroup(m_inst->id()));
upgradeTask->setGroup(APPLICATION->instances()->getInstanceGroup(m_inst->id()));
upgradeTask->setIcon(m_inst->iconKey());
unique_qobject_ptr<Task> task(LAUNCHER->instances()->wrapInstanceTask(upgradeTask));
unique_qobject_ptr<Task> task(APPLICATION->instances()->wrapInstanceTask(upgradeTask));
runModalTask(task.get());
}

View File

@ -19,7 +19,7 @@
#include "minecraft/legacy/LegacyInstance.h"
#include "pages/BasePage.h"
#include <Launcher.h>
#include <Application.h>
#include "tasks/Task.h"
namespace Ui
@ -40,7 +40,7 @@ public:
}
virtual QIcon icon() const override
{
return LAUNCHER->getThemedIcon("checkupdate");
return APPLICATION->getThemedIcon("checkupdate");
}
virtual QString id() const override
{

View File

@ -1,7 +1,7 @@
#include "LogPage.h"
#include "ui_LogPage.h"
#include "Launcher.h"
#include "Application.h"
#include <QIcon>
#include <QScrollBar>
@ -125,9 +125,9 @@ LogPage::LogPage(InstancePtr instance, QWidget *parent)
// set up fonts in the log proxy
{
QString fontFamily = LAUNCHER->settings()->get("ConsoleFont").toString();
QString fontFamily = APPLICATION->settings()->get("ConsoleFont").toString();
bool conversionOk = false;
int fontSize = LAUNCHER->settings()->get("ConsoleFontSize").toInt(&conversionOk);
int fontSize = APPLICATION->settings()->get("ConsoleFontSize").toInt(&conversionOk);
if(!conversionOk)
{
fontSize = 11;

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