NOISSUE continue reshuffling the codebase

This commit is contained in:
Petr Mrázek
2021-11-22 03:55:16 +01:00
parent 5040231f8d
commit b258eac215
244 changed files with 516 additions and 768 deletions

View File

@ -0,0 +1,35 @@
#include "ColorCache.h"
/**
* Blend the color with the front color, adapting to the back color
*/
QColor ColorCache::blend(QColor color)
{
if (Rainbow::luma(m_front) > Rainbow::luma(m_back))
{
// for dark color schemes, produce a fitting color first
color = Rainbow::tint(m_front, color, 0.5);
}
// adapt contrast
return Rainbow::mix(m_front, color, m_bias);
}
/**
* Blend the color with the back color
*/
QColor ColorCache::blendBackground(QColor color)
{
// adapt contrast
return Rainbow::mix(m_back, color, m_bias);
}
void ColorCache::recolorAll()
{
auto iter = m_colors.begin();
while(iter != m_colors.end())
{
iter->front = blend(iter->original);
iter->back = blendBackground(iter->original);
}
}

119
launcher/ui/ColorCache.h Normal file
View File

@ -0,0 +1,119 @@
#pragma once
#include <QtGui/QColor>
#include <rainbow.h>
#include <MessageLevel.h>
#include <QMap>
class ColorCache
{
public:
ColorCache(QColor front, QColor back, qreal bias)
{
m_front = front;
m_back = back;
m_bias = bias;
};
void addColor(int key, QColor color)
{
m_colors[key] = {color, blend(color), blendBackground(color)};
}
void setForeground(QColor front)
{
if(m_front != front)
{
m_front = front;
recolorAll();
}
}
void setBackground(QColor back)
{
if(m_back != back)
{
m_back = back;
recolorAll();
}
}
QColor getFront(int key)
{
auto iter = m_colors.find(key);
if(iter == m_colors.end())
{
return QColor();
}
return (*iter).front;
}
QColor getBack(int key)
{
auto iter = m_colors.find(key);
if(iter == m_colors.end())
{
return QColor();
}
return (*iter).back;
}
/**
* Blend the color with the front color, adapting to the back color
*/
QColor blend(QColor color);
/**
* Blend the color with the back color
*/
QColor blendBackground(QColor color);
protected:
void recolorAll();
protected:
struct ColorEntry
{
QColor original;
QColor front;
QColor back;
};
protected:
qreal m_bias;
QColor m_front;
QColor m_back;
QMap<int, ColorEntry> m_colors;
};
class LogColorCache : public ColorCache
{
public:
LogColorCache(QColor front, QColor back)
: ColorCache(front, back, 1.0)
{
addColor((int)MessageLevel::Launcher, QColor("purple"));
addColor((int)MessageLevel::Debug, QColor("green"));
addColor((int)MessageLevel::Warning, QColor("orange"));
addColor((int)MessageLevel::Error, QColor("red"));
addColor((int)MessageLevel::Fatal, QColor("red"));
addColor((int)MessageLevel::Message, front);
}
QColor getFront(MessageLevel::Enum level)
{
if(!m_colors.contains((int) level))
{
return ColorCache::getFront((int)MessageLevel::Message);
}
return ColorCache::getFront((int)level);
}
QColor getBack(MessageLevel::Enum level)
{
if(level == MessageLevel::Fatal)
{
return QColor(Qt::black);
}
return QColor(Qt::transparent);
}
};

136
launcher/ui/GuiUtil.cpp Normal file
View File

@ -0,0 +1,136 @@
#include "GuiUtil.h"
#include <QClipboard>
#include <QApplication>
#include <QFileDialog>
#include "ui/dialogs/ProgressDialog.h"
#include "ui/dialogs/CustomMessageBox.h"
#include "net/PasteUpload.h"
#include "Application.h"
#include <settings/SettingsObject.h>
#include <DesktopServices.h>
#include <BuildConfig.h>
QString GuiUtil::uploadPaste(const QString &text, QWidget *parentWidget)
{
ProgressDialog dialog(parentWidget);
auto APIKeySetting = APPLICATION->settings()->get("PasteEEAPIKey").toString();
if(APIKeySetting == "multimc")
{
APIKeySetting = BuildConfig.PASTE_EE_KEY;
}
std::unique_ptr<PasteUpload> paste(new PasteUpload(parentWidget, text, APIKeySetting));
if (!paste->validateText())
{
CustomMessageBox::selectable(
parentWidget, QObject::tr("Upload failed"),
QObject::tr("The log file is too big. You'll have to upload it manually."),
QMessageBox::Warning)->exec();
return QString();
}
dialog.execWithTask(paste.get());
if (!paste->wasSuccessful())
{
CustomMessageBox::selectable(
parentWidget,
QObject::tr("Upload failed"),
paste->failReason(),
QMessageBox::Critical
)->exec();
return QString();
}
else
{
const QString link = paste->pasteLink();
setClipboardText(link);
CustomMessageBox::selectable(
parentWidget, QObject::tr("Upload finished"),
QObject::tr("The <a href=\"%1\">link to the uploaded log</a> has been placed in your clipboard.").arg(link),
QMessageBox::Information)->exec();
return link;
}
}
void GuiUtil::setClipboardText(const QString &text)
{
QApplication::clipboard()->setText(text);
}
static QStringList BrowseForFileInternal(QString context, QString caption, QString filter, QString defaultPath, QWidget *parentWidget, bool single)
{
static QMap<QString, QString> savedPaths;
QFileDialog w(parentWidget, caption);
QSet<QString> locations;
auto f = [&](QStandardPaths::StandardLocation l)
{
QString location = QStandardPaths::writableLocation(l);
QFileInfo finfo(location);
if (!finfo.exists()) {
return;
}
locations.insert(location);
};
f(QStandardPaths::DesktopLocation);
f(QStandardPaths::DocumentsLocation);
f(QStandardPaths::DownloadLocation);
f(QStandardPaths::HomeLocation);
QList<QUrl> urls;
for (auto location : locations)
{
urls.append(QUrl::fromLocalFile(location));
}
urls.append(QUrl::fromLocalFile(defaultPath));
w.setFileMode(single ? QFileDialog::ExistingFile : QFileDialog::ExistingFiles);
w.setAcceptMode(QFileDialog::AcceptOpen);
w.setNameFilter(filter);
QString pathToOpen;
if(savedPaths.contains(context))
{
pathToOpen = savedPaths[context];
}
else
{
pathToOpen = defaultPath;
}
if(!pathToOpen.isEmpty())
{
QFileInfo finfo(pathToOpen);
if(finfo.exists() && finfo.isDir())
{
w.setDirectory(finfo.absoluteFilePath());
}
}
w.setSidebarUrls(urls);
if (w.exec())
{
savedPaths[context] = w.directory().absolutePath();
return w.selectedFiles();
}
savedPaths[context] = w.directory().absolutePath();
return {};
}
QString GuiUtil::BrowseForFile(QString context, QString caption, QString filter, QString defaultPath, QWidget *parentWidget)
{
auto resultList = BrowseForFileInternal(context, caption, filter, defaultPath, parentWidget, true);
if(resultList.size())
{
return resultList[0];
}
return QString();
}
QStringList GuiUtil::BrowseForFiles(QString context, QString caption, QString filter, QString defaultPath, QWidget *parentWidget)
{
return BrowseForFileInternal(context, caption, filter, defaultPath, parentWidget, false);
}

11
launcher/ui/GuiUtil.h Normal file
View File

@ -0,0 +1,11 @@
#pragma once
#include <QWidget>
namespace GuiUtil
{
QString uploadPaste(const QString &text, QWidget *parentWidget);
void setClipboardText(const QString &text);
QStringList BrowseForFiles(QString context, QString caption, QString filter, QString defaultPath, QWidget *parentWidget);
QString BrowseForFile(QString context, QString caption, QString filter, QString defaultPath, QWidget *parentWidget);
}

View File

@ -0,0 +1,237 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "InstanceWindow.h"
#include "Application.h"
#include <QScrollBar>
#include <QMessageBox>
#include <QHBoxLayout>
#include <QPushButton>
#include <qlayoutitem.h>
#include <QCloseEvent>
#include "ui/dialogs/CustomMessageBox.h"
#include "ui/dialogs/ProgressDialog.h"
#include "ui/widgets/PageContainer.h"
#include "InstancePageProvider.h"
#include "icons/IconList.h"
InstanceWindow::InstanceWindow(InstancePtr instance, QWidget *parent)
: QMainWindow(parent), m_instance(instance)
{
setAttribute(Qt::WA_DeleteOnClose);
auto icon = APPLICATION->icons()->getIcon(m_instance->iconKey());
QString windowTitle = tr("Console window for ") + m_instance->name();
// Set window properties
{
setWindowIcon(icon);
setWindowTitle(windowTitle);
}
// Add page container
{
auto provider = std::make_shared<InstancePageProvider>(m_instance);
m_container = new PageContainer(provider.get(), "console", this);
m_container->setParentContainer(this);
setCentralWidget(m_container);
setContentsMargins(0, 0, 0, 0);
}
// Add custom buttons to the page container layout.
{
auto horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalLayout->setContentsMargins(6, -1, 6, -1);
auto btnHelp = new QPushButton();
btnHelp->setText(tr("Help"));
horizontalLayout->addWidget(btnHelp);
connect(btnHelp, SIGNAL(clicked(bool)), m_container, SLOT(help()));
auto spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addSpacerItem(spacer);
m_killButton = new QPushButton();
horizontalLayout->addWidget(m_killButton);
connect(m_killButton, SIGNAL(clicked(bool)), SLOT(on_btnKillMinecraft_clicked()));
m_launchOfflineButton = new QPushButton();
horizontalLayout->addWidget(m_launchOfflineButton);
m_launchOfflineButton->setText(tr("Launch Offline"));
updateLaunchButtons();
connect(m_launchOfflineButton, SIGNAL(clicked(bool)), SLOT(on_btnLaunchMinecraftOffline_clicked()));
m_closeButton = new QPushButton();
m_closeButton->setText(tr("Close"));
horizontalLayout->addWidget(m_closeButton);
connect(m_closeButton, SIGNAL(clicked(bool)), SLOT(on_closeButton_clicked()));
m_container->addButtons(horizontalLayout);
}
// restore window state
{
auto base64State = APPLICATION->settings()->get("ConsoleWindowState").toByteArray();
restoreState(QByteArray::fromBase64(base64State));
auto base64Geometry = APPLICATION->settings()->get("ConsoleWindowGeometry").toByteArray();
restoreGeometry(QByteArray::fromBase64(base64Geometry));
}
// set up instance and launch process recognition
{
auto launchTask = m_instance->getLaunchTask();
on_InstanceLaunchTask_changed(launchTask);
connect(m_instance.get(), &BaseInstance::launchTaskChanged, this, &InstanceWindow::on_InstanceLaunchTask_changed);
connect(m_instance.get(), &BaseInstance::runningStatusChanged, this, &InstanceWindow::on_RunningState_changed);
}
// set up instance destruction detection
{
connect(m_instance.get(), &BaseInstance::statusChanged, this, &InstanceWindow::on_instanceStatusChanged);
}
show();
}
void InstanceWindow::on_instanceStatusChanged(BaseInstance::Status, BaseInstance::Status newStatus)
{
if(newStatus == BaseInstance::Status::Gone)
{
m_doNotSave = true;
close();
}
}
void InstanceWindow::updateLaunchButtons()
{
if(m_instance->isRunning())
{
m_launchOfflineButton->setEnabled(false);
m_killButton->setText(tr("Kill"));
m_killButton->setObjectName("killButton");
m_killButton->setToolTip(tr("Kill the running instance"));
}
else if(!m_instance->canLaunch())
{
m_launchOfflineButton->setEnabled(false);
m_killButton->setText(tr("Launch"));
m_killButton->setObjectName("launchButton");
m_killButton->setToolTip(tr("Launch the instance"));
m_killButton->setEnabled(false);
}
else
{
m_launchOfflineButton->setEnabled(true);
m_killButton->setText(tr("Launch"));
m_killButton->setObjectName("launchButton");
m_killButton->setToolTip(tr("Launch the instance"));
}
// NOTE: this is a hack to force the button to recalculate its style
m_killButton->setStyleSheet("/* */");
m_killButton->setStyleSheet(QString());
}
void InstanceWindow::on_btnLaunchMinecraftOffline_clicked()
{
APPLICATION->launch(m_instance, false, nullptr);
}
void InstanceWindow::on_InstanceLaunchTask_changed(shared_qobject_ptr<LaunchTask> proc)
{
m_proc = proc;
}
void InstanceWindow::on_RunningState_changed(bool running)
{
updateLaunchButtons();
m_container->refreshContainer();
if(running) {
selectPage("log");
}
}
void InstanceWindow::on_closeButton_clicked()
{
close();
}
void InstanceWindow::closeEvent(QCloseEvent *event)
{
bool proceed = true;
if(!m_doNotSave)
{
proceed &= m_container->prepareToClose();
}
if(!proceed)
{
return;
}
APPLICATION->settings()->set("ConsoleWindowState", saveState().toBase64());
APPLICATION->settings()->set("ConsoleWindowGeometry", saveGeometry().toBase64());
emit isClosing();
event->accept();
}
bool InstanceWindow::saveAll()
{
return m_container->saveAll();
}
void InstanceWindow::on_btnKillMinecraft_clicked()
{
if(m_instance->isRunning())
{
APPLICATION->kill(m_instance);
}
else
{
APPLICATION->launch(m_instance, true, nullptr);
}
}
QString InstanceWindow::instanceId()
{
return m_instance->id();
}
bool InstanceWindow::selectPage(QString pageId)
{
return m_container->selectPage(pageId);
}
void InstanceWindow::refreshContainer()
{
m_container->refreshContainer();
}
InstanceWindow::~InstanceWindow()
{
}
bool InstanceWindow::requestClose()
{
if(m_container->prepareToClose())
{
close();
return true;
}
return false;
}

View File

@ -0,0 +1,76 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QMainWindow>
#include <QSystemTrayIcon>
#include "LaunchController.h"
#include "launch/LaunchTask.h"
#include "ui/pages/BasePageContainer.h"
#include "QObjectPtr.h"
class QPushButton;
class PageContainer;
class InstanceWindow : public QMainWindow, public BasePageContainer
{
Q_OBJECT
public:
explicit InstanceWindow(InstancePtr proc, QWidget *parent = 0);
virtual ~InstanceWindow();
bool selectPage(QString pageId) override;
void refreshContainer() override;
QString instanceId();
// save all settings and changes (prepare for launch)
bool saveAll();
// request closing the window (from a page)
bool requestClose() override;
signals:
void isClosing();
private
slots:
void on_closeButton_clicked();
void on_btnKillMinecraft_clicked();
void on_btnLaunchMinecraftOffline_clicked();
void on_InstanceLaunchTask_changed(shared_qobject_ptr<LaunchTask> proc);
void on_RunningState_changed(bool running);
void on_instanceStatusChanged(BaseInstance::Status, BaseInstance::Status newStatus);
protected:
void closeEvent(QCloseEvent *) override;
private:
void updateLaunchButtons();
private:
shared_qobject_ptr<LaunchTask> m_proc;
InstancePtr m_instance;
bool m_doNotSave = false;
PageContainer *m_container = nullptr;
QPushButton *m_closeButton = nullptr;
QPushButton *m_killButton = nullptr;
QPushButton *m_launchOfflineButton = nullptr;
};

1949
launcher/ui/MainWindow.cpp Normal file

File diff suppressed because it is too large Load Diff

221
launcher/ui/MainWindow.h Normal file
View File

@ -0,0 +1,221 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QMainWindow>
#include <QProcess>
#include <QTimer>
#include "BaseInstance.h"
#include "minecraft/auth/MinecraftAccount.h"
#include "net/NetJob.h"
#include "updater/GoUpdate.h"
class LaunchController;
class NewsChecker;
class NotificationChecker;
class QToolButton;
class InstanceProxyModel;
class LabeledToolButton;
class QLabel;
class MinecraftLauncher;
class BaseProfilerFactory;
class InstanceView;
class KonamiCode;
class InstanceTask;
class MainWindow : public QMainWindow
{
Q_OBJECT
class Ui;
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
bool eventFilter(QObject *obj, QEvent *ev) override;
void closeEvent(QCloseEvent *event) override;
void changeEvent(QEvent * event) override;
void checkInstancePathForProblems();
void updatesAllowedChanged(bool allowed);
void droppedURLs(QList<QUrl> urls);
signals:
void isClosing();
protected:
QMenu * createPopupMenu() override;
private slots:
void onCatToggled(bool);
void on_actionAbout_triggered();
void on_actionAddInstance_triggered();
void on_actionREDDIT_triggered();
void on_actionDISCORD_triggered();
void on_actionCopyInstance_triggered();
void on_actionChangeInstGroup_triggered();
void on_actionChangeInstIcon_triggered();
void on_changeIconButton_clicked(bool)
{
on_actionChangeInstIcon_triggered();
}
void on_actionViewInstanceFolder_triggered();
void on_actionConfig_Folder_triggered();
void on_actionViewSelectedInstFolder_triggered();
void on_actionViewSelectedMCFolder_triggered();
void refreshInstances();
void on_actionViewCentralModsFolder_triggered();
void checkForUpdates();
void on_actionSettings_triggered();
void on_actionInstanceSettings_triggered();
void on_actionManageAccounts_triggered();
void on_actionReportBug_triggered();
void on_actionPatreon_triggered();
void on_actionMoreNews_triggered();
void newsButtonClicked();
void on_actionLaunchInstance_triggered();
void on_actionLaunchInstanceOffline_triggered();
void on_actionDeleteInstance_triggered();
void deleteGroup();
void on_actionExportInstance_triggered();
void on_actionRenameInstance_triggered();
void on_renameButton_clicked(bool)
{
on_actionRenameInstance_triggered();
}
void on_actionEditInstance_triggered();
void on_actionEditInstNotes_triggered();
void on_actionWorlds_triggered();
void on_actionScreenshots_triggered();
void taskEnd();
/**
* called when an icon is changed in the icon model.
*/
void iconUpdated(QString);
void showInstanceContextMenu(const QPoint &);
void updateToolsMenu();
void instanceActivated(QModelIndex);
void instanceChanged(const QModelIndex &current, const QModelIndex &previous);
void instanceSelectRequest(QString id);
void instanceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
void selectionBad();
void startTask(Task *task);
void updateAvailable(GoUpdate::Status status);
void updateNotAvailable();
void notificationsChanged();
void defaultAccountChanged();
void changeActiveAccount();
void repopulateAccountsMenu();
void updateNewsLabel();
/*!
* Runs the DownloadTask and installs updates.
*/
void downloadUpdates(GoUpdate::Status status);
void konamiTriggered();
void globalSettingsClosed();
private:
void retranslateUi();
void addInstance(QString url = QString());
void activateInstance(InstancePtr instance);
void setCatBackground(bool enabled);
void updateInstanceToolIcon(QString new_icon);
void setSelectedInstanceById(const QString &id);
void updateStatusCenter();
void runModalTask(Task *task);
void instanceFromInstanceTask(InstanceTask *task);
void finalizeInstance(InstancePtr inst);
private:
std::unique_ptr<Ui> ui;
// these are managed by Qt's memory management model!
InstanceView *view = nullptr;
InstanceProxyModel *proxymodel = nullptr;
QToolButton *newsLabel = nullptr;
QLabel *m_statusLeft = nullptr;
QLabel *m_statusCenter = nullptr;
QMenu *accountMenu = nullptr;
QToolButton *accountMenuButton = nullptr;
KonamiCode * secretEventFilter = nullptr;
unique_qobject_ptr<NewsChecker> m_newsChecker;
unique_qobject_ptr<NotificationChecker> m_notificationChecker;
InstancePtr m_selectedInstance;
QString m_currentInstIcon;
// managed by the application object
Task *m_versionLoadTask = nullptr;
};

View File

@ -0,0 +1,149 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AboutDialog.h"
#include "ui_AboutDialog.h"
#include <QIcon>
#include "Application.h"
#include "BuildConfig.h"
#include <net/NetJob.h>
#include "HoeDown.h"
namespace {
// Credits
// This is a hack, but I can't think of a better way to do this easily without screwing with QTextDocument...
QString getCreditsHtml(QStringList patrons)
{
QString patronsHeading = QObject::tr("Patrons", "About Credits");
QString output;
QTextStream stream(&output);
stream.setCodec(QTextCodec::codecForName("UTF-8"));
stream << "<center>\n";
// TODO: possibly retrieve from git history at build time?
stream << "<h3>" << QObject::tr("Developers", "About Credits") << "</h3>\n";
stream << "<p>Andrew Okin &lt;<a href='mailto:forkk@forkk.net'>forkk@forkk.net</a>&gt;</p>\n";
stream << "<p>Petr Mrázek &lt;<a href='mailto:peterix@gmail.com'>peterix@gmail.com</a>&gt;</p>\n";
stream << "<p>Sky Welch &lt;<a href='mailto:multimc@bunnies.io'>multimc@bunnies.io</a>&gt;</p>\n";
stream << "<p>Jan (02JanDal) &lt;<a href='mailto:02jandal@gmail.com'>02jandal@gmail.com</a>&gt;</p>\n";
stream << "<p>RoboSky &lt;<a href='https://twitter.com/RoboSky_'>@RoboSky_</a>&gt;</p>\n";
stream << "<br />\n";
stream << "<h3>" << QObject::tr("With thanks to", "About Credits") << "</h3>\n";
stream << "<p>Orochimarufan &lt;<a href='mailto:orochimarufan.x3@gmail.com'>orochimarufan.x3@gmail.com</a>&gt;</p>\n";
stream << "<p>TakSuyu &lt;<a href='mailto:taksuyu@gmail.com'>taksuyu@gmail.com</a>&gt;</p>\n";
stream << "<p>Kilobyte &lt;<a href='mailto:stiepen22@gmx.de'>stiepen22@gmx.de</a>&gt;</p>\n";
stream << "<p>Rootbear75 &lt;<a href='https://twitter.com/rootbear75'>@rootbear75</a>&gt;</p>\n";
stream << "<p>Zeker Zhayard &lt;<a href='https://twitter.com/zeker_zhayard'>@Zeker_Zhayard</a>&gt;</p>\n";
stream << "<br />\n";
if(!patrons.isEmpty()) {
stream << "<h3>" << QObject::tr("Patrons", "About Credits") << "</h3>\n";
for (QString patron : patrons)
{
stream << "<p>" << patron << "</p>\n";
}
}
stream << "</center>\n";
return output;
}
QString getLicenseHtml()
{
HoeDown hoedown;
QFile dataFile(":/documents/COPYING.md");
dataFile.open(QIODevice::ReadOnly);
QString output = hoedown.process(dataFile.readAll());
return output;
}
}
AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog)
{
ui->setupUi(this);
QString launcherName = BuildConfig.LAUNCHER_NAME;
setWindowTitle(tr("About %1").arg(launcherName));
QString chtml = getCreditsHtml(QStringList());
ui->creditsText->setHtml(chtml);
QString lhtml = getLicenseHtml();
ui->licenseText->setHtml(lhtml);
ui->urlLabel->setOpenExternalLinks(true);
ui->icon->setPixmap(APPLICATION->getThemedIcon("logo").pixmap(64));
ui->title->setText(launcherName);
ui->versionLabel->setText(tr("Version") +": " + BuildConfig.printableVersionString());
ui->platformLabel->setText(tr("Platform") +": " + BuildConfig.BUILD_PLATFORM);
if (BuildConfig.VERSION_BUILD >= 0)
ui->buildNumLabel->setText(tr("Build Number") +": " + QString::number(BuildConfig.VERSION_BUILD));
else
ui->buildNumLabel->setVisible(false);
if (!BuildConfig.VERSION_CHANNEL.isEmpty())
ui->channelLabel->setText(tr("Channel") +": " + BuildConfig.VERSION_CHANNEL);
else
ui->channelLabel->setVisible(false);
ui->redistributionText->setHtml(tr(
"<p>We keep MultiMC open source because we think it's important to be able to see the source code for a project like this, and we do so using the Apache license.</p>\n"
"<p>Part of the reason for using the Apache license is we don't want people using the &quot;MultiMC&quot; name when redistributing the project. "
"This means people must take the time to go through the source code and remove all references to &quot;MultiMC&quot;, including but not limited to the project "
"icon and the title of windows, (no <b>MultiMC-fork</b> in the title).</p>\n"
"<p>The Apache license covers reasonable use for the name - a mention of the project's origins in the About dialog and the license is acceptable. "
"However, it should be abundantly clear that the project is a fork <b>without</b> implying that you have our blessing.</p>"
));
QString urlText("<html><head/><body><p><a href=\"%1\">%1</a></p></body></html>");
ui->urlLabel->setText(urlText.arg(BuildConfig.LAUNCHER_GIT));
QString copyText("© 2012-2021 %1");
ui->copyLabel->setText(copyText.arg(BuildConfig.LAUNCHER_COPYRIGHT));
connect(ui->closeButton, SIGNAL(clicked()), SLOT(close()));
connect(ui->aboutQt, &QPushButton::clicked, &QApplication::aboutQt);
loadPatronList();
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::loadPatronList()
{
netJob = new NetJob("Patreon Patron List");
netJob->addNetAction(Net::Download::makeByteArray(QUrl("https://files.multimc.org/patrons.txt"), &dataSink));
connect(netJob.get(), &NetJob::succeeded, this, &AboutDialog::patronListLoaded);
netJob->start(APPLICATION->network());
}
void AboutDialog::patronListLoaded()
{
QString patronListStr(dataSink);
dataSink.clear();
QString html = getCreditsHtml(patronListStr.split("\n", QString::SkipEmptyParts));
ui->creditsText->setHtml(html);
}

View File

@ -0,0 +1,47 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <net/NetJob.h>
namespace Ui
{
class AboutDialog;
}
class AboutDialog : public QDialog
{
Q_OBJECT
public:
explicit AboutDialog(QWidget *parent = 0);
~AboutDialog();
public
slots:
/// Starts loading a list of Patreon patrons.
void loadPatronList();
/// Slot for when the patron list loads successfully.
void patronListLoaded();
private:
Ui::AboutDialog *ui;
NetJob::Ptr netJob;
QByteArray dataSink;
};

View File

@ -0,0 +1,316 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AboutDialog</class>
<widget class="QDialog" name="AboutDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>783</width>
<height>843</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>450</width>
<height>400</height>
</size>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="icon">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>64</width>
<height>64</height>
</size>
</property>
<property name="baseSize">
<size>
<width>64</width>
<height>64</height>
</size>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="title">
<property name="font">
<font>
<pointsize>15</pointsize>
</font>
</property>
<property name="text">
<string notr="true">MultiMC 5</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="aboutTab">
<attribute name="title">
<string>About</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
<widget class="QLabel" name="aboutLabel">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;A custom launcher that makes managing Minecraft easier by allowing you to have multiple instances of Minecraft at once.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="urlLabel">
<property name="font">
<font>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string notr="true">GIT URL</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="copyLabel">
<property name="font">
<font>
<pointsize>8</pointsize>
<kerning>true</kerning>
</font>
</property>
<property name="text">
<string notr="true">COPYRIGHT</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="versionLabel">
<property name="text">
<string>Version:</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="platformLabel">
<property name="text">
<string>Platform:</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="buildNumLabel">
<property name="text">
<string>Build Number:</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="channelLabel">
<property name="text">
<string>Channel:</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>212</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<widget class="QWidget" name="creditsTab">
<attribute name="title">
<string>Credits</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QTextEdit" name="creditsText">
<property name="readOnly">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::TextBrowserInteraction</set>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="licenseTab">
<attribute name="title">
<string>License</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QTextEdit" name="licenseText">
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<family>DejaVu Sans Mono</family>
</font>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::TextBrowserInteraction</set>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="forkingTab">
<attribute name="title">
<string>Forking/Redistribution</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QTextEdit" name="redistributionText">
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="aboutQt">
<property name="autoFillBackground">
<bool>false</bool>
</property>
<property name="text">
<string>About Qt</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="closeButton">
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>creditsText</tabstop>
<tabstop>licenseText</tabstop>
<tabstop>redistributionText</tabstop>
<tabstop>aboutQt</tabstop>
<tabstop>closeButton</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,144 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QLayout>
#include <QPushButton>
#include "Application.h"
#include "CopyInstanceDialog.h"
#include "ui_CopyInstanceDialog.h"
#include "ui/dialogs/IconPickerDialog.h"
#include "BaseVersion.h"
#include "icons/IconList.h"
#include "tasks/Task.h"
#include "BaseInstance.h"
#include "InstanceList.h"
CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget *parent)
:QDialog(parent), ui(new Ui::CopyInstanceDialog), m_original(original)
{
ui->setupUi(this);
resize(minimumSizeHint());
layout()->setSizeConstraint(QLayout::SetFixedSize);
InstIconKey = original->iconKey();
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
ui->instNameTextBox->setText(original->name());
ui->instNameTextBox->setFocus();
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(APPLICATION->instances()->getInstanceGroup(m_original->id()));
if(index == -1)
{
index = 0;
}
ui->groupBox->setCurrentIndex(index);
ui->groupBox->lineEdit()->setPlaceholderText(tr("No group"));
ui->copySavesCheckbox->setChecked(m_copySaves);
ui->keepPlaytimeCheckbox->setChecked(m_keepPlaytime);
}
CopyInstanceDialog::~CopyInstanceDialog()
{
delete ui;
}
void CopyInstanceDialog::updateDialogState()
{
auto allowOK = !instName().isEmpty();
auto OkButton = ui->buttonBox->button(QDialogButtonBox::Ok);
if(OkButton->isEnabled() != allowOK)
{
OkButton->setEnabled(allowOK);
}
}
QString CopyInstanceDialog::instName() const
{
auto result = ui->instNameTextBox->text().trimmed();
if(result.size())
{
return result;
}
return QString();
}
QString CopyInstanceDialog::iconKey() const
{
return InstIconKey;
}
QString CopyInstanceDialog::instGroup() const
{
return ui->groupBox->currentText();
}
void CopyInstanceDialog::on_iconButton_clicked()
{
IconPickerDialog dlg(this);
dlg.execWithSelection(InstIconKey);
if (dlg.result() == QDialog::Accepted)
{
InstIconKey = dlg.selectedIconKey;
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
}
}
void CopyInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1)
{
updateDialogState();
}
bool CopyInstanceDialog::shouldCopySaves() const
{
return m_copySaves;
}
void CopyInstanceDialog::on_copySavesCheckbox_stateChanged(int state)
{
if(state == Qt::Unchecked)
{
m_copySaves = false;
}
else if(state == Qt::Checked)
{
m_copySaves = true;
}
}
bool CopyInstanceDialog::shouldKeepPlaytime() const
{
return m_keepPlaytime;
}
void CopyInstanceDialog::on_keepPlaytimeCheckbox_stateChanged(int state)
{
if(state == Qt::Unchecked)
{
m_keepPlaytime = false;
}
else if(state == Qt::Checked)
{
m_keepPlaytime = true;
}
}

