chore: format some of the project files (#3677)

This commit is contained in:
Seth Flynn 2025-04-29 04:23:25 -04:00 committed by GitHub
commit e9afa16aa1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
21 changed files with 140 additions and 119 deletions

View File

@ -5,3 +5,9 @@ bbb3b3e6f6e3c0f95873f22e6d0a4aaf350f49d9
# (nix) alejandra -> nixfmt # (nix) alejandra -> nixfmt
4c81d8c53d09196426568c4a31a4e752ed05397a 4c81d8c53d09196426568c4a31a4e752ed05397a
# reformat codebase
1d468ac35ad88d8c77cc83f25e3704d9bd7df01b
# format a part of codebase
5c8481a118c8fefbfe901001d7828eaf6866eac4

View File

@ -128,6 +128,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <sys.h> #include <sys.h>
#include <QStringLiteral>
#include "SysInfo.h" #include "SysInfo.h"
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX

View File

@ -167,8 +167,8 @@ bool LogModel::isOverFlow()
return m_numLines >= m_maxLines && m_stopOnOverflow; return m_numLines >= m_maxLines && m_stopOnOverflow;
} }
MessageLevel::Enum LogModel::previousLevel()
MessageLevel::Enum LogModel::previousLevel() { {
if (!m_content.isEmpty()) { if (!m_content.isEmpty()) {
return m_content.last().level; return m_content.last().level;
} }

View File

@ -107,7 +107,7 @@ std::optional<LogParser::ParsedItem> LogParser::parseNext()
if (m_buffer.trimmed().isEmpty()) { if (m_buffer.trimmed().isEmpty()) {
auto text = QString(m_buffer); auto text = QString(m_buffer);
m_buffer.clear(); m_buffer.clear();
return LogParser::PlainText { text }; return LogParser::PlainText{ text };
} }
// check if we have a full xml log4j event // check if we have a full xml log4j event

View File

@ -1003,7 +1003,6 @@ QMap<QString, QString> MinecraftInstance::createCensorFilterFromSession(AuthSess
return filter; return filter;
} }
QStringList MinecraftInstance::getLogFileSearchPaths() QStringList MinecraftInstance::getLogFileSearchPaths()
{ {
return { FS::PathCombine(gameRoot(), "crash-reports"), FS::PathCombine(gameRoot(), "logs"), gameRoot() }; return { FS::PathCombine(gameRoot(), "crash-reports"), FS::PathCombine(gameRoot(), "logs"), gameRoot() };

View File

@ -84,7 +84,7 @@ class Mod : public Resource {
bool valid() const override; bool valid() const override;
[[nodiscard]] int compare(const Resource & other, SortType type) const override; [[nodiscard]] int compare(const Resource& other, SortType type) const override;
[[nodiscard]] bool applyFilter(QRegularExpression filter) const override; [[nodiscard]] bool applyFilter(QRegularExpression filter) const override;
// Delete all the files of this mod // Delete all the files of this mod

View File

@ -48,7 +48,8 @@ TexturePackFolderModel::TexturePackFolderModel(const QDir& dir, BaseInstance* in
m_column_names = QStringList({ "Enable", "Image", "Name", "Last Modified", "Provider", "Size" }); m_column_names = QStringList({ "Enable", "Image", "Name", "Last Modified", "Provider", "Size" });
m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Last Modified"), tr("Provider"), tr("Size") }); m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Last Modified"), tr("Provider"), tr("Size") });
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::DATE, SortType::PROVIDER, SortType::SIZE }; m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::DATE, SortType::PROVIDER, SortType::SIZE };
m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive }; m_column_resize_modes = { QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Stretch,
QHeaderView::Interactive, QHeaderView::Interactive, QHeaderView::Interactive };
m_columnsHideable = { false, true, false, true, true, true }; m_columnsHideable = { false, true, false, true, true, true };
m_columnsHiddenByDefault = { false, false, false, false, false, true }; m_columnsHiddenByDefault = { false, false, false, false, false, true };
} }

View File

