Merge branch 'develop' into better-launch

Signed-off-by: TheKodeToad <TheKodeToad@proton.me>
This commit is contained in:
TheKodeToad
2023-08-16 20:46:16 +01:00
737 changed files with 20254 additions and 18943 deletions

View File

@ -40,36 +40,27 @@
#include "ui_ServersPage.h"
#include <FileSystem.h>
#include <sstream>
#include <io/stream_reader.h>
#include <tag_string.h>
#include <tag_primitive.h>
#include <tag_list.h>
#include <tag_compound.h>
#include <minecraft/MinecraftInstance.h>
#include <tag_compound.h>
#include <tag_list.h>
#include <tag_primitive.h>
#include <tag_string.h>
#include <sstream>
#include <QFileSystemWatcher>
#include <QMenu>
#include <QTimer>
static const int COLUMN_COUNT = 2; // 3 , TBD: latency and other nice things.
static const int COLUMN_COUNT = 2; // 3 , TBD: latency and other nice things.
struct Server
{
struct Server {
// Types
enum class AcceptsTextures : int
{
ASK = 0,
ALWAYS = 1,
NEVER = 2
};
enum class AcceptsTextures : int { ASK = 0, ALWAYS = 1, NEVER = 2 };
// Methods
Server()
{
m_name = QObject::tr("Minecraft Server");
}
Server(const QString & name, const QString & address)
Server() { m_name = QObject::tr("Minecraft Server"); }
Server(const QString& name, const QString& address)
{
m_name = name;
m_address = address;
@ -82,21 +73,16 @@ struct Server
std::string nameStr(server["name"]);
m_name = QString::fromUtf8(nameStr.c_str());
if(server["icon"])
{
if (server["icon"]) {
std::string base64str(server["icon"]);
m_icon = QByteArray::fromBase64(base64str.c_str());
}
if(server.has_key("acceptTextures", nbt::tag_type::Byte))
{
if (server.has_key("acceptTextures", nbt::tag_type::Byte)) {
bool value = server["acceptTextures"].as<nbt::tag_byte>().get();
if(value)
{
if (value) {
m_acceptsTextures = AcceptsTextures::ALWAYS;
}
else
{
} else {
m_acceptsTextures = AcceptsTextures::NEVER;
}
}
@ -106,12 +92,10 @@ struct Server
{
server.insert("name", m_name.trimmed().toUtf8().toStdString());
server.insert("ip", m_address.trimmed().toUtf8().toStdString());
if(m_icon.size())
{
if (m_icon.size()) {
server.insert("icon", m_icon.toBase64().toStdString());
}
if(m_acceptsTextures != AcceptsTextures::ASK)
{
if (m_acceptsTextures != AcceptsTextures::ASK) {
server.insert("acceptTextures", nbt::tag_byte(m_acceptsTextures == AcceptsTextures::ALWAYS));
}
}
@ -127,64 +111,54 @@ struct Server
// Data - temporary
bool m_checked = false;
bool m_up = false;
QString m_motd; // https://mctools.org/motd-creator
QString m_motd; // https://mctools.org/motd-creator
int m_ping = 0;
int m_currentPlayers = 0;
int m_maxPlayers = 0;
};
static std::unique_ptr <nbt::tag_compound> parseServersDat(const QString& filename)
static std::unique_ptr<nbt::tag_compound> parseServersDat(const QString& filename)
{
try
{
try {
QByteArray input = FS::read(filename);
std::istringstream foo(std::string(input.constData(), input.size()));
auto pair = nbt::io::read_compound(foo);
if(pair.first != "")
if (pair.first != "")
return nullptr;
if(pair.second == nullptr)
if (pair.second == nullptr)
return nullptr;
return std::move(pair.second);
}
catch (...)
{
} catch (...) {
return nullptr;
}
}
static bool serializeServerDat(const QString& filename, nbt::tag_compound * levelInfo)
static bool serializeServerDat(const QString& filename, nbt::tag_compound* levelInfo)
{
try
{
if(!FS::ensureFilePathExists(filename))
{
try {
if (!FS::ensureFilePathExists(filename)) {
return false;
}
std::ostringstream s;
nbt::io::write_tag("", *levelInfo, s);
QByteArray val(s.str().data(), (int) s.str().size() );
QByteArray val(s.str().data(), (int)s.str().size());
FS::write(filename, val);
return true;
}
catch (...)
{
} catch (...) {
return false;
}
}
class ServersModel: public QAbstractListModel
{
class ServersModel : public QAbstractListModel {
Q_OBJECT
public:
enum Roles
{
public:
enum Roles {
ServerPtrRole = Qt::UserRole,
};
explicit ServersModel(const QString &path, QObject *parent = 0)
: QAbstractListModel(parent)
explicit ServersModel(const QString& path, QObject* parent = 0) : QAbstractListModel(parent)
{
m_path = path;
m_watcher = new QFileSystemWatcher(this);
@ -194,18 +168,16 @@ public:
m_saveTimer.setInterval(5000);
connect(&m_saveTimer, &QTimer::timeout, this, &ServersModel::save_internal);
}
virtual ~ServersModel() {};
virtual ~ServersModel(){};
void observe()
{
if(m_observed)
{
if (m_observed) {
return;
}
m_observed = true;
if(!m_loaded)
{
if (!m_loaded) {
load();
}
@ -214,8 +186,7 @@ public:
void unobserve()
{
if(!m_observed)
{
if (!m_observed) {
return;
}
m_observed = false;
@ -225,8 +196,7 @@ public:
void lock()
{
if(m_locked)
{
if (m_locked) {
return;
}
saveNow();
@ -237,8 +207,7 @@ public:
void unlock()
{
if(!m_locked)
{
if (!m_locked) {
return;
}
m_locked = false;
@ -248,12 +217,10 @@ public:
int addEmptyRow(int position)
{
if(m_locked)
{
if (m_locked) {
return -1;
}
if(position < 0 || position >= rowCount())
{
if (position < 0 || position >= rowCount()) {
position = rowCount();
}
beginInsertRows(QModelIndex(), position, position);
@ -265,36 +232,32 @@ public:
bool removeRow(int row)
{
if(m_locked)
{
if (m_locked) {
return false;
}
if(row < 0 || row >= rowCount())
{
if (row < 0 || row >= rowCount()) {
return false;
}
beginRemoveRows(QModelIndex(), row, row);
m_servers.removeAt(row);
endRemoveRows(); // does absolutely nothing, the selected server stays as the next line...
endRemoveRows(); // does absolutely nothing, the selected server stays as the next line...
scheduleSave();
return true;
}
bool moveUp(int row)
{
if(m_locked)
{
if (m_locked) {
return false;
}
if(row <= 0)
{
if (row <= 0) {
return false;
}
beginMoveRows(QModelIndex(), row, row, QModelIndex(), row - 1);
#if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)
m_servers.swapItemsAt(row-1, row);
m_servers.swapItemsAt(row - 1, row);
#else
m_servers.swap(row-1, row);
m_servers.swap(row - 1, row);
#endif
endMoveRows();
scheduleSave();
@ -303,20 +266,18 @@ public:
bool moveDown(int row)
{
if(m_locked)
{
if (m_locked) {
return false;
}
int count = rowCount();
if(row + 1 >= count)
{
if (row + 1 >= count) {
return false;
}
beginMoveRows(QModelIndex(), row, row, QModelIndex(), row + 2);
#if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)
m_servers.swapItemsAt(row+1, row);
m_servers.swapItemsAt(row + 1, row);
#else
m_servers.swap(row+1, row);
m_servers.swap(row + 1, row);
#endif
endMoveRows();
scheduleSave();
@ -328,10 +289,8 @@ public:
if (section < 0 || section >= COLUMN_COUNT)
return QVariant();
if(role == Qt::DisplayRole)
{
switch(section)
{
if (role == Qt::DisplayRole) {
switch (section) {
case 0:
return tr("Name");
case 1:
@ -344,90 +303,81 @@ public:
return QAbstractListModel::headerData(section, orientation, role);
}
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
if (!index.isValid())
return QVariant();
int row = index.row();
int column = index.column();
if(column < 0 || column >= COLUMN_COUNT)
if (column < 0 || column >= COLUMN_COUNT)
return QVariant();
if (row < 0 || row >= m_servers.size())
return QVariant();
switch(column)
{
switch (column) {
case 0:
switch (role)
{
case Qt::DecorationRole:
{
auto & bytes = m_servers[row].m_icon;
if(bytes.size())
{
QPixmap px;
if(px.loadFromData(bytes))
return QIcon(px);
switch (role) {
case Qt::DecorationRole: {
auto& bytes = m_servers[row].m_icon;
if (bytes.size()) {
QPixmap px;
if (px.loadFromData(bytes))
return QIcon(px);
}
return APPLICATION->getThemedIcon("unknown_server");
}
return APPLICATION->getThemedIcon("unknown_server");
}
case Qt::DisplayRole:
return m_servers[row].m_name;
case ServerPtrRole:
return QVariant::fromValue<void *>((void *)&m_servers[row]);
default:
return QVariant();
case Qt::DisplayRole:
return m_servers[row].m_name;
case ServerPtrRole:
return QVariant::fromValue<void*>((void*)&m_servers[row]);
default:
return QVariant();
}
case 1:
switch (role)
{
case Qt::DisplayRole:
return m_servers[row].m_address;
default:
return QVariant();
switch (role) {
case Qt::DisplayRole:
return m_servers[row].m_address;
default:
return QVariant();
}
case 2:
switch (role)
{
case Qt::DisplayRole:
return m_servers[row].m_ping;
default:
return QVariant();
switch (role) {
case Qt::DisplayRole:
return m_servers[row].m_ping;
default:
return QVariant();
}
default:
return QVariant();
}
}
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override
virtual int rowCount(const QModelIndex& parent = QModelIndex()) const override
{
return parent.isValid() ? 0 : m_servers.size();
}
int columnCount(const QModelIndex & parent) const override
int columnCount(const QModelIndex& parent) const override
{
return parent.isValid() ? 0 : COLUMN_COUNT;
}
Server * at(int index)
Server* at(int index)
{
if(index < 0 || index >= rowCount())
{
if (index < 0 || index >= rowCount()) {
return nullptr;
}
return &m_servers[index];
}
void setName(int row, const QString & name)
void setName(int row, const QString& name)
{
if(m_locked)
{
if (m_locked) {
return;
}
auto server = at(row);
if(!server || server->m_name == name)
{
if (!server || server->m_name == name) {
return;
}
server->m_name = name;
@ -435,15 +385,13 @@ public:
scheduleSave();
}
void setAddress(int row, const QString & address)
void setAddress(int row, const QString& address)
{
if(m_locked)
{
if (m_locked) {
return;
}
auto server = at(row);
if(!server || server->m_address == address)
{
if (!server || server->m_address == address) {
return;
}
server->m_address = address;
@ -453,13 +401,11 @@ public:
void setAcceptsTextures(int row, Server::AcceptsTextures textures)
{
if(m_locked)
{
if (m_locked) {
return;
}
auto server = at(row);
if(!server || server->m_acceptsTextures == textures)
{
if (!server || server->m_acceptsTextures == textures) {
return;
}
server->m_acceptsTextures = textures;
@ -473,12 +419,10 @@ public:
beginResetModel();
QList<Server> servers;
auto serversDat = parseServersDat(serversPath());
if(serversDat)
{
auto &serversList = serversDat->at("servers").as<nbt::tag_list>();
for(auto iter = serversList.begin(); iter != serversList.end(); iter++)
{
auto & serverTag = (*iter).as<nbt::tag_compound>();
if (serversDat) {
auto& serversList = serversDat->at("servers").as<nbt::tag_list>();
for (auto iter = serversList.begin(); iter != serversList.end(); iter++) {
auto& serverTag = (*iter).as<nbt::tag_compound>();
Server s(serverTag);
servers.append(s);
}
@ -490,14 +434,12 @@ public:
void saveNow()
{
if(saveIsScheduled())
{
if (saveIsScheduled()) {
save_internal();
}
}
public slots:
public slots:
void dirChanged(const QString& path)
{
qDebug() << "Changed:" << path;
@ -508,7 +450,7 @@ public slots:
qDebug() << "Changed:" << path;
}
private slots:
private slots:
void save_internal()
{
cancelSave();
@ -517,31 +459,27 @@ private slots:
nbt::tag_compound out;
nbt::tag_list list;
for(auto & server: m_servers)
{
for (auto& server : m_servers) {
nbt::tag_compound serverNbt;
server.serialize(serverNbt);
list.push_back(std::move(serverNbt));
}
out.insert("servers", nbt::value(std::move(list)));
if(!serializeServerDat(path, &out))
{
if (!serializeServerDat(path, &out)) {
qDebug() << "Failed to save server list:" << path << "Will try again.";
scheduleSave();
}
}
private:
private:
void scheduleSave()
{
if(!m_loaded)
{
if (!m_loaded) {
qDebug() << "Server list should never save if it didn't successfully load, path:" << m_path;
return;
}
if(!m_dirty)
{
if (!m_dirty) {
m_dirty = true;
qDebug() << "Server list save is scheduled for" << m_path;
}
@ -562,24 +500,17 @@ private:
void updateFSObserver()
{
bool observingFS = m_watcher->directories().contains(m_path);
if(m_observed && m_locked)
{
if(!observingFS)
{
if (m_observed && m_locked) {
if (!observingFS) {
qWarning() << "Will watch" << m_path;
if(!m_watcher->addPath(m_path))
{
if (!m_watcher->addPath(m_path)) {
qWarning() << "Failed to start watching" << m_path;
}
}
}
else
{
if(observingFS)
{
} else {
if (observingFS) {
qWarning() << "Will stop watching" << m_path;
if(!m_watcher->removePath(m_path))
{
if (!m_watcher->removePath(m_path)) {
qWarning() << "Failed to stop watching" << m_path;
}
}
@ -592,34 +523,31 @@ private:
return foo.filePath();
}
private:
private:
bool m_loaded = false;
bool m_locked = false;
bool m_observed = false;
bool m_dirty = false;
QString m_path;
QList<Server> m_servers;
QFileSystemWatcher *m_watcher = nullptr;
QFileSystemWatcher* m_watcher = nullptr;
QTimer m_saveTimer;
};
ServersPage::ServersPage(InstancePtr inst, QWidget* parent)
: QMainWindow(parent), ui(new Ui::ServersPage)
ServersPage::ServersPage(InstancePtr inst, QWidget* parent) : QMainWindow(parent), ui(new Ui::ServersPage)
{
ui->setupUi(this);
m_inst = inst;
m_model = new ServersModel(inst->gameRoot(), this);
ui->serversView->setIconSize(QSize(64,64));
ui->serversView->setIconSize(QSize(64, 64));
ui->serversView->setModel(m_model);
ui->serversView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->serversView, &QTreeView::customContextMenuRequested, this, &ServersPage::ShowContextMenu);
auto head = ui->serversView->header();
if(head->count())
{
if (head->count()) {
head->setSectionResizeMode(0, QHeaderView::Stretch);
for(int i = 1; i < head->count(); i++)
{
for (int i = 1; i < head->count(); i++) {
head->setSectionResizeMode(i, QHeaderView::ResizeToContents);
}
}
@ -633,8 +561,7 @@ ServersPage::ServersPage(InstancePtr inst, QWidget* parent)
connect(m_model, &QAbstractItemModel::rowsRemoved, this, &ServersPage::rowsRemoved);
m_locked = m_inst->isRunning();
if(m_locked)
{
if (m_locked) {
m_model->lock();
}
@ -659,40 +586,33 @@ void ServersPage::ShowContextMenu(const QPoint& pos)
delete menu;
}
QMenu * ServersPage::createPopupMenu()
QMenu* ServersPage::createPopupMenu()
{
QMenu* filteredMenu = QMainWindow::createPopupMenu();
filteredMenu->removeAction( ui->toolBar->toggleViewAction() );
filteredMenu->removeAction(ui->toolBar->toggleViewAction());
return filteredMenu;
}
void ServersPage::runningStateChanged(bool running)
{
if(m_locked == running)
{
if (m_locked == running) {
return;
}
m_locked = running;
if(m_locked)
{
if (m_locked) {
m_model->lock();
}
else
{
} else {
m_model->unlock();
}
updateState();
}
void ServersPage::currentChanged(const QModelIndex &current, const QModelIndex &previous)
void ServersPage::currentChanged(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous)
{
int nextServer = -1;
if (!current.isValid())
{
if (!current.isValid()) {
nextServer = -1;
}
else
{
} else {
nextServer = current.row();
}
currentServer = nextServer;
@ -700,20 +620,15 @@ void ServersPage::currentChanged(const QModelIndex &current, const QModelIndex &
}
// WARNING: this is here because currentChanged is not accurate when removing rows. the current item needs to be fixed up after removal.
void ServersPage::rowsRemoved(const QModelIndex& parent, int first, int last)
void ServersPage::rowsRemoved([[maybe_unused]] const QModelIndex& parent, int first, int last)
{
if(currentServer < first)
{
if (currentServer < first) {
// current was before the removal
return;
}
else if(currentServer >= first && currentServer <= last)
{
} else if (currentServer >= first && currentServer <= last) {
// current got removed...
return;
}
else
{
} else {
// current was past the removal
int count = last - first + 1;
currentServer -= count;
@ -749,14 +664,11 @@ void ServersPage::updateState()
ui->actionRemove->setEnabled(serverEditEnabled);
ui->actionJoin->setEnabled(serverEditEnabled);
if(server)
{
if (server) {
ui->addressLine->setText(server->m_address);
ui->nameLine->setText(server->m_name);
ui->resourceComboBox->setCurrentIndex(int(server->m_acceptsTextures));
}
else
{
} else {
ui->addressLine->setText(QString());
ui->nameLine->setText(QString());
ui->resourceComboBox->setCurrentIndex(0);
@ -788,27 +700,25 @@ void ServersPage::closedImpl()
void ServersPage::on_actionAdd_triggered()
{
int position = m_model->addEmptyRow(currentServer + 1);
if(position < 0)
{
if (position < 0) {
return;
}
// select the new row
ui->serversView->selectionModel()->setCurrentIndex(
m_model->index(position),
QItemSelectionModel::SelectCurrent | QItemSelectionModel::Clear | QItemSelectionModel::Rows
);
m_model->index(position), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Clear | QItemSelectionModel::Rows);
currentServer = position;
}
void ServersPage::on_actionRemove_triggered()
{
auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"),
tr("You are about to remove \"%1\".\n"
"This is permanent and the server will be gone from your list forever (A LONG TIME).\n\n"
"Are you sure?")
.arg(m_model->at(currentServer)->m_name),
QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
->exec();
auto response =
CustomMessageBox::selectable(this, tr("Confirm Removal"),
tr("You are about to remove \"%1\".\n"
"This is permanent and the server will be gone from your list forever (A LONG TIME).\n\n"
"Are you sure?")
.arg(m_model->at(currentServer)->m_name),
QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
->exec();
if (response != QMessageBox::Yes)
return;
@ -818,23 +728,21 @@ void ServersPage::on_actionRemove_triggered()
void ServersPage::on_actionMove_Up_triggered()
{
if(m_model->moveUp(currentServer))
{
currentServer --;
if (m_model->moveUp(currentServer)) {
currentServer--;
}
}
void ServersPage::on_actionMove_Down_triggered()
{
if(m_model->moveDown(currentServer))
{
currentServer ++;
if (m_model->moveDown(currentServer)) {
currentServer++;
}
}
void ServersPage::on_actionJoin_triggered()
{
const auto &address = m_model->at(currentServer)->m_address;
const auto& address = m_model->at(currentServer)->m_address;
APPLICATION->launch(m_inst, true, false, std::make_shared<MinecraftServerTarget>(MinecraftServerTarget::parse(address)));
}