View File

@ -0,0 +1,58 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include "BaseVersion.h"
#include <BaseInstance.h>
class BaseInstance;
namespace Ui
{
class CopyInstanceDialog;
}
class CopyInstanceDialog : public QDialog
{
Q_OBJECT
public:
explicit CopyInstanceDialog(InstancePtr original, QWidget *parent = 0);
~CopyInstanceDialog();
void updateDialogState();
QString instName() const;
QString instGroup() const;
QString iconKey() const;
bool shouldCopySaves() const;
bool shouldKeepPlaytime() const;
private
slots:
void on_iconButton_clicked();
void on_instNameTextBox_textChanged(const QString &arg1);
void on_copySavesCheckbox_stateChanged(int state);
void on_keepPlaytimeCheckbox_stateChanged(int state);
private:
Ui::CopyInstanceDialog *ui;
QString InstIconKey;
InstancePtr m_original;
bool m_copySaves = true;
bool m_keepPlaytime = true;
};

View File

@ -0,0 +1,182 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CopyInstanceDialog</class>
<widget class="QDialog" name="CopyInstanceDialog">
<property name="windowModality">
<enum>Qt::ApplicationModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>345</width>
<height>323</height>
</rect>
</property>
<property name="windowTitle">
<string>Copy Instance</string>
</property>
<property name="windowIcon">
<iconset>
<normaloff>:/icons/toolbar/copy</normaloff>:/icons/toolbar/copy</iconset>
</property>
<property name="modal">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="iconBtnLayout">
<item>
<spacer name="iconBtnLeftSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QToolButton" name="iconButton">
<property name="icon">
<iconset>
<normaloff>:/icons/instances/grass</normaloff>:/icons/instances/grass</iconset>
</property>
<property name="iconSize">
<size>
<width>80</width>
<height>80</height>
</size>
</property>
</widget>
</item>
<item>
<spacer name="iconBtnRightSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QLineEdit" name="instNameTextBox">
<property name="placeholderText">
<string>Name</string>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="labelVersion_3">
<property name="text">
<string>&amp;Group</string>
</property>
<property name="buddy">
<cstring>groupBox</cstring>
</property>
</widget>
</item>
<item row="0" column="1" colspan="2">
<widget class="QComboBox" name="groupBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QCheckBox" name="copySavesCheckbox">
<property name="text">
<string>Copy saves</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="keepPlaytimeCheckbox">
<property name="text">
<string>Keep play time</string>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>iconButton</tabstop>
<tabstop>instNameTextBox</tabstop>
<tabstop>groupBox</tabstop>
<tabstop>copySavesCheckbox</tabstop>
<tabstop>keepPlaytimeCheckbox</tabstop>
</tabstops>
<resources>
<include location="../../graphics.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>CopyInstanceDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>CopyInstanceDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,35 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CustomMessageBox.h"
namespace CustomMessageBox
{
QMessageBox *selectable(QWidget *parent, const QString &title, const QString &text,
QMessageBox::Icon icon, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
QMessageBox *messageBox = new QMessageBox(parent);
messageBox->setWindowTitle(title);
messageBox->setText(text);
messageBox->setStandardButtons(buttons);
messageBox->setDefaultButton(defaultButton);
messageBox->setTextInteractionFlags(Qt::TextSelectableByMouse);
messageBox->setIcon(icon);
messageBox->setTextInteractionFlags(Qt::TextBrowserInteraction);
return messageBox;
}
}

View File

@ -0,0 +1,26 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QMessageBox>
namespace CustomMessageBox
{
QMessageBox *selectable(QWidget *parent, const QString &title, const QString &text,
QMessageBox::Icon icon = QMessageBox::NoIcon,
QMessageBox::StandardButtons buttons = QMessageBox::Ok,
QMessageBox::StandardButton defaultButton = QMessageBox::NoButton);
}

View File

@ -0,0 +1,61 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "EditAccountDialog.h"
#include "ui_EditAccountDialog.h"
#include <DesktopServices.h>
#include <QUrl>
EditAccountDialog::EditAccountDialog(const QString &text, QWidget *parent, int flags)
: QDialog(parent), ui(new Ui::EditAccountDialog)
{
ui->setupUi(this);
ui->label->setText(text);
ui->label->setVisible(!text.isEmpty());
ui->userTextBox->setEnabled(flags & UsernameField);
ui->passTextBox->setEnabled(flags & PasswordField);
}
EditAccountDialog::~EditAccountDialog()
{
delete ui;
}
void EditAccountDialog::on_label_linkActivated(const QString &link)
{
DesktopServices::openUrl(QUrl(link));
}
void EditAccountDialog::setUsername(const QString & user) const
{
ui->userTextBox->setText(user);
}
QString EditAccountDialog::username() const
{
return ui->userTextBox->text();
}
void EditAccountDialog::setPassword(const QString & pass) const
{
ui->passTextBox->setText(pass);
}
QString EditAccountDialog::password() const
{
return ui->passTextBox->text();
}

View File

@ -0,0 +1,56 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
namespace Ui
{
class EditAccountDialog;
}
class EditAccountDialog : public QDialog
{
Q_OBJECT
public:
explicit EditAccountDialog(const QString &text = "", QWidget *parent = 0,
int flags = UsernameField | PasswordField);
~EditAccountDialog();
void setUsername(const QString & user) const;
void setPassword(const QString & pass) const;
QString username() const;
QString password() const;
enum Flags
{
NoFlags = 0,
//! Specifies that the dialog should have a username field.
UsernameField,
//! Specifies that the dialog should have a password field.
PasswordField,
};
private slots:
void on_label_linkActivated(const QString &link);
private:
Ui::EditAccountDialog *ui;
};

View File

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>EditAccountDialog</class>
<widget class="QDialog" name="EditAccountDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>148</height>
</rect>
</property>
<property name="windowTitle">
<string>Login</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string notr="true">Message label placeholder.</string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="userTextBox">
<property name="placeholderText">
<string>Email</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="passTextBox">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
<property name="placeholderText">
<string>Password</string>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>EditAccountDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>EditAccountDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,482 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ExportInstanceDialog.h"
#include "ui_ExportInstanceDialog.h"
#include <BaseInstance.h>
#include <MMCZip.h>
#include <QFileDialog>
#include <QMessageBox>
#include <qfilesystemmodel.h>
#include <QSortFilterProxyModel>
#include <QDebug>
#include <qstack.h>
#include <QSaveFile>
#include "MMCStrings.h"
#include "SeparatorPrefixTree.h"
#include "Application.h"
#include <icons/IconList.h>
#include <FileSystem.h>
class PackIgnoreProxy : public QSortFilterProxyModel
{
Q_OBJECT
public:
PackIgnoreProxy(InstancePtr instance, QObject *parent) : QSortFilterProxyModel(parent)
{
m_instance = instance;
}
// NOTE: Sadly, we have to do sorting ourselves.
bool lessThan(const QModelIndex &left, const QModelIndex &right) const
{
QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());
if (!fsm)
{
return QSortFilterProxyModel::lessThan(left, right);
}
bool asc = sortOrder() == Qt::AscendingOrder ? true : false;
QFileInfo leftFileInfo = fsm->fileInfo(left);
QFileInfo rightFileInfo = fsm->fileInfo(right);
if (!leftFileInfo.isDir() && rightFileInfo.isDir())
{
return !asc;
}
if (leftFileInfo.isDir() && !rightFileInfo.isDir())
{
return asc;
}
// sort and proxy model breaks the original model...
if (sortColumn() == 0)
{
return Strings::naturalCompare(leftFileInfo.fileName(), rightFileInfo.fileName(),
Qt::CaseInsensitive) < 0;
}
if (sortColumn() == 1)
{
auto leftSize = leftFileInfo.size();
auto rightSize = rightFileInfo.size();
if ((leftSize == rightSize) || (leftFileInfo.isDir() && rightFileInfo.isDir()))
{
return Strings::naturalCompare(leftFileInfo.fileName(),
rightFileInfo.fileName(),
Qt::CaseInsensitive) < 0
? asc
: !asc;
}
return leftSize < rightSize;
}
return QSortFilterProxyModel::lessThan(left, right);
}
virtual Qt::ItemFlags flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
auto sourceIndex = mapToSource(index);
Qt::ItemFlags flags = sourceIndex.flags();
if (index.column() == 0)
{
flags |= Qt::ItemIsUserCheckable;
if (sourceIndex.model()->hasChildren(sourceIndex))
{
flags |= Qt::ItemIsTristate;
}
}
return flags;
}
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
{
QModelIndex sourceIndex = mapToSource(index);
if (index.column() == 0 && role == Qt::CheckStateRole)
{
QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());
auto blockedPath = relPath(fsm->filePath(sourceIndex));
auto cover = blocked.cover(blockedPath);
if (!cover.isNull())
{
return QVariant(Qt::Unchecked);
}
else if (blocked.exists(blockedPath))
{
return QVariant(Qt::PartiallyChecked);
}
else
{
return QVariant(Qt::Checked);
}
}
return sourceIndex.data(role);
}
virtual bool setData(const QModelIndex &index, const QVariant &value,
int role = Qt::EditRole)
{
if (index.column() == 0 && role == Qt::CheckStateRole)
{
Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
return setFilterState(index, state);
}
QModelIndex sourceIndex = mapToSource(index);
return QSortFilterProxyModel::sourceModel()->setData(sourceIndex, value, role);
}
QString relPath(const QString &path) const
{
QString prefix = QDir().absoluteFilePath(m_instance->instanceRoot());
prefix += '/';
if (!path.startsWith(prefix))
{
return QString();
}
return path.mid(prefix.size());
}
bool setFilterState(QModelIndex index, Qt::CheckState state)
{
QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());
if (!fsm)
{
return false;
}
QModelIndex sourceIndex = mapToSource(index);
auto blockedPath = relPath(fsm->filePath(sourceIndex));
bool changed = false;
if (state == Qt::Unchecked)
{
// blocking a path
auto &node = blocked.insert(blockedPath);
// get rid of all blocked nodes below
node.clear();
changed = true;
}
else if (state == Qt::Checked || state == Qt::PartiallyChecked)
{
if (!blocked.remove(blockedPath))
{
auto cover = blocked.cover(blockedPath);
qDebug() << "Blocked by cover" << cover;
// uncover
blocked.remove(cover);
// block all contents, except for any cover
QModelIndex rootIndex =
fsm->index(FS::PathCombine(m_instance->instanceRoot(), cover));
QModelIndex doing = rootIndex;
int row = 0;
QStack<QModelIndex> todo;
while (1)
{
auto node = doing.child(row, 0);
if (!node.isValid())
{
if (!todo.size())
{
break;
}
else
{
doing = todo.pop();
row = 0;
continue;
}
}
auto relpath = relPath(fsm->filePath(node));
if (blockedPath.startsWith(relpath)) // cover found?
{
// continue processing cover later
todo.push(node);
}
else
{
// or just block this one.
blocked.insert(relpath);
}
row++;
}
}
changed = true;
}
if (changed)
{
// update the thing
emit dataChanged(index, index, {Qt::CheckStateRole});
// update everything above index
QModelIndex up = index.parent();
while (1)
{
if (!up.isValid())
break;
emit dataChanged(up, up, {Qt::CheckStateRole});
up = up.parent();
}
// and everything below the index
QModelIndex doing = index;
int row = 0;
QStack<QModelIndex> todo;
while (1)
{
auto node = doing.child(row, 0);
if (!node.isValid())
{
if (!todo.size())
{
break;
}
else
{
doing = todo.pop();
row = 0;
continue;
}
}
emit dataChanged(node, node, {Qt::CheckStateRole});
todo.push(node);
row++;
}
// siblings and unrelated nodes are ignored
}
return true;
}
bool shouldExpand(QModelIndex index)
{
QModelIndex sourceIndex = mapToSource(index);
QFileSystemModel *fsm = qobject_cast<QFileSystemModel *>(sourceModel());
if (!fsm)
{
return false;
}
auto blockedPath = relPath(fsm->filePath(sourceIndex));
auto found = blocked.find(blockedPath);
if(found)
{
return !found->leaf();
}
return false;
}
void setBlockedPaths(QStringList paths)
{
beginResetModel();
blocked.clear();
blocked.insert(paths);
endResetModel();
}
const SeparatorPrefixTree<'/'> & blockedPaths() const
{
return blocked;
}
protected:
bool filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const
{
Q_UNUSED(source_parent)
// adjust the columns you want to filter out here
// return false for those that will be hidden
if (source_column == 2 || source_column == 3)
return false;
return true;
}
private:
InstancePtr m_instance;
SeparatorPrefixTree<'/'> blocked;
};
ExportInstanceDialog::ExportInstanceDialog(InstancePtr instance, QWidget *parent)
: QDialog(parent), ui(new Ui::ExportInstanceDialog), m_instance(instance)
{
ui->setupUi(this);
auto model = new QFileSystemModel(this);
proxyModel = new PackIgnoreProxy(m_instance, this);
loadPackIgnore();
proxyModel->setSourceModel(model);
auto root = instance->instanceRoot();
ui->treeView->setModel(proxyModel);
ui->treeView->setRootIndex(proxyModel->mapFromSource(model->index(root)));
ui->treeView->sortByColumn(0, Qt::AscendingOrder);
connect(proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(rowsInserted(QModelIndex,int,int)));
model->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Hidden);
model->setRootPath(root);
auto headerView = ui->treeView->header();
headerView->setSectionResizeMode(QHeaderView::ResizeToContents);
headerView->setSectionResizeMode(0, QHeaderView::Stretch);
}
ExportInstanceDialog::~ExportInstanceDialog()
{
delete ui;
}
/// Save icon to instance's folder is needed
void SaveIcon(InstancePtr m_instance)
{
auto iconKey = m_instance->iconKey();
auto iconList = APPLICATION->icons();
auto mmcIcon = iconList->icon(iconKey);
if(!mmcIcon || mmcIcon->isBuiltIn()) {
return;
}
auto path = mmcIcon->getFilePath();
if(!path.isNull()) {
QFileInfo inInfo (path);
FS::copy(path, FS::PathCombine(m_instance->instanceRoot(), inInfo.fileName())) ();
return;
}
auto & image = mmcIcon->m_images[mmcIcon->type()];
auto & icon = image.icon;
auto sizes = icon.availableSizes();
if(sizes.size() == 0)
{
return;
}
auto areaOf = [](QSize size)
{
return size.width() * size.height();
};
QSize largest = sizes[0];
// find variant with largest area
for(auto size: sizes)
{
if(areaOf(largest) < areaOf(size))
{
largest = size;
}
}
auto pixmap = icon.pixmap(largest);
pixmap.save(FS::PathCombine(m_instance->instanceRoot(), iconKey + ".png"));
}
bool ExportInstanceDialog::doExport()
{
auto name = FS::RemoveInvalidFilenameChars(m_instance->name());
const QString output = QFileDialog::getSaveFileName(
this, tr("Export %1").arg(m_instance->name()),
FS::PathCombine(QDir::homePath(), name + ".zip"), "Zip (*.zip)", nullptr, QFileDialog::DontConfirmOverwrite);
if (output.isEmpty())
{
return false;
}
if (QFile::exists(output))
{
int ret =
QMessageBox::question(this, tr("Overwrite?"),
tr("This file already exists. Do you want to overwrite it?"),
QMessageBox::No, QMessageBox::Yes);
if (ret == QMessageBox::No)
{
return false;
}
}
SaveIcon(m_instance);
auto & blocked = proxyModel->blockedPaths();
using std::placeholders::_1;
if (!JlCompress::compressDir(output, m_instance->instanceRoot(), name, std::bind(&SeparatorPrefixTree<'/'>::covers, blocked, _1)))
{
QMessageBox::warning(this, tr("Error"), tr("Unable to export instance"));
return false;
}
return true;
}
void ExportInstanceDialog::done(int result)
{
savePackIgnore();
if (result == QDialog::Accepted)
{
if (doExport())
{
QDialog::done(QDialog::Accepted);
return;
}
else
{
return;
}
}
QDialog::done(result);
}
void ExportInstanceDialog::rowsInserted(QModelIndex parent, int top, int bottom)
{
//WARNING: possible off-by-one?
for(int i = top; i < bottom; i++)
{
auto node = parent.child(i, 0);
if(proxyModel->shouldExpand(node))
{
auto expNode = node.parent();
if(!expNode.isValid())
{
continue;
}
ui->treeView->expand(node);
}
}
}
QString ExportInstanceDialog::ignoreFileName()
{
return FS::PathCombine(m_instance->instanceRoot(), ".packignore");
}
void ExportInstanceDialog::loadPackIgnore()
{
auto filename = ignoreFileName();
QFile ignoreFile(filename);
if(!ignoreFile.open(QIODevice::ReadOnly))
{
return;
}
auto data = ignoreFile.readAll();
auto string = QString::fromUtf8(data);
proxyModel->setBlockedPaths(string.split('\n', QString::SkipEmptyParts));
}
void ExportInstanceDialog::savePackIgnore()
{
auto data = proxyModel->blockedPaths().toStringList().join('\n').toUtf8();
auto filename = ignoreFileName();
try
{
FS::write(filename, data);
}
catch (const Exception &e)
{
qWarning() << e.cause();
}
}
#include "ExportInstanceDialog.moc"

View File

@ -0,0 +1,54 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <QModelIndex>
#include <memory>
class BaseInstance;
class PackIgnoreProxy;
typedef std::shared_ptr<BaseInstance> InstancePtr;
namespace Ui
{
class ExportInstanceDialog;
}
class ExportInstanceDialog : public QDialog
{
Q_OBJECT
public:
explicit ExportInstanceDialog(InstancePtr instance, QWidget *parent = 0);
~ExportInstanceDialog();
virtual void done(int result);
private:
bool doExport();
void loadPackIgnore();
void savePackIgnore();
QString ignoreFileName();
private:
Ui::ExportInstanceDialog *ui;
InstancePtr m_instance;
PackIgnoreProxy * proxyModel;
private slots:
void rowsInserted(QModelIndex parent, int top, int bottom);
};

View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExportInstanceDialog</class>
<widget class="QDialog" name="ExportInstanceDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>720</width>
<height>625</height>
</rect>
</property>
<property name="windowTitle">
<string>Export Instance</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeView" name="treeView">
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
</attribute>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>treeView</tabstop>
</tabstops>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ExportInstanceDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ExportInstanceDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,163 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <QKeyEvent>
#include <QPushButton>
#include <QFileDialog>
#include "Application.h"
#include "IconPickerDialog.h"
#include "ui_IconPickerDialog.h"
#include "ui/instanceview/InstanceDelegate.h"
#include "icons/IconList.h"
#include "icons/IconUtils.h"
#include <DesktopServices.h>
IconPickerDialog::IconPickerDialog(QWidget *parent)
: QDialog(parent), ui(new Ui::IconPickerDialog)
{
ui->setupUi(this);
setWindowModality(Qt::WindowModal);
auto contentsWidget = ui->iconView;
contentsWidget->setViewMode(QListView::IconMode);
contentsWidget->setFlow(QListView::LeftToRight);
contentsWidget->setIconSize(QSize(48, 48));
contentsWidget->setMovement(QListView::Static);
contentsWidget->setResizeMode(QListView::Adjust);
contentsWidget->setSelectionMode(QAbstractItemView::SingleSelection);
contentsWidget->setSpacing(5);
contentsWidget->setWordWrap(false);
contentsWidget->setWrapping(true);
contentsWidget->setUniformItemSizes(true);
contentsWidget->setTextElideMode(Qt::ElideRight);
contentsWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
contentsWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
contentsWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
contentsWidget->setItemDelegate(new ListViewDelegate());
// contentsWidget->setAcceptDrops(true);
contentsWidget->setDropIndicatorShown(true);
contentsWidget->viewport()->setAcceptDrops(true);
contentsWidget->setDragDropMode(QAbstractItemView::DropOnly);
contentsWidget->setDefaultDropAction(Qt::CopyAction);
contentsWidget->installEventFilter(this);
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);
auto buttonRemove = ui->buttonBox->addButton(tr("Remove Icon"), QDialogButtonBox::ResetRole);
connect(buttonAdd, SIGNAL(clicked(bool)), SLOT(addNewIcon()));
connect(buttonRemove, SIGNAL(clicked(bool)), SLOT(removeSelectedIcon()));
connect(contentsWidget, SIGNAL(doubleClicked(QModelIndex)), SLOT(activated(QModelIndex)));
connect(contentsWidget->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SLOT(selectionChanged(QItemSelection, QItemSelection)));
auto buttonFolder = ui->buttonBox->addButton(tr("Open Folder"), QDialogButtonBox::ResetRole);
connect(buttonFolder, &QPushButton::clicked, this, &IconPickerDialog::openFolder);
}
bool IconPickerDialog::eventFilter(QObject *obj, QEvent *evt)
{
if (obj != ui->iconView)
return QDialog::eventFilter(obj, evt);
if (evt->type() != QEvent::KeyPress)
{
return QDialog::eventFilter(obj, evt);
}
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(evt);
switch (keyEvent->key())
{
case Qt::Key_Delete:
removeSelectedIcon();
return true;
case Qt::Key_Plus:
addNewIcon();
return true;
default:
break;
}
return QDialog::eventFilter(obj, evt);
}
void IconPickerDialog::addNewIcon()
{
//: The title of the select icons open file dialog
QString selectIcons = tr("Select Icons");
//: The type of icon files
auto filter = IconUtils::getIconFilter();
QStringList fileNames = QFileDialog::getOpenFileNames(this, selectIcons, QString(), tr("Icons %1").arg(filter));
APPLICATION->icons()->installIcons(fileNames);
}
void IconPickerDialog::removeSelectedIcon()
{
APPLICATION->icons()->deleteIcon(selectedIconKey);
}
void IconPickerDialog::activated(QModelIndex index)
{
selectedIconKey = index.data(Qt::UserRole).toString();
accept();
}
void IconPickerDialog::selectionChanged(QItemSelection selected, QItemSelection deselected)
{
if (selected.empty())
return;
QString key = selected.first().indexes().first().data(Qt::UserRole).toString();
if (!key.isEmpty()) {
selectedIconKey = key;
}
}
int IconPickerDialog::execWithSelection(QString selection)
{
auto list = APPLICATION->icons();
auto contentsWidget = ui->iconView;
selectedIconKey = selection;
int index_nr = list->getIconIndex(selection);
auto model_index = list->index(index_nr);
contentsWidget->selectionModel()->select(
model_index, QItemSelectionModel::Current | QItemSelectionModel::Select);
QMetaObject::invokeMethod(this, "delayed_scroll", Qt::QueuedConnection, Q_ARG(QModelIndex, model_index));
return QDialog::exec();
}
void IconPickerDialog::delayed_scroll(QModelIndex model_index)
{
auto contentsWidget = ui->iconView;
contentsWidget->scrollTo(model_index);
}
IconPickerDialog::~IconPickerDialog()
{
delete ui;
}
void IconPickerDialog::openFolder()
{
DesktopServices::openDirectory(APPLICATION->icons()->getDirectory(), true);
}

View File

@ -0,0 +1,49 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <QItemSelection>
namespace Ui
{
class IconPickerDialog;
}
class IconPickerDialog : public QDialog
{
Q_OBJECT
public:
explicit IconPickerDialog(QWidget *parent = 0);
~IconPickerDialog();
int execWithSelection(QString selection);
QString selectedIconKey;
protected:
virtual bool eventFilter(QObject *, QEvent *);
private:
Ui::IconPickerDialog *ui;
private
slots:
void selectionChanged(QItemSelection, QItemSelection);
void activated(QModelIndex);
void delayed_scroll(QModelIndex);
void addNewIcon();
void removeSelectedIcon();
void openFolder();
};