@ -166,7 +166,7 @@ auto HttpMetaCache::evictEntry(MetaEntryPtr entry) -> bool
return true; return true;
} }
//returns true on success, false otherwise // returns true on success, false otherwise
auto HttpMetaCache::evictAll() -> bool auto HttpMetaCache::evictAll() -> bool
{ {
bool ret = true; bool ret = true;
@ -178,7 +178,7 @@ auto HttpMetaCache::evictAll() -> bool
qCWarning(taskHttpMetaCacheLogC) << "Unexpected missing cache entry" << entry->m_basePath; qCWarning(taskHttpMetaCacheLogC) << "Unexpected missing cache entry" << entry->m_basePath;
} }
map.entry_list.clear(); map.entry_list.clear();
//AND all return codes together so the result is true iff all runs of deletePath() are true // AND all return codes together so the result is true iff all runs of deletePath() are true
ret &= FS::deletePath(map.base_path); ret &= FS::deletePath(map.base_path);
} }
return ret; return ret;

View File

@ -79,7 +79,6 @@ Q_DECLARE_METATYPE(TaskStepProgress)
using TaskStepProgressList = QList<std::shared_ptr<TaskStepProgress>>; using TaskStepProgressList = QList<std::shared_ptr<TaskStepProgress>>;
/*! /*!
* Represents a task that has to be done. * Represents a task that has to be done.
* To create a task, you need to subclass this class, implement the executeTask() method and call * To create a task, you need to subclass this class, implement the executeTask() method and call
@ -177,9 +176,9 @@ class Task : public QObject, public QRunnable {
virtual void executeTask() = 0; virtual void executeTask() = 0;
protected slots: protected slots:
//! The Task subclass must call this method when the task has succeeded //! The Task subclass must call this method when the task has succeeded
virtual void emitSucceeded(); virtual void emitSucceeded();
//! **The Task subclass** must call this method when the task has aborted. External code should call abort() instead. //! **The Task subclass** must call this method when the task has aborted. External code should call abort() instead.
virtual void emitAborted(); virtual void emitAborted();
//! The Task subclass must call this method when the task has failed //! The Task subclass must call this method when the task has failed
virtual void emitFailed(QString reason = ""); virtual void emitFailed(QString reason = "");

View File

@ -1311,7 +1311,7 @@ void MainWindow::on_actionReportBug_triggered()
void MainWindow::on_actionClearMetadata_triggered() void MainWindow::on_actionClearMetadata_triggered()
{ {
//This if contains side effects! // This if contains side effects!
if (!APPLICATION->metacache()->evictAll()) { if (!APPLICATION->metacache()->evictAll()) {
CustomMessageBox::selectable(this, tr("Error"), CustomMessageBox::selectable(this, tr("Error"),
tr("Metadata cache clear Failed!\nTo clear the metadata cache manually, press Folders -> View " tr("Metadata cache clear Failed!\nTo clear the metadata cache manually, press Folders -> View "

View File

@ -62,7 +62,7 @@
JavaPage::JavaPage(QWidget* parent) : QWidget(parent), ui(new Ui::JavaPage) JavaPage::JavaPage(QWidget* parent) : QWidget(parent), ui(new Ui::JavaPage)
{ {
ui->setupUi(this); ui->setupUi(this);
if (BuildConfig.JAVA_DOWNLOADER_ENABLED) { if (BuildConfig.JAVA_DOWNLOADER_ENABLED) {
ui->managedJavaList->initialize(new JavaInstallList(this, true)); ui->managedJavaList->initialize(new JavaInstallList(this, true));
ui->managedJavaList->setResizeOn(2); ui->managedJavaList->setResizeOn(2);

View File

@ -37,11 +37,11 @@
#include <Application.h> #include <Application.h>
#include <QObjectPtr.h> #include <QObjectPtr.h>
#include "ui/widgets/JavaSettingsWidget.h"
#include <QDialog> #include <QDialog>
#include <QStringListModel> #include <QStringListModel>
#include "JavaCommon.h" #include "JavaCommon.h"
#include "ui/pages/BasePage.h" #include "ui/pages/BasePage.h"
#include "ui/widgets/JavaSettingsWidget.h"
class SettingsObject; class SettingsObject;

View File

@ -35,17 +35,18 @@
#pragma once #pragma once
#include <QWidget>
#include "Application.h" #include "Application.h"
#include "BaseInstance.h" #include "BaseInstance.h"
#include "ui/pages/BasePage.h" #include "ui/pages/BasePage.h"
#include "ui/widgets/MinecraftSettingsWidget.h" #include "ui/widgets/MinecraftSettingsWidget.h"
#include <QWidget>
class InstanceSettingsPage : public MinecraftSettingsWidget, public BasePage { class InstanceSettingsPage : public MinecraftSettingsWidget, public BasePage {
Q_OBJECT Q_OBJECT
public: public:
explicit InstanceSettingsPage(MinecraftInstancePtr instance, QWidget* parent = nullptr) : MinecraftSettingsWidget(std::move(instance), parent) explicit InstanceSettingsPage(MinecraftInstancePtr instance, QWidget* parent = nullptr)
: MinecraftSettingsWidget(std::move(instance), parent)
{ {
connect(APPLICATION, &Application::globalSettingsAboutToOpen, this, &InstanceSettingsPage::saveSettings); connect(APPLICATION, &Application::globalSettingsAboutToOpen, this, &InstanceSettingsPage::saveSettings);
connect(APPLICATION, &Application::globalSettingsClosed, this, &InstanceSettingsPage::loadSettings); connect(APPLICATION, &Application::globalSettingsClosed, this, &InstanceSettingsPage::loadSettings);

View File

@ -347,13 +347,18 @@ void ManagedPackPage::onUpdateTaskCompleted(bool did_succeed) const
if (m_instance_window != nullptr) if (m_instance_window != nullptr)
m_instance_window->close(); m_instance_window->close();
CustomMessageBox::selectable(nullptr, tr("Update Successful"), tr("The instance updated to pack version %1 successfully.").arg(m_inst->getManagedPackVersionName()), QMessageBox::Information) CustomMessageBox::selectable(nullptr, tr("Update Successful"),
->show(); tr("The instance updated to pack version %1 successfully.").arg(m_inst->getManagedPackVersionName()),
QMessageBox::Information)
->show();
} else { } else {
CustomMessageBox::selectable(nullptr, tr("Update Failed"), tr("The instance failed to update to pack version %1. Please check launcher logs for more information.").arg(m_inst->getManagedPackVersionName()), QMessageBox::Critical) CustomMessageBox::selectable(
->show(); nullptr, tr("Update Failed"),
tr("The instance failed to update to pack version %1. Please check launcher logs for more information.")
.arg(m_inst->getManagedPackVersionName()),
QMessageBox::Critical)
->show();
} }
} }
void ModrinthManagedPackPage::update() void ModrinthManagedPackPage::update()

View File

@ -1,21 +1,22 @@
#include <QObject> #include <qtconcurrentrun.h>
#include <QTcpSocket>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <qtconcurrentrun.h> #include <QObject>
#include <QTcpSocket>
#include <Exception.h> #include <Exception.h>
#include "McClient.h"
#include "Json.h" #include "Json.h"
#include "McClient.h"
// 7 first bits // 7 first bits
#define SEGMENT_BITS 0x7F #define SEGMENT_BITS 0x7F
// last bit // last bit
#define CONTINUE_BIT 0x80 #define CONTINUE_BIT 0x80
McClient::McClient(QObject *parent, QString domain, QString ip, short port): QObject(parent), m_domain(domain), m_ip(ip), m_port(port) {} McClient::McClient(QObject* parent, QString domain, QString ip, short port) : QObject(parent), m_domain(domain), m_ip(ip), m_port(port) {}
void McClient::getStatusData() { void McClient::getStatusData()
{
qDebug() << "Connecting to socket.."; qDebug() << "Connecting to socket..";
connect(&m_socket, &QTcpSocket::connected, this, [this]() { connect(&m_socket, &QTcpSocket::connected, this, [this]() {
@ -25,28 +26,28 @@ void McClient::getStatusData() {
connect(&m_socket, &QTcpSocket::readyRead, this, &McClient::readRawResponse); connect(&m_socket, &QTcpSocket::readyRead, this, &McClient::readRawResponse);
}); });
connect(&m_socket, &QTcpSocket::errorOccurred, this, [this]() { connect(&m_socket, &QTcpSocket::errorOccurred, this, [this]() { emitFail("Socket disconnected: " + m_socket.errorString()); });
emitFail("Socket disconnected: " + m_socket.errorString());
});
m_socket.connectToHost(m_ip, m_port); m_socket.connectToHost(m_ip, m_port);
} }
void McClient::sendRequest() { void McClient::sendRequest()
{
QByteArray data; QByteArray data;
writeVarInt(data, 0x00); // packet ID writeVarInt(data, 0x00); // packet ID
writeVarInt(data, 763); // hardcoded protocol version (763 = 1.20.1) writeVarInt(data, 763); // hardcoded protocol version (763 = 1.20.1)
writeVarInt(data, m_domain.size()); // server address length writeVarInt(data, m_domain.size()); // server address length
writeString(data, m_domain.toStdString()); // server address writeString(data, m_domain.toStdString()); // server address
writeFixedInt(data, m_port, 2); // server port writeFixedInt(data, m_port, 2); // server port
writeVarInt(data, 0x01); // next state writeVarInt(data, 0x01); // next state
writePacketToSocket(data); // send handshake packet writePacketToSocket(data); // send handshake packet
writeVarInt(data, 0x00); // packet ID writeVarInt(data, 0x00); // packet ID
writePacketToSocket(data); // send status packet writePacketToSocket(data); // send status packet
} }
void McClient::readRawResponse() { void McClient::readRawResponse()
{
if (m_responseReadState == 2) { if (m_responseReadState == 2) {
return; return;
} }
@ -56,28 +57,27 @@ void McClient::readRawResponse() {
m_wantedRespLength = readVarInt(m_resp); m_wantedRespLength = readVarInt(m_resp);
m_responseReadState = 1; m_responseReadState = 1;
} }
if (m_responseReadState == 1 && m_resp.size() >= m_wantedRespLength) { if (m_responseReadState == 1 && m_resp.size() >= m_wantedRespLength) {
if (m_resp.size() > m_wantedRespLength) { if (m_resp.size() > m_wantedRespLength) {
qDebug() << "Warning: Packet length doesn't match actual packet size (" << m_wantedRespLength << " expected vs " << m_resp.size() << " received)"; qDebug() << "Warning: Packet length doesn't match actual packet size (" << m_wantedRespLength << " expected vs "
<< m_resp.size() << " received)";
} }
parseResponse(); parseResponse();
m_responseReadState = 2; m_responseReadState = 2;
} }
} }
void McClient::parseResponse() { void McClient::parseResponse()
{
qDebug() << "Received response successfully"; qDebug() << "Received response successfully";
int packetID = readVarInt(m_resp); int packetID = readVarInt(m_resp);
if (packetID != 0x00) { if (packetID != 0x00) {
throw Exception( throw Exception(QString("Packet ID doesn't match expected value (0x00 vs 0x%1)").arg(packetID, 0, 16));
QString("Packet ID doesn't match expected value (0x00 vs 0x%1)")
.arg(packetID, 0, 16)
);
} }
Q_UNUSED(readVarInt(m_resp)); // json length Q_UNUSED(readVarInt(m_resp)); // json length
// 'resp' should now be the JSON string // 'resp' should now be the JSON string
QJsonDocument doc = QJsonDocument::fromJson(m_resp); QJsonDocument doc = QJsonDocument::fromJson(m_resp);
@ -85,8 +85,9 @@ void McClient::parseResponse() {
} }
// From https://wiki.vg/Protocol#VarInt_and_VarLong // From https://wiki.vg/Protocol#VarInt_and_VarLong
void McClient::writeVarInt(QByteArray &data, int value) { void McClient::writeVarInt(QByteArray& data, int value)
while ((value & ~SEGMENT_BITS)) { // check if the value is too big to fit in 7 bits {
while ((value & ~SEGMENT_BITS)) { // check if the value is too big to fit in 7 bits
// Write 7 bits // Write 7 bits
data.append((value & SEGMENT_BITS) | CONTINUE_BIT); data.append((value & SEGMENT_BITS) | CONTINUE_BIT);
@ -98,7 +99,8 @@ void McClient::writeVarInt(QByteArray &data, int value) {
} }
// From https://wiki.vg/Protocol#VarInt_and_VarLong // From https://wiki.vg/Protocol#VarInt_and_VarLong
int McClient::readVarInt(QByteArray &data) { int McClient::readVarInt(QByteArray& data)
{
int value = 0; int value = 0;
int position = 0; int position = 0;
char currentByte; char currentByte;
@ -107,17 +109,20 @@ int McClient::readVarInt(QByteArray &data) {
currentByte = readByte(data); currentByte = readByte(data);
value |= (currentByte & SEGMENT_BITS) << position; value |= (currentByte & SEGMENT_BITS) << position;
if ((currentByte & CONTINUE_BIT) == 0) break; if ((currentByte & CONTINUE_BIT) == 0)
break;
position += 7; position += 7;
} }
if (position >= 32) throw Exception("VarInt is too big"); if (position >= 32)
throw Exception("VarInt is too big");
return value; return value;
} }
char McClient::readByte(QByteArray &data) { char McClient::readByte(QByteArray& data)
{
if (data.isEmpty()) { if (data.isEmpty()) {
throw Exception("No more bytes to read"); throw Exception("No more bytes to read");
} }
@ -128,17 +133,20 @@ char McClient::readByte(QByteArray &data) {
} }
// write number with specified size in big endian format // write number with specified size in big endian format
void McClient::writeFixedInt(QByteArray &data, int value, int size) { void McClient::writeFixedInt(QByteArray& data, int value, int size)
{
for (int i = size - 1; i >= 0; i--) { for (int i = size - 1; i >= 0; i--) {
data.append((value >> (i * 8)) & 0xFF); data.append((value >> (i * 8)) & 0xFF);
} }
} }
void McClient::writeString(QByteArray &data, const std::string &value) { void McClient::writeString(QByteArray& data, const std::string& value)
{
data.append(value.c_str()); data.append(value.c_str());
} }
void McClient::writePacketToSocket(QByteArray &data) { void McClient::writePacketToSocket(QByteArray& data)
{
// we prefix the packet with its length // we prefix the packet with its length
QByteArray dataWithSize; QByteArray dataWithSize;
writeVarInt(dataWithSize, data.size()); writeVarInt(dataWithSize, data.size());
@ -151,14 +159,15 @@ void McClient::writePacketToSocket(QByteArray &data) {
data.clear(); data.clear();
} }
void McClient::emitFail(QString error)
void McClient::emitFail(QString error) { {
qDebug() << "Minecraft server ping for status error:" << error; qDebug() << "Minecraft server ping for status error:" << error;
emit failed(error); emit failed(error);
emit finished(); emit finished();
} }
void McClient::emitSucceed(QJsonObject data) { void McClient::emitSucceed(QJsonObject data)
{
emit succeeded(data); emit succeeded(data);
emit finished(); emit finished();
} }

View File

@ -1,8 +1,8 @@
#include <QObject> #include <QFuture>
#include <QTcpSocket>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QFuture> #include <QObject>
#include <QTcpSocket>
#include <Exception.h> #include <Exception.h>
@ -22,29 +22,30 @@ class McClient : public QObject {
unsigned m_wantedRespLength = 0; unsigned m_wantedRespLength = 0;
QByteArray m_resp; QByteArray m_resp;
public: public:
explicit McClient(QObject *parent, QString domain, QString ip, short port); explicit McClient(QObject* parent, QString domain, QString ip, short port);
//! Read status data of the server, and calls the succeeded() signal with the parsed JSON data //! Read status data of the server, and calls the succeeded() signal with the parsed JSON data
void getStatusData(); void getStatusData();
private:
private:
void sendRequest(); void sendRequest();
//! Accumulate data until we have a full response, then call parseResponse() once //! Accumulate data until we have a full response, then call parseResponse() once
void readRawResponse(); void readRawResponse();
void parseResponse(); void parseResponse();
void writeVarInt(QByteArray &data, int value); void writeVarInt(QByteArray& data, int value);
int readVarInt(QByteArray &data); int readVarInt(QByteArray& data);
char readByte(QByteArray &data); char readByte(QByteArray& data);
//! write number with specified size in big endian format //! write number with specified size in big endian format
void writeFixedInt(QByteArray &data, int value, int size); void writeFixedInt(QByteArray& data, int value, int size);
void writeString(QByteArray &data, const std::string &value); void writeString(QByteArray& data, const std::string& value);
void writePacketToSocket(QByteArray &data); void writePacketToSocket(QByteArray& data);
void emitFail(QString error); void emitFail(QString error);
void emitSucceed(QJsonObject data); void emitSucceed(QJsonObject data);
signals: signals:
void succeeded(QJsonObject data); void succeeded(QJsonObject data);
void failed(QString error); void failed(QString error);
void finished(); void finished();

View File

@ -1,23 +1,25 @@
#include <QObject>
#include <QDnsLookup>
#include <QtNetwork/qtcpsocket.h> #include <QtNetwork/qtcpsocket.h>
#include <QDnsLookup>
#include <QHostInfo> #include <QHostInfo>
#include <QObject>
#include "McResolver.h" #include "McResolver.h"
McResolver::McResolver(QObject *parent, QString domain, int port): QObject(parent), m_constrDomain(domain), m_constrPort(port) {} McResolver::McResolver(QObject* parent, QString domain, int port) : QObject(parent), m_constrDomain(domain), m_constrPort(port) {}
void McResolver::ping() { void McResolver::ping()
{
pingWithDomainSRV(m_constrDomain, m_constrPort); pingWithDomainSRV(m_constrDomain, m_constrPort);
} }
void McResolver::pingWithDomainSRV(QString domain, int port) { void McResolver::pingWithDomainSRV(QString domain, int port)
QDnsLookup *lookup = new QDnsLookup(this); {
QDnsLookup* lookup = new QDnsLookup(this);
lookup->setName(QString("_minecraft._tcp.%1").arg(domain)); lookup->setName(QString("_minecraft._tcp.%1").arg(domain));
lookup->setType(QDnsLookup::SRV); lookup->setType(QDnsLookup::SRV);
connect(lookup, &QDnsLookup::finished, this, [this, domain, port]() { connect(lookup, &QDnsLookup::finished, this, [this, domain, port]() {
QDnsLookup *lookup = qobject_cast<QDnsLookup *>(sender()); QDnsLookup* lookup = qobject_cast<QDnsLookup*>(sender());
lookup->deleteLater(); lookup->deleteLater();
@ -43,8 +45,9 @@ void McResolver::pingWithDomainSRV(QString domain, int port) {
lookup->lookup(); lookup->lookup();
} }
void McResolver::pingWithDomainA(QString domain, int port) { void McResolver::pingWithDomainA(QString domain, int port)
QHostInfo::lookupHost(domain, this, [this, port](const QHostInfo &hostInfo){ {
QHostInfo::lookupHost(domain, this, [this, port](const QHostInfo& hostInfo) {
if (hostInfo.error() != QHostInfo::NoError) { if (hostInfo.error() != QHostInfo::NoError) {
emitFail("A record lookup failed"); emitFail("A record lookup failed");
return; return;
@ -55,19 +58,21 @@ void McResolver::pingWithDomainA(QString domain, int port) {
emitFail("No A entries found for domain"); emitFail("No A entries found for domain");
return; return;
} }
const auto& firstRecord = records.at(0); const auto& firstRecord = records.at(0);
emitSucceed(firstRecord.toString(), port); emitSucceed(firstRecord.toString(), port);
}); });
} }
void McResolver::emitFail(QString error) { void McResolver::emitFail(QString error)
{
qDebug() << "DNS resolver error:" << error; qDebug() << "DNS resolver error:" << error;
emit failed(error); emit failed(error);
emit finished(); emit finished();
} }
void McResolver::emitSucceed(QString ip, int port) { void McResolver::emitSucceed(QString ip, int port)
{
emit succeeded(ip, port); emit succeeded(ip, port);
emit finished(); emit finished();
} }

View File

@ -1,8 +1,8 @@
#include <QtNetwork/qtcpsocket.h>
#include <QDnsLookup>
#include <QHostInfo>
#include <QObject> #include <QObject>
#include <QString> #include <QString>
#include <QDnsLookup>
#include <QtNetwork/qtcpsocket.h>
#include <QHostInfo>
// resolve the IP and port of a Minecraft server // resolve the IP and port of a Minecraft server
class McResolver : public QObject { class McResolver : public QObject {
@ -11,17 +11,17 @@ class McResolver : public QObject {
QString m_constrDomain; QString m_constrDomain;
int m_constrPort; int m_constrPort;
public: public:
explicit McResolver(QObject *parent, QString domain, int port); explicit McResolver(QObject* parent, QString domain, int port);
void ping(); void ping();
private: private:
void pingWithDomainSRV(QString domain, int port); void pingWithDomainSRV(QString domain, int port);
void pingWithDomainA(QString domain, int port); void pingWithDomainA(QString domain, int port);
void emitFail(QString error); void emitFail(QString error);
void emitSucceed(QString ip, int port); void emitSucceed(QString ip, int port);
signals: signals:
void succeeded(QString ip, int port); void succeeded(QString ip, int port);
void failed(QString error); void failed(QString error);
void finished(); void finished();

View File

@ -1,47 +1,41 @@
#include <QFutureWatcher> #include <QFutureWatcher>
#include "ServerPingTask.h"
#include "McResolver.h"
#include "McClient.h"
#include <Json.h> #include <Json.h>
#include "McClient.h"
#include "McResolver.h"
#include "ServerPingTask.h"
unsigned getOnlinePlayers(QJsonObject data) { unsigned getOnlinePlayers(QJsonObject data)
{
return Json::requireInteger(Json::requireObject(data, "players"), "online"); return Json::requireInteger(Json::requireObject(data, "players"), "online");
} }
void ServerPingTask::executeTask() { void ServerPingTask::executeTask()
{
qDebug() << "Querying status of " << QString("%1:%2").arg(m_domain).arg(m_port); qDebug() << "Querying status of " << QString("%1:%2").arg(m_domain).arg(m_port);
// Resolve the actual IP and port for the server // Resolve the actual IP and port for the server
McResolver *resolver = new McResolver(nullptr, m_domain, m_port); McResolver* resolver = new McResolver(nullptr, m_domain, m_port);
QObject::connect(resolver, &McResolver::succeeded, this, [this, resolver](QString ip, int port) { QObject::connect(resolver, &McResolver::succeeded, this, [this, resolver](QString ip, int port) {
qDebug() << "Resolved Address for" << m_domain << ": " << ip << ":" << port; qDebug() << "Resolved Address for" << m_domain << ": " << ip << ":" << port;
// Now that we have the IP and port, query the server // Now that we have the IP and port, query the server
McClient *client = new McClient(nullptr, m_domain, ip, port); McClient* client = new McClient(nullptr, m_domain, ip, port);
QObject::connect(client, &McClient::succeeded, this, [this](QJsonObject data) { QObject::connect(client, &McClient::succeeded, this, [this](QJsonObject data) {
m_outputOnlinePlayers = getOnlinePlayers(data); m_outputOnlinePlayers = getOnlinePlayers(data);
qDebug() << "Online players: " << m_outputOnlinePlayers; qDebug() << "Online players: " << m_outputOnlinePlayers;
emitSucceeded(); emitSucceeded();
}); });
QObject::connect(client, &McClient::failed, this, [this](QString error) { QObject::connect(client, &McClient::failed, this, [this](QString error) { emitFailed(error); });
emitFailed(error);
});
// Delete McClient object when done // Delete McClient object when done
QObject::connect(client, &McClient::finished, this, [this, client]() { QObject::connect(client, &McClient::finished, this, [this, client]() { client->deleteLater(); });
client->deleteLater();
});
client->getStatusData(); client->getStatusData();
}); });
QObject::connect(resolver, &McResolver::failed, this, [this](QString error) { QObject::connect(resolver, &McResolver::failed, this, [this](QString error) { emitFailed(error); });
emitFailed(error);
});
// Delete McResolver object when done // Delete McResolver object when done
QObject::connect(resolver, &McResolver::finished, [resolver]() { QObject::connect(resolver, &McResolver::finished, [resolver]() { resolver->deleteLater(); });
resolver->deleteLater();
});
resolver->ping(); resolver->ping();
} }

View File

@ -5,18 +5,17 @@
#include <tasks/Task.h> #include <tasks/Task.h>
class ServerPingTask : public Task { class ServerPingTask : public Task {
Q_OBJECT Q_OBJECT
public: public:
explicit ServerPingTask(QString domain, int port) : Task(), m_domain(domain), m_port(port) {} explicit ServerPingTask(QString domain, int port) : Task(), m_domain(domain), m_port(port) {}
~ServerPingTask() override = default; ~ServerPingTask() override = default;
int m_outputOnlinePlayers = -1; int m_outputOnlinePlayers = -1;
private: private:
QString m_domain; QString m_domain;
int m_port; int m_port;
protected: protected:
virtual void executeTask() override; virtual void executeTask() override;
}; };

View File

@ -18,7 +18,8 @@
#include "HintOverrideProxyStyle.h" #include "HintOverrideProxyStyle.h"
HintOverrideProxyStyle::HintOverrideProxyStyle(QStyle* style) : QProxyStyle(style) { HintOverrideProxyStyle::HintOverrideProxyStyle(QStyle* style) : QProxyStyle(style)
{
setObjectName(style->objectName()); setObjectName(style->objectName());
} }