View File

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>IconPickerDialog</class>
<widget class="QDialog" name="IconPickerDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>676</width>
<height>555</height>
</rect>
</property>
<property name="windowTitle">
<string>Pick icon</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListView" name="iconView"/>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>IconPickerDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>IconPickerDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,119 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "LoginDialog.h"
#include "ui_LoginDialog.h"
#include "minecraft/auth/AccountTask.h"
#include <QtWidgets/QPushButton>
LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LoginDialog)
{
ui->setupUi(this);
ui->progressBar->setVisible(false);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
LoginDialog::~LoginDialog()
{
delete ui;
}
// Stage 1: User interaction
void LoginDialog::accept()
{
setUserInputsEnabled(false);
ui->progressBar->setVisible(true);
// Setup the login task and start it
m_account = MinecraftAccount::createFromUsername(ui->userTextBox->text());
m_loginTask = m_account->login(nullptr, ui->passTextBox->text());
connect(m_loginTask.get(), &Task::failed, this, &LoginDialog::onTaskFailed);
connect(m_loginTask.get(), &Task::succeeded, this, &LoginDialog::onTaskSucceeded);
connect(m_loginTask.get(), &Task::status, this, &LoginDialog::onTaskStatus);
connect(m_loginTask.get(), &Task::progress, this, &LoginDialog::onTaskProgress);
m_loginTask->start();
}
void LoginDialog::setUserInputsEnabled(bool enable)
{
ui->userTextBox->setEnabled(enable);
ui->passTextBox->setEnabled(enable);
ui->buttonBox->setEnabled(enable);
}
// Enable the OK button only when both textboxes contain something.
void LoginDialog::on_userTextBox_textEdited(const QString &newText)
{
ui->buttonBox->button(QDialogButtonBox::Ok)
->setEnabled(!newText.isEmpty() && !ui->passTextBox->text().isEmpty());
}
void LoginDialog::on_passTextBox_textEdited(const QString &newText)
{
ui->buttonBox->button(QDialogButtonBox::Ok)
->setEnabled(!newText.isEmpty() && !ui->userTextBox->text().isEmpty());
}
void LoginDialog::onTaskFailed(const QString &reason)
{
// Set message
auto lines = reason.split('\n');
QString processed;
for(auto line: lines) {
if(line.size()) {
processed += "<font color='red'>" + line + "</font><br />";
}
else {
processed += "<br />";
}
}
ui->label->setText(processed);
// Re-enable user-interaction
setUserInputsEnabled(true);
ui->progressBar->setVisible(false);
}
void LoginDialog::onTaskSucceeded()
{
QDialog::accept();
}
void LoginDialog::onTaskStatus(const QString &status)
{
ui->label->setText(status);
}
void LoginDialog::onTaskProgress(qint64 current, qint64 total)
{
ui->progressBar->setMaximum(total);
ui->progressBar->setValue(current);
}
// Public interface
MinecraftAccountPtr LoginDialog::newAccount(QWidget *parent, QString msg)
{
LoginDialog dlg(parent);
dlg.ui->label->setText(msg);
if (dlg.exec() == QDialog::Accepted)
{
return dlg.m_account;
}
return 0;
}

View File

@ -0,0 +1,59 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QtWidgets/QDialog>
#include <QtCore/QEventLoop>
#include "minecraft/auth/MinecraftAccount.h"
#include "tasks/Task.h"
namespace Ui
{
class LoginDialog;
}
class LoginDialog : public QDialog
{
Q_OBJECT
public:
~LoginDialog();
static MinecraftAccountPtr newAccount(QWidget *parent, QString message);
private:
explicit LoginDialog(QWidget *parent = 0);
void setUserInputsEnabled(bool enable);
protected
slots:
void accept();
void onTaskFailed(const QString &reason);
void onTaskSucceeded();
void onTaskStatus(const QString &status);
void onTaskProgress(qint64 current, qint64 total);
void on_userTextBox_textEdited(const QString &newText);
void on_passTextBox_textEdited(const QString &newText);
private:
Ui::LoginDialog *ui;
MinecraftAccountPtr m_account;
Task::Ptr m_loginTask;
};

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LoginDialog</class>
<widget class="QDialog" name="LoginDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>421</width>
<height>198</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Add Account</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string notr="true">Message label placeholder.</string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="userTextBox">
<property name="placeholderText">
<string>Email</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="passTextBox">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
<property name="placeholderText">
<string>Password</string>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="progressBar">
<property name="value">
<number>24</number>
</property>
<property name="textVisible">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,141 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MSALoginDialog.h"
#include "ui_MSALoginDialog.h"
#include "minecraft/auth/AccountTask.h"
#include <QtWidgets/QPushButton>
#include <QUrl>
MSALoginDialog::MSALoginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MSALoginDialog)
{
ui->setupUi(this);
ui->progressBar->setVisible(false);
// ui->buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false);
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
int MSALoginDialog::exec() {
setUserInputsEnabled(false);
ui->progressBar->setVisible(true);
// Setup the login task and start it
m_account = MinecraftAccount::createBlankMSA();
m_loginTask = m_account->loginMSA(nullptr);
connect(m_loginTask.get(), &Task::failed, this, &MSALoginDialog::onTaskFailed);
connect(m_loginTask.get(), &Task::succeeded, this, &MSALoginDialog::onTaskSucceeded);
connect(m_loginTask.get(), &Task::status, this, &MSALoginDialog::onTaskStatus);
connect(m_loginTask.get(), &Task::progress, this, &MSALoginDialog::onTaskProgress);
connect(m_loginTask.get(), &AccountTask::showVerificationUriAndCode, this, &MSALoginDialog::showVerificationUriAndCode);
connect(m_loginTask.get(), &AccountTask::hideVerificationUriAndCode, this, &MSALoginDialog::hideVerificationUriAndCode);
connect(&m_externalLoginTimer, &QTimer::timeout, this, &MSALoginDialog::externalLoginTick);
m_loginTask->start();
return QDialog::exec();
}
MSALoginDialog::~MSALoginDialog()
{
delete ui;
}
void MSALoginDialog::externalLoginTick() {
m_externalLoginElapsed++;
ui->progressBar->setValue(m_externalLoginElapsed);
ui->progressBar->repaint();
if(m_externalLoginElapsed >= m_externalLoginTimeout) {
m_externalLoginTimer.stop();
}
}
void MSALoginDialog::showVerificationUriAndCode(const QUrl& uri, const QString& code, int expiresIn) {
m_externalLoginElapsed = 0;
m_externalLoginTimeout = expiresIn;
m_externalLoginTimer.setInterval(1000);
m_externalLoginTimer.setSingleShot(false);
m_externalLoginTimer.start();
ui->progressBar->setMaximum(expiresIn);
ui->progressBar->setValue(m_externalLoginElapsed);
QString urlString = uri.toString();
QString linkString = QString("<a href=\"%1\">%2</a>").arg(urlString, urlString);
ui->label->setText(tr("<p>Please open up %1 in a browser and put in the code <b>%2</b> to proceed with login.</p>").arg(linkString, code));
}
void MSALoginDialog::hideVerificationUriAndCode() {
m_externalLoginTimer.stop();
}
void MSALoginDialog::setUserInputsEnabled(bool enable)
{
ui->buttonBox->setEnabled(enable);
}
void MSALoginDialog::onTaskFailed(const QString &reason)
{
// Set message
auto lines = reason.split('\n');
QString processed;
for(auto line: lines) {
if(line.size()) {
processed += "<font color='red'>" + line + "</font><br />";
}
else {
processed += "<br />";
}
}
ui->label->setText(processed);
// Re-enable user-interaction
setUserInputsEnabled(true);
ui->progressBar->setVisible(false);
}
void MSALoginDialog::onTaskSucceeded()
{
QDialog::accept();
}
void MSALoginDialog::onTaskStatus(const QString &status)
{
ui->label->setText(status);
}
void MSALoginDialog::onTaskProgress(qint64 current, qint64 total)
{
ui->progressBar->setMaximum(total);
ui->progressBar->setValue(current);
}
// Public interface
MinecraftAccountPtr MSALoginDialog::newAccount(QWidget *parent, QString msg)
{
MSALoginDialog dlg(parent);
dlg.ui->label->setText(msg);
if (dlg.exec() == QDialog::Accepted)
{
return dlg.m_account;
}
return 0;
}

View File

@ -0,0 +1,63 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QtWidgets/QDialog>
#include <QtCore/QEventLoop>
#include <QTimer>
#include "minecraft/auth/MinecraftAccount.h"
namespace Ui
{
class MSALoginDialog;
}
class MSALoginDialog : public QDialog
{
Q_OBJECT
public:
~MSALoginDialog();
static MinecraftAccountPtr newAccount(QWidget *parent, QString message);
int exec() override;
private:
explicit MSALoginDialog(QWidget *parent = 0);
void setUserInputsEnabled(bool enable);
protected
slots:
void onTaskFailed(const QString &reason);
void onTaskSucceeded();
void onTaskStatus(const QString &status);
void onTaskProgress(qint64 current, qint64 total);
void showVerificationUriAndCode(const QUrl &uri, const QString &code, int expiresIn);
void hideVerificationUriAndCode();
void externalLoginTick();
private:
Ui::MSALoginDialog *ui;
MinecraftAccountPtr m_account;
shared_qobject_ptr<AccountTask> m_loginTask;
QTimer m_externalLoginTimer;
int m_externalLoginElapsed = 0;
int m_externalLoginTimeout = 0;
};

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MSALoginDialog</class>
<widget class="QDialog" name="MSALoginDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>491</width>
<height>143</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Add Microsoft Account</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string notr="true">Message label placeholder.
aaaaa</string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="progressBar">
<property name="value">
<number>24</number>
</property>
<property name="textVisible">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,106 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Application.h"
#include "NewComponentDialog.h"
#include "ui_NewComponentDialog.h"
#include <BaseVersion.h>
#include <icons/IconList.h>
#include <tasks/Task.h>
#include <InstanceList.h>
#include "VersionSelectDialog.h"
#include "ProgressDialog.h"
#include "IconPickerDialog.h"
#include <QLayout>
#include <QPushButton>
#include <QFileDialog>
#include <QValidator>
#include <meta/Index.h>
#include <meta/VersionList.h>
NewComponentDialog::NewComponentDialog(const QString & initialName, const QString & initialUid, QWidget *parent)
: QDialog(parent), ui(new Ui::NewComponentDialog)
{
ui->setupUi(this);
resize(minimumSizeHint());
ui->nameTextBox->setText(initialName);
ui->uidTextBox->setText(initialUid);
connect(ui->nameTextBox, &QLineEdit::textChanged, this, &NewComponentDialog::updateDialogState);
connect(ui->uidTextBox, &QLineEdit::textChanged, this, &NewComponentDialog::updateDialogState);
auto groups = APPLICATION->instances()->getGroups().toSet();
ui->nameTextBox->setFocus();
originalPlaceholderText = ui->uidTextBox->placeholderText();
updateDialogState();
}
NewComponentDialog::~NewComponentDialog()
{
delete ui;
}
void NewComponentDialog::updateDialogState()
{
auto protoUid = ui->nameTextBox->text().toLower();
protoUid.remove(QRegularExpression("[^a-z]"));
if(protoUid.isEmpty())
{
ui->uidTextBox->setPlaceholderText(originalPlaceholderText);
}
else
{
QString suggestedUid = "org.multimc.custom." + protoUid;
ui->uidTextBox->setPlaceholderText(suggestedUid);
}
bool allowOK = !name().isEmpty() && !uid().isEmpty() && !uidBlacklist.contains(uid());
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(allowOK);
}
QString NewComponentDialog::name() const
{
auto result = ui->nameTextBox->text();
if(result.size())
{
return result.trimmed();
}
return QString();
}
QString NewComponentDialog::uid() const
{
auto result = ui->uidTextBox->text();
if(result.size())
{
return result.trimmed();
}
result = ui->uidTextBox->placeholderText();
if(result.size() && result != originalPlaceholderText)
{
return result.trimmed();
}
return QString();
}
void NewComponentDialog::setBlacklist(QStringList badUids)
{
uidBlacklist = badUids;
}

View File

@ -0,0 +1,48 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <QString>
#include <QStringList>
namespace Ui
{
class NewComponentDialog;
}
class NewComponentDialog : public QDialog
{
Q_OBJECT
public:
explicit NewComponentDialog(const QString & initialName = QString(), const QString & initialUid = QString(), QWidget *parent = 0);
virtual ~NewComponentDialog();
void setBlacklist(QStringList badUids);
QString name() const;
QString uid() const;
private slots:
void updateDialogState();
private:
Ui::NewComponentDialog *ui;
QString originalPlaceholderText;
QStringList uidBlacklist;
};

View File

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>NewComponentDialog</class>
<widget class="QDialog" name="NewComponentDialog">
<property name="windowModality">
<enum>Qt::ApplicationModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>345</width>
<height>146</height>
</rect>
</property>
<property name="windowTitle">
<string>Add Empty Component</string>
</property>
<property name="windowIcon">
<iconset>
<normaloff>:/icons/toolbar/copy</normaloff>:/icons/toolbar/copy</iconset>
</property>
<property name="modal">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLineEdit" name="nameTextBox">
<property name="placeholderText">
<string>Name</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="uidTextBox">
<property name="placeholderText">
<string>uid</string>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>nameTextBox</tabstop>
<tabstop>uidTextBox</tabstop>
</tabstops>
<resources>
<include location="../../graphics.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>NewComponentDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>NewComponentDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,255 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Application.h"
#include "NewInstanceDialog.h"
#include "ui_NewInstanceDialog.h"
#include <BaseVersion.h>
#include <icons/IconList.h>
#include <tasks/Task.h>
#include <InstanceList.h>
#include "VersionSelectDialog.h"
#include "ProgressDialog.h"
#include "IconPickerDialog.h"
#include <QLayout>
#include <QPushButton>
#include <QFileDialog>
#include <QValidator>
#include <QDialogButtonBox>
#include "ui/widgets/PageContainer.h"
#include "ui/pages/modplatform/VanillaPage.h"
#include "ui/pages/modplatform/atlauncher/AtlPage.h"
#include "ui/pages/modplatform/ftb/FtbPage.h"
#include "ui/pages/modplatform/legacy_ftb/Page.h"
#include "ui/pages/modplatform/flame/FlamePage.h"
#include "ui/pages/modplatform/ImportPage.h"
#include "ui/pages/modplatform/technic/TechnicPage.h"
NewInstanceDialog::NewInstanceDialog(const QString & initialGroup, const QString & url, QWidget *parent)
: QDialog(parent), ui(new Ui::NewInstanceDialog)
{
ui->setupUi(this);
setWindowIcon(APPLICATION->getThemedIcon("new"));
InstIconKey = "default";
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
auto groups = APPLICATION->instances()->getGroups().toSet();
auto groupList = QStringList(groups.toList());
groupList.sort(Qt::CaseInsensitive);
groupList.removeOne("");
groupList.push_front(initialGroup);
groupList.push_front("");
ui->groupBox->addItems(groupList);
int index = groupList.indexOf(initialGroup);
if(index == -1)
{
index = 0;
}
ui->groupBox->setCurrentIndex(index);
ui->groupBox->lineEdit()->setPlaceholderText(tr("No group"));
// NOTE: m_buttons must be initialized before PageContainer, because it indirectly accesses m_buttons through setSuggestedPack! Do not move this below.
m_buttons = new QDialogButtonBox(QDialogButtonBox::Help | QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
m_container = new PageContainer(this);
m_container->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Expanding);
m_container->layout()->setContentsMargins(0, 0, 0, 0);
ui->verticalLayout->insertWidget(2, m_container);
m_container->addButtons(m_buttons);
// Bonk Qt over its stupid head and make sure it understands which button is the default one...
// See: https://stackoverflow.com/questions/24556831/qbuttonbox-set-default-button
auto OkButton = m_buttons->button(QDialogButtonBox::Ok);
OkButton->setDefault(true);
OkButton->setAutoDefault(true);
connect(OkButton, &QPushButton::clicked, this, &NewInstanceDialog::accept);
auto CancelButton = m_buttons->button(QDialogButtonBox::Cancel);
CancelButton->setDefault(false);
CancelButton->setAutoDefault(false);
connect(CancelButton, &QPushButton::clicked, this, &NewInstanceDialog::reject);
auto HelpButton = m_buttons->button(QDialogButtonBox::Help);
HelpButton->setDefault(false);
HelpButton->setAutoDefault(false);
connect(HelpButton, &QPushButton::clicked, m_container, &PageContainer::help);
if(!url.isEmpty())
{
QUrl actualUrl(url);
m_container->selectPage("import");
importPage->setUrl(url);
}
updateDialogState();
restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("NewInstanceGeometry").toByteArray()));
}
void NewInstanceDialog::reject()
{
APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
QDialog::reject();
}
void NewInstanceDialog::accept()
{
APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
importIconNow();
QDialog::accept();
}
QList<BasePage *> NewInstanceDialog::getPages()
{
importPage = new ImportPage(this);
flamePage = new FlamePage(this);
auto technicPage = new TechnicPage(this);
return
{
new VanillaPage(this),
importPage,
new AtlPage(this),
flamePage,
new FtbPage(this),
new LegacyFTB::Page(this),
technicPage
};
}
QString NewInstanceDialog::dialogTitle()
{
return tr("New Instance");
}
NewInstanceDialog::~NewInstanceDialog()
{
delete ui;
}
void NewInstanceDialog::setSuggestedPack(const QString& name, InstanceTask* task)
{
creationTask.reset(task);
ui->instNameTextBox->setPlaceholderText(name);
if(!task)
{
ui->iconButton->setIcon(APPLICATION->icons()->getIcon("default"));
importIcon = false;
}
auto allowOK = task && !instName().isEmpty();
m_buttons->button(QDialogButtonBox::Ok)->setEnabled(allowOK);
}
void NewInstanceDialog::setSuggestedIconFromFile(const QString &path, const QString &name)
{
importIcon = true;
importIconPath = path;
importIconName = name;
//Hmm, for some reason they can be to small
ui->iconButton->setIcon(QIcon(path));
}
void NewInstanceDialog::setSuggestedIcon(const QString &key)
{
auto icon = APPLICATION->icons()->getIcon(key);
importIcon = false;
ui->iconButton->setIcon(icon);
}
InstanceTask * NewInstanceDialog::extractTask()
{
InstanceTask * extracted = creationTask.get();
creationTask.release();
extracted->setName(instName());
extracted->setGroup(instGroup());
extracted->setIcon(iconKey());
return extracted;
}
void NewInstanceDialog::updateDialogState()
{
auto allowOK = creationTask && !instName().isEmpty();
auto OkButton = m_buttons->button(QDialogButtonBox::Ok);
if(OkButton->isEnabled() != allowOK)
{
OkButton->setEnabled(allowOK);
}
}
QString NewInstanceDialog::instName() const
{
auto result = ui->instNameTextBox->text().trimmed();
if(result.size())
{
return result;
}
result = ui->instNameTextBox->placeholderText().trimmed();
if(result.size())
{
return result;
}
return QString();
}
QString NewInstanceDialog::instGroup() const
{
return ui->groupBox->currentText();
}
QString NewInstanceDialog::iconKey() const
{
return InstIconKey;
}
void NewInstanceDialog::on_iconButton_clicked()
{
importIconNow(); //so the user can switch back
IconPickerDialog dlg(this);
dlg.execWithSelection(InstIconKey);
if (dlg.result() == QDialog::Accepted)
{
InstIconKey = dlg.selectedIconKey;
ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey));
importIcon = false;
}
}
void NewInstanceDialog::on_instNameTextBox_textChanged(const QString &arg1)
{
updateDialogState();
}
void NewInstanceDialog::importIconNow()
{
if(importIcon) {
APPLICATION->icons()->installIcon(importIconPath, importIconName);
InstIconKey = importIconName;
importIcon = false;
}
APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64());
}

View File

@ -0,0 +1,80 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include "BaseVersion.h"
#include "ui/pages/BasePageProvider.h"
#include "InstanceTask.h"
namespace Ui
{
class NewInstanceDialog;
}
class PageContainer;
class QDialogButtonBox;
class ImportPage;
class FlamePage;
class NewInstanceDialog : public QDialog, public BasePageProvider
{
Q_OBJECT
public:
explicit NewInstanceDialog(const QString & initialGroup, const QString & url = QString(), QWidget *parent = 0);
~NewInstanceDialog();
void updateDialogState();
void setSuggestedPack(const QString & name = QString(), InstanceTask * task = nullptr);
void setSuggestedIconFromFile(const QString &path, const QString &name);
void setSuggestedIcon(const QString &key);
InstanceTask * extractTask();
QString dialogTitle() override;
QList<BasePage *> getPages() override;
QString instName() const;
QString instGroup() const;
QString iconKey() const;
public slots:
void accept() override;
void reject() override;
private slots:
void on_iconButton_clicked();
void on_instNameTextBox_textChanged(const QString &arg1);
private:
Ui::NewInstanceDialog *ui = nullptr;
PageContainer * m_container = nullptr;
QDialogButtonBox * m_buttons = nullptr;
QString InstIconKey;
ImportPage *importPage = nullptr;
FlamePage *flamePage = nullptr;
std::unique_ptr<InstanceTask> creationTask;
bool importIcon = false;
QString importIconPath;
QString importIconName;
void importIconNow();
};

View File

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>NewInstanceDialog</class>
<widget class="QDialog" name="NewInstanceDialog">
<property name="windowModality">
<enum>Qt::ApplicationModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>730</width>
<height>127</height>
</rect>
</property>
<property name="windowTitle">
<string>New Instance</string>
</property>
<property name="windowIcon">
<iconset>
<normaloff>:/icons/toolbar/new</normaloff>:/icons/toolbar/new</iconset>
</property>
<property name="modal">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QGridLayout" name="gridLayout_2">
<item row="1" column="2">
<widget class="QComboBox" name="groupBox">
<property name="editable">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="groupLabel">
<property name="text">
<string>&amp;Group:</string>
</property>
<property name="buddy">
<cstring>groupBox</cstring>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QLineEdit" name="instNameTextBox"/>
</item>
<item row="0" column="1">
<widget class="QLabel" name="nameLabel">
<property name="text">
<string>&amp;Name:</string>
</property>
<property name="buddy">
<cstring>instNameTextBox</cstring>
</property>
</widget>
</item>
<item row="0" column="0" rowspan="2">
<widget class="QToolButton" name="iconButton">
<property name="iconSize">
<size>
<width>80</width>
<height>80</height>
</size>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>iconButton</tabstop>
<tabstop>instNameTextBox</tabstop>
<tabstop>groupBox</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,86 @@
#include "NotificationDialog.h"
#include "ui_NotificationDialog.h"
#include <QTimerEvent>
#include <QStyle>
NotificationDialog::NotificationDialog(const NotificationChecker::NotificationEntry &entry, QWidget *parent) :
QDialog(parent, Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::CustomizeWindowHint),
ui(new Ui::NotificationDialog)
{
ui->setupUi(this);
QStyle::StandardPixmap icon;
switch (entry.type)
{
case NotificationChecker::NotificationEntry::Critical:
icon = QStyle::SP_MessageBoxCritical;
break;
case NotificationChecker::NotificationEntry::Warning:
icon = QStyle::SP_MessageBoxWarning;
break;
default:
case NotificationChecker::NotificationEntry::Information:
icon = QStyle::SP_MessageBoxInformation;
break;
}
ui->iconLabel->setPixmap(style()->standardPixmap(icon, 0, this));
ui->messageLabel->setText(entry.message);
m_dontShowAgainText = tr("Don't show again");
m_closeText = tr("Close");
ui->dontShowAgainBtn->setText(m_dontShowAgainText + QString(" (%1)").arg(m_dontShowAgainTime));
ui->closeBtn->setText(m_closeText + QString(" (%1)").arg(m_closeTime));
startTimer(1000);
}
NotificationDialog::~NotificationDialog()
{
delete ui;
}
void NotificationDialog::timerEvent(QTimerEvent *event)
{
if (m_dontShowAgainTime > 0)
{
m_dontShowAgainTime--;
if (m_dontShowAgainTime == 0)
{
ui->dontShowAgainBtn->setText(m_dontShowAgainText);
ui->dontShowAgainBtn->setEnabled(true);
}
else
{
ui->dontShowAgainBtn->setText(m_dontShowAgainText + QString(" (%1)").arg(m_dontShowAgainTime));
}
}
if (m_closeTime > 0)
{
m_closeTime--;
if (m_closeTime == 0)
{
ui->closeBtn->setText(m_closeText);
ui->closeBtn->setEnabled(true);
}
else
{
ui->closeBtn->setText(m_closeText + QString(" (%1)").arg(m_closeTime));
}
}
if (m_closeTime == 0 && m_dontShowAgainTime == 0)
{
killTimer(event->timerId());
}
}
void NotificationDialog::on_dontShowAgainBtn_clicked()
{
done(DontShowAgain);
}
void NotificationDialog::on_closeBtn_clicked()
{
done(Normal);
}

View File

@ -0,0 +1,44 @@
#ifndef NOTIFICATIONDIALOG_H
#define NOTIFICATIONDIALOG_H
#include <QDialog>
#include "notifications/NotificationChecker.h"
namespace Ui {
class NotificationDialog;
}
class NotificationDialog : public QDialog
{
Q_OBJECT
public:
explicit NotificationDialog(const NotificationChecker::NotificationEntry &entry, QWidget *parent = 0);
~NotificationDialog();
enum ExitCode
{
Normal,
DontShowAgain
};
protected:
void timerEvent(QTimerEvent *event);
private:
Ui::NotificationDialog *ui;
int m_dontShowAgainTime = 10;
int m_closeTime = 5;
QString m_dontShowAgainText;
QString m_closeText;
private
slots:
void on_dontShowAgainBtn_clicked();
void on_closeBtn_clicked();
};
#endif // NOTIFICATIONDIALOG_H

View File

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>NotificationDialog</class>
<widget class="QDialog" name="NotificationDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>320</width>
<height>240</height>
</rect>
</property>
<property name="windowTitle">
<string>Notification</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout" stretch="1,0">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,1">
<item>
<widget class="QLabel" name="iconLabel">
<property name="text">
<string notr="true">TextLabel</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="messageLabel">
<property name="text">
<string notr="true">TextLabel</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::TextBrowserInteraction</set>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="dontShowAgainBtn">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Don't show again</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="closeBtn">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,115 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ProfileSelectDialog.h"
#include "ui_ProfileSelectDialog.h"
#include <QItemSelectionModel>
#include <QDebug>
#include "SkinUtils.h"
#include "Application.h"
#include "ui/dialogs/ProgressDialog.h"
ProfileSelectDialog::ProfileSelectDialog(const QString &message, int flags, QWidget *parent)
: QDialog(parent), ui(new Ui::ProfileSelectDialog)
{
ui->setupUi(this);
m_accounts = APPLICATION->accounts();
auto view = ui->listView;
//view->setModel(m_accounts.get());
//view->hideColumn(AccountList::ActiveColumn);
view->setColumnCount(1);
view->setRootIsDecorated(false);
// FIXME: use a real model, not this
if(QTreeWidgetItem* header = view->headerItem())
{
header->setText(0, tr("Name"));
}
else
{
view->setHeaderLabel(tr("Name"));
}
QList <QTreeWidgetItem *> items;
for (int i = 0; i < m_accounts->count(); i++)
{
MinecraftAccountPtr account = m_accounts->at(i);
QString profileLabel;
if(account->isInUse()) {
profileLabel = tr("%1 (in use)").arg(account->profileName());
}
else {
profileLabel = account->profileName();
}
auto item = new QTreeWidgetItem(view);
item->setText(0, profileLabel);
item->setIcon(0, account->getFace());
item->setData(0, AccountList::PointerRole, QVariant::fromValue(account));
items.append(item);
}
view->addTopLevelItems(items);
// Set the message label.
ui->msgLabel->setVisible(!message.isEmpty());
ui->msgLabel->setText(message);
// Flags...
ui->globalDefaultCheck->setVisible(flags & GlobalDefaultCheckbox);
ui->instDefaultCheck->setVisible(flags & InstanceDefaultCheckbox);
qDebug() << flags;
// Select the first entry in the list.
ui->listView->setCurrentIndex(ui->listView->model()->index(0, 0));
connect(ui->listView, SIGNAL(doubleClicked(QModelIndex)), SLOT(on_buttonBox_accepted()));
}
ProfileSelectDialog::~ProfileSelectDialog()
{
delete ui;
}
MinecraftAccountPtr ProfileSelectDialog::selectedAccount() const
{
return m_selected;
}
bool ProfileSelectDialog::useAsGlobalDefault() const
{
return ui->globalDefaultCheck->isChecked();
}
bool ProfileSelectDialog::useAsInstDefaullt() const
{
return ui->instDefaultCheck->isChecked();
}
void ProfileSelectDialog::on_buttonBox_accepted()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0)
{
QModelIndex selected = selection.first();
m_selected = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>();
}
close();
}
void ProfileSelectDialog::on_buttonBox_rejected()
{
close();
}

View File

@ -0,0 +1,90 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <memory>
#include "minecraft/auth/AccountList.h"
namespace Ui
{
class ProfileSelectDialog;
}
class ProfileSelectDialog : public QDialog
{
Q_OBJECT
public:
enum Flags
{
NoFlags = 0,
/*!
* Shows a check box on the dialog that allows the user to specify that the account
* they've selected should be used as the global default for all instances.
*/
GlobalDefaultCheckbox,
/*!
* Shows a check box on the dialog that allows the user to specify that the account
* they've selected should be used as the default for the instance they are currently launching.
* This is not currently implemented.
*/
InstanceDefaultCheckbox,
};
/*!
* Constructs a new account select dialog with the given parent and message.
* The message will be shown at the top of the dialog. It is an empty string by default.
*/
explicit ProfileSelectDialog(const QString& message="", int flags=0, QWidget *parent = 0);
~ProfileSelectDialog();
/*!
* Gets a pointer to the account that the user selected.
* This is null if the user clicked cancel or hasn't clicked OK yet.
*/
MinecraftAccountPtr selectedAccount() const;
/*!
* Returns true if the user checked the "use as global default" checkbox.
* If the checkbox wasn't shown, this function returns false.
*/
bool useAsGlobalDefault() const;
/*!
* Returns true if the user checked the "use as instance default" checkbox.
* If the checkbox wasn't shown, this function returns false.
*/
bool useAsInstDefaullt() const;
public
slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
protected:
shared_qobject_ptr<AccountList> m_accounts;
//! The account that was selected when the user clicked OK.
MinecraftAccountPtr m_selected;
private:
Ui::ProfileSelectDialog *ui;
};

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ProfileSelectDialog</class>
<widget class="QDialog" name="ProfileSelectDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>465</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Select an Account</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="msgLabel">
<property name="text">
<string>Select a profile.</string>
</property>
</widget>
</item>
<item>
<widget class="QTreeWidget" name="listView">
<column>
<property name="text">
<string notr="true">1</string>
</property>
</column>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QCheckBox" name="globalDefaultCheck">
<property name="text">
<string>Use as default?</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="instDefaultCheck">
<property name="text">
<string>Use as default for this instance only?</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,250 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ProfileSetupDialog.h"
#include "ui_ProfileSetupDialog.h"
#include <QPushButton>
#include <QAction>
#include <QRegExpValidator>
#include <QJsonDocument>
#include <QDebug>
#include "ui/dialogs/ProgressDialog.h"
#include <Application.h>
#include "minecraft/auth/flows/AuthRequest.h"
#include "minecraft/auth/flows/Parsers.h"
ProfileSetupDialog::ProfileSetupDialog(MinecraftAccountPtr accountToSetup, QWidget *parent)
: QDialog(parent), m_accountToSetup(accountToSetup), ui(new Ui::ProfileSetupDialog)
{
ui->setupUi(this);
ui->errorLabel->setVisible(false);
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;
nameEdit->setValidator(new QRegExpValidator(permittedNames));
nameEdit->setClearButtonEnabled(true);
validityAction = nameEdit->addAction(yellowIcon, QLineEdit::LeadingPosition);
connect(nameEdit, &QLineEdit::textEdited, this, &ProfileSetupDialog::nameEdited);
checkStartTimer.setSingleShot(true);
connect(&checkStartTimer, &QTimer::timeout, this, &ProfileSetupDialog::startCheck);
setNameStatus(NameStatus::NotSet, QString());
}
ProfileSetupDialog::~ProfileSetupDialog()
{
delete ui;
}
void ProfileSetupDialog::on_buttonBox_accepted()
{
setupProfile(currentCheck);
}
void ProfileSetupDialog::on_buttonBox_rejected()
{
reject();
}
void ProfileSetupDialog::setNameStatus(ProfileSetupDialog::NameStatus status, QString errorString = QString())
{
nameStatus = status;
auto okButton = ui->buttonBox->button(QDialogButtonBox::Ok);
switch(nameStatus)
{
case NameStatus::Available: {
validityAction->setIcon(goodIcon);
okButton->setEnabled(true);
}
break;
case NameStatus::NotSet:
case NameStatus::Pending:
validityAction->setIcon(yellowIcon);
okButton->setEnabled(false);
break;
case NameStatus::Exists:
case NameStatus::Error:
validityAction->setIcon(badIcon);
okButton->setEnabled(false);
break;
}
if(!errorString.isEmpty()) {
ui->errorLabel->setText(errorString);
ui->errorLabel->setVisible(true);
}
else {
ui->errorLabel->setVisible(false);
}
}
void ProfileSetupDialog::nameEdited(const QString& name)
{
if(!ui->nameEdit->hasAcceptableInput()) {
setNameStatus(NameStatus::NotSet, tr("Name is too short - must be between 3 and 16 characters long."));
return;
}
scheduleCheck(name);
}
void ProfileSetupDialog::scheduleCheck(const QString& name) {
queuedCheck = name;
setNameStatus(NameStatus::Pending);
checkStartTimer.start(1000);
}
void ProfileSetupDialog::startCheck() {
if(isChecking) {
return;
}
if(queuedCheck.isNull()) {
return;
}
checkName(queuedCheck);
}
void ProfileSetupDialog::checkName(const QString &name) {
if(isChecking) {
return;
}
currentCheck = name;
isChecking = true;
auto token = m_accountToSetup->accessToken();
auto url = QString("https://api.minecraftservices.com/minecraft/profile/name/%1/available").arg(name);
QNetworkRequest request = QNetworkRequest(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Accept", "application/json");
request.setRawHeader("Authorization", QString("Bearer %1").arg(token).toUtf8());
AuthRequest *requestor = new AuthRequest(this);
connect(requestor, &AuthRequest::finished, this, &ProfileSetupDialog::checkFinished);
requestor->get(request);
}
void ProfileSetupDialog::checkFinished(
QNetworkReply::NetworkError error,
QByteArray data,
QList<QNetworkReply::RawHeaderPair> headers
) {
if(error == QNetworkReply::NoError) {
auto doc = QJsonDocument::fromJson(data);
auto root = doc.object();
auto statusValue = root.value("status").toString("INVALID");
if(statusValue == "AVAILABLE") {
setNameStatus(NameStatus::Available);
}
else if (statusValue == "DUPLICATE") {
setNameStatus(NameStatus::Exists, tr("Minecraft profile with name %1 already exists.").arg(currentCheck));
}
else if (statusValue == "NOT_ALLOWED") {
setNameStatus(NameStatus::Exists, tr("The name %1 is not allowed.").arg(currentCheck));
}
else {
setNameStatus(NameStatus::Error, tr("Unhandled profile name status: %1").arg(statusValue));
}
}
else {
setNameStatus(NameStatus::Error, tr("Failed to check name availability."));
}
isChecking = false;
}
void ProfileSetupDialog::setupProfile(const QString &profileName) {
if(isWorking) {
return;
}
auto token = m_accountToSetup->accessToken();
auto url = QString("https://api.minecraftservices.com/minecraft/profile");
QNetworkRequest request = QNetworkRequest(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Accept", "application/json");
request.setRawHeader("Authorization", QString("Bearer %1").arg(token).toUtf8());
QString payloadTemplate("{\"profileName\":\"%1\"}");
auto data = payloadTemplate.arg(profileName).toUtf8();
AuthRequest *requestor = new AuthRequest(this);
connect(requestor, &AuthRequest::finished, this, &ProfileSetupDialog::setupProfileFinished);
requestor->post(request, data);
isWorking = true;
auto button = ui->buttonBox->button(QDialogButtonBox::Cancel);
button->setEnabled(false);
}
namespace {
struct MojangError{
static MojangError fromJSON(QByteArray data) {
MojangError out;
out.error = QString::fromUtf8(data);
auto doc = QJsonDocument::fromJson(data, &out.parseError);
auto object = doc.object();
out.fullyParsed = true;
out.fullyParsed &= Parsers::getString(object.value("path"), out.path);
out.fullyParsed &= Parsers::getString(object.value("error"), out.error);
out.fullyParsed &= Parsers::getString(object.value("errorMessage"), out.errorMessage);
return out;
}
QString rawError;
QJsonParseError parseError;
bool fullyParsed;
QString path;
QString error;
QString errorMessage;
};
}
void ProfileSetupDialog::setupProfileFinished(
QNetworkReply::NetworkError error,
QByteArray data,
QList<QNetworkReply::RawHeaderPair> headers
) {
isWorking = false;
if(error == QNetworkReply::NoError) {
/*
* data contains the profile in the response
* ... we could parse it and update the account, but let's just return back to the normal login flow instead...
*/
accept();
}
else {
auto parsedError = MojangError::fromJSON(data);
ui->errorLabel->setVisible(true);
ui->errorLabel->setText(tr("The server returned the following error:") + "\n\n" + parsedError.errorMessage);
qDebug() << parsedError.rawError;
auto button = ui->buttonBox->button(QDialogButtonBox::Cancel);
button->setEnabled(true);
}
}

View File

@ -0,0 +1,88 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <QIcon>
#include <QTimer>
#include <QNetworkReply>
#include <memory>
#include <minecraft/auth/MinecraftAccount.h>
namespace Ui
{
class ProfileSetupDialog;
}
class ProfileSetupDialog : public QDialog
{
Q_OBJECT
public:
explicit ProfileSetupDialog(MinecraftAccountPtr accountToSetup, QWidget *parent = 0);
~ProfileSetupDialog();
enum class NameStatus
{
NotSet,
Pending,
Available,
Exists,
Error
} nameStatus = NameStatus::NotSet;
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void nameEdited(const QString &name);
void checkFinished(
QNetworkReply::NetworkError error,
QByteArray data,
QList<QNetworkReply::RawHeaderPair> headers
);
void startCheck();
void setupProfileFinished(
QNetworkReply::NetworkError error,
QByteArray data,
QList<QNetworkReply::RawHeaderPair> headers
);
protected:
void scheduleCheck(const QString &name);
void checkName(const QString &name);
void setNameStatus(NameStatus status, QString errorString);
void setupProfile(const QString & profileName);
private:
MinecraftAccountPtr m_accountToSetup;
Ui::ProfileSetupDialog *ui;
QIcon goodIcon;
QIcon yellowIcon;
QIcon badIcon;
QAction * validityAction = nullptr;
QString queuedCheck;
bool isChecking = false;
bool isWorking = false;
QString currentCheck;
QTimer checkStartTimer;
};

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ProfileSetupDialog</class>
<widget class="QDialog" name="ProfileSetupDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>615</width>
<height>208</height>
</rect>
</property>
<property name="windowTitle">
<string>Choose Minecraft name</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="descriptionLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>You just need to take one more step to be able to play Minecraft on this account.
Choose your name carefully:</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="buddy">
<cstring>nameEdit</cstring>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLineEdit" name="nameEdit"/>
</item>
<item row="4" column="0" colspan="2">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="errorLabel">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string notr="true">Errors go here</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>nameEdit</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,196 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ProgressDialog.h"
#include "ui_ProgressDialog.h"
#include <QKeyEvent>
#include <QDebug>
#include "tasks/Task.h"
ProgressDialog::ProgressDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ProgressDialog)
{
ui->setupUi(this);
this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
setSkipButton(false);
changeProgress(0, 100);
}
void ProgressDialog::setSkipButton(bool present, QString label)
{
ui->skipButton->setAutoDefault(false);
ui->skipButton->setDefault(false);
ui->skipButton->setFocusPolicy(Qt::ClickFocus);
ui->skipButton->setEnabled(present);
ui->skipButton->setVisible(present);
ui->skipButton->setText(label);
updateSize();
}
void ProgressDialog::on_skipButton_clicked(bool checked)
{
Q_UNUSED(checked);
task->abort();
}
ProgressDialog::~ProgressDialog()
{
delete ui;
}
void ProgressDialog::updateSize()
{
QSize qSize = QSize(480, minimumSizeHint().height());
resize(qSize);
setFixedSize(qSize);
}
int ProgressDialog::execWithTask(Task *task)
{
this->task = task;
QDialog::DialogCode result;
if(!task)
{
qDebug() << "Programmer error: progress dialog created with null task.";
return Accepted;
}
if(handleImmediateResult(result))
{
return result;
}
// Connect signals.
connect(task, SIGNAL(started()), SLOT(onTaskStarted()));
connect(task, SIGNAL(failed(QString)), SLOT(onTaskFailed(QString)));
connect(task, SIGNAL(succeeded()), SLOT(onTaskSucceeded()));
connect(task, SIGNAL(status(QString)), SLOT(changeStatus(const QString &)));
connect(task, SIGNAL(progress(qint64, qint64)), SLOT(changeProgress(qint64, qint64)));
// if this didn't connect to an already running task, invoke start
if(!task->isRunning())
{
task->start();
}
if(task->isRunning())
{
changeProgress(task->getProgress(), task->getTotalProgress());
changeStatus(task->getStatus());
return QDialog::exec();
}
else if(handleImmediateResult(result))
{
return result;
}
else
{
return QDialog::Rejected;
}
}
// TODO: only provide the unique_ptr overloads
int ProgressDialog::execWithTask(std::unique_ptr<Task> &&task)
{
connect(this, &ProgressDialog::destroyed, task.get(), &Task::deleteLater);
return execWithTask(task.release());
}
int ProgressDialog::execWithTask(std::unique_ptr<Task> &task)
{
connect(this, &ProgressDialog::destroyed, task.get(), &Task::deleteLater);
return execWithTask(task.release());
}
bool ProgressDialog::handleImmediateResult(QDialog::DialogCode &result)
{
if(task->isFinished())
{
if(task->wasSuccessful())
{
result = QDialog::Accepted;
}
else
{
result = QDialog::Rejected;
}
return true;
}
return false;
}
Task *ProgressDialog::getTask()
{
return task;
}
void ProgressDialog::onTaskStarted()
{
}
void ProgressDialog::onTaskFailed(QString failure)
{
reject();
}
void ProgressDialog::onTaskSucceeded()
{
accept();
}
void ProgressDialog::changeStatus(const QString &status)
{
ui->statusLabel->setText(status);
updateSize();
}
void ProgressDialog::changeProgress(qint64 current, qint64 total)
{
ui->taskProgressBar->setMaximum(total);
ui->taskProgressBar->setValue(current);
}
void ProgressDialog::keyPressEvent(QKeyEvent *e)
{
if(ui->skipButton->isVisible())
{
if (e->key() == Qt::Key_Escape)
{
on_skipButton_clicked(true);
return;
}
else if(e->key() == Qt::Key_Tab)
{
ui->skipButton->setFocusPolicy(Qt::StrongFocus);
ui->skipButton->setFocus();
ui->skipButton->setAutoDefault(true);
ui->skipButton->setDefault(true);
return;
}
}
QDialog::keyPressEvent(e);
}
void ProgressDialog::closeEvent(QCloseEvent *e)
{
if (task && task->isRunning())
{
e->ignore();
}
else
{
QDialog::closeEvent(e);
}
}

View File

@ -0,0 +1,71 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <memory>
class Task;
namespace Ui
{
class ProgressDialog;
}
class ProgressDialog : public QDialog
{
Q_OBJECT
public:
explicit ProgressDialog(QWidget *parent = 0);
~ProgressDialog();
void updateSize();
int execWithTask(Task *task);
int execWithTask(std::unique_ptr<Task> &&task);
int execWithTask(std::unique_ptr<Task> &task);
void setSkipButton(bool present, QString label = QString());
Task *getTask();
public
slots:
void onTaskStarted();
void onTaskFailed(QString failure);
void onTaskSucceeded();
void changeStatus(const QString &status);
void changeProgress(qint64 current, qint64 total);
private
slots:
void on_skipButton_clicked(bool checked);
protected:
virtual void keyPressEvent(QKeyEvent *e);
virtual void closeEvent(QCloseEvent *e);
private:
bool handleImmediateResult(QDialog::DialogCode &result);
private:
Ui::ProgressDialog *ui;
Task *task;
};

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ProgressDialog</class>
<widget class="QDialog" name="ProgressDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>100</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>400</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>600</width>
<height>16777215</height>
</size>
</property>
<property name="windowTitle">
<string>Please wait...</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="statusLabel">
<property name="text">
<string>Task Status...</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QProgressBar" name="taskProgressBar">
<property name="value">
<number>24</number>
</property>
<property name="textVisible">
<bool>false</bool>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QPushButton" name="skipButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Skip</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,155 @@
#include <QFileInfo>
#include <QFileDialog>
#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"
void SkinUploadDialog::on_buttonBox_rejected()
{
close();
}
void SkinUploadDialog::on_buttonBox_accepted()
{
AuthSessionPtr session = std::make_shared<AuthSession>();
auto login = m_acct->refresh(session);
ProgressDialog prog(this);
if (prog.execWithTask((Task*)login.get()) != QDialog::Accepted)
{
//FIXME: recover with password prompt
CustomMessageBox::selectable(this, tr("Skin Upload"), tr("Failed to login!"), QMessageBox::Warning)->exec();
close();
return;
}
QString fileName;
QString input = ui->skinPathTextBox->text();
QRegExp urlPrefixMatcher("^([a-z]+)://.+$");
bool isLocalFile = false;
// it has an URL prefix -> it is an URL
if(urlPrefixMatcher.exactMatch(input))
{
QUrl fileURL = input;
if(fileURL.isValid())
{
// local?
if(fileURL.isLocalFile())
{
isLocalFile = true;
fileName = fileURL.toLocalFile();
}
else
{
CustomMessageBox::selectable(
this,
tr("Skin Upload"),
tr("Using remote URLs for setting skins is not implemented yet."),
QMessageBox::Warning
)->exec();
close();
return;
}
}
else
{
CustomMessageBox::selectable(
this,
tr("Skin Upload"),
tr("You cannot use an invalid URL for uploading skins."),
QMessageBox::Warning
)->exec();
close();
return;
}
}
else
{
// just assume it's a path then
isLocalFile = true;
fileName = ui->skinPathTextBox->text();
}
if (isLocalFile && !QFile::exists(fileName))
{
CustomMessageBox::selectable(this, tr("Skin Upload"), tr("Skin file does not exist!"), QMessageBox::Warning)->exec();
close();
return;
}
SkinUpload::Model model = SkinUpload::STEVE;
if (ui->steveBtn->isChecked())
{
model = SkinUpload::STEVE;
}
else if (ui->alexBtn->isChecked())
{
model = SkinUpload::ALEX;
}
SequentialTask skinUpload;
skinUpload.addTask(shared_qobject_ptr<SkinUpload>(new SkinUpload(this, session, FS::read(fileName), model)));
auto selectedCape = ui->capeCombo->currentData().toString();
if(selectedCape != m_acct->accountData()->minecraftProfile.currentCape) {
skinUpload.addTask(shared_qobject_ptr<CapeChange>(new CapeChange(this, session, selectedCape)));
}
if (prog.execWithTask(&skinUpload) != QDialog::Accepted)
{
CustomMessageBox::selectable(this, tr("Skin Upload"), tr("Failed to upload skin!"), QMessageBox::Warning)->exec();
close();
return;
}
CustomMessageBox::selectable(this, tr("Skin Upload"), tr("Success"), QMessageBox::Information)->exec();
close();
}
void SkinUploadDialog::on_skinBrowseBtn_clicked()
{
QString raw_path = QFileDialog::getOpenFileName(this, tr("Select Skin Texture"), QString(), "*.png");
if (raw_path.isEmpty() || !QFileInfo::exists(raw_path))
{
return;
}
QString cooked_path = FS::NormalizePath(raw_path);
ui->skinPathTextBox->setText(cooked_path);
}
SkinUploadDialog::SkinUploadDialog(MinecraftAccountPtr acct, QWidget *parent)
:QDialog(parent), m_acct(acct), ui(new Ui::SkinUploadDialog)
{
ui->setupUi(this);
// FIXME: add a model for this, download/refresh the capes on demand
auto &data = *acct->accountData();
int index = 0;
ui->capeCombo->addItem(tr("No Cape"), QVariant());
auto currentCape = data.minecraftProfile.currentCape;
if(currentCape.isEmpty()) {
ui->capeCombo->setCurrentIndex(index);
}
for(auto & cape: data.minecraftProfile.capes) {
index++;
if(cape.data.size()) {
QPixmap capeImage;
if(capeImage.loadFromData(cape.data, "PNG")) {
QPixmap preview = QPixmap(10, 16);
QPainter painter(&preview);
painter.drawPixmap(0, 0, capeImage.copy(1, 1, 10, 16));
ui->capeCombo->addItem(capeImage, cape.alias, cape.id);
if(currentCape == cape.id) {
ui->capeCombo->setCurrentIndex(index);
}
continue;
}
}
ui->capeCombo->addItem(cape.alias, cape.id);
if(currentCape == cape.id) {
ui->capeCombo->setCurrentIndex(index);
}
}
}

View File

@ -0,0 +1,29 @@
#pragma once
#include <QDialog>
#include <minecraft/auth/MinecraftAccount.h>
namespace Ui
{
class SkinUploadDialog;
}
class SkinUploadDialog : public QDialog {
Q_OBJECT
public:
explicit SkinUploadDialog(MinecraftAccountPtr acct, QWidget *parent = 0);
virtual ~SkinUploadDialog() {};
public slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void on_skinBrowseBtn_clicked();
protected:
MinecraftAccountPtr m_acct;
private:
Ui::SkinUploadDialog *ui;
};

View File

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SkinUploadDialog</class>
<widget class="QDialog" name="SkinUploadDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>394</width>
<height>360</height>
</rect>
</property>
<property name="windowTitle">
<string>Skin Upload</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="fileBox">
<property name="title">
<string>Skin File</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLineEdit" name="skinPathTextBox"/>
</item>
<item>
<widget class="QPushButton" name="skinBrowseBtn">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>28</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="modelBox">
<property name="title">
<string>Player Model</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_1">
<item>
<widget class="QRadioButton" name="steveBtn">
<property name="text">
<string>Steve Model</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="alexBtn">
<property name="text">
<string>Alex Model</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="capeBox">
<property name="title">
<string>Cape</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QComboBox" name="capeCombo"/>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,182 @@
#include "UpdateDialog.h"
#include "ui_UpdateDialog.h"
#include <QDebug>
#include "Application.h"
#include <settings/SettingsObject.h>
#include <Json.h>
#include "BuildConfig.h"
#include "HoeDown.h"
UpdateDialog::UpdateDialog(bool hasUpdate, QWidget *parent) : QDialog(parent), ui(new Ui::UpdateDialog)
{
ui->setupUi(this);
auto channel = APPLICATION->settings()->get("UpdateChannel").toString();
if(hasUpdate)
{
ui->label->setText(tr("A new %1 update is available!").arg(channel));
}
else
{
ui->label->setText(tr("No %1 updates found. You are running the latest version.").arg(channel));
ui->btnUpdateNow->setHidden(true);
ui->btnUpdateLater->setText(tr("Close"));
}
ui->changelogBrowser->setHtml(tr("<center><h1>Loading changelog...</h1></center>"));
loadChangelog();
restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("UpdateDialogGeometry").toByteArray()));
}
UpdateDialog::~UpdateDialog()
{
}
void UpdateDialog::loadChangelog()
{
auto channel = APPLICATION->settings()->get("UpdateChannel").toString();
dljob.reset(new NetJob("Changelog"));
QString url;
if(channel == "stable")
{
url = QString("https://raw.githubusercontent.com/MultiMC/Launcher/%1/changelog.md").arg(channel);
m_changelogType = CHANGELOG_MARKDOWN;
}
else
{
url = QString("https://api.github.com/repos/MultiMC/Launcher/compare/%1...%2").arg(BuildConfig.GIT_COMMIT, channel);
m_changelogType = CHANGELOG_COMMITS;
}
dljob->addNetAction(Net::Download::makeByteArray(QUrl(url), &changelogData));
connect(dljob.get(), &NetJob::succeeded, this, &UpdateDialog::changelogLoaded);
connect(dljob.get(), &NetJob::failed, this, &UpdateDialog::changelogFailed);
dljob->start(APPLICATION->network());
}
QString reprocessMarkdown(QByteArray markdown)
{
HoeDown hoedown;
QString output = hoedown.process(markdown);
// HACK: easier than customizing hoedown
output.replace(QRegExp("GH-([0-9]+)"), "<a href=\"https://github.com/MultiMC/Launcher/issues/\\1\">GH-\\1</a>");
qDebug() << output;
return output;
}
QString reprocessCommits(QByteArray json)
{
auto channel = APPLICATION->settings()->get("UpdateChannel").toString();
try
{
QString result;
auto document = Json::requireDocument(json);
auto rootobject = Json::requireObject(document);
auto status = Json::requireString(rootobject, "status");
auto diff_url = Json::requireString(rootobject, "html_url");
auto print_commits = [&]()
{
result += "<table cellspacing=0 cellpadding=2 style='border-width: 1px; border-style: solid'>";
auto commitarray = Json::requireArray(rootobject, "commits");
for(int i = commitarray.size() - 1; i >= 0; i--)
{
const auto & commitval = commitarray[i];
auto commitobj = Json::requireObject(commitval);
auto parents_info = Json::ensureArray(commitobj, "parents");
// NOTE: this ignores merge commits, because they have more than one parent
if(parents_info.size() > 1)
{
continue;
}
auto commit_url = Json::requireString(commitobj, "html_url");
auto commit_info = Json::requireObject(commitobj, "commit");
auto commit_message = Json::requireString(commit_info, "message");
auto lines = commit_message.split('\n');
QRegularExpression regexp("(?<prefix>(GH-(?<issuenr>[0-9]+))|(NOISSUE)|(SCRATCH))? *(?<rest>.*) *");
auto match = regexp.match(lines.takeFirst(), 0, QRegularExpression::NormalMatch);
auto issuenr = match.captured("issuenr");
auto prefix = match.captured("prefix");
auto rest = match.captured("rest");
result += "<tr><td>";
if(issuenr.length())
{
result += QString("<a href=\"https://github.com/MultiMC/Launcher/issues/%1\">GH-%2</a>").arg(issuenr, issuenr);
}
else if(prefix.length())
{
result += QString("<a href=\"%1\">%2</a>").arg(commit_url, prefix);
}
else
{
result += QString("<a href=\"%1\">NOISSUE</a>").arg(commit_url);
}
result += "</td>";
lines.prepend(rest);
result += "<td><p>" + lines.join("<br />") + "</p></td></tr>";
}
result += "</table>";
};
if(status == "identical")
{
return QObject::tr("<p>There are no code changes between your current version and latest %1.</p>").arg(channel);
}
else if(status == "ahead")
{
result += QObject::tr("<p>Following commits were added since last update:</p>");
print_commits();
}
else if(status == "diverged")
{
auto commit_ahead = Json::requireInteger(rootobject, "ahead_by");
auto commit_behind = Json::requireInteger(rootobject, "behind_by");
result += QObject::tr("<p>The update removes %1 commits and adds the following %2:</p>").arg(commit_behind).arg(commit_ahead);
print_commits();
}
result += QObject::tr("<p>You can <a href=\"%1\">look at the changes on github</a>.</p>").arg(diff_url);
return result;
}
catch (const JSONValidationError &e)
{
qWarning() << "Got an unparseable commit log from github:" << e.what();
qDebug() << json;
}
return QString();
}
void UpdateDialog::changelogLoaded()
{
QString result;
switch(m_changelogType)
{
case CHANGELOG_COMMITS:
result = reprocessCommits(changelogData);
break;
case CHANGELOG_MARKDOWN:
result = reprocessMarkdown(changelogData);
break;
}
changelogData.clear();
ui->changelogBrowser->setHtml(result);
}
void UpdateDialog::changelogFailed(QString reason)
{
ui->changelogBrowser->setHtml(tr("<p align=\"center\" <span style=\"font-size:22pt;\">Failed to fetch changelog... Error: %1</span></p>").arg(reason));
}
void UpdateDialog::on_btnUpdateLater_clicked()
{
reject();
}
void UpdateDialog::on_btnUpdateNow_clicked()
{
done(UPDATE_NOW);
}
void UpdateDialog::closeEvent(QCloseEvent* evt)
{
APPLICATION->settings()->set("UpdateDialogGeometry", saveGeometry().toBase64());
QDialog::closeEvent(evt);
}

View File

@ -0,0 +1,67 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include "net/NetJob.h"
namespace Ui
{
class UpdateDialog;
}
enum UpdateAction
{
UPDATE_LATER = QDialog::Rejected,
UPDATE_NOW = QDialog::Accepted,
};
enum ChangelogType
{
CHANGELOG_MARKDOWN,
CHANGELOG_COMMITS
};
class UpdateDialog : public QDialog
{
Q_OBJECT
public:
explicit UpdateDialog(bool hasUpdate = true, QWidget *parent = 0);
~UpdateDialog();
public slots:
void on_btnUpdateNow_clicked();
void on_btnUpdateLater_clicked();
/// Starts loading the changelog
void loadChangelog();
/// Slot for when the chengelog loads successfully.
void changelogLoaded();
/// Slot for when the chengelog fails to load...
void changelogFailed(QString reason);
protected:
void closeEvent(QCloseEvent * ) override;
private:
Ui::UpdateDialog *ui;
QByteArray changelogData;
NetJob::Ptr dljob;
ChangelogType m_changelogType = CHANGELOG_MARKDOWN;
};

View File

@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>UpdateDialog</class>
<widget class="QDialog" name="UpdateDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>657</width>
<height>673</height>
</rect>
</property>
<property name="windowTitle">
<string>MultiMC Update</string>
</property>
<property name="windowIcon">
<iconset>
<normaloff>:/icons/toolbar/checkupdate</normaloff>:/icons/toolbar/checkupdate</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="font">
<font>
<pointsize>14</pointsize>
</font>
</property>
<property name="text">
<string/>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property>
<property name="buddy">
<cstring>changelogBrowser</cstring>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QTextBrowser" name="changelogBrowser">
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QPushButton" name="btnUpdateNow">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Update now</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="btnUpdateLater">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Don't update yet</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>changelogBrowser</tabstop>
<tabstop>btnUpdateNow</tabstop>
<tabstop>btnUpdateLater</tabstop>
</tabstops>
<resources>
<include location="../../resources/multimc/multimc.qrc"/>
</resources>
<connections/>
</ui>

View File

@ -0,0 +1,141 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "VersionSelectDialog.h"
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QDebug>
#include "ui/dialogs/ProgressDialog.h"
#include "ui/widgets/VersionSelectWidget.h"
#include "ui/dialogs/CustomMessageBox.h"
#include "BaseVersion.h"
#include "BaseVersionList.h"
#include "tasks/Task.h"
#include "Application.h"
#include "VersionProxyModel.h"
VersionSelectDialog::VersionSelectDialog(BaseVersionList *vlist, QString title, QWidget *parent, bool cancelable)
: QDialog(parent)
{
setObjectName(QStringLiteral("VersionSelectDialog"));
resize(400, 347);
m_verticalLayout = new QVBoxLayout(this);
m_verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
m_versionWidget = new VersionSelectWidget(parent);
m_verticalLayout->addWidget(m_versionWidget);
m_horizontalLayout = new QHBoxLayout();
m_horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
m_refreshButton = new QPushButton(this);
m_refreshButton->setObjectName(QStringLiteral("refreshButton"));
m_horizontalLayout->addWidget(m_refreshButton);
m_buttonBox = new QDialogButtonBox(this);
m_buttonBox->setObjectName(QStringLiteral("buttonBox"));
m_buttonBox->setOrientation(Qt::Horizontal);
m_buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
m_horizontalLayout->addWidget(m_buttonBox);
m_verticalLayout->addLayout(m_horizontalLayout);
retranslate();
QObject::connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
QObject::connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
QMetaObject::connectSlotsByName(this);
setWindowModality(Qt::WindowModal);
setWindowTitle(title);
m_vlist = vlist;
if (!cancelable)
{
m_buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false);
}
}
void VersionSelectDialog::retranslate()
{
// FIXME: overrides custom title given in constructor!
setWindowTitle(tr("Choose Version"));
m_refreshButton->setToolTip(tr("Reloads the version list."));
m_refreshButton->setText(tr("&Refresh"));
}
void VersionSelectDialog::setCurrentVersion(const QString& version)
{
m_currentVersion = version;
m_versionWidget->setCurrentVersion(version);
}
void VersionSelectDialog::setEmptyString(QString emptyString)
{
m_versionWidget->setEmptyString(emptyString);
}
void VersionSelectDialog::setEmptyErrorString(QString emptyErrorString)
{
m_versionWidget->setEmptyErrorString(emptyErrorString);
}
void VersionSelectDialog::setResizeOn(int column)
{
resizeOnColumn = column;
}
int VersionSelectDialog::exec()
{
QDialog::open();
m_versionWidget->initialize(m_vlist);
if(resizeOnColumn != -1)
{
m_versionWidget->setResizeOn(resizeOnColumn);
}
return QDialog::exec();
}
void VersionSelectDialog::selectRecommended()
{
m_versionWidget->selectRecommended();
}
BaseVersionPtr VersionSelectDialog::selectedVersion() const
{
return m_versionWidget->selectedVersion();
}
void VersionSelectDialog::on_refreshButton_clicked()
{
m_versionWidget->loadList();
}
void VersionSelectDialog::setExactFilter(BaseVersionList::ModelRoles role, QString filter)
{
m_versionWidget->setExactFilter(role, filter);
}
void VersionSelectDialog::setFuzzyFilter(BaseVersionList::ModelRoles role, QString filter)
{
m_versionWidget->setFuzzyFilter(role, filter);
}

View File

@ -0,0 +1,78 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include <QSortFilterProxyModel>
#include "BaseVersionList.h"
class QVBoxLayout;
class QHBoxLayout;
class QDialogButtonBox;
class VersionSelectWidget;
class QPushButton;
namespace Ui
{
class VersionSelectDialog;
}
class VersionProxyModel;
class VersionSelectDialog : public QDialog
{
Q_OBJECT
public:
explicit VersionSelectDialog(BaseVersionList *vlist, QString title, QWidget *parent = 0, bool cancelable = true);
virtual ~VersionSelectDialog() {};
int exec() override;
BaseVersionPtr selectedVersion() const;
void setCurrentVersion(const QString & version);
void setFuzzyFilter(BaseVersionList::ModelRoles role, QString filter);
void setExactFilter(BaseVersionList::ModelRoles role, QString filter);
void setEmptyString(QString emptyString);
void setEmptyErrorString(QString emptyErrorString);
void setResizeOn(int column);
private slots:
void on_refreshButton_clicked();
private:
void retranslate();
void selectRecommended();
private:
QString m_currentVersion;
VersionSelectWidget *m_versionWidget = nullptr;
QVBoxLayout *m_verticalLayout = nullptr;
QHBoxLayout *m_horizontalLayout = nullptr;
QPushButton *m_refreshButton = nullptr;
QDialogButtonBox *m_buttonBox = nullptr;
BaseVersionList *m_vlist = nullptr;
VersionProxyModel *m_proxyModel = nullptr;
int resizeOnColumn = -1;
Task * loadTask = nullptr;
};

View File

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

View File

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

View File

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

View File

@ -0,0 +1,428 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "InstanceDelegate.h"
#include <QPainter>
#include <QTextOption>
#include <QTextLayout>
#include <QApplication>
#include <QtMath>
#include <QDebug>
#include "InstanceView.h"
#include "BaseInstance.h"
#include "InstanceList.h"
#include <xdgicon.h>
#include <QTextEdit>
// Origin: Qt
static void viewItemTextLayout(QTextLayout &textLayout, int lineWidth, qreal &height,
qreal &widthUsed)
{
height = 0;
widthUsed = 0;
textLayout.beginLayout();
QString str = textLayout.text();
while (true)
{
QTextLine line = textLayout.createLine();
if (!line.isValid())
break;
if (line.textLength() == 0)
break;
line.setLineWidth(lineWidth);
line.setPosition(QPointF(0, height));
height += line.height();
widthUsed = qMax(widthUsed, line.naturalTextWidth());
}
textLayout.endLayout();
}
ListViewDelegate::ListViewDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}
void drawSelectionRect(QPainter *painter, const QStyleOptionViewItem &option,
const QRect &rect)
{
if ((option.state & QStyle::State_Selected))
painter->fillRect(rect, option.palette.brush(QPalette::Highlight));
else
{
QColor backgroundColor = option.palette.color(QPalette::Background);
backgroundColor.setAlpha(160);
painter->fillRect(rect, QBrush(backgroundColor));
}
}
void drawFocusRect(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect)
{
if (!(option.state & QStyle::State_HasFocus))
return;
QStyleOptionFocusRect opt;
opt.direction = option.direction;
opt.fontMetrics = option.fontMetrics;
opt.palette = option.palette;
opt.rect = rect;
// opt.state = option.state | QStyle::State_KeyboardFocusChange |
// QStyle::State_Item;
auto col = option.state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base;
opt.backgroundColor = option.palette.color(col);
// Apparently some widget styles expect this hint to not be set
painter->setRenderHint(QPainter::Antialiasing, false);
QStyle *style = option.widget ? option.widget->style() : QApplication::style();
style->drawPrimitive(QStyle::PE_FrameFocusRect, &opt, painter, option.widget);
painter->setRenderHint(QPainter::Antialiasing);
}
// TODO this can be made a lot prettier
void drawProgressOverlay(QPainter *painter, const QStyleOptionViewItem &option,
const int value, const int maximum)
{
if (maximum == 0 || value == maximum)
{
return;
}
painter->save();
qreal percent = (qreal)value / (qreal)maximum;
QColor color = option.palette.color(QPalette::Dark);
color.setAlphaF(0.70f);
painter->setBrush(color);
painter->setPen(QPen(QBrush(), 0));
painter->drawPie(option.rect, 90 * 16, -percent * 360 * 16);
painter->restore();
}
void drawBadges(QPainter *painter, const QStyleOptionViewItem &option, BaseInstance *instance, QIcon::Mode mode, QIcon::State state)
{
QList<QString> pixmaps;
if (instance->isRunning())
{
pixmaps.append("status-running");
}
else if (instance->hasCrashed() || instance->hasVersionBroken())
{
pixmaps.append("status-bad");
}
if (instance->hasUpdateAvailable())
{
pixmaps.append("checkupdate");
}
static const int itemSide = 24;
static const int spacing = 1;
const int itemsPerRow = qMax(1, qFloor(double(option.rect.width() + spacing) / double(itemSide + spacing)));
const int rows = qCeil((double)pixmaps.size() / (double)itemsPerRow);
QListIterator<QString> it(pixmaps);
painter->translate(option.rect.topLeft());
for (int y = 0; y < rows; ++y)
{
for (int x = 0; x < itemsPerRow; ++x)
{
if (!it.hasNext())
{
return;
}
// FIXME: inject this.
auto icon = XdgIcon::fromTheme(it.next());
// opt.icon.paint(painter, iconbox, Qt::AlignCenter, mode, state);
const QPixmap pixmap;
// itemSide
QRect badgeRect(
option.rect.width() - x * itemSide + qMax(x - 1, 0) * spacing - itemSide,
y * itemSide + qMax(y - 1, 0) * spacing,
itemSide,
itemSide
);
icon.paint(painter, badgeRect, Qt::AlignCenter, mode, state);
}
}
painter->translate(-option.rect.topLeft());
}
static QSize viewItemTextSize(const QStyleOptionViewItem *option)
{
QStyle *style = option->widget ? option->widget->style() : QApplication::style();
QTextOption textOption;
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
QTextLayout textLayout;
textLayout.setTextOption(textOption);
textLayout.setFont(option->font);
textLayout.setText(option->text);
const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, option, option->widget) + 1;
QRect bounds(0, 0, 100 - 2 * textMargin, 600);
qreal height = 0, widthUsed = 0;
viewItemTextLayout(textLayout, bounds.width(), height, widthUsed);
const QSize size(qCeil(widthUsed), qCeil(height));
return QSize(size.width() + 2 * textMargin, size.height());
}
void ListViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
painter->save();
painter->setClipRect(opt.rect);
opt.features |= QStyleOptionViewItem::WrapText;
opt.text = index.data().toString();
opt.textElideMode = Qt::ElideRight;
opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter;
QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
// const int iconSize = style->pixelMetric(QStyle::PM_IconViewIconSize);
const int iconSize = 48;
QRect iconbox = opt.rect;
const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, opt.widget) + 1;
QRect textRect = opt.rect;
QRect textHighlightRect = textRect;
// clip the decoration on top, remove width padding
textRect.adjust(textMargin, iconSize + textMargin + 5, -textMargin, 0);
textHighlightRect.adjust(0, iconSize + 5, 0, 0);
// draw background
{
// FIXME: unused
// QSize textSize = viewItemTextSize ( &opt );
drawSelectionRect(painter, opt, textHighlightRect);
/*
QPalette::ColorGroup cg;
QStyleOptionViewItem opt2(opt);
if ((opt.widget && opt.widget->isEnabled()) || (opt.state & QStyle::State_Enabled))
{
if (!(opt.state & QStyle::State_Active))
cg = QPalette::Inactive;
else
cg = QPalette::Normal;
}
else
{
cg = QPalette::Disabled;
}
*/
/*
opt2.palette.setCurrentColorGroup(cg);
// fill in background, if any
if (opt.backgroundBrush.style() != Qt::NoBrush)
{
QPointF oldBO = painter->brushOrigin();
painter->setBrushOrigin(opt.rect.topLeft());
painter->fillRect(opt.rect, opt.backgroundBrush);
painter->setBrushOrigin(oldBO);
}
drawSelectionRect(painter, opt2, textHighlightRect);
*/
/*
if (opt.showDecorationSelected)
{
drawSelectionRect(painter, opt2, opt.rect);
drawFocusRect(painter, opt2, opt.rect);
// painter->fillRect ( opt.rect, opt.palette.brush ( cg, QPalette::Highlight ) );
}
else
{
// if ( opt.state & QStyle::State_Selected )
{
// QRect textRect = subElementRect ( QStyle::SE_ItemViewItemText, opt,
// opt.widget );
// painter->fillRect ( textHighlightRect, opt.palette.brush ( cg,
// QPalette::Highlight ) );
drawSelectionRect(painter, opt2, textHighlightRect);
drawFocusRect(painter, opt2, textHighlightRect);
}
}
*/
}
// icon mode and state, also used for badges
QIcon::Mode mode = QIcon::Normal;
if (!(opt.state & QStyle::State_Enabled))
mode = QIcon::Disabled;
else if (opt.state & QStyle::State_Selected)
mode = QIcon::Selected;
QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off;
// draw the icon
{
iconbox.setHeight(iconSize);
opt.icon.paint(painter, iconbox, Qt::AlignCenter, mode, state);
}
// set the text colors
QPalette::ColorGroup cg =
opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled;
if (cg == QPalette::Normal && !(opt.state & QStyle::State_Active))
cg = QPalette::Inactive;
if (opt.state & QStyle::State_Selected)
{
painter->setPen(opt.palette.color(cg, QPalette::HighlightedText));
}
else
{
painter->setPen(opt.palette.color(cg, QPalette::Text));
}
// draw the text
QTextOption textOption;
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
textOption.setTextDirection(opt.direction);
textOption.setAlignment(QStyle::visualAlignment(opt.direction, opt.displayAlignment));
QTextLayout textLayout;
textLayout.setTextOption(textOption);
textLayout.setFont(opt.font);
textLayout.setText(opt.text);
qreal width, height;
viewItemTextLayout(textLayout, textRect.width(), height, width);
const int lineCount = textLayout.lineCount();
const QRect layoutRect = QStyle::alignedRect(
opt.direction, opt.displayAlignment, QSize(textRect.width(), int(height)), textRect);
const QPointF position = layoutRect.topLeft();
for (int i = 0; i < lineCount; ++i)
{
const QTextLine line = textLayout.lineAt(i);
line.draw(painter, position);
}
// FIXME: this really has no business of being here. Make generic.
auto instance = (BaseInstance*)index.data(InstanceList::InstancePointerRole)
.value<void *>();
if (instance)
{
drawBadges(painter, opt, instance, mode, state);
}
drawProgressOverlay(painter, opt, index.data(InstanceViewRoles::ProgressValueRole).toInt(),
index.data(InstanceViewRoles::ProgressMaximumRole).toInt());
painter->restore();
}
QSize ListViewDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
opt.features |= QStyleOptionViewItem::WrapText;
opt.text = index.data().toString();
opt.textElideMode = Qt::ElideRight;
opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter;
QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &option, opt.widget) + 1;
int height = 48 + textMargin * 2 + 5; // TODO: turn constants into variables
QSize szz = viewItemTextSize(&opt);
height += szz.height();
// FIXME: maybe the icon items could scale and keep proportions?
QSize sz(100, height);
return sz;
}
class NoReturnTextEdit: public QTextEdit
{
Q_OBJECT
public:
explicit NoReturnTextEdit(QWidget *parent) : QTextEdit(parent)
{
setTextInteractionFlags(Qt::TextEditorInteraction);
setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
}
bool event(QEvent * event) override
{
auto eventType = event->type();
if(eventType == QEvent::KeyPress || eventType == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
auto key = keyEvent->key();
if (key == Qt::Key_Return || key == Qt::Key_Enter)
{
emit editingDone();
return true;
}
if(key == Qt::Key_Tab)
{
return true;
}
}
return QTextEdit::event(event);
}
signals:
void editingDone();
};
void ListViewDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
const int iconSize = 48;
QRect textRect = option.rect;
// QStyle *style = option.widget ? option.widget->style() : QApplication::style();
textRect.adjust(0, iconSize + 5, 0, 0);
editor->setGeometry(textRect);
}
void ListViewDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
auto text = index.data(Qt::EditRole).toString();
QTextEdit * realeditor = qobject_cast<NoReturnTextEdit *>(editor);
realeditor->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
realeditor->append(text);
realeditor->selectAll();
realeditor->document()->clearUndoRedoStacks();
}
void ListViewDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
QTextEdit * realeditor = qobject_cast<NoReturnTextEdit *>(editor);
QString text = realeditor->toPlainText();
text.replace(QChar('\n'), QChar(' '));
text = text.trimmed();
if(text.size() != 0)
{
model->setData(index, text);
}
}
QWidget * ListViewDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
auto editor = new NoReturnTextEdit(parent);
connect(editor, &NoReturnTextEdit::editingDone, this, &ListViewDelegate::editingDone);
return editor;
}
void ListViewDelegate::editingDone()
{
NoReturnTextEdit *editor = qobject_cast<NoReturnTextEdit *>(sender());
emit commitData(editor);
emit closeEditor(editor);
}
#include "InstanceDelegate.moc"

View File

@ -0,0 +1,39 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QStyledItemDelegate>
#include <QCache>
class ListViewDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit ListViewDelegate(QObject *parent = 0);
virtual ~ListViewDelegate() {}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const override;
QWidget * createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const override;
void setEditorData(QWidget * editor, const QModelIndex & index) const override;
void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const override;
private slots:
void editingDone();
};

View File

@ -0,0 +1,71 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "InstanceProxyModel.h"
#include "InstanceView.h"
#include "Application.h"
#include <BaseInstance.h>
#include <icons/IconList.h>
#include <QDebug>
InstanceProxyModel::InstanceProxyModel(QObject *parent) : QSortFilterProxyModel(parent) {
m_naturalSort.setNumericMode(true);
m_naturalSort.setCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive);
// FIXME: use loaded translation as source of locale instead, hook this up to translation changes
m_naturalSort.setLocale(QLocale::system());
}
QVariant InstanceProxyModel::data(const QModelIndex & index, int role) const
{
QVariant data = QSortFilterProxyModel::data(index, role);
if(role == Qt::DecorationRole)
{
return QVariant(APPLICATION->icons()->getIcon(data.toString()));
}
return data;
}
bool InstanceProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const {
const QString leftCategory = left.data(InstanceViewRoles::GroupRole).toString();
const QString rightCategory = right.data(InstanceViewRoles::GroupRole).toString();
if (leftCategory == rightCategory) {
return subSortLessThan(left, right);
}
else {
// FIXME: real group sorting happens in InstanceView::updateGeometries(), see LocaleString
auto result = leftCategory.localeAwareCompare(rightCategory);
if(result == 0) {
return subSortLessThan(left, right);
}
return result < 0;
}
}
bool InstanceProxyModel::subSortLessThan(const QModelIndex &left, const QModelIndex &right) const
{
BaseInstance *pdataLeft = static_cast<BaseInstance *>(left.internalPointer());
BaseInstance *pdataRight = static_cast<BaseInstance *>(right.internalPointer());
QString sortMode = APPLICATION->settings()->get("InstSortMode").toString();
if (sortMode == "LastLaunch")
{
return pdataLeft->lastLaunch() > pdataRight->lastLaunch();
}
else
{
return m_naturalSort.compare(pdataLeft->name(), pdataRight->name()) < 0;
}
}

View File

@ -0,0 +1,35 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QSortFilterProxyModel>
#include <QCollator>
class InstanceProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
InstanceProxyModel(QObject *parent = 0);
protected:
QVariant data(const QModelIndex & index, int role) const override;
bool lessThan(const QModelIndex &left, const QModelIndex &right) const override;
bool subSortLessThan(const QModelIndex &left, const QModelIndex &right) const;
private:
QCollator m_naturalSort;
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,153 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QListView>
#include <QLineEdit>
#include <QScrollBar>
#include <QCache>
#include "VisualGroup.h"
#include <functional>
struct InstanceViewRoles
{
enum
{
GroupRole = Qt::UserRole,
ProgressValueRole,
ProgressMaximumRole
};
};
class InstanceView : public QAbstractItemView
{
Q_OBJECT
public:
InstanceView(QWidget *parent = 0);
~InstanceView();
void setModel(QAbstractItemModel *model) override;
using visibilityFunction = std::function<bool(const QString &)>;
void setSourceOfGroupCollapseStatus(visibilityFunction f) {
fVisibility = f;
}
/// return geometry rectangle occupied by the specified model item
QRect geometryRect(const QModelIndex &index) const;
/// return visual rectangle occupied by the specified model item
virtual QRect visualRect(const QModelIndex &index) const override;
/// get the model index at the specified visual point
virtual QModelIndex indexAt(const QPoint &point) const override;
QString groupNameAt(const QPoint &point);
void setSelection(const QRect &rect, const QItemSelectionModel::SelectionFlags commands) override;
virtual int horizontalOffset() const override;
virtual int verticalOffset() const override;
virtual void scrollContentsBy(int dx, int dy) override;
virtual void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible) override;
virtual QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override;
virtual QRegion visualRegionForSelection(const QItemSelection &selection) const override;
int spacing() const
{
return m_spacing;
};
public slots:
virtual void updateGeometries() override;
protected slots:
virtual void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) override;
virtual void rowsInserted(const QModelIndex &parent, int start, int end) override;
virtual void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override;
void modelReset();
void rowsRemoved();
void currentChanged(const QModelIndex &current, const QModelIndex &previous) override;
signals:
void droppedURLs(QList<QUrl> urls);
void groupStateChanged(QString group, bool collapsed);
protected:
bool isIndexHidden(const QModelIndex &index) const override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
void paintEvent(QPaintEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void dragEnterEvent(QDragEnterEvent *event) override;
void dragMoveEvent(QDragMoveEvent *event) override;
void dragLeaveEvent(QDragLeaveEvent *event) override;
void dropEvent(QDropEvent *event) override;
void startDrag(Qt::DropActions supportedActions) override;
void updateScrollbar();
private:
friend struct VisualGroup;
QList<VisualGroup *> m_groups;
visibilityFunction fVisibility;
// geometry
int m_leftMargin = 5;
int m_rightMargin = 5;
int m_bottomMargin = 5;
int m_categoryMargin = 5;
int m_spacing = 5;
int m_itemWidth = 100;
int m_currentItemsPerRow = -1;
int m_currentCursorColumn= -1;
mutable QCache<int, QRect> geometryCache;
// point where the currently active mouse action started in geometry coordinates
QPoint m_pressedPosition;
QPersistentModelIndex m_pressedIndex;
bool m_pressedAlreadySelected;
VisualGroup *m_pressedCategory;
QItemSelectionModel::SelectionFlag m_ctrlDragSelectionFlag;
QPoint m_lastDragPosition;
VisualGroup *category(const QModelIndex &index) const;
VisualGroup *category(const QString &cat) const;
VisualGroup *categoryAt(const QPoint &pos, VisualGroup::HitResults & result) const;
int itemsPerRow() const
{
return m_currentItemsPerRow;
};
int contentWidth() const;
private: /* methods */
int itemWidth() const;
int calculateItemsPerRow() const;
int verticalScrollToValue(const QModelIndex &index, const QRect &rect, QListView::ScrollHint hint) const;
QPixmap renderToPixmap(const QModelIndexList &indices, QRect *r) const;
QList<QPair<QRect, QModelIndex>> draggablePaintPairs(const QModelIndexList &indices, QRect *r) const;
bool isDragEventAccepted(QDropEvent *event);
QPair<VisualGroup *, VisualGroup::HitResults> rowDropPos(const QPoint &pos);
QPoint offset() const;
};

View File

@ -0,0 +1,317 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "VisualGroup.h"
#include <QModelIndex>
#include <QPainter>
#include <QtMath>
#include <QApplication>
#include <QDebug>
#include "InstanceView.h"
VisualGroup::VisualGroup(const QString &text, InstanceView *view) : view(view), text(text), collapsed(false)
{
}
VisualGroup::VisualGroup(const VisualGroup *other)
: view(other->view), text(other->text), collapsed(other->collapsed)
{
}
void VisualGroup::update()
{
auto temp_items = items();
auto itemsPerRow = view->itemsPerRow();
int numRows = qMax(1, qCeil((qreal)temp_items.size() / (qreal)itemsPerRow));
rows = QVector<VisualRow>(numRows);
int maxRowHeight = 0;
int positionInRow = 0;
int currentRow = 0;
int offsetFromTop = 0;
for (auto item: temp_items)
{
if(positionInRow == itemsPerRow)
{
rows[currentRow].height = maxRowHeight;
rows[currentRow].top = offsetFromTop;
currentRow ++;
offsetFromTop += maxRowHeight + 5;
positionInRow = 0;
maxRowHeight = 0;
}
auto itemHeight = view->itemDelegate()->sizeHint(view->viewOptions(), item).height();
if(itemHeight > maxRowHeight)
{
maxRowHeight = itemHeight;
}
rows[currentRow].items.append(item);
positionInRow++;
}
rows[currentRow].height = maxRowHeight;
rows[currentRow].top = offsetFromTop;
}
QPair<int, int> VisualGroup::positionOf(const QModelIndex &index) const
{
int y = 0;
for (auto & row: rows)
{
for(auto x = 0; x < row.items.size(); x++)
{
if(row.items[x] == index)
{
return qMakePair(x,y);
}
}
y++;
}
qWarning() << "Item" << index.row() << index.data(Qt::DisplayRole).toString() << "not found in visual group" << text;
return qMakePair(0, 0);
}
int VisualGroup::rowTopOf(const QModelIndex &index) const
{
auto position = positionOf(index);
return rows[position.second].top;
}
int VisualGroup::rowHeightOf(const QModelIndex &index) const
{
auto position = positionOf(index);
return rows[position.second].height;
}
VisualGroup::HitResults VisualGroup::hitScan(const QPoint &pos) const
{
VisualGroup::HitResults results = VisualGroup::NoHit;
int y_start = verticalPosition();
int body_start = y_start + headerHeight();
int body_end = body_start + contentHeight() + 5; // FIXME: wtf is this 5?
int y = pos.y();
// int x = pos.x();
if (y < y_start)
{
results = VisualGroup::NoHit;
}
else if (y < body_start)
{
results = VisualGroup::HeaderHit;
int collapseSize = headerHeight() - 4;
// the icon
QRect iconRect = QRect(view->m_leftMargin + 2, 2 + y_start, collapseSize, collapseSize);
if (iconRect.contains(pos))
{
results |= VisualGroup::CheckboxHit;
}
}
else if (y < body_end)
{
results |= VisualGroup::BodyHit;
}
return results;
}
void VisualGroup::drawHeader(QPainter *painter, const QStyleOptionViewItem &option)
{
painter->setRenderHint(QPainter::Antialiasing);
const QRect optRect = option.rect;
QFont font(QApplication::font());
font.setBold(true);
const QFontMetrics fontMetrics = QFontMetrics(font);
QColor outlineColor = option.palette.text().color();
outlineColor.setAlphaF(0.35);
//BEGIN: top left corner
{
painter->save();
painter->setPen(outlineColor);
const QPointF topLeft(optRect.topLeft());
QRectF arc(topLeft, QSizeF(4, 4));
arc.translate(0.5, 0.5);
painter->drawArc(arc, 1440, 1440);
painter->restore();
}
//END: top left corner
//BEGIN: left vertical line
{
QPoint start(optRect.topLeft());
start.ry() += 3;
QPoint verticalGradBottom(optRect.topLeft());
verticalGradBottom.ry() += fontMetrics.height() + 5;
QLinearGradient gradient(start, verticalGradBottom);
gradient.setColorAt(0, outlineColor);
gradient.setColorAt(1, Qt::transparent);
painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient);
}
//END: left vertical line
//BEGIN: horizontal line
{
QPoint start(optRect.topLeft());
start.rx() += 3;
QPoint horizontalGradTop(optRect.topLeft());
horizontalGradTop.rx() += optRect.width() - 6;
painter->fillRect(QRect(start, QSize(optRect.width() - 6, 1)), outlineColor);
}
//END: horizontal line
//BEGIN: top right corner
{
painter->save();
painter->setPen(outlineColor);
QPointF topRight(optRect.topRight());
topRight.rx() -= 4;
QRectF arc(topRight, QSizeF(4, 4));
arc.translate(0.5, 0.5);
painter->drawArc(arc, 0, 1440);
painter->restore();
}
//END: top right corner
//BEGIN: right vertical line
{
QPoint start(optRect.topRight());
start.ry() += 3;
QPoint verticalGradBottom(optRect.topRight());
verticalGradBottom.ry() += fontMetrics.height() + 5;
QLinearGradient gradient(start, verticalGradBottom);
gradient.setColorAt(0, outlineColor);
gradient.setColorAt(1, Qt::transparent);
painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient);
}
//END: right vertical line
//BEGIN: checkboxy thing
{
painter->save();
painter->setRenderHint(QPainter::Antialiasing, false);
painter->setFont(font);
QColor penColor(option.palette.text().color());
penColor.setAlphaF(0.6);
painter->setPen(penColor);
QRect iconSubRect(option.rect);
iconSubRect.setTop(iconSubRect.top() + 7);
iconSubRect.setLeft(iconSubRect.left() + 7);
int sizing = fontMetrics.height();
int even = ( (sizing - 1) % 2 );
iconSubRect.setHeight(sizing - even);
iconSubRect.setWidth(sizing - even);
painter->drawRect(iconSubRect);
/*
if(collapsed)
painter->drawText(iconSubRect, Qt::AlignHCenter | Qt::AlignVCenter, "+");
else
painter->drawText(iconSubRect, Qt::AlignHCenter | Qt::AlignVCenter, "-");
*/
painter->setBrush(option.palette.text());
painter->fillRect(iconSubRect.x(), iconSubRect.y() + iconSubRect.height() / 2,
iconSubRect.width(), 2, penColor);
if (collapsed)
{
painter->fillRect(iconSubRect.x() + iconSubRect.width() / 2, iconSubRect.y(), 2,
iconSubRect.height(), penColor);
}
painter->restore();
}
//END: checkboxy thing
//BEGIN: text
{
QRect textRect(option.rect);
textRect.setTop(textRect.top() + 7);
textRect.setLeft(textRect.left() + 7 + fontMetrics.height() + 7);
textRect.setHeight(fontMetrics.height());
textRect.setRight(textRect.right() - 7);
painter->save();
painter->setFont(font);
QColor penColor(option.palette.text().color());
penColor.setAlphaF(0.6);
painter->setPen(penColor);
painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, text);
painter->restore();
}
//END: text
}
int VisualGroup::totalHeight() const
{
return headerHeight() + 5 + contentHeight(); // FIXME: wtf is that '5'?
}
int VisualGroup::headerHeight() const
{
QFont font(QApplication::font());
font.setBold(true);
QFontMetrics fontMetrics(font);
const int height = fontMetrics.height() + 1 /* 1 pixel-width gradient */
+ 11 /* top and bottom separation */;
return height;
/*
int raw = view->viewport()->fontMetrics().height() + 4;
// add english. maybe. depends on font height.
if (raw % 2 == 0)
raw++;
return std::min(raw, 25);
*/
}
int VisualGroup::contentHeight() const
{
if (collapsed)
{
return 0;
}
auto last = rows[numRows() - 1];
return last.top + last.height;
}
int VisualGroup::numRows() const
{
return rows.size();
}
int VisualGroup::verticalPosition() const
{
return m_verticalPosition;
}
QList<QModelIndex> VisualGroup::items() const
{
QList<QModelIndex> indices;
for (int i = 0; i < view->model()->rowCount(); ++i)
{
const QModelIndex index = view->model()->index(i, 0);
if (index.data(InstanceViewRoles::GroupRole).toString() == text)
{
indices.append(index);
}
}
return indices;
}

View File

@ -0,0 +1,106 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QString>
#include <QRect>
#include <QVector>
#include <QStyleOption>
class InstanceView;
class QPainter;
class QModelIndex;
struct VisualRow
{
QList<QModelIndex> items;
int height = 0;
int top = 0;
inline int size() const
{
return items.size();
}
inline QModelIndex &operator[](int i)
{
return items[i];
}
};
struct VisualGroup
{
/* constructors */
VisualGroup(const QString &text, InstanceView *view);
VisualGroup(const VisualGroup *other);
/* data */
InstanceView *view = nullptr;
QString text;
bool collapsed = false;
QVector<VisualRow> rows;
int firstItemIndex = 0;
int m_verticalPosition = 0;
/* logic */
/// update the internal list of items and flow them into the rows.
void update();
/// draw the header at y-position.
void drawHeader(QPainter *painter, const QStyleOptionViewItem &option);
/// height of the group, in total. includes a small bit of padding.
int totalHeight() const;
/// height of the group header, in pixels
int headerHeight() const;
/// height of the group content, in pixels
int contentHeight() const;
/// the number of visual rows this group has
int numRows() const;
/// actually calculate the above value
int calculateNumRows() const;
/// the height at which this group starts, in pixels
int verticalPosition() const;
/// relative geometry - top of the row of the given item
int rowTopOf(const QModelIndex &index) const;
/// height of the row of the given item
int rowHeightOf(const QModelIndex &index) const;
/// x/y position of the given item inside the group (in items!)
QPair<int, int> positionOf(const QModelIndex &index) const;
enum HitResult
{
NoHit = 0x0,
TextHit = 0x1,
CheckboxHit = 0x2,
HeaderHit = 0x4,
BodyHit = 0x8
};
Q_DECLARE_FLAGS(HitResults, HitResult)
/// shoot! BANG! what did we hit?
HitResults hitScan (const QPoint &pos) const;
QList<QModelIndex> items() const;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(VisualGroup::HitResults)

View File

@ -0,0 +1,62 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PageDialog.h"
#include <QDialogButtonBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QKeyEvent>
#include "Application.h"
#include "settings/SettingsObject.h"
#include "ui/widgets/IconLabel.h"
#include "ui/widgets/PageContainer.h"
PageDialog::PageDialog(BasePageProvider *pageProvider, QString defaultId, QWidget *parent)
: QDialog(parent)
{
setWindowTitle(pageProvider->dialogTitle());
m_container = new PageContainer(pageProvider, defaultId, this);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(m_container);
mainLayout->setSpacing(0);
mainLayout->setContentsMargins(0, 0, 0, 0);
setLayout(mainLayout);
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Help | QDialogButtonBox::Close);
buttons->button(QDialogButtonBox::Close)->setDefault(true);
buttons->setContentsMargins(6, 0, 6, 0);
m_container->addButtons(buttons);
connect(buttons->button(QDialogButtonBox::Close), SIGNAL(clicked()), this, SLOT(close()));
connect(buttons->button(QDialogButtonBox::Help), SIGNAL(clicked()), m_container, SLOT(help()));
restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("PagedGeometry").toByteArray()));
}
void PageDialog::closeEvent(QCloseEvent *event)
{
qDebug() << "Paged dialog close requested";
if (m_container->prepareToClose())
{
qDebug() << "Paged dialog close approved";
APPLICATION->settings()->set("PagedGeometry", saveGeometry().toBase64());
qDebug() << "Paged dialog geometry saved";
QDialog::closeEvent(event);
}
}

View File

@ -0,0 +1,35 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QDialog>
#include "ui/pages/BasePageProvider.h"
class PageContainer;
class PageDialog : public QDialog
{
Q_OBJECT
public:
explicit PageDialog(BasePageProvider *pageProvider, QString defaultId = QString(), QWidget *parent = 0);
virtual ~PageDialog() {}
private
slots:
virtual void closeEvent(QCloseEvent *event);
private:
PageContainer * m_container;
};

View File

@ -0,0 +1,58 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QString>
#include <QIcon>
#include <memory>
#include "BasePageContainer.h"
class BasePage
{
public:
virtual ~BasePage() {}
virtual QString id() const = 0;
virtual QString displayName() const = 0;
virtual QIcon icon() const = 0;
virtual bool apply() { return true; }
virtual bool shouldDisplay() const { return true; }
virtual QString helpPage() const { return QString(); }
void opened()
{
isOpened = true;
openedImpl();
}
void closed()
{
isOpened = false;
closedImpl();
}
virtual void openedImpl() {}
virtual void closedImpl() {}
virtual void setParentContainer(BasePageContainer * container)
{
m_container = container;
};
public:
int stackIndex = -1;
int listIndex = -1;
protected:
BasePageContainer * m_container = nullptr;
bool isOpened = false;
};
typedef std::shared_ptr<BasePage> BasePagePtr;

View File

@ -0,0 +1,10 @@
#pragma once
class BasePageContainer
{
public:
virtual ~BasePageContainer(){};
virtual bool selectPage(QString pageId) = 0;
virtual void refreshContainer() = 0;
virtual bool requestClose() = 0;
};

View File

@ -0,0 +1,68 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "ui/pages/BasePage.h"
#include <memory>
#include <functional>
class BasePageProvider
{
public:
virtual QList<BasePage *> getPages() = 0;
virtual QString dialogTitle() = 0;
};
class GenericPageProvider : public BasePageProvider
{
typedef std::function<BasePage *()> PageCreator;
public:
explicit GenericPageProvider(const QString &dialogTitle)
: m_dialogTitle(dialogTitle)
{
}
virtual ~GenericPageProvider() {}
QList<BasePage *> getPages() override
{
QList<BasePage *> pages;
for (PageCreator creator : m_creators)
{
pages.append(creator());
}
return pages;
}
QString dialogTitle() override { return m_dialogTitle; }
void setDialogTitle(const QString &title)
{
m_dialogTitle = title;
}
void addPageCreator(PageCreator page)
{
m_creators.append(page);
}
template<typename PageClass>
void addPage()
{
addPageCreator([](){return new PageClass();});
}
private:
QList<PageCreator> m_creators;
QString m_dialogTitle;
};

View File

@ -0,0 +1,260 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AccountListPage.h"
#include "ui_AccountListPage.h"
#include <QItemSelectionModel>
#include <QMenu>
#include <QDebug>
#include "net/NetJob.h"
#include "ui/dialogs/ProgressDialog.h"
#include "ui/dialogs/LoginDialog.h"
#include "ui/dialogs/MSALoginDialog.h"
#include "ui/dialogs/CustomMessageBox.h"
#include "ui/dialogs/SkinUploadDialog.h"
#include "tasks/Task.h"
#include "minecraft/auth/AccountTask.h"
#include "minecraft/services/SkinDelete.h"
#include "Application.h"
#include "BuildConfig.h"
#include "Secrets.h"
AccountListPage::AccountListPage(QWidget *parent)
: QMainWindow(parent), ui(new Ui::AccountListPage)
{
ui->setupUi(this);
ui->listView->setEmptyString(tr(
"Welcome!\n"
"If you're new here, you can click the \"Add\" button to add your Mojang or Minecraft account."
));
ui->listView->setEmptyMode(VersionListView::String);
ui->listView->setContextMenuPolicy(Qt::CustomContextMenu);
m_accounts = APPLICATION->accounts();
ui->listView->setModel(m_accounts.get());
ui->listView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
ui->listView->header()->setSectionResizeMode(1, QHeaderView::Stretch);
ui->listView->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
ui->listView->setSelectionMode(QAbstractItemView::SingleSelection);
// Expand the account column
QItemSelectionModel *selectionModel = ui->listView->selectionModel();
connect(selectionModel, &QItemSelectionModel::selectionChanged, [this](const QItemSelection &sel, const QItemSelection &dsel) {
updateButtonStates();
});
connect(ui->listView, &VersionListView::customContextMenuRequested, this, &AccountListPage::ShowContextMenu);
connect(m_accounts.get(), &AccountList::listChanged, this, &AccountListPage::listChanged);
connect(m_accounts.get(), &AccountList::listActivityChanged, this, &AccountListPage::listChanged);
connect(m_accounts.get(), &AccountList::defaultAccountChanged, this, &AccountListPage::listChanged);
updateButtonStates();
// Xbox authentication won't work without a client identifier, so disable the button if it is missing
ui->actionAddMicrosoft->setVisible(Secrets::hasMSAClientID());
}
AccountListPage::~AccountListPage()
{
delete ui;
}
void AccountListPage::ShowContextMenu(const QPoint& pos)
{
auto menu = ui->toolBar->createContextMenu(this, tr("Context menu"));
menu->exec(ui->listView->mapToGlobal(pos));
delete menu;
}
void AccountListPage::changeEvent(QEvent* event)
{
if (event->type() == QEvent::LanguageChange)
{
ui->retranslateUi(this);
}
QMainWindow::changeEvent(event);
}
QMenu * AccountListPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction(ui->toolBar->toggleViewAction() );
return filteredMenu;
}
void AccountListPage::listChanged()
{
updateButtonStates();
}
void AccountListPage::on_actionAddMojang_triggered()
{
MinecraftAccountPtr account = LoginDialog::newAccount(
this,
tr("Please enter your Mojang account email and password to add your account.")
);
if (account)
{
m_accounts->addAccount(account);
if (m_accounts->count() == 1) {
m_accounts->setDefaultAccount(account);
}
}
}
void AccountListPage::on_actionAddMicrosoft_triggered()
{
if(BuildConfig.BUILD_PLATFORM == "osx64") {
CustomMessageBox::selectable(
this,
tr("Microsoft Accounts not available"),
tr(
"Microsoft accounts are only usable on macOS 10.13 or newer, with fully updated MultiMC.\n\n"
"Please update both your operating system and MultiMC."
),
QMessageBox::Warning
)->exec();
return;
}
MinecraftAccountPtr account = MSALoginDialog::newAccount(
this,
tr("Please enter your Mojang account email and password to add your account.")
);
if (account)
{
m_accounts->addAccount(account);
if (m_accounts->count() == 1) {
m_accounts->setDefaultAccount(account);
}
}
}
void AccountListPage::on_actionRemove_triggered()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0)
{
QModelIndex selected = selection.first();
m_accounts->removeAccount(selected);
}
}
void AccountListPage::on_actionRefresh_triggered() {
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0) {
QModelIndex selected = selection.first();
MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>();
AuthSessionPtr session = std::make_shared<AuthSession>();
auto task = account->refresh(session);
if (task) {
ProgressDialog progDialog(this);
progDialog.execWithTask(task.get());
// TODO: respond to results of the task
}
}
}
void AccountListPage::on_actionSetDefault_triggered()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0)
{
QModelIndex selected = selection.first();
MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>();
m_accounts->setDefaultAccount(account);
}
}
void AccountListPage::on_actionNoDefault_triggered()
{
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);
if(m_accounts->defaultAccount().get() == nullptr) {
ui->actionNoDefault->setEnabled(false);
ui->actionNoDefault->setChecked(true);
}
else {
ui->actionNoDefault->setEnabled(true);
ui->actionNoDefault->setChecked(false);
}
}
void AccountListPage::on_actionUploadSkin_triggered()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() > 0)
{
QModelIndex selected = selection.first();
MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>();
SkinUploadDialog dialog(account, this);
dialog.exec();
}
}
void AccountListPage::on_actionDeleteSkin_triggered()
{
QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes();
if (selection.size() <= 0)
return;
QModelIndex selected = selection.first();
AuthSessionPtr session = std::make_shared<AuthSession>();
MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>();
auto login = account->refresh(session);
ProgressDialog prog(this);
if (prog.execWithTask((Task*)login.get()) != QDialog::Accepted) {
CustomMessageBox::selectable(this, tr("Skin Delete"), tr("Failed to login!"), QMessageBox::Warning)->exec();
return;
}
auto deleteSkinTask = std::make_shared<SkinDelete>(this, session);
if (prog.execWithTask((Task*)deleteSkinTask.get()) != QDialog::Accepted) {
CustomMessageBox::selectable(this, tr("Skin Delete"), tr("Failed to delete current skin!"), QMessageBox::Warning)->exec();
return;
}
}

View File

@ -0,0 +1,85 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QMainWindow>
#include <memory>
#include "ui/pages/BasePage.h"
#include "minecraft/auth/AccountList.h"
#include "Application.h"
namespace Ui
{
class AccountListPage;
}
class AuthenticateTask;
class AccountListPage : public QMainWindow, public BasePage
{
Q_OBJECT
public:
explicit AccountListPage(QWidget *parent = 0);
~AccountListPage();
QString displayName() const override
{
return tr("Accounts");
}
QIcon icon() const override
{
auto icon = APPLICATION->getThemedIcon("accounts");
if(icon.isNull())
{
icon = APPLICATION->getThemedIcon("noaccount");
}
return icon;
}
QString id() const override
{
return "accounts";
}
QString helpPage() const override
{
return "Getting-Started#adding-an-account";
}
public slots:
void on_actionAddMojang_triggered();
void on_actionAddMicrosoft_triggered();
void on_actionRemove_triggered();
void on_actionRefresh_triggered();
void on_actionSetDefault_triggered();
void on_actionNoDefault_triggered();
void on_actionUploadSkin_triggered();
void on_actionDeleteSkin_triggered();
void listChanged();
//! Updates the states of the dialog's buttons.
void updateButtonStates();
protected slots:
void ShowContextMenu(const QPoint &pos);
private:
void changeEvent(QEvent * event) override;
QMenu * createPopupMenu() override;
shared_qobject_ptr<AccountList> m_accounts;
Ui::AccountListPage *ui;
};

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AccountListPage</class>
<widget class="QMainWindow" name="AccountListPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="VersionListView" name="listView">
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="allColumnsShowFocus">
<bool>true</bool>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
</attribute>
</widget>
</item>
</layout>
</widget>
<widget class="WideBar" name="toolBar">
<attribute name="toolBarArea">
<enum>RightToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actionAddMicrosoft"/>
<addaction name="actionAddMojang"/>
<addaction name="actionRefresh"/>
<addaction name="actionRemove"/>
<addaction name="actionSetDefault"/>
<addaction name="actionNoDefault"/>
<addaction name="separator"/>
<addaction name="actionUploadSkin"/>
<addaction name="actionDeleteSkin"/>
</widget>
<action name="actionAddMojang">
<property name="text">
<string>Add Mojang</string>
</property>
</action>
<action name="actionRemove">
<property name="text">
<string>Remove</string>
</property>
</action>
<action name="actionSetDefault">
<property name="text">
<string>Set Default</string>
</property>
</action>
<action name="actionNoDefault">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>No Default</string>
</property>
</action>
<action name="actionUploadSkin">
<property name="text">
<string>Upload Skin</string>
</property>
</action>
<action name="actionDeleteSkin">
<property name="text">
<string>Delete Skin</string>
</property>
<property name="toolTip">
<string>Delete the currently active skin and go back to the default one</string>
</property>
</action>
<action name="actionAddMicrosoft">
<property name="text">
<string>Add Microsoft</string>
</property>
</action>
<action name="actionRefresh">
<property name="text">
<string>Refresh</string>
</property>
<property name="toolTip">
<string>Refresh the account tokens</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>VersionListView</class>
<extends>QTreeView</extends>
<header>ui/widgets/VersionListView.h</header>
</customwidget>
<customwidget>
<class>WideBar</class>
<extends>QToolBar</extends>
<header>ui/widgets/WideBar.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,51 @@
#include "CustomCommandsPage.h"
#include <QVBoxLayout>
#include <QTabWidget>
#include <QTabBar>
CustomCommandsPage::CustomCommandsPage(QWidget* parent): QWidget(parent)
{
auto verticalLayout = new QVBoxLayout(this);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
auto tabWidget = new QTabWidget(this);
tabWidget->setObjectName(QStringLiteral("tabWidget"));
commands = new CustomCommands(this);
commands->setContentsMargins(6, 6, 6, 6);
tabWidget->addTab(commands, "Foo");
tabWidget->tabBar()->hide();
verticalLayout->addWidget(tabWidget);
loadSettings();
}
CustomCommandsPage::~CustomCommandsPage()
{
}
bool CustomCommandsPage::apply()
{
applySettings();
return true;
}
void CustomCommandsPage::applySettings()
{
auto s = APPLICATION->settings();
s->set("PreLaunchCommand", commands->prelaunchCommand());
s->set("WrapperCommand", commands->wrapperCommand());
s->set("PostExitCommand", commands->postexitCommand());
}
void CustomCommandsPage::loadSettings()
{
auto s = APPLICATION->settings();
commands->initialize(
false,
true,
s->get("PreLaunchCommand").toString(),
s->get("WrapperCommand").toString(),
s->get("PostExitCommand").toString()
);
}

View File

@ -0,0 +1,55 @@
/* Copyright 2018-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QDialog>
#include "ui/pages/BasePage.h"
#include <Application.h>
#include "ui/widgets/CustomCommands.h"
class CustomCommandsPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit CustomCommandsPage(QWidget *parent = 0);
~CustomCommandsPage();
QString displayName() const override
{
return tr("Custom Commands");
}
QIcon icon() const override
{
return APPLICATION->getThemedIcon("custom-commands");
}
QString id() const override
{
return "custom-commands";
}
QString helpPage() const override
{
return "Custom-commands";
}
bool apply() override;
private:
void applySettings();
void loadSettings();
CustomCommands * commands;
};

View File

@ -0,0 +1,233 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ExternalToolsPage.h"
#include "ui_ExternalToolsPage.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QStandardPaths>
#include <QTabBar>
#include "settings/SettingsObject.h"
#include "tools/BaseProfiler.h"
#include <FileSystem.h>
#include "Application.h"
#include <tools/MCEditTool.h>
ExternalToolsPage::ExternalToolsPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::ExternalToolsPage)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();
#if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
ui->jsonEditorTextBox->setClearButtonEnabled(true);
#endif
ui->mceditLink->setOpenExternalLinks(true);
ui->jvisualvmLink->setOpenExternalLinks(true);
ui->jprofilerLink->setOpenExternalLinks(true);
loadSettings();
}
ExternalToolsPage::~ExternalToolsPage()
{
delete ui;
}
void ExternalToolsPage::loadSettings()
{
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());
// Editors
ui->jsonEditorTextBox->setText(s->get("JsonEditor").toString());
}
void ExternalToolsPage::applySettings()
{
auto s = APPLICATION->settings();
s->set("JProfilerPath", ui->jprofilerPathEdit->text());
s->set("JVisualVMPath", ui->jvisualvmPathEdit->text());
s->set("MCEditPath", ui->mceditPathEdit->text());
// Editors
QString jsonEditor = ui->jsonEditorTextBox->text();
if (!jsonEditor.isEmpty() &&
(!QFileInfo(jsonEditor).exists() || !QFileInfo(jsonEditor).isExecutable()))
{
QString found = QStandardPaths::findExecutable(jsonEditor);
if (!found.isEmpty())
{
jsonEditor = found;
}
}
s->set("JsonEditor", jsonEditor);
}
void ExternalToolsPage::on_jprofilerPathBtn_clicked()
{
QString raw_dir = ui->jprofilerPathEdit->text();
QString error;
do
{
raw_dir = QFileDialog::getExistingDirectory(this, tr("JProfiler Folder"), raw_dir);
if (raw_dir.isEmpty())
{
break;
}
QString cooked_dir = FS::NormalizePath(raw_dir);
if (!APPLICATION->profilers()["jprofiler"]->check(cooked_dir, &error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking JProfiler install:\n%1").arg(error));
continue;
}
else
{
ui->jprofilerPathEdit->setText(cooked_dir);
break;
}
} while (1);
}
void ExternalToolsPage::on_jprofilerCheckBtn_clicked()
{
QString 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));
}
else
{
QMessageBox::information(this, tr("OK"), tr("JProfiler setup seems to be OK"));
}
}
void ExternalToolsPage::on_jvisualvmPathBtn_clicked()
{
QString raw_dir = ui->jvisualvmPathEdit->text();
QString error;
do
{
raw_dir = QFileDialog::getOpenFileName(this, tr("JVisualVM Executable"), raw_dir);
if (raw_dir.isEmpty())
{
break;
}
QString cooked_dir = FS::NormalizePath(raw_dir);
if (!APPLICATION->profilers()["jvisualvm"]->check(cooked_dir, &error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking JVisualVM install:\n%1").arg(error));
continue;
}
else
{
ui->jvisualvmPathEdit->setText(cooked_dir);
break;
}
} while (1);
}
void ExternalToolsPage::on_jvisualvmCheckBtn_clicked()
{
QString 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));
}
else
{
QMessageBox::information(this, tr("OK"), tr("JVisualVM setup seems to be OK"));
}
}
void ExternalToolsPage::on_mceditPathBtn_clicked()
{
QString raw_dir = ui->mceditPathEdit->text();
QString error;
do
{
#ifdef Q_OS_OSX
raw_dir = QFileDialog::getOpenFileName(this, tr("MCEdit Application"), raw_dir);
#else
raw_dir = QFileDialog::getExistingDirectory(this, tr("MCEdit Folder"), raw_dir);
#endif
if (raw_dir.isEmpty())
{
break;
}
QString cooked_dir = FS::NormalizePath(raw_dir);
if (!APPLICATION->mcedit()->check(cooked_dir, error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking MCEdit install:\n%1").arg(error));
continue;
}
else
{
ui->mceditPathEdit->setText(cooked_dir);
break;
}
} while (1);
}
void ExternalToolsPage::on_mceditCheckBtn_clicked()
{
QString error;
if (!APPLICATION->mcedit()->check(ui->mceditPathEdit->text(), error))
{
QMessageBox::critical(this, tr("Error"), tr("Error while checking MCEdit install:\n%1").arg(error));
}
else
{
QMessageBox::information(this, tr("OK"), tr("MCEdit setup seems to be OK"));
}
}
void ExternalToolsPage::on_jsonEditorBrowseBtn_clicked()
{
QString raw_file = QFileDialog::getOpenFileName(
this, tr("JSON Editor"),
ui->jsonEditorTextBox->text().isEmpty()
#if defined(Q_OS_LINUX)
? QString("/usr/bin")
#else
? QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation).first()
#endif
: ui->jsonEditorTextBox->text());
if (raw_file.isEmpty())
{
return;
}
QString cooked_file = FS::NormalizePath(raw_file);
// it has to exist and be an executable
if (QFileInfo(cooked_file).exists() && QFileInfo(cooked_file).isExecutable())
{
ui->jsonEditorTextBox->setText(cooked_file);
}
else
{
QMessageBox::warning(this, tr("Invalid"),
tr("The file chosen does not seem to be an executable"));
}
}
bool ExternalToolsPage::apply()
{
applySettings();
return true;
}

View File

@ -0,0 +1,74 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QWidget>
#include "ui/pages/BasePage.h"
#include <Application.h>
namespace Ui {
class ExternalToolsPage;
}
class ExternalToolsPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit ExternalToolsPage(QWidget *parent = 0);
~ExternalToolsPage();
QString displayName() const override
{
return tr("External Tools");
}
QIcon icon() const override
{
auto icon = APPLICATION->getThemedIcon("externaltools");
if(icon.isNull())
{
icon = APPLICATION->getThemedIcon("loadermods");
}
return icon;
}
QString id() const override
{
return "external-tools";
}
QString helpPage() const override
{
return "Tools";
}
virtual bool apply() override;
private:
void loadSettings();
void applySettings();
private:
Ui::ExternalToolsPage *ui;
private
slots:
void on_jprofilerPathBtn_clicked();
void on_jprofilerCheckBtn_clicked();
void on_jvisualvmPathBtn_clicked();
void on_jvisualvmCheckBtn_clicked();
void on_mceditPathBtn_clicked();
void on_mceditCheckBtn_clicked();
void on_jsonEditorBrowseBtn_clicked();
};

View File

@ -0,0 +1,194 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExternalToolsPage</class>
<widget class="QWidget" name="ExternalToolsPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>673</width>
<height>751</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string notr="true">JProfiler</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_10">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLineEdit" name="jprofilerPathEdit"/>
</item>
<item>
<widget class="QPushButton" name="jprofilerPathBtn">
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPushButton" name="jprofilerCheckBtn">
<property name="text">
<string>Check</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="jprofilerLink">
<property name="text">
<string notr="true">&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;https://www.ej-technologies.com/products/jprofiler/overview.html&quot;&gt;https://www.ej-technologies.com/products/jprofiler/overview.html&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_3">
<property name="title">
<string notr="true">JVisualVM</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_11">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QLineEdit" name="jvisualvmPathEdit"/>
</item>
<item>
<widget class="QPushButton" name="jvisualvmPathBtn">
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPushButton" name="jvisualvmCheckBtn">
<property name="text">
<string>Check</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="jvisualvmLink">
<property name="text">
<string notr="true">&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;https://visualvm.github.io/&quot;&gt;https://visualvm.github.io/&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_4">
<property name="title">
<string notr="true">MCEdit</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_12">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QLineEdit" name="mceditPathEdit"/>
</item>
<item>
<widget class="QPushButton" name="mceditPathBtn">
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPushButton" name="mceditCheckBtn">
<property name="text">
<string>Check</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="mceditLink">
<property name="text">
<string notr="true">&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;https://www.mcedit.net/&quot;&gt;https://www.mcedit.net/&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="editorsBox">
<property name="title">
<string>External Editors (leave empty for system default)</string>
</property>
<layout class="QGridLayout" name="foldersBoxLayout_2">
<item row="0" column="1">
<widget class="QLineEdit" name="jsonEditorTextBox"/>
</item>
<item row="0" column="0">
<widget class="QLabel" name="labelJsonEditor">
<property name="text">
<string>Text Editor:</string>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QToolButton" name="jsonEditorBrowseBtn">
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>216</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,153 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "JavaPage.h"
#include "JavaCommon.h"
#include "ui_JavaPage.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDir>
#include <QTabBar>
#include "ui/dialogs/VersionSelectDialog.h"
#include "java/JavaUtils.h"
#include "java/JavaInstallList.h"
#include "settings/SettingsObject.h"
#include <FileSystem.h>
#include "Application.h"
#include <sys.h>
JavaPage::JavaPage(QWidget *parent) : QWidget(parent), ui(new Ui::JavaPage)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();
auto sysMiB = Sys::getSystemRam() / Sys::mebibyte;
ui->maxMemSpinBox->setMaximum(sysMiB);
loadSettings();
}
JavaPage::~JavaPage()
{
delete ui;
}
bool JavaPage::apply()
{
applySettings();
return true;
}
void JavaPage::applySettings()
{
auto s = APPLICATION->settings();
// Memory
int min = ui->minMemSpinBox->value();
int max = ui->maxMemSpinBox->value();
if(min < max)
{
s->set("MinMemAlloc", min);
s->set("MaxMemAlloc", max);
}
else
{
s->set("MinMemAlloc", max);
s->set("MaxMemAlloc", min);
}
s->set("PermGen", ui->permGenSpinBox->value());
// Java Settings
s->set("JavaPath", ui->javaPathTextBox->text());
s->set("JvmArgs", ui->jvmArgsTextBox->text());
JavaCommon::checkJVMArgs(s->get("JvmArgs").toString(), this->parentWidget());
}
void JavaPage::loadSettings()
{
auto s = APPLICATION->settings();
// Memory
int min = s->get("MinMemAlloc").toInt();
int max = s->get("MaxMemAlloc").toInt();
if(min < max)
{
ui->minMemSpinBox->setValue(min);
ui->maxMemSpinBox->setValue(max);
}
else
{
ui->minMemSpinBox->setValue(max);
ui->maxMemSpinBox->setValue(min);
}
ui->permGenSpinBox->setValue(s->get("PermGen").toInt());
// Java Settings
ui->javaPathTextBox->setText(s->get("JavaPath").toString());
ui->jvmArgsTextBox->setText(s->get("JvmArgs").toString());
}
void JavaPage::on_javaDetectBtn_clicked()
{
JavaInstallPtr java;
VersionSelectDialog vselect(APPLICATION->javalist().get(), tr("Select a Java version"), this, true);
vselect.setResizeOn(2);
vselect.exec();
if (vselect.result() == QDialog::Accepted && vselect.selectedVersion())
{
java = std::dynamic_pointer_cast<JavaInstall>(vselect.selectedVersion());
ui->javaPathTextBox->setText(java->path);
}
}
void JavaPage::on_javaBrowseBtn_clicked()
{
QString raw_path = QFileDialog::getOpenFileName(this, tr("Find Java executable"));
// do not allow current dir - it's dirty. Do not allow dirs that don't exist
if(raw_path.isEmpty())
{
return;
}
QString cooked_path = FS::NormalizePath(raw_path);
QFileInfo javaInfo(cooked_path);;
if(!javaInfo.exists() || !javaInfo.isExecutable())
{
return;
}
ui->javaPathTextBox->setText(cooked_path);
}
void JavaPage::on_javaTestBtn_clicked()
{
if(checker)
{
return;
}
checker.reset(new JavaCommon::TestCheck(
this, ui->javaPathTextBox->text(), ui->jvmArgsTextBox->text(),
ui->minMemSpinBox->value(), ui->maxMemSpinBox->value(), ui->permGenSpinBox->value()));
connect(checker.get(), SIGNAL(finished()), SLOT(checkerFinished()));
checker->run();
}
void JavaPage::checkerFinished()
{
checker.reset();
}

View File

@ -0,0 +1,72 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QDialog>
#include "ui/pages/BasePage.h"
#include "JavaCommon.h"
#include <Application.h>
#include <QObjectPtr.h>
class SettingsObject;
namespace Ui
{
class JavaPage;
}
class JavaPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit JavaPage(QWidget *parent = 0);
~JavaPage();
QString displayName() const override
{
return tr("Java");
}
QIcon icon() const override
{
return APPLICATION->getThemedIcon("java");
}
QString id() const override
{
return "java-settings";
}
QString helpPage() const override
{
return "Java-settings";
}
bool apply() override;
private:
void applySettings();
void loadSettings();
private
slots:
void on_javaDetectBtn_clicked();
void on_javaTestBtn_clicked();
void on_javaBrowseBtn_clicked();
void checkerFinished();
private:
Ui::JavaPage *ui;
unique_qobject_ptr<JavaCommon::TestCheck> checker;
};

View File

@ -0,0 +1,260 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>JavaPage</class>
<widget class="QWidget" name="JavaPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>545</width>
<height>580</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QGroupBox" name="memoryGroupBox">
<property name="title">
<string>Memory</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="1" column="1">
<widget class="QSpinBox" name="maxMemSpinBox">
<property name="toolTip">
<string>The maximum amount of memory Minecraft is allowed to use.</string>
</property>
<property name="suffix">
<string notr="true"> MiB</string>
</property>
<property name="minimum">
<number>128</number>
</property>
<property name="maximum">
<number>65536</number>
</property>
<property name="singleStep">
<number>128</number>
</property>
<property name="value">
<number>1024</number>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="labelMinMem">
<property name="text">
<string>Minimum memory allocation:</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelMaxMem">
<property name="text">
<string>Maximum memory allocation:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="minMemSpinBox">
<property name="toolTip">
<string>The amount of memory Minecraft is started with.</string>
</property>
<property name="suffix">
<string notr="true"> MiB</string>
</property>
<property name="minimum">
<number>128</number>
</property>
<property name="maximum">
<number>65536</number>
</property>
<property name="singleStep">
<number>128</number>
</property>
<property name="value">
<number>256</number>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelPermGen">
<property name="text">
<string notr="true">PermGen:</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QSpinBox" name="permGenSpinBox">
<property name="toolTip">
<string>The amount of memory available to store loaded Java classes.</string>
</property>
<property name="suffix">
<string notr="true"> MiB</string>
</property>
<property name="minimum">
<number>64</number>
</property>
<property name="maximum">
<number>999999999</number>
</property>
<property name="singleStep">
<number>8</number>
</property>
<property name="value">
<number>64</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="javaSettingsGroupBox">
<property name="title">
<string>Java Runtime</string>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QLabel" name="labelJavaPath">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Java path:</string>
</property>
</widget>
</item>
<item row="0" column="1" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLineEdit" name="javaPathTextBox"/>
</item>
<item>
<widget class="QPushButton" name="javaBrowseBtn">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>28</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="2" column="1" colspan="2">
<widget class="QLineEdit" name="jvmArgsTextBox"/>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelJVMArgs">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>JVM arguments:</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QPushButton" name="javaDetectBtn">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Auto-detect...</string>
</property>
</widget>
</item>
<item row="3" column="2">
<widget class="QPushButton" name="javaTestBtn">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Test</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>minMemSpinBox</tabstop>
<tabstop>maxMemSpinBox</tabstop>
<tabstop>permGenSpinBox</tabstop>
<tabstop>javaBrowseBtn</tabstop>
<tabstop>javaPathTextBox</tabstop>
<tabstop>jvmArgsTextBox</tabstop>
<tabstop>javaDetectBtn</tabstop>
<tabstop>javaTestBtn</tabstop>
<tabstop>tabWidget</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,51 @@
#include "LanguagePage.h"
#include "ui/widgets/LanguageSelectionWidget.h"
#include <QVBoxLayout>
LanguagePage::LanguagePage(QWidget* parent) :
QWidget(parent)
{
setObjectName(QStringLiteral("languagePage"));
auto layout = new QVBoxLayout(this);
mainWidget = new LanguageSelectionWidget(this);
layout->setContentsMargins(0,0,0,0);
layout->addWidget(mainWidget);
retranslate();
}
LanguagePage::~LanguagePage()
{
}
bool LanguagePage::apply()
{
applySettings();
return true;
}
void LanguagePage::applySettings()
{
auto settings = APPLICATION->settings();
QString key = mainWidget->getSelectedLanguageKey();
settings->set("Language", key);
}
void LanguagePage::loadSettings()
{
// NIL
}
void LanguagePage::retranslate()
{
mainWidget->retranslate();
}
void LanguagePage::changeEvent(QEvent* event)
{
if (event->type() == QEvent::LanguageChange)
{
retranslate();
}
QWidget::changeEvent(event);
}

View File

@ -0,0 +1,60 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include "ui/pages/BasePage.h"
#include <Application.h>
#include <QWidget>
class LanguageSelectionWidget;
class LanguagePage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit LanguagePage(QWidget *parent = 0);
virtual ~LanguagePage();
QString displayName() const override
{
return tr("Language");
}
QIcon icon() const override
{
return APPLICATION->getThemedIcon("language");
}
QString id() const override
{
return "language-settings";
}
QString helpPage() const override
{
return "Language-settings";
}
bool apply() override;
void changeEvent(QEvent * ) override;
private:
void applySettings();
void loadSettings();
void retranslate();
private:
LanguageSelectionWidget *mainWidget;
};

View File

@ -0,0 +1,466 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "LauncherPage.h"
#include "ui_LauncherPage.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDir>
#include <QTextCharFormat>
#include "updater/UpdateChecker.h"
#include "settings/SettingsObject.h"
#include <FileSystem.h>
#include "Application.h"
#include "BuildConfig.h"
#include "ui/themes/ITheme.h"
#include <QApplication>
#include <QProcess>
// FIXME: possibly move elsewhere
enum InstSortMode
{
// Sort alphabetically by name.
Sort_Name,
// Sort by which instance was launched most recently.
Sort_LastLaunch
};
LauncherPage::LauncherPage(QWidget *parent) : QWidget(parent), ui(new Ui::LauncherPage)
{
ui->setupUi(this);
auto origForeground = ui->fontPreview->palette().color(ui->fontPreview->foregroundRole());
auto origBackground = ui->fontPreview->palette().color(ui->fontPreview->backgroundRole());
m_colors.reset(new LogColorCache(origForeground, origBackground));
ui->sortingModeGroup->setId(ui->sortByNameBtn, Sort_Name);
ui->sortingModeGroup->setId(ui->sortLastLaunchedBtn, Sort_LastLaunch);
defaultFormat = new QTextCharFormat(ui->fontPreview->currentCharFormat());
m_languageModel = APPLICATION->translations();
loadSettings();
if(BuildConfig.UPDATER_ENABLED)
{
QObject::connect(APPLICATION->updateChecker().get(), &UpdateChecker::channelListLoaded, this, &LauncherPage::refreshUpdateChannelList);
if (APPLICATION->updateChecker()->hasChannels())
{
refreshUpdateChannelList();
}
else
{
APPLICATION->updateChecker()->updateChanList(false);
}
}
else
{
ui->updateSettingsBox->setHidden(true);
}
// Analytics
if(BuildConfig.ANALYTICS_ID.isEmpty())
{
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->analyticsTab));
}
connect(ui->fontSizeBox, SIGNAL(valueChanged(int)), SLOT(refreshFontPreview()));
connect(ui->consoleFont, SIGNAL(currentFontChanged(QFont)), SLOT(refreshFontPreview()));
//move mac data button
QFile file(QDir::current().absolutePath() + "/dontmovemacdata");
if (!file.exists())
{
ui->migrateDataFolderMacBtn->setVisible(false);
}
}
LauncherPage::~LauncherPage()
{
delete ui;
delete defaultFormat;
}
bool LauncherPage::apply()
{
applySettings();
return true;
}
void LauncherPage::on_instDirBrowseBtn_clicked()
{
QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Instance Folder"), ui->instDirTextBox->text());
// do not allow current dir - it's dirty. Do not allow dirs that don't exist
if (!raw_dir.isEmpty() && QDir(raw_dir).exists())
{
QString cooked_dir = FS::NormalizePath(raw_dir);
if (FS::checkProblemticPathJava(QDir(cooked_dir)))
{
QMessageBox warning;
warning.setText(tr("You're trying to specify an instance folder which\'s path "
"contains at least one \'!\'. "
"Java is known to cause problems if that is the case, your "
"instances (probably) won't start!"));
warning.setInformativeText(
tr("Do you really want to use this path? "
"Selecting \"No\" will close this and not alter your instance path."));
warning.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
int result = warning.exec();
if (result == QMessageBox::Yes)
{
ui->instDirTextBox->setText(cooked_dir);
}
}
else
{
ui->instDirTextBox->setText(cooked_dir);
}
}
}
void LauncherPage::on_iconsDirBrowseBtn_clicked()
{
QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Icons Folder"), ui->iconsDirTextBox->text());
// do not allow current dir - it's dirty. Do not allow dirs that don't exist
if (!raw_dir.isEmpty() && QDir(raw_dir).exists())
{
QString cooked_dir = FS::NormalizePath(raw_dir);
ui->iconsDirTextBox->setText(cooked_dir);
}
}
void LauncherPage::on_modsDirBrowseBtn_clicked()
{
QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Mods Folder"), ui->modsDirTextBox->text());
// do not allow current dir - it's dirty. Do not allow dirs that don't exist
if (!raw_dir.isEmpty() && QDir(raw_dir).exists())
{
QString cooked_dir = FS::NormalizePath(raw_dir);
ui->modsDirTextBox->setText(cooked_dir);
}
}
void LauncherPage::on_migrateDataFolderMacBtn_clicked()
{
QFile file(QDir::current().absolutePath() + "/dontmovemacdata");
file.remove();
QProcess::startDetached(qApp->arguments()[0]);
qApp->quit();
}
void LauncherPage::refreshUpdateChannelList()
{
// Stop listening for selection changes. It's going to change a lot while we update it and
// we don't need to update the
// description label constantly.
QObject::disconnect(ui->updateChannelComboBox, SIGNAL(currentIndexChanged(int)), this,
SLOT(updateChannelSelectionChanged(int)));
QList<UpdateChecker::ChannelListEntry> channelList = APPLICATION->updateChecker()->getChannelList();
ui->updateChannelComboBox->clear();
int selection = -1;
for (int i = 0; i < channelList.count(); i++)
{
UpdateChecker::ChannelListEntry entry = channelList.at(i);
// When it comes to selection, we'll rely on the indexes of a channel entry being the
// same in the
// combo box as it is in the update checker's channel list.
// This probably isn't very safe, but the channel list doesn't change often enough (or
// at all) for
// this to be a big deal. Hope it doesn't break...
ui->updateChannelComboBox->addItem(entry.name);
// If the update channel we just added was the selected one, set the current index in
// the combo box to it.
if (entry.id == m_currentUpdateChannel)
{
qDebug() << "Selected index" << i << "channel id" << m_currentUpdateChannel;
selection = i;
}
}
ui->updateChannelComboBox->setCurrentIndex(selection);
// Start listening for selection changes again and update the description label.
QObject::connect(ui->updateChannelComboBox, SIGNAL(currentIndexChanged(int)), this,
SLOT(updateChannelSelectionChanged(int)));
refreshUpdateChannelDesc();
// Now that we've updated the channel list, we can enable the combo box.
// It starts off disabled so that if the channel list hasn't been loaded, it will be
// disabled.
ui->updateChannelComboBox->setEnabled(true);
}
void LauncherPage::updateChannelSelectionChanged(int index)
{
refreshUpdateChannelDesc();
}
void LauncherPage::refreshUpdateChannelDesc()
{
// Get the channel list.
QList<UpdateChecker::ChannelListEntry> channelList = APPLICATION->updateChecker()->getChannelList();
int selectedIndex = ui->updateChannelComboBox->currentIndex();
if (selectedIndex < 0)
{
return;
}
if (selectedIndex < channelList.count())
{
// Find the channel list entry with the given index.
UpdateChecker::ChannelListEntry selected = channelList.at(selectedIndex);
// Set the description text.
ui->updateChannelDescLabel->setText(selected.description);
// Set the currently selected channel ID.
m_currentUpdateChannel = selected.id;
}
}
void LauncherPage::applySettings()
{
auto s = APPLICATION->settings();
if (ui->resetNotificationsBtn->isChecked())
{
s->set("ShownNotifications", QString());
}
// Updates
s->set("AutoUpdate", ui->autoUpdateCheckBox->isChecked());
s->set("UpdateChannel", m_currentUpdateChannel);
auto original = s->get("IconTheme").toString();
//FIXME: make generic
switch (ui->themeComboBox->currentIndex())
{
case 1:
s->set("IconTheme", "pe_dark");
break;
case 2:
s->set("IconTheme", "pe_light");
break;
case 3:
s->set("IconTheme", "pe_blue");
break;
case 4:
s->set("IconTheme", "pe_colored");
break;
case 5:
s->set("IconTheme", "OSX");
break;
case 6:
s->set("IconTheme", "iOS");
break;
case 7:
s->set("IconTheme", "flat");
break;
case 8:
s->set("IconTheme", "custom");
break;
case 0:
default:
s->set("IconTheme", "multimc");
break;
}
if(original != s->get("IconTheme"))
{
APPLICATION->setIconTheme(s->get("IconTheme").toString());
}
auto originalAppTheme = s->get("ApplicationTheme").toString();
auto newAppTheme = ui->themeComboBoxColors->currentData().toString();
if(originalAppTheme != newAppTheme)
{
s->set("ApplicationTheme", newAppTheme);
APPLICATION->setApplicationTheme(newAppTheme, false);
}
// Console settings
s->set("ShowConsole", ui->showConsoleCheck->isChecked());
s->set("AutoCloseConsole", ui->autoCloseConsoleCheck->isChecked());
s->set("ShowConsoleOnError", ui->showConsoleErrorCheck->isChecked());
QString consoleFontFamily = ui->consoleFont->currentFont().family();
s->set("ConsoleFont", consoleFontFamily);
s->set("ConsoleFontSize", ui->fontSizeBox->value());
s->set("ConsoleMaxLines", ui->lineLimitSpinBox->value());
s->set("ConsoleOverflowStop", ui->checkStopLogging->checkState() != Qt::Unchecked);
// Folders
// TODO: Offer to move instances to new instance folder.
s->set("InstanceDir", ui->instDirTextBox->text());
s->set("CentralModsDir", ui->modsDirTextBox->text());
s->set("IconsDir", ui->iconsDirTextBox->text());
auto sortMode = (InstSortMode)ui->sortingModeGroup->checkedId();
switch (sortMode)
{
case Sort_LastLaunch:
s->set("InstSortMode", "LastLaunch");
break;
case Sort_Name:
default:
s->set("InstSortMode", "Name");
break;
}
// Analytics
if(!BuildConfig.ANALYTICS_ID.isEmpty())
{
s->set("Analytics", ui->analyticsCheck->isChecked());
}
}
void LauncherPage::loadSettings()
{
auto s = APPLICATION->settings();
// Updates
ui->autoUpdateCheckBox->setChecked(s->get("AutoUpdate").toBool());
m_currentUpdateChannel = s->get("UpdateChannel").toString();
//FIXME: make generic
auto theme = s->get("IconTheme").toString();
if (theme == "pe_dark")
{
ui->themeComboBox->setCurrentIndex(1);
}
else if (theme == "pe_light")
{
ui->themeComboBox->setCurrentIndex(2);
}
else if (theme == "pe_blue")
{
ui->themeComboBox->setCurrentIndex(3);
}
else if (theme == "pe_colored")
{
ui->themeComboBox->setCurrentIndex(4);
}
else if (theme == "OSX")
{
ui->themeComboBox->setCurrentIndex(5);
}
else if (theme == "iOS")
{
ui->themeComboBox->setCurrentIndex(6);
}
else if (theme == "flat")
{
ui->themeComboBox->setCurrentIndex(7);
}
else if (theme == "custom")
{
ui->themeComboBox->setCurrentIndex(8);
}
else
{
ui->themeComboBox->setCurrentIndex(0);
}
{
auto currentTheme = s->get("ApplicationTheme").toString();
auto themes = APPLICATION->getValidApplicationThemes();
int idx = 0;
for(auto &theme: themes)
{
ui->themeComboBoxColors->addItem(theme->name(), theme->id());
if(currentTheme == theme->id())
{
ui->themeComboBoxColors->setCurrentIndex(idx);
}
idx++;
}
}
// Console settings
ui->showConsoleCheck->setChecked(s->get("ShowConsole").toBool());
ui->autoCloseConsoleCheck->setChecked(s->get("AutoCloseConsole").toBool());
ui->showConsoleErrorCheck->setChecked(s->get("ShowConsoleOnError").toBool());
QString fontFamily = APPLICATION->settings()->get("ConsoleFont").toString();
QFont consoleFont(fontFamily);
ui->consoleFont->setCurrentFont(consoleFont);
bool conversionOk = true;
int fontSize = APPLICATION->settings()->get("ConsoleFontSize").toInt(&conversionOk);
if(!conversionOk)
{
fontSize = 11;
}
ui->fontSizeBox->setValue(fontSize);
refreshFontPreview();
ui->lineLimitSpinBox->setValue(s->get("ConsoleMaxLines").toInt());
ui->checkStopLogging->setChecked(s->get("ConsoleOverflowStop").toBool());
// Folders
ui->instDirTextBox->setText(s->get("InstanceDir").toString());
ui->modsDirTextBox->setText(s->get("CentralModsDir").toString());
ui->iconsDirTextBox->setText(s->get("IconsDir").toString());
QString sortMode = s->get("InstSortMode").toString();
if (sortMode == "LastLaunch")
{
ui->sortLastLaunchedBtn->setChecked(true);
}
else
{
ui->sortByNameBtn->setChecked(true);
}
// Analytics
if(!BuildConfig.ANALYTICS_ID.isEmpty())
{
ui->analyticsCheck->setChecked(s->get("Analytics").toBool());
}
}
void LauncherPage::refreshFontPreview()
{
int fontSize = ui->fontSizeBox->value();
QString fontFamily = ui->consoleFont->currentFont().family();
ui->fontPreview->clear();
defaultFormat->setFont(QFont(fontFamily, fontSize));
{
QTextCharFormat format(*defaultFormat);
format.setForeground(m_colors->getFront(MessageLevel::Error));
// append a paragraph/line
auto workCursor = ui->fontPreview->textCursor();
workCursor.movePosition(QTextCursor::End);
workCursor.insertText(tr("[Something/ERROR] A spooky error!"), format);
workCursor.insertBlock();
}
{
QTextCharFormat format(*defaultFormat);
format.setForeground(m_colors->getFront(MessageLevel::Message));
// append a paragraph/line
auto workCursor = ui->fontPreview->textCursor();
workCursor.movePosition(QTextCursor::End);
workCursor.insertText(tr("[Test/INFO] A harmless message..."), format);
workCursor.insertBlock();
}
{
QTextCharFormat format(*defaultFormat);
format.setForeground(m_colors->getFront(MessageLevel::Warning));
// append a paragraph/line
auto workCursor = ui->fontPreview->textCursor();
workCursor.movePosition(QTextCursor::End);
workCursor.insertText(tr("[Something/WARN] A not so spooky warning."), format);
workCursor.insertBlock();
}
}

View File

@ -0,0 +1,103 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QDialog>
#include "java/JavaChecker.h"
#include "ui/pages/BasePage.h"
#include <Application.h>
#include "ui/ColorCache.h"
#include <translations/TranslationsModel.h>
class QTextCharFormat;
class SettingsObject;
namespace Ui
{
class LauncherPage;
}
class LauncherPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit LauncherPage(QWidget *parent = 0);
~LauncherPage();
QString displayName() const override
{
return "Launcher";
}
QIcon icon() const override
{
return APPLICATION->getThemedIcon("launcher");
}
QString id() const override
{
return "launcher-settings";
}
QString helpPage() const override
{
return "Launcher-settings";
}
bool apply() override;
private:
void applySettings();
void loadSettings();
private
slots:
void on_instDirBrowseBtn_clicked();
void on_modsDirBrowseBtn_clicked();
void on_iconsDirBrowseBtn_clicked();
void on_migrateDataFolderMacBtn_clicked();
/*!
* Updates the list of update channels in the combo box.
*/
void refreshUpdateChannelList();
/*!
* Updates the channel description label.
*/
void refreshUpdateChannelDesc();
/*!
* Updates the font preview
*/
void refreshFontPreview();
void updateChannelSelectionChanged(int index);
private:
Ui::LauncherPage *ui;
/*!
* Stores the currently selected update channel.
*/
QString m_currentUpdateChannel;
// default format for the font preview...
QTextCharFormat *defaultFormat;
std::unique_ptr<LogColorCache> m_colors;
std::shared_ptr<TranslationsModel> m_languageModel;
};

View File

@ -0,0 +1,584 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LauncherPage</class>
<widget class="QWidget" name="LauncherPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>514</width>
<height>629</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="toolTip">
<string notr="true"/>
</property>
<property name="tabShape">
<enum>QTabWidget::Rounded</enum>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="featuresTab">
<attribute name="title">
<string>Features</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_9">
<item>
<widget class="QGroupBox" name="updateSettingsBox">
<property name="title">
<string>Update Settings</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_7">
<item>
<widget class="QCheckBox" name="autoUpdateCheckBox">
<property name="text">
<string>Check for updates on start?</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="updateChannelLabel">
<property name="text">
<string>Up&amp;date Channel:</string>
</property>
<property name="buddy">
<cstring>updateChannelComboBox</cstring>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="updateChannelComboBox">
<property name="enabled">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="updateChannelDescLabel">
<property name="text">
<string>No channel selected.</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="foldersBox">
<property name="title">
<string>Folders</string>
</property>
<layout class="QGridLayout" name="foldersBoxLayout">
<item row="0" column="0">
<widget class="QLabel" name="labelInstDir">
<property name="text">
<string>I&amp;nstances:</string>
</property>
<property name="buddy">
<cstring>instDirTextBox</cstring>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="instDirTextBox"/>
</item>
<item row="0" column="2">
<widget class="QToolButton" name="instDirBrowseBtn">
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelModsDir">
<property name="text">
<string>&amp;Mods:</string>
</property>
<property name="buddy">
<cstring>modsDirTextBox</cstring>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="modsDirTextBox"/>
</item>
<item row="1" column="2">
<widget class="QToolButton" name="modsDirBrowseBtn">
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="iconsDirTextBox"/>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelIconsDir">
<property name="text">
<string>&amp;Icons:</string>
</property>
<property name="buddy">
<cstring>iconsDirTextBox</cstring>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QToolButton" name="iconsDirBrowseBtn">
<property name="text">
<string notr="true">...</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QPushButton" name="migrateDataFolderMacBtn">
<property name="text">
<string>Move the data to new location (will restart the launcher)</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<widget class="QWidget" name="generalTab">
<attribute name="title">
<string>User Interface</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_6">
<item>
<widget class="QGroupBox" name="groupBox_3">
<property name="title">
<string>Launcher notifications</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
<widget class="QPushButton" name="resetNotificationsBtn">
<property name="text">
<string>Reset hidden notifications</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="sortingModeBox">
<property name="enabled">
<bool>true</bool>
</property>
<property name="title">
<string>Instance view sorting mode</string>
</property>
<layout class="QHBoxLayout" name="sortingModeBoxLayout">
<item>
<widget class="QRadioButton" name="sortLastLaunchedBtn">
<property name="text">
<string>By &amp;last launched</string>
</property>
<attribute name="buttonGroup">
<string notr="true">sortingModeGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="sortByNameBtn">
<property name="text">
<string>By &amp;name</string>
</property>
<attribute name="buttonGroup">
<string notr="true">sortingModeGroup</string>
</attribute>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="themeBox">
<property name="title">
<string>Theme</string>
</property>
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>&amp;Icons</string>
</property>
<property name="buddy">
<cstring>themeComboBox</cstring>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="themeComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="focusPolicy">
<enum>Qt::StrongFocus</enum>
</property>
<item>
<property name="text">
<string>Default</string>
</property>
</item>
<item>
<property name="text">
<string>Simple (Dark Icons)</string>
</property>
</item>
<item>
<property name="text">
<string>Simple (Light Icons)</string>
</property>
</item>
<item>
<property name="text">
<string>Simple (Blue Icons)</string>
</property>
</item>
<item>
<property name="text">
<string>Simple (Colored Icons)</string>
</property>
</item>
<item>
<property name="text">
<string notr="true">OSX</string>
</property>
</item>
<item>
<property name="text">
<string notr="true">iOS</string>
</property>
</item>
<item>
<property name="text">
<string notr="true">Flat</string>
</property>
</item>
<item>
<property name="text">
<string>Custom</string>
</property>
</item>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="themeComboBoxColors">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="focusPolicy">
<enum>Qt::StrongFocus</enum>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Colors</string>
</property>
<property name="buddy">
<cstring>themeComboBoxColors</cstring>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="generalTabSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<widget class="QWidget" name="consoleTab">
<attribute name="title">
<string>Console</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QGroupBox" name="consoleSettingsBox">
<property name="title">
<string>Console Settings</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QCheckBox" name="showConsoleCheck">
<property name="text">
<string>Show console while the game is running?</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="autoCloseConsoleCheck">
<property name="text">
<string>Automatically close console when the game quits?</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="showConsoleErrorCheck">
<property name="text">
<string>Show console when the game crashes?</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_4">
<property name="title">
<string>History limit</string>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="1" column="0">
<widget class="QCheckBox" name="checkStopLogging">
<property name="text">
<string>Stop logging when log overflows</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QSpinBox" name="lineLimitSpinBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="suffix">
<string> lines</string>
</property>
<property name="minimum">
<number>10000</number>
</property>
<property name="maximum">
<number>1000000</number>
</property>
<property name="singleStep">
<number>10000</number>
</property>
<property name="value">
<number>100000</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="themeBox_2">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>Console font</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="1" column="0" colspan="2">
<widget class="QTextEdit" name="fontPreview">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="undoRedoEnabled">
<bool>false</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QFontComboBox" name="consoleFont">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="fontSizeBox">
<property name="minimum">
<number>5</number>
</property>
<property name="maximum">
<number>16</number>
</property>
<property name="value">
<number>11</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="analyticsTab">
<attribute name="title">
<string>Analytics</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_8">
<item>
<widget class="QGroupBox" name="consoleSettingsBox_2">
<property name="title">
<string>Analytics Settings</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QCheckBox" name="analyticsCheck">
<property name="text">
<string>Send anonymous usage statistics?</string>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_5">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;
&lt;body&gt;
&lt;p&gt;The launcher sends anonymous usage statistics on every start of the application.&lt;/p&gt;&lt;p&gt;The following data is collected:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Launcher version.&lt;/li&gt;
&lt;li&gt;Operating system name, version and architecture.&lt;/li&gt;
&lt;li&gt;CPU architecture (kernel architecture on linux).&lt;/li&gt;
&lt;li&gt;Size of system memory.&lt;/li&gt;
&lt;li&gt;Java version, architecture and memory settings.&lt;/li&gt;
&lt;/ul&gt;
&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>autoUpdateCheckBox</tabstop>
<tabstop>updateChannelComboBox</tabstop>
<tabstop>instDirTextBox</tabstop>
<tabstop>instDirBrowseBtn</tabstop>
<tabstop>modsDirTextBox</tabstop>
<tabstop>modsDirBrowseBtn</tabstop>
<tabstop>iconsDirTextBox</tabstop>
<tabstop>iconsDirBrowseBtn</tabstop>
<tabstop>resetNotificationsBtn</tabstop>
<tabstop>sortLastLaunchedBtn</tabstop>
<tabstop>sortByNameBtn</tabstop>
<tabstop>themeComboBox</tabstop>
<tabstop>themeComboBoxColors</tabstop>
<tabstop>showConsoleCheck</tabstop>
<tabstop>autoCloseConsoleCheck</tabstop>
<tabstop>showConsoleErrorCheck</tabstop>
<tabstop>lineLimitSpinBox</tabstop>
<tabstop>checkStopLogging</tabstop>
<tabstop>consoleFont</tabstop>
<tabstop>fontSizeBox</tabstop>
<tabstop>fontPreview</tabstop>
</tabstops>
<resources/>
<connections/>
<buttongroups>
<buttongroup name="sortingModeGroup"/>
</buttongroups>
</ui>

View File

@ -0,0 +1,91 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MinecraftPage.h"
#include "ui_MinecraftPage.h"
#include <QMessageBox>
#include <QDir>
#include <QTabBar>
#include "settings/SettingsObject.h"
#include "Application.h"
MinecraftPage::MinecraftPage(QWidget *parent) : QWidget(parent), ui(new Ui::MinecraftPage)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();
loadSettings();
updateCheckboxStuff();
}
MinecraftPage::~MinecraftPage()
{
delete ui;
}
bool MinecraftPage::apply()
{
applySettings();
return true;
}
void MinecraftPage::updateCheckboxStuff()
{
ui->windowWidthSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked());
ui->windowHeightSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked());
}
void MinecraftPage::on_maximizedCheckBox_clicked(bool checked)
{
Q_UNUSED(checked);
updateCheckboxStuff();
}
void MinecraftPage::applySettings()
{
auto s = APPLICATION->settings();
// Window Size
s->set("LaunchMaximized", ui->maximizedCheckBox->isChecked());
s->set("MinecraftWinWidth", ui->windowWidthSpinBox->value());
s->set("MinecraftWinHeight", ui->windowHeightSpinBox->value());
// Native library workarounds
s->set("UseNativeOpenAL", ui->useNativeOpenALCheck->isChecked());
s->set("UseNativeGLFW", ui->useNativeGLFWCheck->isChecked());
// Game time
s->set("ShowGameTime", ui->showGameTime->isChecked());
s->set("ShowGlobalGameTime", ui->showGlobalGameTime->isChecked());
s->set("RecordGameTime", ui->recordGameTime->isChecked());
}
void MinecraftPage::loadSettings()
{
auto s = APPLICATION->settings();
// Window Size
ui->maximizedCheckBox->setChecked(s->get("LaunchMaximized").toBool());
ui->windowWidthSpinBox->setValue(s->get("MinecraftWinWidth").toInt());
ui->windowHeightSpinBox->setValue(s->get("MinecraftWinHeight").toInt());
ui->useNativeOpenALCheck->setChecked(s->get("UseNativeOpenAL").toBool());
ui->useNativeGLFWCheck->setChecked(s->get("UseNativeGLFW").toBool());
ui->showGameTime->setChecked(s->get("ShowGameTime").toBool());
ui->showGlobalGameTime->setChecked(s->get("ShowGlobalGameTime").toBool());
ui->recordGameTime->setChecked(s->get("RecordGameTime").toBool());
}

View File

@ -0,0 +1,70 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QDialog>
#include "java/JavaChecker.h"
#include "ui/pages/BasePage.h"
#include <Application.h>
class SettingsObject;
namespace Ui
{
class MinecraftPage;
}
class MinecraftPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit MinecraftPage(QWidget *parent = 0);
~MinecraftPage();
QString displayName() const override
{
return tr("Minecraft");
}
QIcon icon() const override
{
return APPLICATION->getThemedIcon("minecraft");
}
QString id() const override
{
return "minecraft-settings";
}
QString helpPage() const override
{
return "Minecraft-settings";
}
bool apply() override;
private:
void updateCheckboxStuff();
void applySettings();
void loadSettings();
private
slots:
void on_maximizedCheckBox_clicked(bool checked);
private:
Ui::MinecraftPage *ui;
};

View File

@ -0,0 +1,196 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MinecraftPage</class>
<widget class="QWidget" name="MinecraftPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>936</width>
<height>1134</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QVBoxLayout" name="mainLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="tabShape">
<enum>QTabWidget::Rounded</enum>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="minecraftTab">
<attribute name="title">
<string notr="true">Minecraft</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QGroupBox" name="windowSizeGroupBox">
<property name="title">
<string>Window Size</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QCheckBox" name="maximizedCheckBox">
<property name="text">
<string>Start Minecraft maximized?</string>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayoutWindowSize">
<item row="1" column="0">
<widget class="QLabel" name="labelWindowHeight">
<property name="text">
<string>Window hei&amp;ght:</string>
</property>
<property name="buddy">
<cstring>windowHeightSpinBox</cstring>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="labelWindowWidth">
<property name="text">
<string>W&amp;indow width:</string>
</property>
<property name="buddy">
<cstring>windowWidthSpinBox</cstring>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="windowWidthSpinBox">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>65536</number>
</property>
<property name="singleStep">
<number>1</number>
</property>
<property name="value">
<number>854</number>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QSpinBox" name="windowHeightSpinBox">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>65536</number>
</property>
<property name="value">
<number>480</number>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="nativeLibWorkaroundGroupBox">
<property name="title">
<string>Native library workarounds</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
<widget class="QCheckBox" name="useNativeGLFWCheck">
<property name="text">
<string>Use system installation of GLFW</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="useNativeOpenALCheck">
<property name="text">
<string>Use system installation of OpenAL</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="gameTimeGroupBox">
<property name="title">
<string>Game time</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_6">
<item>
<widget class="QCheckBox" name="showGameTime">
<property name="text">
<string>Show time spent playing instances</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="showGlobalGameTime">
<property name="text">
<string>Show time spent playing across all instances</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="recordGameTime">
<property name="text">
<string>Record time spent playing instances</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacerMinecraft">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>maximizedCheckBox</tabstop>
<tabstop>windowWidthSpinBox</tabstop>
<tabstop>windowHeightSpinBox</tabstop>
<tabstop>useNativeGLFWCheck</tabstop>
<tabstop>useNativeOpenALCheck</tabstop>
</tabstops>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,81 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PasteEEPage.h"
#include "ui_PasteEEPage.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QStandardPaths>
#include <QTabBar>
#include "settings/SettingsObject.h"
#include "tools/BaseProfiler.h"
#include "Application.h"
PasteEEPage::PasteEEPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::PasteEEPage)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();\
connect(ui->customAPIkeyEdit, &QLineEdit::textEdited, this, &PasteEEPage::textEdited);
loadSettings();
}
PasteEEPage::~PasteEEPage()
{
delete ui;
}
void PasteEEPage::loadSettings()
{
auto s = APPLICATION->settings();
QString keyToUse = s->get("PasteEEAPIKey").toString();
if(keyToUse == "multimc")
{
ui->multimcButton->setChecked(true);
}
else
{
ui->customButton->setChecked(true);
ui->customAPIkeyEdit->setText(keyToUse);
}
}
void PasteEEPage::applySettings()
{
auto s = APPLICATION->settings();
QString pasteKeyToUse;
if (ui->customButton->isChecked())
pasteKeyToUse = ui->customAPIkeyEdit->text();
else
{
pasteKeyToUse = "multimc";
}
s->set("PasteEEAPIKey", pasteKeyToUse);
}
bool PasteEEPage::apply()
{
applySettings();
return true;
}
void PasteEEPage::textEdited(const QString& text)
{
ui->customButton->setChecked(true);
}

View File

@ -0,0 +1,62 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QWidget>
#include "ui/pages/BasePage.h"
#include <Application.h>
namespace Ui {
class PasteEEPage;
}
class PasteEEPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit PasteEEPage(QWidget *parent = 0);
~PasteEEPage();
QString displayName() const override
{
return tr("Log Upload");
}
QIcon icon() const override
{
return APPLICATION->getThemedIcon("log");
}
QString id() const override
{
return "log-upload";
}
QString helpPage() const override
{
return "Log-Upload";
}
virtual bool apply() override;
private:
void loadSettings();
void applySettings();
private slots:
void textEdited(const QString &text);
private:
Ui::PasteEEPage *ui;
};

View File

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PasteEEPage</class>
<widget class="QWidget" name="PasteEEPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>491</width>
<height>474</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string notr="true">Tab 1</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>paste.ee API key</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_10">
<item>
<widget class="QRadioButton" name="multimcButton">
<property name="text">
<string>MultiMC key - 12MB &amp;upload limit</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pasteButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="customButton">
<property name="text">
<string>&amp;Your own key - 12MB upload limit:</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pasteButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QLineEdit" name="customAPIkeyEdit">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
<property name="placeholderText">
<string>Paste your API key here!</string>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;https://paste.ee&quot;&gt;paste.ee&lt;/a&gt; is used by MultiMC for log uploads. If you have a &lt;a href=&quot;https://paste.ee&quot;&gt;paste.ee&lt;/a&gt; account, you can add your API key here and have your uploaded logs paired with your account.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>216</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>multimcButton</tabstop>
<tabstop>customButton</tabstop>
<tabstop>customAPIkeyEdit</tabstop>
</tabstops>
<resources/>
<connections/>
<buttongroups>
<buttongroup name="pasteButtonGroup"/>
</buttongroups>
</ui>

View File

@ -0,0 +1,106 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ProxyPage.h"
#include "ui_ProxyPage.h"
#include <QTabBar>
#include "settings/SettingsObject.h"
#include "Application.h"
#include "Application.h"
ProxyPage::ProxyPage(QWidget *parent) : QWidget(parent), ui(new Ui::ProxyPage)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();
loadSettings();
updateCheckboxStuff();
connect(ui->proxyGroup, SIGNAL(buttonClicked(int)), SLOT(proxyChanged(int)));
}
ProxyPage::~ProxyPage()
{
delete ui;
}
bool ProxyPage::apply()
{
applySettings();
return true;
}
void ProxyPage::updateCheckboxStuff()
{
ui->proxyAddrBox->setEnabled(!ui->proxyNoneBtn->isChecked() &&
!ui->proxyDefaultBtn->isChecked());
ui->proxyAuthBox->setEnabled(!ui->proxyNoneBtn->isChecked() &&
!ui->proxyDefaultBtn->isChecked());
}
void ProxyPage::proxyChanged(int)
{
updateCheckboxStuff();
}
void ProxyPage::applySettings()
{
auto s = APPLICATION->settings();
// Proxy
QString proxyType = "None";
if (ui->proxyDefaultBtn->isChecked())
proxyType = "Default";
else if (ui->proxyNoneBtn->isChecked())
proxyType = "None";
else if (ui->proxySOCKS5Btn->isChecked())
proxyType = "SOCKS5";
else if (ui->proxyHTTPBtn->isChecked())
proxyType = "HTTP";
s->set("ProxyType", proxyType);
s->set("ProxyAddr", ui->proxyAddrEdit->text());
s->set("ProxyPort", ui->proxyPortEdit->value());
s->set("ProxyUser", ui->proxyUserEdit->text());
s->set("ProxyPass", ui->proxyPassEdit->text());
APPLICATION->updateProxySettings(
proxyType,
ui->proxyAddrEdit->text(),
ui->proxyPortEdit->value(),
ui->proxyUserEdit->text(),
ui->proxyPassEdit->text()
);
}
void ProxyPage::loadSettings()
{
auto s = APPLICATION->settings();
// Proxy
QString proxyType = s->get("ProxyType").toString();
if (proxyType == "Default")
ui->proxyDefaultBtn->setChecked(true);
else if (proxyType == "None")
ui->proxyNoneBtn->setChecked(true);
else if (proxyType == "SOCKS5")
ui->proxySOCKS5Btn->setChecked(true);
else if (proxyType == "HTTP")
ui->proxyHTTPBtn->setChecked(true);
ui->proxyAddrEdit->setText(s->get("ProxyAddr").toString());
ui->proxyPortEdit->setValue(s->get("ProxyPort").value<uint16_t>());
ui->proxyUserEdit->setText(s->get("ProxyUser").toString());
ui->proxyPassEdit->setText(s->get("ProxyPass").toString());
}

View File

@ -0,0 +1,66 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <memory>
#include <QDialog>
#include "ui/pages/BasePage.h"
#include <Application.h>
namespace Ui
{
class ProxyPage;
}
class ProxyPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit ProxyPage(QWidget *parent = 0);
~ProxyPage();
QString displayName() const override
{
return tr("Proxy");
}
QIcon icon() const override
{
return APPLICATION->getThemedIcon("proxy");
}
QString id() const override
{
return "proxy-settings";
}
QString helpPage() const override
{
return "Proxy-settings";
}
bool apply() override;
private:
void updateCheckboxStuff();
void applySettings();
void loadSettings();
private
slots:
void proxyChanged(int);
private:
Ui::ProxyPage *ui;
};

View File

@ -0,0 +1,203 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ProxyPage</class>
<widget class="QWidget" name="ProxyPage">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>598</width>
<height>617</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<widget class="QWidget" name="tabWidgetPage1">
<attribute name="title">
<string notr="true"/>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="proxyPlainTextWarningLabel_2">
<property name="text">
<string>This only applies to the launcher. Minecraft does not accept proxy settings.</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QGroupBox" name="proxyTypeBox">
<property name="title">
<string>Type</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QRadioButton" name="proxyDefaultBtn">
<property name="toolTip">
<string>Uses your system's default proxy settings.</string>
</property>
<property name="text">
<string>&amp;Default</string>
</property>
<attribute name="buttonGroup">
<string notr="true">proxyGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="proxyNoneBtn">
<property name="text">
<string>&amp;None</string>
</property>
<attribute name="buttonGroup">
<string notr="true">proxyGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="proxySOCKS5Btn">
<property name="text">
<string>SOC&amp;KS5</string>
</property>
<attribute name="buttonGroup">
<string notr="true">proxyGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="proxyHTTPBtn">
<property name="text">
<string>H&amp;TTP</string>
</property>
<attribute name="buttonGroup">
<string notr="true">proxyGroup</string>
</attribute>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="proxyAddrBox">
<property name="title">
<string>Address and Port</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLineEdit" name="proxyAddrEdit">
<property name="placeholderText">
<string notr="true">127.0.0.1</string>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="proxyPortEdit">
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="buttonSymbols">
<enum>QAbstractSpinBox::PlusMinus</enum>
</property>
<property name="maximum">
<number>65535</number>
</property>
<property name="value">
<number>8080</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="proxyAuthBox">
<property name="title">
<string>Authentication</string>
</property>
<layout class="QGridLayout" name="gridLayout_5">
<item row="0" column="1">
<widget class="QLineEdit" name="proxyUserEdit"/>
</item>
<item row="0" column="0">
<widget class="QLabel" name="proxyUsernameLabel">
<property name="text">
<string>Username:</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="proxyPasswordLabel">
<property name="text">
<string>Password:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="proxyPassEdit">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QLabel" name="proxyPlainTextWarningLabel">
<property name="text">
<string>Note: Proxy username and password are stored in plain text inside the launcher's configuration file!</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
<buttongroups>
<buttongroup name="proxyGroup"/>
</buttongroups>
</ui>

View File

@ -0,0 +1,37 @@
#include "GameOptionsPage.h"
#include "ui_GameOptionsPage.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/gameoptions/GameOptions.h"
GameOptionsPage::GameOptionsPage(MinecraftInstance * inst, QWidget* parent)
: QWidget(parent), ui(new Ui::GameOptionsPage)
{
ui->setupUi(this);
ui->tabWidget->tabBar()->hide();
m_model = inst->gameOptionsModel();
ui->optionsView->setModel(m_model.get());
auto head = ui->optionsView->header();
if(head->count())
{
head->setSectionResizeMode(0, QHeaderView::ResizeToContents);
for(int i = 1; i < head->count(); i++)
{
head->setSectionResizeMode(i, QHeaderView::Stretch);
}
}
}
GameOptionsPage::~GameOptionsPage()
{
// m_model->save();
}
void GameOptionsPage::openedImpl()
{
// m_model->observe();
}
void GameOptionsPage::closedImpl()
{
// m_model->unobserve();
}

View File

@ -0,0 +1,63 @@
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QWidget>
#include <QString>
#include "ui/pages/BasePage.h"
#include <Application.h>
namespace Ui
{
class GameOptionsPage;
}
class GameOptions;
class MinecraftInstance;
class GameOptionsPage : public QWidget, public BasePage
{
Q_OBJECT
public:
explicit GameOptionsPage(MinecraftInstance *inst, QWidget *parent = 0);
virtual ~GameOptionsPage();
void openedImpl() override;
void closedImpl() override;
virtual QString displayName() const override
{
return tr("Game Options");
}
virtual QIcon icon() const override
{
return APPLICATION->getThemedIcon("settings");
}
virtual QString id() const override
{
return "gameoptions";
}
virtual QString helpPage() const override
{
return "Game-Options-management";
}
private: // data
Ui::GameOptionsPage *ui = nullptr;
std::shared_ptr<GameOptions> m_model;
};

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