New code style refactor

This commit is contained in:
Jack Andersen 2018-12-07 19:19:40 -10:00
parent a1ed397436
commit 39a8b1608d
24 changed files with 2019 additions and 2329 deletions

View File

@ -16,10 +16,8 @@ const QString CurPlatformString = QStringLiteral("linux");
#error HECL does not know which OS to fetch for #error HECL does not know which OS to fetch for
#endif #endif
QString PlatformToString(Platform plat) QString PlatformToString(Platform plat) {
{ switch (plat) {
switch (plat)
{
case Platform::MacOS: case Platform::MacOS:
return QStringLiteral("macos"); return QStringLiteral("macos");
case Platform::Win32: case Platform::Win32:
@ -34,18 +32,15 @@ QString PlatformToString(Platform plat)
Architecture CurArchitecture = Architecture::Invalid; Architecture CurArchitecture = Architecture::Invalid;
QString CurArchitectureString; QString CurArchitectureString;
Platform StringToPlatform(const QString& str) Platform StringToPlatform(const QString& str) {
{
for (int i = 1; i < int(Platform::MAXPlatform); ++i) for (int i = 1; i < int(Platform::MAXPlatform); ++i)
if (!str.compare(PlatformToString(Platform(i)), Qt::CaseInsensitive)) if (!str.compare(PlatformToString(Platform(i)), Qt::CaseInsensitive))
return Platform(i); return Platform(i);
return Platform::Invalid; return Platform::Invalid;
} }
QString ArchitectureToString(Architecture arch) QString ArchitectureToString(Architecture arch) {
{ switch (arch) {
switch (arch)
{
case Architecture::X86: case Architecture::X86:
return QStringLiteral("x86"); return QStringLiteral("x86");
case Architecture::X86_64: case Architecture::X86_64:
@ -59,18 +54,15 @@ QString ArchitectureToString(Architecture arch)
} }
} }
Architecture StringToArchitecture(const QString& str) Architecture StringToArchitecture(const QString& str) {
{
for (int i = 1; i < int(Architecture::MAXArchitecture); ++i) for (int i = 1; i < int(Architecture::MAXArchitecture); ++i)
if (!str.compare(ArchitectureToString(Architecture(i)), Qt::CaseInsensitive)) if (!str.compare(ArchitectureToString(Architecture(i)), Qt::CaseInsensitive))
return Architecture(i); return Architecture(i);
return Architecture::Invalid; return Architecture::Invalid;
} }
QString VectorISAToString(VectorISA visa) QString VectorISAToString(VectorISA visa) {
{ switch (visa) {
switch (visa)
{
case VectorISA::X87: case VectorISA::X87:
return QStringLiteral("x87"); return QStringLiteral("x87");
case VectorISA::SSE: case VectorISA::SSE:
@ -90,20 +82,17 @@ QString VectorISAToString(VectorISA visa)
} }
} }
VectorISA StringToVectorISA(const QString& str) VectorISA StringToVectorISA(const QString& str) {
{
for (int i = 1; i < int(VectorISA::MAXVectorISA); ++i) for (int i = 1; i < int(VectorISA::MAXVectorISA); ++i)
if (!str.compare(VectorISAToString(VectorISA(i)), Qt::CaseInsensitive)) if (!str.compare(VectorISAToString(VectorISA(i)), Qt::CaseInsensitive))
return VectorISA(i); return VectorISA(i);
return VectorISA::Invalid; return VectorISA::Invalid;
} }
URDEVersion::URDEVersion(const QString& filename) URDEVersion::URDEVersion(const QString& filename) {
{
int idx; int idx;
QString useFilename = filename; QString useFilename = filename;
if ((idx = filename.indexOf('.')) >= 0) if ((idx = filename.indexOf('.')) >= 0) {
{
m_extension = QString(filename).remove(0, idx); m_extension = QString(filename).remove(0, idx);
useFilename.truncate(idx); useFilename.truncate(idx);
} }
@ -118,20 +107,16 @@ URDEVersion::URDEVersion(const QString& filename)
m_vectorISA = StringToVectorISA(list[4]); m_vectorISA = StringToVectorISA(list[4]);
} }
QString URDEVersion::fileString(bool withExtension) const QString URDEVersion::fileString(bool withExtension) const {
{
if (m_version < 0) if (m_version < 0)
return {}; return {};
if (withExtension && !m_extension.isEmpty()) if (withExtension && !m_extension.isEmpty())
return QString("urde-%1-%2-%3-%4%5").arg(QString::number(m_version), return QString("urde-%1-%2-%3-%4%5")
PlatformToString(m_platform), .arg(QString::number(m_version), PlatformToString(m_platform), ArchitectureToString(m_architecture),
ArchitectureToString(m_architecture), VectorISAToString(m_vectorISA), m_extension);
VectorISAToString(m_vectorISA),
m_extension);
else else
return QString("urde-%1-%2-%3-%4").arg(QString::number(m_version), return QString("urde-%1-%2-%3-%4")
PlatformToString(m_platform), .arg(QString::number(m_version), PlatformToString(m_platform), ArchitectureToString(m_architecture),
ArchitectureToString(m_architecture),
VectorISAToString(m_vectorISA)); VectorISAToString(m_vectorISA));
} }
@ -139,8 +124,7 @@ QString URDEVersion::fileString(bool withExtension) const
static void HUPHandler(int) {} static void HUPHandler(int) {}
#endif #endif
void InitializePlatform() void InitializePlatform() {
{
#ifndef _WIN32 #ifndef _WIN32
/* This can happen when terminating hecl - do nothing */ /* This can happen when terminating hecl - do nothing */
signal(SIGHUP, HUPHandler); signal(SIGHUP, HUPHandler);
@ -150,13 +134,11 @@ void InitializePlatform()
const_cast<Architecture&>(CurArchitecture) = Architecture::X86_64; const_cast<Architecture&>(CurArchitecture) = Architecture::X86_64;
#elif ZEUS_ARCH_X86 #elif ZEUS_ARCH_X86
#if !defined(__APPLE__) && !defined(_WIN32) #if !defined(__APPLE__) && !defined(_WIN32)
const_cast<Architecture&>(CurArchitecture) = const_cast<Architecture&>(CurArchitecture) = (sysconf(_SC_WORD_BIT) == 64 ? Architecture::X86_64 : Architecture::X86);
(sysconf(_SC_WORD_BIT) == 64 ? Architecture::X86_64 : Architecture::X86);
#elif _WIN32 #elif _WIN32
bool isWOW = false; bool isWOW = false;
IsWow64Process(GetCurrentProcess(), &isWOW); IsWow64Process(GetCurrentProcess(), &isWOW);
const_cast<Architecture&>(CurArchitecture) = const_cast<Architecture&>(CurArchitecture) = (isWOW ? Architecture::X86_64 : Architecture::X86);
(isWOW ? Architecture::X86_64 : Architecture::X86);
#endif #endif
#endif #endif
const_cast<QString&>(CurArchitectureString) = ArchitectureToString(CurArchitecture); const_cast<QString&>(CurArchitectureString) = ArchitectureToString(CurArchitecture);

View File

@ -4,14 +4,7 @@
#include <QMetaType> #include <QMetaType>
#include "zeus/Math.hpp" #include "zeus/Math.hpp"
enum class Platform enum class Platform { Invalid, MacOS, Win32, Linux, MAXPlatform };
{
Invalid,
MacOS,
Win32,
Linux,
MAXPlatform
};
QString PlatformToString(Platform plat); QString PlatformToString(Platform plat);
Platform StringToPlatform(const QString& str); Platform StringToPlatform(const QString& str);
@ -25,43 +18,24 @@ constexpr Platform CurPlatform = Platform::Linux;
extern const QString CurPlatformString; extern const QString CurPlatformString;
enum class Architecture enum class Architecture { Invalid, X86, X86_64, ARM, AARCH64, MAXArchitecture };
{
Invalid,
X86,
X86_64,
ARM,
AARCH64,
MAXArchitecture
};
QString ArchitectureToString(Architecture arch); QString ArchitectureToString(Architecture arch);
Architecture StringToArchitecture(const QString& str); Architecture StringToArchitecture(const QString& str);
extern Architecture CurArchitecture; extern Architecture CurArchitecture;
extern QString CurArchitectureString; extern QString CurArchitectureString;
enum class VectorISA enum class VectorISA { Invalid, X87, SSE, SSE2, SSE3, SSE41, AVX, AVX2, MAXVectorISA };
{
Invalid,
X87,
SSE,
SSE2,
SSE3,
SSE41,
AVX,
AVX2,
MAXVectorISA
};
QString VectorISAToString(VectorISA visa); QString VectorISAToString(VectorISA visa);
VectorISA StringToVectorISA(const QString& str); VectorISA StringToVectorISA(const QString& str);
class URDEVersion class URDEVersion {
{
int m_version = -1; int m_version = -1;
Platform m_platform = CurPlatform; Platform m_platform = CurPlatform;
Architecture m_architecture = CurArchitecture; Architecture m_architecture = CurArchitecture;
VectorISA m_vectorISA = VectorISA::Invalid; VectorISA m_vectorISA = VectorISA::Invalid;
QString m_extension; QString m_extension;
public: public:
URDEVersion() = default; URDEVersion() = default;
explicit URDEVersion(const QString& filename); explicit URDEVersion(const QString& filename);
@ -75,4 +49,3 @@ public:
Q_DECLARE_METATYPE(URDEVersion); Q_DECLARE_METATYPE(URDEVersion);
void InitializePlatform(); void InitializePlatform();

View File

@ -6,43 +6,38 @@
#if KEY_PINNING #if KEY_PINNING
static const char AxioDLPublicKeyPEM[] = static const char AxioDLPublicKeyPEM[] =
"-----BEGIN PUBLIC KEY-----\n" "-----BEGIN PUBLIC KEY-----\n"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvtshImzoP1a++9P5RK0k\n" "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvtshImzoP1a++9P5RK0k\n"
"btTOpwie7O7S/wWFZxwwbMezEPhjw2uu86TPqJe3P/1v+6xRKrEf9zFn/sKNygvD\n" "btTOpwie7O7S/wWFZxwwbMezEPhjw2uu86TPqJe3P/1v+6xRKrEf9zFn/sKNygvD\n"
"bO64ZkJre4M46IYd0XxwIhiu7PBR+13CD+fqbrbYwPkoG090CP4MtZZN6mt5NAKB\n" "bO64ZkJre4M46IYd0XxwIhiu7PBR+13CD+fqbrbYwPkoG090CP4MtZZN6mt5NAKB\n"
"QHoIj0wV5K/jJE9cBQxViwOqrxK05Cl/ivy0gRtpL7Ot6S+QHL3++rb6U2hWydIQ\n" "QHoIj0wV5K/jJE9cBQxViwOqrxK05Cl/ivy0gRtpL7Ot6S+QHL3++rb6U2hWydIQ\n"
"kS+ucufKCIL77RcDwAc9vwNvzxf9EUU2pmq+EsEtLgRw3fR6BInoltOI8P9X5Wo6\n" "kS+ucufKCIL77RcDwAc9vwNvzxf9EUU2pmq+EsEtLgRw3fR6BInoltOI8P9X5Wo6\n"
"/skeg92xZA++vv0neq5gjjDfa2A1zDgJRysz3Xps/AMlLOe55XCzXse9BpvChT+Z\n" "/skeg92xZA++vv0neq5gjjDfa2A1zDgJRysz3Xps/AMlLOe55XCzXse9BpvChT+Z\n"
"pwIDAQAB\n" "pwIDAQAB\n"
"-----END PUBLIC KEY-----\n"; "-----END PUBLIC KEY-----\n";
static const QSslKey AxioDLPublicKey = static const QSslKey AxioDLPublicKey = QSslKey({AxioDLPublicKeyPEM}, QSsl::Rsa, QSsl::Pem, QSsl::PublicKey);
QSslKey({AxioDLPublicKeyPEM}, QSsl::Rsa, QSsl::Pem, QSsl::PublicKey);
static const char AxioDLEdgePublicKeyPEM[] = static const char AxioDLEdgePublicKeyPEM[] =
"-----BEGIN PUBLIC KEY-----\n" "-----BEGIN PUBLIC KEY-----\n"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4a8ZLg3LRU0FiK6m8g2pT3qVBTMA\n" "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4a8ZLg3LRU0FiK6m8g2pT3qVBTMA\n"
"K2Uu5VGl7iamdGpUjynQ4uYWMx+WXf2Qkh7UZZgYvA6UeWHEs3M6ME8T6g==\n" "K2Uu5VGl7iamdGpUjynQ4uYWMx+WXf2Qkh7UZZgYvA6UeWHEs3M6ME8T6g==\n"
"-----END PUBLIC KEY-----\n"; "-----END PUBLIC KEY-----\n";
static const QSslKey AxioDLEdgePublicKey = static const QSslKey AxioDLEdgePublicKey = QSslKey({AxioDLEdgePublicKeyPEM}, QSsl::Ec, QSsl::Pem, QSsl::PublicKey);
QSslKey({AxioDLEdgePublicKeyPEM}, QSsl::Ec, QSsl::Pem, QSsl::PublicKey);
#endif #endif
void DownloadManager::_validateCert(QNetworkReply* reply) void DownloadManager::_validateCert(QNetworkReply* reply) {
{
#if KEY_PINNING #if KEY_PINNING
QSslCertificate peerCert = reply->sslConfiguration().peerCertificate(); QSslCertificate peerCert = reply->sslConfiguration().peerCertificate();
QSslKey peerKey = peerCert.publicKey(); QSslKey peerKey = peerCert.publicKey();
if (peerKey != AxioDLPublicKey && peerKey != AxioDLEdgePublicKey) if (peerKey != AxioDLPublicKey && peerKey != AxioDLEdgePublicKey) {
{
auto cn = peerCert.subjectInfo(QSslCertificate::CommonName); auto cn = peerCert.subjectInfo(QSslCertificate::CommonName);
if (!cn.empty()) if (!cn.empty())
setError(QNetworkReply::SslHandshakeFailedError, setError(QNetworkReply::SslHandshakeFailedError,
QStringLiteral("Certificate pinning mismatch \"") + cn.first() + "\""); QStringLiteral("Certificate pinning mismatch \"") + cn.first() + "\"");
else else
setError(QNetworkReply::SslHandshakeFailedError, setError(QNetworkReply::SslHandshakeFailedError, QStringLiteral("Certificate pinning mismatch"));
QStringLiteral("Certificate pinning mismatch"));
reply->abort(); reply->abort();
} }
#endif #endif
@ -51,8 +46,7 @@ void DownloadManager::_validateCert(QNetworkReply* reply)
static const QString Domain = QStringLiteral("https://releases.axiodl.com/"); static const QString Domain = QStringLiteral("https://releases.axiodl.com/");
static const QString Index = QStringLiteral("index.txt"); static const QString Index = QStringLiteral("index.txt");
void DownloadManager::fetchIndex() void DownloadManager::fetchIndex() {
{
if (m_indexInProgress) if (m_indexInProgress)
return; return;
@ -60,16 +54,13 @@ void DownloadManager::fetchIndex()
QString url = Domain + CurPlatformString + '/' + Index; QString url = Domain + CurPlatformString + '/' + Index;
m_indexInProgress = m_netManager.get(QNetworkRequest(url)); m_indexInProgress = m_netManager.get(QNetworkRequest(url));
connect(m_indexInProgress, SIGNAL(finished()), connect(m_indexInProgress, SIGNAL(finished()), this, SLOT(indexFinished()));
this, SLOT(indexFinished())); connect(m_indexInProgress, SIGNAL(error(QNetworkReply::NetworkError)), this,
connect(m_indexInProgress, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(indexError(QNetworkReply::NetworkError)));
this, SLOT(indexError(QNetworkReply::NetworkError))); connect(m_indexInProgress, SIGNAL(encrypted()), this, SLOT(indexValidateCert()));
connect(m_indexInProgress, SIGNAL(encrypted()),
this, SLOT(indexValidateCert()));
} }
void DownloadManager::fetchBinary(const QString& str, const QString& outPath) void DownloadManager::fetchBinary(const QString& str, const QString& outPath) {
{
if (m_binaryInProgress) if (m_binaryInProgress)
return; return;
@ -78,31 +69,26 @@ void DownloadManager::fetchBinary(const QString& str, const QString& outPath)
QString url = Domain + CurPlatformString + '/' + str; QString url = Domain + CurPlatformString + '/' + str;
m_binaryInProgress = m_netManager.get(QNetworkRequest(url)); m_binaryInProgress = m_netManager.get(QNetworkRequest(url));
connect(m_binaryInProgress, SIGNAL(finished()), connect(m_binaryInProgress, SIGNAL(finished()), this, SLOT(binaryFinished()));
this, SLOT(binaryFinished())); connect(m_binaryInProgress, SIGNAL(error(QNetworkReply::NetworkError)), this,
connect(m_binaryInProgress, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(binaryError(QNetworkReply::NetworkError)));
this, SLOT(binaryError(QNetworkReply::NetworkError))); connect(m_binaryInProgress, SIGNAL(encrypted()), this, SLOT(binaryValidateCert()));
connect(m_binaryInProgress, SIGNAL(encrypted()), connect(m_binaryInProgress, SIGNAL(downloadProgress(qint64, qint64)), this,
this, SLOT(binaryValidateCert())); SLOT(binaryDownloadProgress(qint64, qint64)));
connect(m_binaryInProgress, SIGNAL(downloadProgress(qint64, qint64)),
this, SLOT(binaryDownloadProgress(qint64, qint64)));
if (m_progBar) if (m_progBar) {
{
m_progBar->setEnabled(true); m_progBar->setEnabled(true);
m_progBar->setValue(0); m_progBar->setValue(0);
} }
} }
void DownloadManager::indexFinished() void DownloadManager::indexFinished() {
{
if (m_hasError) if (m_hasError)
return; return;
QStringList files; QStringList files;
while (!m_indexInProgress->atEnd()) while (!m_indexInProgress->atEnd()) {
{
QString line = QString::fromUtf8(m_indexInProgress->readLine()).trimmed(); QString line = QString::fromUtf8(m_indexInProgress->readLine()).trimmed();
if (line.isEmpty()) if (line.isEmpty())
continue; continue;
@ -116,20 +102,15 @@ void DownloadManager::indexFinished()
m_indexInProgress = nullptr; m_indexInProgress = nullptr;
} }
void DownloadManager::indexError(QNetworkReply::NetworkError error) void DownloadManager::indexError(QNetworkReply::NetworkError error) {
{
setError(error, m_indexInProgress->errorString()); setError(error, m_indexInProgress->errorString());
m_indexInProgress->deleteLater(); m_indexInProgress->deleteLater();
m_indexInProgress = nullptr; m_indexInProgress = nullptr;
} }
void DownloadManager::indexValidateCert() void DownloadManager::indexValidateCert() { _validateCert(m_indexInProgress); }
{
_validateCert(m_indexInProgress);
}
void DownloadManager::binaryFinished() void DownloadManager::binaryFinished() {
{
if (m_hasError) if (m_hasError)
return; return;
@ -139,8 +120,7 @@ void DownloadManager::binaryFinished()
QByteArray all = m_binaryInProgress->readAll(); QByteArray all = m_binaryInProgress->readAll();
QBuffer buff(&all); QBuffer buff(&all);
QuaZip zip(&buff); QuaZip zip(&buff);
if (!zip.open(QuaZip::mdUnzip)) if (!zip.open(QuaZip::mdUnzip)) {
{
setError(QNetworkReply::UnknownContentError, "Unable to open zip archive."); setError(QNetworkReply::UnknownContentError, "Unable to open zip archive.");
m_binaryInProgress->deleteLater(); m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr; m_binaryInProgress = nullptr;
@ -154,8 +134,7 @@ void DownloadManager::binaryFinished()
m_binaryInProgress = nullptr; m_binaryInProgress = nullptr;
} }
void DownloadManager::binaryError(QNetworkReply::NetworkError error) void DownloadManager::binaryError(QNetworkReply::NetworkError error) {
{
setError(error, m_binaryInProgress->errorString()); setError(error, m_binaryInProgress->errorString());
m_binaryInProgress->deleteLater(); m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr; m_binaryInProgress = nullptr;
@ -167,15 +146,10 @@ void DownloadManager::binaryError(QNetworkReply::NetworkError error)
m_failedHandler(); m_failedHandler();
} }
void DownloadManager::binaryValidateCert() void DownloadManager::binaryValidateCert() { _validateCert(m_binaryInProgress); }
{
_validateCert(m_binaryInProgress);
}
void DownloadManager::binaryDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) void DownloadManager::binaryDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) {
{ if (m_progBar) {
if (m_progBar)
{
if (bytesReceived == bytesTotal) if (bytesReceived == bytesTotal)
m_progBar->setValue(100); m_progBar->setValue(100);
else else

View File

@ -8,8 +8,7 @@
class QuaZip; class QuaZip;
class DownloadManager : public QObject class DownloadManager : public QObject {
{
Q_OBJECT Q_OBJECT
QNetworkAccessManager m_netManager; QNetworkAccessManager m_netManager;
QNetworkReply* m_indexInProgress = nullptr; QNetworkReply* m_indexInProgress = nullptr;
@ -22,15 +21,13 @@ class DownloadManager : public QObject
std::function<void(QuaZip& file)> m_completionHandler; std::function<void(QuaZip& file)> m_completionHandler;
std::function<void()> m_failedHandler; std::function<void()> m_failedHandler;
void resetError() void resetError() {
{
m_hasError = false; m_hasError = false;
if (m_errorLabel) if (m_errorLabel)
m_errorLabel->setText(QString()); m_errorLabel->setText(QString());
} }
void setError(QNetworkReply::NetworkError error, const QString& errStr) void setError(QNetworkReply::NetworkError error, const QString& errStr) {
{
if (m_hasError && error == QNetworkReply::OperationCanceledError) if (m_hasError && error == QNetworkReply::OperationCanceledError)
return; return;
m_hasError = true; m_hasError = true;
@ -41,13 +38,10 @@ class DownloadManager : public QObject
void _validateCert(QNetworkReply* reply); void _validateCert(QNetworkReply* reply);
public: public:
explicit DownloadManager(QObject* parent = Q_NULLPTR) explicit DownloadManager(QObject* parent = Q_NULLPTR) : QObject(parent), m_netManager(this) {}
: QObject(parent), m_netManager(this) {}
void connectWidgets(QProgressBar* progBar, QLabel* errorLabel, void connectWidgets(QProgressBar* progBar, QLabel* errorLabel,
std::function<void(const QStringList& index)>&& indexCompletionHandler, std::function<void(const QStringList& index)>&& indexCompletionHandler,
std::function<void(QuaZip& file)>&& completionHandler, std::function<void(QuaZip& file)>&& completionHandler, std::function<void()>&& failedHandler) {
std::function<void()>&& failedHandler)
{
m_progBar = progBar; m_progBar = progBar;
m_errorLabel = errorLabel; m_errorLabel = errorLabel;
m_indexCompletionHandler = std::move(indexCompletionHandler); m_indexCompletionHandler = std::move(indexCompletionHandler);
@ -67,6 +61,4 @@ public slots:
void binaryError(QNetworkReply::NetworkError error); void binaryError(QNetworkReply::NetworkError error);
void binaryValidateCert(); void binaryValidateCert();
void binaryDownloadProgress(qint64 bytesReceived, qint64 bytesTotal); void binaryDownloadProgress(qint64 bytesReceived, qint64 bytesTotal);
}; };

View File

@ -2,19 +2,16 @@
#include <QLabel> #include <QLabel>
class ErrorLabel : public QLabel class ErrorLabel : public QLabel {
{
public: public:
ErrorLabel(QWidget* parent = Q_NULLPTR) : QLabel(parent) {} ErrorLabel(QWidget* parent = Q_NULLPTR) : QLabel(parent) {}
void setText(const QString& str, bool success = false) void setText(const QString& str, bool success = false) {
{
QPalette pal = QLabel::palette(); QPalette pal = QLabel::palette();
if (success) if (success)
pal.setColor(QPalette::WindowText, QColor(0,255,0)); pal.setColor(QPalette::WindowText, QColor(0, 255, 0));
else else
pal.setColor(QPalette::WindowText, QColor(255,47,0)); pal.setColor(QPalette::WindowText, QColor(255, 47, 0));
QLabel::setPalette(pal); QLabel::setPalette(pal);
QLabel::setText(str); QLabel::setText(str);
} }
}; };

View File

@ -6,53 +6,52 @@
// http://misc.flogisoft.com/bash/tip_colors_and_formatting // http://misc.flogisoft.com/bash/tip_colors_and_formatting
// http://invisible-island.net/xterm/ctlseqs/ctlseqs.html // http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharFormat& textCharFormat, void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharFormat& textCharFormat,
const QTextCharFormat& defaultTextCharFormat) const QTextCharFormat& defaultTextCharFormat) {
{
switch (attribute) { switch (attribute) {
case 0 : { // Normal/Default (reset all attributes) case 0: { // Normal/Default (reset all attributes)
textCharFormat = defaultTextCharFormat; textCharFormat = defaultTextCharFormat;
break; break;
} }
case 1 : { // Bold/Bright (bold or increased intensity) case 1: { // Bold/Bright (bold or increased intensity)
textCharFormat.setFontWeight(QFont::Bold); textCharFormat.setFontWeight(QFont::Bold);
break; break;
} }
case 2 : { // Dim/Faint (decreased intensity) case 2: { // Dim/Faint (decreased intensity)
textCharFormat.setFontWeight(QFont::Light); textCharFormat.setFontWeight(QFont::Light);
break; break;
} }
case 3 : { // Italicized (italic on) case 3: { // Italicized (italic on)
textCharFormat.setFontItalic(true); textCharFormat.setFontItalic(true);
break; break;
} }
case 4 : { // Underscore (single underlined) case 4: { // Underscore (single underlined)
textCharFormat.setUnderlineStyle(QTextCharFormat::SingleUnderline); textCharFormat.setUnderlineStyle(QTextCharFormat::SingleUnderline);
textCharFormat.setFontUnderline(true); textCharFormat.setFontUnderline(true);
break; break;
} }
case 5 : { // Blink (slow, appears as Bold) case 5: { // Blink (slow, appears as Bold)
textCharFormat.setFontWeight(QFont::Bold); textCharFormat.setFontWeight(QFont::Bold);
break; break;
} }
case 6 : { // Blink (rapid, appears as very Bold) case 6: { // Blink (rapid, appears as very Bold)
textCharFormat.setFontWeight(QFont::Black); textCharFormat.setFontWeight(QFont::Black);
break; break;
} }
case 7 : { // Reverse/Inverse (swap foreground and background) case 7: { // Reverse/Inverse (swap foreground and background)
QBrush foregroundBrush = textCharFormat.foreground(); QBrush foregroundBrush = textCharFormat.foreground();
textCharFormat.setForeground(textCharFormat.background()); textCharFormat.setForeground(textCharFormat.background());
textCharFormat.setBackground(foregroundBrush); textCharFormat.setBackground(foregroundBrush);
break; break;
} }
case 8 : { // Concealed/Hidden/Invisible (usefull for passwords) case 8: { // Concealed/Hidden/Invisible (usefull for passwords)
textCharFormat.setForeground(textCharFormat.background()); textCharFormat.setForeground(textCharFormat.background());
break; break;
} }
case 9 : { // Crossed-out characters case 9: { // Crossed-out characters
textCharFormat.setFontStrikeOut(true); textCharFormat.setFontStrikeOut(true);
break; break;
} }
case 10 : { // Primary (default) font case 10: { // Primary (default) font
textCharFormat.setFont(defaultTextCharFormat.font()); textCharFormat.setFont(defaultTextCharFormat.font());
break; break;
} }
@ -70,49 +69,50 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
QStringList fontStyles = fontDatabase.styles(fontFamily); QStringList fontStyles = fontDatabase.styles(fontFamily);
int fontStyleIndex = attribute - 11; int fontStyleIndex = attribute - 11;
if (fontStyleIndex < fontStyles.length()) { if (fontStyleIndex < fontStyles.length()) {
textCharFormat.setFont(fontDatabase.font(fontFamily, fontStyles.at(fontStyleIndex), textCharFormat.font().pointSize())); textCharFormat.setFont(
fontDatabase.font(fontFamily, fontStyles.at(fontStyleIndex), textCharFormat.font().pointSize()));
} }
break; break;
} }
case 20 : { // Fraktur (unsupported) case 20: { // Fraktur (unsupported)
break; break;
} }
case 21 : { // Set Bold off case 21: { // Set Bold off
textCharFormat.setFontWeight(QFont::Normal); textCharFormat.setFontWeight(QFont::Normal);
break; break;
} }
case 22 : { // Set Dim off case 22: { // Set Dim off
textCharFormat.setFontWeight(QFont::Normal); textCharFormat.setFontWeight(QFont::Normal);
break; break;
} }
case 23 : { // Unset italic and unset fraktur case 23: { // Unset italic and unset fraktur
textCharFormat.setFontItalic(false); textCharFormat.setFontItalic(false);
break; break;
} }
case 24 : { // Unset underlining case 24: { // Unset underlining
textCharFormat.setUnderlineStyle(QTextCharFormat::NoUnderline); textCharFormat.setUnderlineStyle(QTextCharFormat::NoUnderline);
textCharFormat.setFontUnderline(false); textCharFormat.setFontUnderline(false);
break; break;
} }
case 25 : { // Unset Blink/Bold case 25: { // Unset Blink/Bold
textCharFormat.setFontWeight(QFont::Normal); textCharFormat.setFontWeight(QFont::Normal);
break; break;
} }
case 26 : { // Reserved case 26: { // Reserved
break; break;
} }
case 27 : { // Positive (non-inverted) case 27: { // Positive (non-inverted)
QBrush backgroundBrush = textCharFormat.background(); QBrush backgroundBrush = textCharFormat.background();
textCharFormat.setBackground(textCharFormat.foreground()); textCharFormat.setBackground(textCharFormat.foreground());
textCharFormat.setForeground(backgroundBrush); textCharFormat.setForeground(backgroundBrush);
break; break;
} }
case 28 : { case 28: {
textCharFormat.setForeground(defaultTextCharFormat.foreground()); textCharFormat.setForeground(defaultTextCharFormat.foreground());
textCharFormat.setBackground(defaultTextCharFormat.background()); textCharFormat.setBackground(defaultTextCharFormat.background());
break; break;
} }
case 29 : { case 29: {
textCharFormat.setUnderlineStyle(QTextCharFormat::NoUnderline); textCharFormat.setUnderlineStyle(QTextCharFormat::NoUnderline);
textCharFormat.setFontUnderline(false); textCharFormat.setFontUnderline(false);
break; break;
@ -124,99 +124,94 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
case 34: case 34:
case 35: case 35:
case 36: case 36:
case 37: case 37: {
{
int colorIndex = attribute - 30; int colorIndex = attribute - 30;
QColor color; QColor color;
if (QFont::Normal < textCharFormat.fontWeight()) { if (QFont::Normal < textCharFormat.fontWeight()) {
switch (colorIndex) { switch (colorIndex) {
case 0 : { case 0: {
color = Qt::darkGray; color = Qt::darkGray;
break; break;
} }
case 1 : { case 1: {
color = Qt::red; color = Qt::red;
break; break;
} }
case 2 : { case 2: {
color = Qt::green; color = Qt::green;
break; break;
} }
case 3 : { case 3: {
color = Qt::yellow; color = Qt::yellow;
break; break;
} }
case 4 : { case 4: {
color = Qt::blue; color = Qt::blue;
break; break;
} }
case 5 : { case 5: {
color = Qt::magenta; color = Qt::magenta;
break; break;
} }
case 6 : { case 6: {
color = Qt::cyan; color = Qt::cyan;
break; break;
} }
case 7 : { case 7: {
color = Qt::white; color = Qt::white;
break; break;
} }
default : { default: { Q_ASSERT(false); }
Q_ASSERT(false);
}
} }
} else { } else {
/* Normally dark colors, but forced to light colors for visibility */ /* Normally dark colors, but forced to light colors for visibility */
switch (colorIndex) { switch (colorIndex) {
case 0 : { case 0: {
color = Qt::darkGray; color = Qt::darkGray;
break; break;
} }
case 1 : { case 1: {
color = Qt::red; color = Qt::red;
break; break;
} }
case 2 : { case 2: {
color = Qt::green; color = Qt::green;
break; break;
} }
case 3 : { case 3: {
color = Qt::yellow; color = Qt::yellow;
break; break;
} }
case 4 : { case 4: {
color = Qt::blue; color = Qt::blue;
break; break;
} }
case 5 : { case 5: {
color = Qt::magenta; color = Qt::magenta;
break; break;
} }
case 6 : { case 6: {
color = Qt::cyan; color = Qt::cyan;
break; break;
} }
case 7 : { case 7: {
color = Qt::white; color = Qt::white;
break; break;
} }
default : { default: { Q_ASSERT(false); }
Q_ASSERT(false);
}
} }
} }
textCharFormat.setForeground(color); textCharFormat.setForeground(color);
break; break;
} }
case 38 : { case 38: {
if (i.hasNext()) { if (i.hasNext()) {
bool ok = false; bool ok = false;
int selector = i.next().toInt(&ok); int selector = i.next().toInt(&ok);
Q_ASSERT(ok); Q_ASSERT(ok);
QColor color; QColor color;
switch (selector) { switch (selector) {
case 2 : { case 2: {
if (!i.hasNext()) { if (!i.hasNext()) {
break; break;
} }
@ -235,23 +230,17 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
color.setRgb(red, green, blue); color.setRgb(red, green, blue);
break; break;
} }
case 5 : case 5: {
{
if (!i.hasNext()) { if (!i.hasNext()) {
break; break;
} }
int index = i.next().toInt(&ok); int index = i.next().toInt(&ok);
Q_ASSERT(ok); Q_ASSERT(ok);
if (index >= 0 && index <= 0x07) if (index >= 0 && index <= 0x07) { // 0x00-0x07: standard colors (as in ESC [ 30..37 m)
{ // 0x00-0x07: standard colors (as in ESC [ 30..37 m)
return ParseEscapeSequence(index - 0x00 + 30, i, textCharFormat, defaultTextCharFormat); return ParseEscapeSequence(index - 0x00 + 30, i, textCharFormat, defaultTextCharFormat);
} } else if (index >= 0x08 && index <= 0x0F) { // 0x08-0x0F: high intensity colors (as in ESC [ 90..97 m)
else if (index >= 0x08 && index <= 0x0F)
{ // 0x08-0x0F: high intensity colors (as in ESC [ 90..97 m)
return ParseEscapeSequence(index - 0x08 + 90, i, textCharFormat, defaultTextCharFormat); return ParseEscapeSequence(index - 0x08 + 90, i, textCharFormat, defaultTextCharFormat);
} } else if (index >= 0x10 && index <= 0xE7) { // 0x10-0xE7: 6*6*6=216 colors: 16 + 36*r + 6*g + b (0≤r,g,b≤5)
else if (index >= 0x10 && index <= 0xE7)
{ // 0x10-0xE7: 6*6*6=216 colors: 16 + 36*r + 6*g + b (0≤r,g,b≤5)
index -= 0x10; index -= 0x10;
int red = index % 6; int red = index % 6;
index /= 6; index /= 6;
@ -262,9 +251,7 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
Q_ASSERT(index == 0); Q_ASSERT(index == 0);
color.setRgb(red, green, blue); color.setRgb(red, green, blue);
break; break;
} } else if (index >= 0xE8 && index <= 0xFF) { // 0xE8-0xFF: grayscale from black to white in 24 steps
else if (index >= 0xE8 && index <= 0xFF)
{ // 0xE8-0xFF: grayscale from black to white in 24 steps
qreal intensity = qreal(index - 0xE8) / (0xFF - 0xE8); qreal intensity = qreal(index - 0xE8) / (0xFF - 0xE8);
color.setRgbF(intensity, intensity, intensity); color.setRgbF(intensity, intensity, intensity);
break; break;
@ -272,14 +259,12 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
textCharFormat.setForeground(color); textCharFormat.setForeground(color);
break; break;
} }
default : { default: { break; }
break;
}
} }
} }
break; break;
} }
case 39 : { case 39: {
textCharFormat.setForeground(defaultTextCharFormat.foreground()); textCharFormat.setForeground(defaultTextCharFormat.foreground());
break; break;
} }
@ -294,53 +279,51 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
int colorIndex = attribute - 40; int colorIndex = attribute - 40;
QColor color; QColor color;
switch (colorIndex) { switch (colorIndex) {
case 0 : { case 0: {
color = Qt::darkGray; color = Qt::darkGray;
break; break;
} }
case 1 : { case 1: {
color = Qt::red; color = Qt::red;
break; break;
} }
case 2 : { case 2: {
color = Qt::green; color = Qt::green;
break; break;
} }
case 3 : { case 3: {
color = Qt::yellow; color = Qt::yellow;
break; break;
} }
case 4 : { case 4: {
color = Qt::blue; color = Qt::blue;
break; break;
} }
case 5 : { case 5: {
color = Qt::magenta; color = Qt::magenta;
break; break;
} }
case 6 : { case 6: {
color = Qt::cyan; color = Qt::cyan;
break; break;
} }
case 7 : { case 7: {
color = Qt::white; color = Qt::white;
break; break;
} }
default : { default: { Q_ASSERT(false); }
Q_ASSERT(false);
}
} }
textCharFormat.setBackground(color); textCharFormat.setBackground(color);
break; break;
} }
case 48 : { case 48: {
if (i.hasNext()) { if (i.hasNext()) {
bool ok = false; bool ok = false;
int selector = i.next().toInt(&ok); int selector = i.next().toInt(&ok);
Q_ASSERT(ok); Q_ASSERT(ok);
QColor color; QColor color;
switch (selector) { switch (selector) {
case 2 : { case 2: {
if (!i.hasNext()) { if (!i.hasNext()) {
break; break;
} }
@ -359,22 +342,17 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
color.setRgb(red, green, blue); color.setRgb(red, green, blue);
break; break;
} }
case 5 : { case 5: {
if (!i.hasNext()) { if (!i.hasNext()) {
break; break;
} }
int index = i.next().toInt(&ok); int index = i.next().toInt(&ok);
Q_ASSERT(ok); Q_ASSERT(ok);
if (index >= 0x00 && index <= 0x07) if (index >= 0x00 && index <= 0x07) { // 0x00-0x07: standard colors (as in ESC [ 40..47 m)
{ // 0x00-0x07: standard colors (as in ESC [ 40..47 m)
return ParseEscapeSequence(index - 0x00 + 40, i, textCharFormat, defaultTextCharFormat); return ParseEscapeSequence(index - 0x00 + 40, i, textCharFormat, defaultTextCharFormat);
} } else if (index >= 0x08 && index <= 0x0F) { // 0x08-0x0F: high intensity colors (as in ESC [ 100..107 m)
else if (index >= 0x08 && index <= 0x0F)
{ // 0x08-0x0F: high intensity colors (as in ESC [ 100..107 m)
return ParseEscapeSequence(index - 0x08 + 100, i, textCharFormat, defaultTextCharFormat); return ParseEscapeSequence(index - 0x08 + 100, i, textCharFormat, defaultTextCharFormat);
} } else if (index >= 0x10 && index <= 0xE7) { // 0x10-0xE7: 6*6*6=216 colors: 16 + 36*r + 6*g + b (0≤r,g,b≤5)
else if (index >= 0x10 && index <= 0xE7)
{ // 0x10-0xE7: 6*6*6=216 colors: 16 + 36*r + 6*g + b (0≤r,g,b≤5)
index -= 0x10; index -= 0x10;
int red = index % 6; int red = index % 6;
index /= 6; index /= 6;
@ -385,9 +363,7 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
Q_ASSERT(index == 0); Q_ASSERT(index == 0);
color.setRgb(red, green, blue); color.setRgb(red, green, blue);
break; break;
} } else if (index >= 0xE8 && index <= 0xFF) { // 0xE8-0xFF: grayscale from black to white in 24 steps
else if (index >= 0xE8 && index <= 0xFF)
{ // 0xE8-0xFF: grayscale from black to white in 24 steps
qreal intensity = qreal(index - 0xE8) / (0xFF - 0xE8); qreal intensity = qreal(index - 0xE8) / (0xFF - 0xE8);
color.setRgbF(intensity, intensity, intensity); color.setRgbF(intensity, intensity, intensity);
} }
@ -413,45 +389,43 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
int colorIndex = attribute - 90; int colorIndex = attribute - 90;
QColor color; QColor color;
switch (colorIndex) { switch (colorIndex) {
case 0 : { case 0: {
color = Qt::darkGray; color = Qt::darkGray;
break; break;
} }
case 1 : { case 1: {
color = Qt::red; color = Qt::red;
break; break;
} }
case 2 : { case 2: {
color = Qt::green; color = Qt::green;
break; break;
} }
case 3 : { case 3: {
color = Qt::yellow; color = Qt::yellow;
break; break;
} }
case 4 : { case 4: {
color = Qt::blue; color = Qt::blue;
break; break;
} }
case 5 : { case 5: {
color = Qt::magenta; color = Qt::magenta;
break; break;
} }
case 6 : { case 6: {
color = Qt::cyan; color = Qt::cyan;
break; break;
} }
case 7 : { case 7: {
color = Qt::white; color = Qt::white;
break; break;
} }
default : { default: { Q_ASSERT(false); }
Q_ASSERT(false);
} }
} // color.setRedF(color.redF() * 0.8);
//color.setRedF(color.redF() * 0.8); // color.setGreenF(color.greenF() * 0.8);
//color.setGreenF(color.greenF() * 0.8); // color.setBlueF(color.blueF() * 0.8);
//color.setBlueF(color.blueF() * 0.8);
textCharFormat.setForeground(color); textCharFormat.setForeground(color);
break; break;
} }
@ -462,77 +436,66 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
case 104: case 104:
case 105: case 105:
case 106: case 106:
case 107: case 107: {
{
int colorIndex = attribute - 100; int colorIndex = attribute - 100;
QColor color; QColor color;
switch (colorIndex) { switch (colorIndex) {
case 0 : { case 0: {
color = Qt::darkGray; color = Qt::darkGray;
break; break;
} }
case 1 : { case 1: {
color = Qt::red; color = Qt::red;
break; break;
} }
case 2 : { case 2: {
color = Qt::green; color = Qt::green;
break; break;
} }
case 3 : { case 3: {
color = Qt::yellow; color = Qt::yellow;
break; break;
} }
case 4 : { case 4: {
color = Qt::blue; color = Qt::blue;
break; break;
} }
case 5 : { case 5: {
color = Qt::magenta; color = Qt::magenta;
break; break;
} }
case 6 : { case 6: {
color = Qt::cyan; color = Qt::cyan;
break; break;
} }
case 7 : { case 7: {
color = Qt::white; color = Qt::white;
break; break;
} }
default : { default: { Q_ASSERT(false); }
Q_ASSERT(false);
} }
} // color.setRedF(color.redF() * 0.8);
//color.setRedF(color.redF() * 0.8); // color.setGreenF(color.greenF() * 0.8);
//color.setGreenF(color.greenF() * 0.8); // color.setBlueF(color.blueF() * 0.8);
//color.setBlueF(color.blueF() * 0.8);
textCharFormat.setBackground(color); textCharFormat.setBackground(color);
break; break;
} }
default : { default: { break; }
break;
}
} }
} }
void ReturnInsert(QTextCursor& cur, const QString& text) void ReturnInsert(QTextCursor& cur, const QString& text) {
{ auto DoLine = [&](const QString& line) {
auto DoLine = [&](const QString& line) auto DoReturn = [&](const QString& ret) {
{ if (!ret.isEmpty()) {
auto DoReturn = [&](const QString& ret)
{
if (!ret.isEmpty())
{
cur.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, ret.size()); cur.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, ret.size());
cur.insertText(ret); cur.insertText(ret);
} }
}; };
QStringList list = line.split('\r'); QStringList list = line.split('\r');
DoReturn(list.front()); DoReturn(list.front());
if (list.size() > 1) if (list.size() > 1) {
{ for (auto it = list.begin() + 1; it != list.end(); ++it) {
for (auto it = list.begin() + 1; it != list.end(); ++it)
{
cur.movePosition(QTextCursor::StartOfBlock); cur.movePosition(QTextCursor::StartOfBlock);
DoReturn(*it); DoReturn(*it);
} }
@ -545,10 +508,8 @@ void ReturnInsert(QTextCursor& cur, const QString& text)
QStringList lineSplit = text.split('\n'); QStringList lineSplit = text.split('\n');
#endif #endif
DoLine(lineSplit.front()); DoLine(lineSplit.front());
if (lineSplit.size() > 1) if (lineSplit.size() > 1) {
{ for (auto it = lineSplit.begin() + 1; it != lineSplit.end(); ++it) {
for (auto it = lineSplit.begin() + 1; it != lineSplit.end(); ++it)
{
cur.movePosition(QTextCursor::EndOfLine); cur.movePosition(QTextCursor::EndOfLine);
cur.insertBlock(); cur.insertBlock();
DoLine(*it); DoLine(*it);
@ -556,24 +517,18 @@ void ReturnInsert(QTextCursor& cur, const QString& text)
} }
} }
void ReturnInsert(QTextCursor& cur, const QString& text, const QTextCharFormat& format) void ReturnInsert(QTextCursor& cur, const QString& text, const QTextCharFormat& format) {
{ auto DoLine = [&](const QString& line) {
auto DoLine = [&](const QString& line) auto DoReturn = [&](const QString& ret) {
{ if (!ret.isEmpty()) {
auto DoReturn = [&](const QString& ret)
{
if (!ret.isEmpty())
{
cur.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, ret.size()); cur.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, ret.size());
cur.insertText(ret, format); cur.insertText(ret, format);
} }
}; };
QStringList list = line.split('\r'); QStringList list = line.split('\r');
DoReturn(list.front()); DoReturn(list.front());
if (list.size() > 1) if (list.size() > 1) {
{ for (auto it = list.begin() + 1; it != list.end(); ++it) {
for (auto it = list.begin() + 1; it != list.end(); ++it)
{
cur.movePosition(QTextCursor::StartOfBlock); cur.movePosition(QTextCursor::StartOfBlock);
DoReturn(*it); DoReturn(*it);
} }
@ -586,10 +541,8 @@ void ReturnInsert(QTextCursor& cur, const QString& text, const QTextCharFormat&
QStringList lineSplit = text.split('\n'); QStringList lineSplit = text.split('\n');
#endif #endif
DoLine(lineSplit.front()); DoLine(lineSplit.front());
if (lineSplit.size() > 1) if (lineSplit.size() > 1) {
{ for (auto it = lineSplit.begin() + 1; it != lineSplit.end(); ++it) {
for (auto it = lineSplit.begin() + 1; it != lineSplit.end(); ++it)
{
cur.movePosition(QTextCursor::EndOfLine); cur.movePosition(QTextCursor::EndOfLine);
cur.insertBlock(); cur.insertBlock();
DoLine(*it); DoLine(*it);

View File

@ -10,4 +10,3 @@ void ParseEscapeSequence(int attribute, QListIterator<QString>& i, QTextCharForm
void ReturnInsert(QTextCursor& cur, const QString& text); void ReturnInsert(QTextCursor& cur, const QString& text);
void ReturnInsert(QTextCursor& cur, const QString& text, const QTextCharFormat& format); void ReturnInsert(QTextCursor& cur, const QString& text, const QTextCharFormat& format);

View File

@ -8,8 +8,7 @@
* Only contains directory extraction functionality. * Only contains directory extraction functionality.
*/ */
static bool copyData(QIODevice &inFile, QIODevice &outFile) static bool copyData(QIODevice& inFile, QIODevice& outFile) {
{
while (!inFile.atEnd()) { while (!inFile.atEnd()) {
char buf[4096]; char buf[4096];
qint64 readLen = inFile.read(buf, 4096); qint64 readLen = inFile.read(buf, 4096);
@ -21,16 +20,15 @@ static bool copyData(QIODevice &inFile, QIODevice &outFile)
return true; return true;
} }
QStringList ExtractZip::getFileList(QuaZip& zip) QStringList ExtractZip::getFileList(QuaZip& zip) {
{
// Estraggo i nomi dei file // Estraggo i nomi dei file
QStringList lst; QStringList lst;
QuaZipFileInfo64 info; QuaZipFileInfo64 info;
for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) { for (bool more = zip.goToFirstFile(); more; more = zip.goToNextFile()) {
if(!zip.getCurrentFileInfo(&info)) if (!zip.getCurrentFileInfo(&info))
return {}; return {};
lst << info.name; lst << info.name;
//info.name.toLocal8Bit().constData() // info.name.toLocal8Bit().constData()
} }
return lst; return lst;
@ -50,20 +48,21 @@ QStringList ExtractZip::getFileList(QuaZip& zip)
* *
* (1): prima di uscire dalla funzione cancella il file estratto. * (1): prima di uscire dalla funzione cancella il file estratto.
*/ */
bool ExtractZip::extractFile(QuaZip& zip, QString fileName, QString fileDest) bool ExtractZip::extractFile(QuaZip& zip, QString fileName, QString fileDest) {
{
// zip: oggetto dove aggiungere il file // zip: oggetto dove aggiungere il file
// filename: nome del file reale // filename: nome del file reale
// fileincompress: nome del file all'interno del file compresso // fileincompress: nome del file all'interno del file compresso
// Controllo l'apertura dello zip // Controllo l'apertura dello zip
if (zip.getMode()!=QuaZip::mdUnzip) return false; if (zip.getMode() != QuaZip::mdUnzip)
return false;
// Apro il file compresso // Apro il file compresso
if (!fileName.isEmpty()) if (!fileName.isEmpty())
zip.setCurrentFile(fileName); zip.setCurrentFile(fileName);
QuaZipFile inFile(&zip); QuaZipFile inFile(&zip);
if(!inFile.open(QIODevice::ReadOnly) || inFile.getZipError()!=UNZ_OK) return false; if (!inFile.open(QIODevice::ReadOnly) || inFile.getZipError() != UNZ_OK)
return false;
// Controllo esistenza cartella file risultato // Controllo esistenza cartella file risultato
QDir curDir; QDir curDir;
@ -92,10 +91,11 @@ bool ExtractZip::extractFile(QuaZip& zip, QString fileName, QString fileDest)
// Apro il file risultato // Apro il file risultato
QFile outFile; QFile outFile;
outFile.setFileName(fileDest); outFile.setFileName(fileDest);
if(!outFile.open(QIODevice::WriteOnly)) return false; if (!outFile.open(QIODevice::WriteOnly))
return false;
// Copio i dati // Copio i dati
if (!copyData(inFile, outFile) || inFile.getZipError()!=UNZ_OK) { if (!copyData(inFile, outFile) || inFile.getZipError() != UNZ_OK) {
outFile.close(); outFile.close();
return false; return false;
} }
@ -103,7 +103,7 @@ bool ExtractZip::extractFile(QuaZip& zip, QString fileName, QString fileDest)
// Chiudo i file // Chiudo i file
inFile.close(); inFile.close();
if (inFile.getZipError()!=UNZ_OK) { if (inFile.getZipError() != UNZ_OK) {
return false; return false;
} }
@ -124,8 +124,7 @@ bool ExtractZip::extractFile(QuaZip& zip, QString fileName, QString fileDest)
* * la compressione di un file fallisce; * * la compressione di un file fallisce;
* * non si riesce a chiudere l'oggetto zip; * * non si riesce a chiudere l'oggetto zip;
*/ */
bool ExtractZip::extractDir(QuaZip& zip, QString dir) bool ExtractZip::extractDir(QuaZip& zip, QString dir) {
{
QDir directory(dir); QDir directory(dir);
if (!zip.goToFirstFile()) { if (!zip.goToFirstFile()) {
return false; return false;

View File

@ -4,11 +4,9 @@ class QStringList;
class QuaZip; class QuaZip;
class QString; class QString;
class ExtractZip class ExtractZip {
{
public: public:
static QStringList getFileList(QuaZip& zip); static QStringList getFileList(QuaZip& zip);
static bool extractFile(QuaZip& zip, QString fileName, QString fileDest); static bool extractFile(QuaZip& zip, QString fileName, QString fileDest);
static bool extractDir(QuaZip& zip, QString dir); static bool extractDir(QuaZip& zip, QString dir);
}; };

View File

@ -2,10 +2,8 @@
#include <QFileDialog> #include <QFileDialog>
class FileDirDialog : public QFileDialog class FileDirDialog : public QFileDialog {
{
Q_OBJECT Q_OBJECT
public: public:
FileDirDialog(QWidget* parent = nullptr) : QFileDialog(parent) { setFileMode(QFileDialog::Directory); } FileDirDialog(QWidget* parent = nullptr) : QFileDialog(parent) { setFileMode(QFileDialog::Directory); }
}; };

View File

@ -2,8 +2,7 @@
#include "hecl/SteamFinder.hpp" #include "hecl/SteamFinder.hpp"
#include "hecl/hecl.hpp" #include "hecl/hecl.hpp"
namespace hecl::blender namespace hecl::blender {
{
#ifdef __APPLE__ #ifdef __APPLE__
#define DEFAULT_BLENDER_BIN "/Applications/Blender.app/Contents/MacOS/blender" #define DEFAULT_BLENDER_BIN "/Applications/Blender.app/Contents/MacOS/blender"
@ -14,18 +13,16 @@ namespace hecl::blender
#endif #endif
static const std::regex regBlenderVersion(R"(Blender ([0-9]+).([0-9]+) )", static const std::regex regBlenderVersion(R"(Blender ([0-9]+).([0-9]+) )",
std::regex::ECMAScript|std::regex::optimize); std::regex::ECMAScript | std::regex::optimize);
static bool RegFileExists(const hecl::SystemChar* path) static bool RegFileExists(const hecl::SystemChar* path) {
{
if (!path) if (!path)
return false; return false;
hecl::Sstat theStat; hecl::Sstat theStat;
return !hecl::Stat(path, &theStat) && S_ISREG(theStat.st_mode); return !hecl::Stat(path, &theStat) && S_ISREG(theStat.st_mode);
} }
hecl::SystemString FindBlender(int& major, int& minor) hecl::SystemString FindBlender(int& major, int& minor) {
{
major = 0; major = 0;
minor = 0; minor = 0;
@ -42,58 +39,46 @@ hecl::SystemString FindBlender(int& major, int& minor)
/* Child process of blender */ /* Child process of blender */
#if _WIN32 #if _WIN32
if (!blenderBin || !RegFileExists(blenderBin)) if (!blenderBin || !RegFileExists(blenderBin)) {
{
/* Environment not set; try steam */ /* Environment not set; try steam */
steamBlender = hecl::FindCommonSteamApp(_SYS_STR("Blender")); steamBlender = hecl::FindCommonSteamApp(_SYS_STR("Blender"));
if (steamBlender.size()) if (steamBlender.size()) {
{
steamBlender += _SYS_STR("\\blender.exe"); steamBlender += _SYS_STR("\\blender.exe");
blenderBin = steamBlender.c_str(); blenderBin = steamBlender.c_str();
} }
if (!RegFileExists(blenderBin)) if (!RegFileExists(blenderBin)) {
{
/* No steam; try default */ /* No steam; try default */
wchar_t progFiles[256]; wchar_t progFiles[256];
if (GetEnvironmentVariableW(L"ProgramFiles", progFiles, 256)) if (GetEnvironmentVariableW(L"ProgramFiles", progFiles, 256)) {
{
_snwprintf(BLENDER_BIN_BUF, 2048, L"%s\\Blender Foundation\\Blender\\blender.exe", progFiles); _snwprintf(BLENDER_BIN_BUF, 2048, L"%s\\Blender Foundation\\Blender\\blender.exe", progFiles);
blenderBin = BLENDER_BIN_BUF; blenderBin = BLENDER_BIN_BUF;
if (!RegFileExists(blenderBin)) if (!RegFileExists(blenderBin))
blenderBin = nullptr; blenderBin = nullptr;
} } else
else
blenderBin = nullptr; blenderBin = nullptr;
} }
} }
#else #else
if (!RegFileExists(blenderBin)) if (!RegFileExists(blenderBin)) {
{
/* Try steam */ /* Try steam */
steamBlender = hecl::FindCommonSteamApp(_SYS_STR("Blender")); steamBlender = hecl::FindCommonSteamApp(_SYS_STR("Blender"));
if (steamBlender.size()) if (steamBlender.size()) {
{
#ifdef __APPLE__ #ifdef __APPLE__
steamBlender += "/blender.app/Contents/MacOS/blender"; steamBlender += "/blender.app/Contents/MacOS/blender";
#else #else
steamBlender += "/blender"; steamBlender += "/blender";
#endif #endif
blenderBin = steamBlender.c_str(); blenderBin = steamBlender.c_str();
if (!RegFileExists(blenderBin)) if (!RegFileExists(blenderBin)) {
{
blenderBin = DEFAULT_BLENDER_BIN; blenderBin = DEFAULT_BLENDER_BIN;
if (!RegFileExists(blenderBin)) if (!RegFileExists(blenderBin)) {
{
blenderBin = nullptr; blenderBin = nullptr;
} }
} }
} } else {
else
{
blenderBin = DEFAULT_BLENDER_BIN; blenderBin = DEFAULT_BLENDER_BIN;
if (!RegFileExists(blenderBin)) if (!RegFileExists(blenderBin)) {
{
blenderBin = nullptr; blenderBin = nullptr;
} }
} }
@ -119,8 +104,7 @@ hecl::SystemString FindBlender(int& major, int& minor)
#endif #endif
std::cmatch match; std::cmatch match;
if (std::regex_search(versionBuf, match, regBlenderVersion)) if (std::regex_search(versionBuf, match, regBlenderVersion)) {
{
major = atoi(match[1].str().c_str()); major = atoi(match[1].str().c_str());
minor = atoi(match[2].str().c_str()); minor = atoi(match[2].str().c_str());
return blenderBin; return blenderBin;
@ -129,5 +113,4 @@ hecl::SystemString FindBlender(int& major, int& minor)
return blenderBin; return blenderBin;
} }
} } // namespace hecl::blender

View File

@ -2,10 +2,8 @@
#include "hecl/hecl.hpp" #include "hecl/hecl.hpp"
namespace hecl::blender namespace hecl::blender {
{
hecl::SystemString FindBlender(int& major, int& minor); hecl::SystemString FindBlender(int& major, int& minor);
} }

View File

@ -4,15 +4,14 @@
extern hecl::CVar* hecl::com_developer; extern hecl::CVar* hecl::com_developer;
LaunchMenu::LaunchMenu(hecl::CVarCommons& commons, QWidget* parent) LaunchMenu::LaunchMenu(hecl::CVarCommons& commons, QWidget* parent)
: QMenu("Launch Menu", parent), : QMenu("Launch Menu", parent)
m_commons(commons), , m_commons(commons)
m_apiMenu("Graphics API", this), , m_apiMenu("Graphics API", this)
m_msaaMenu("Anti-Aliasing", this), , m_msaaMenu("Anti-Aliasing", this)
m_anisoMenu("Anisotropic Filtering", this), , m_anisoMenu("Anisotropic Filtering", this)
m_apiGroup(this), , m_apiGroup(this)
m_msaaGroup(this), , m_msaaGroup(this)
m_anisoGroup(this) , m_anisoGroup(this) {
{
#ifdef _WIN32 #ifdef _WIN32
initApiAction(QStringLiteral("D3D11")); initApiAction(QStringLiteral("D3D11"));
initApiAction(QStringLiteral("Vulkan")); initApiAction(QStringLiteral("Vulkan"));
@ -48,8 +47,7 @@ LaunchMenu::LaunchMenu(hecl::CVarCommons& commons, QWidget* parent)
initDeveloperMode(); initDeveloperMode();
} }
void LaunchMenu::initApiAction(const QString& action) void LaunchMenu::initApiAction(const QString& action) {
{
QAction* act = m_apiGroup.addAction(action); QAction* act = m_apiGroup.addAction(action);
connect(act, SIGNAL(triggered()), this, SLOT(apiTriggered())); connect(act, SIGNAL(triggered()), this, SLOT(apiTriggered()));
act->setCheckable(true); act->setCheckable(true);
@ -57,8 +55,7 @@ void LaunchMenu::initApiAction(const QString& action)
act->setChecked(true); act->setChecked(true);
} }
void LaunchMenu::initMsaaAction(const QString& action) void LaunchMenu::initMsaaAction(const QString& action) {
{
QAction* act = m_msaaGroup.addAction(action); QAction* act = m_msaaGroup.addAction(action);
connect(act, SIGNAL(triggered()), this, SLOT(msaaTriggered())); connect(act, SIGNAL(triggered()), this, SLOT(msaaTriggered()));
act->setCheckable(true); act->setCheckable(true);
@ -66,8 +63,7 @@ void LaunchMenu::initMsaaAction(const QString& action)
act->setChecked(true); act->setChecked(true);
} }
void LaunchMenu::initAnisoAction(const QString& action) void LaunchMenu::initAnisoAction(const QString& action) {
{
QAction* act = m_anisoGroup.addAction(action); QAction* act = m_anisoGroup.addAction(action);
connect(act, SIGNAL(triggered()), this, SLOT(anisoTriggered())); connect(act, SIGNAL(triggered()), this, SLOT(anisoTriggered()));
act->setCheckable(true); act->setCheckable(true);
@ -75,8 +71,7 @@ void LaunchMenu::initAnisoAction(const QString& action)
act->setChecked(true); act->setChecked(true);
} }
void LaunchMenu::initDeepColor() void LaunchMenu::initDeepColor() {
{
QAction* act = addAction("Deep Color"); QAction* act = addAction("Deep Color");
act->setToolTip(m_commons.m_deepColor->rawHelp().data()); act->setToolTip(m_commons.m_deepColor->rawHelp().data());
act->setCheckable(true); act->setCheckable(true);
@ -84,8 +79,7 @@ void LaunchMenu::initDeepColor()
connect(act, SIGNAL(triggered()), this, SLOT(deepColorTriggered())); connect(act, SIGNAL(triggered()), this, SLOT(deepColorTriggered()));
} }
void LaunchMenu::initDeveloperMode() void LaunchMenu::initDeveloperMode() {
{
QAction* act = addAction("Developer Mode"); QAction* act = addAction("Developer Mode");
act->setToolTip(hecl::com_developer->rawHelp().data()); act->setToolTip(hecl::com_developer->rawHelp().data());
act->setCheckable(true); act->setCheckable(true);
@ -93,34 +87,29 @@ void LaunchMenu::initDeveloperMode()
connect(act, SIGNAL(triggered()), this, SLOT(developerModeTriggered())); connect(act, SIGNAL(triggered()), this, SLOT(developerModeTriggered()));
} }
void LaunchMenu::apiTriggered() void LaunchMenu::apiTriggered() {
{
QString apiStr = qobject_cast<QAction*>(sender())->text(); QString apiStr = qobject_cast<QAction*>(sender())->text();
apiStr = apiStr.remove('&'); apiStr = apiStr.remove('&');
m_commons.setGraphicsApi(apiStr.toStdString()); m_commons.setGraphicsApi(apiStr.toStdString());
m_commons.serialize(); m_commons.serialize();
} }
void LaunchMenu::msaaTriggered() void LaunchMenu::msaaTriggered() {
{
m_commons.setSamples(qobject_cast<QAction*>(sender())->text().toUInt()); m_commons.setSamples(qobject_cast<QAction*>(sender())->text().toUInt());
m_commons.serialize(); m_commons.serialize();
} }
void LaunchMenu::anisoTriggered() void LaunchMenu::anisoTriggered() {
{
m_commons.setAnisotropy(qobject_cast<QAction*>(sender())->text().toUInt()); m_commons.setAnisotropy(qobject_cast<QAction*>(sender())->text().toUInt());
m_commons.serialize(); m_commons.serialize();
} }
void LaunchMenu::deepColorTriggered() void LaunchMenu::deepColorTriggered() {
{
m_commons.setDeepColor(qobject_cast<QAction*>(sender())->isChecked()); m_commons.setDeepColor(qobject_cast<QAction*>(sender())->isChecked());
m_commons.serialize(); m_commons.serialize();
} }
void LaunchMenu::developerModeTriggered() void LaunchMenu::developerModeTriggered() {
{
hecl::CVarManager::instance()->setDeveloperMode(qobject_cast<QAction*>(sender())->isChecked(), true); hecl::CVarManager::instance()->setDeveloperMode(qobject_cast<QAction*>(sender())->isChecked(), true);
m_commons.serialize(); m_commons.serialize();
} }

View File

@ -1,10 +1,11 @@
#pragma once #pragma once
#include <QMenu> #include <QMenu>
namespace hecl { struct CVarCommons; } namespace hecl {
struct CVarCommons;
}
class LaunchMenu : public QMenu class LaunchMenu : public QMenu {
{
Q_OBJECT Q_OBJECT
hecl::CVarCommons& m_commons; hecl::CVarCommons& m_commons;
@ -32,4 +33,3 @@ public slots:
void deepColorTriggered(); void deepColorTriggered();
void developerModeTriggered(); void developerModeTriggered();
}; };

View File

@ -1,4 +1,3 @@
#pragma once #pragma once
void GetMacOSSystemVersion(int& major, int& minor, int& patch); void GetMacOSSystemVersion(int& major, int& minor, int& patch);

View File

@ -11,8 +11,7 @@
#include <shellapi.h> #include <shellapi.h>
#include <TlHelp32.h> #include <TlHelp32.h>
static void KillProcessTree(QProcess& proc) static void KillProcessTree(QProcess& proc) {
{
Q_PID pid = proc.pid(); Q_PID pid = proc.pid();
if (!pid) if (!pid)
return; return;
@ -23,20 +22,16 @@ static void KillProcessTree(QProcess& proc)
HANDLE hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); HANDLE hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (::Process32First(hSnap, &pe)) if (::Process32First(hSnap, &pe)) {
{
BOOL bContinue = TRUE; BOOL bContinue = TRUE;
// kill child processes // kill child processes
while (bContinue) while (bContinue) {
{
// only kill child processes // only kill child processes
if (pe.th32ParentProcessID == myprocID) if (pe.th32ParentProcessID == myprocID) {
{
HANDLE hChildProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID); HANDLE hChildProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
if (hChildProc) if (hChildProc) {
{
::TerminateProcess(hChildProc, 1); ::TerminateProcess(hChildProc, 1);
::CloseHandle(hChildProc); ::CloseHandle(hChildProc);
} }
@ -50,24 +45,22 @@ static void KillProcessTree(QProcess& proc)
proc.terminate(); proc.terminate();
} }
#else #else
static void KillProcessTree(QProcess& proc) static void KillProcessTree(QProcess& proc) {
{
proc.close(); proc.close();
proc.terminate(); proc.terminate();
} }
#endif #endif
MainWindow::MainWindow(QWidget *parent) : MainWindow::MainWindow(QWidget* parent)
QMainWindow(parent) : QMainWindow(parent)
, m_fileMgr(_SYS_STR("urde")) , m_fileMgr(_SYS_STR("urde"))
, m_cvarManager(m_fileMgr) , m_cvarManager(m_fileMgr)
, m_cvarCommons(m_cvarManager) , m_cvarCommons(m_cvarManager)
, m_ui(new Ui::MainWindow) , m_ui(new Ui::MainWindow)
, m_heclProc(this) , m_heclProc(this)
, m_dlManager(this) , m_dlManager(this)
, m_launchMenu(m_cvarCommons, this) , m_launchMenu(m_cvarCommons, this)
, m_settings("AxioDL", "HECL", this) , m_settings("AxioDL", "HECL", this) {
{
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->heclTabs->setCurrentIndex(0); m_ui->heclTabs->setCurrentIndex(0);
@ -85,7 +78,7 @@ MainWindow::MainWindow(QWidget *parent) :
m_ui->gridLayout->addWidget(m_updateURDEButton, 2, 3, 1, 1); m_ui->gridLayout->addWidget(m_updateURDEButton, 2, 3, 1, 1);
m_updateURDEButton->hide(); m_updateURDEButton->hide();
QPalette pal = m_updateURDEButton->palette(); QPalette pal = m_updateURDEButton->palette();
pal.setColor(QPalette::Button, QColor(53,53,72)); pal.setColor(QPalette::Button, QColor(53, 53, 72));
m_updateURDEButton->setPalette(pal); m_updateURDEButton->setPalette(pal);
connect(m_updateURDEButton, SIGNAL(clicked()), this, SLOT(onUpdateURDEPressed())); connect(m_updateURDEButton, SIGNAL(clicked()), this, SLOT(onUpdateURDEPressed()));
@ -101,14 +94,12 @@ MainWindow::MainWindow(QWidget *parent) :
setPath(m_settings.value(QStringLiteral("working_dir")).toString()); setPath(m_settings.value(QStringLiteral("working_dir")).toString());
} }
MainWindow::~MainWindow() MainWindow::~MainWindow() {
{
KillProcessTree(m_heclProc); KillProcessTree(m_heclProc);
delete m_ui; delete m_ui;
} }
void MainWindow::onExtract() void MainWindow::onExtract() {
{
if (m_path.isEmpty()) if (m_path.isEmpty())
return; return;
QString imgPath = QFileDialog::getOpenFileName(this, QStringLiteral("Extract Image"), m_path, QString imgPath = QFileDialog::getOpenFileName(this, QStringLiteral("Extract Image"), m_path,
@ -138,8 +129,7 @@ void MainWindow::onExtract()
connect(m_ui->extractBtn, SIGNAL(clicked()), this, SLOT(doHECLTerminate())); connect(m_ui->extractBtn, SIGNAL(clicked()), this, SLOT(doHECLTerminate()));
} }
void MainWindow::onExtractFinished(int returnCode) void MainWindow::onExtractFinished(int returnCode) {
{
m_cursor.movePosition(QTextCursor::End); m_cursor.movePosition(QTextCursor::End);
m_cursor.insertBlock(); m_cursor.insertBlock();
disconnect(m_ui->extractBtn, SIGNAL(clicked()), nullptr, nullptr); disconnect(m_ui->extractBtn, SIGNAL(clicked()), nullptr, nullptr);
@ -147,8 +137,7 @@ void MainWindow::onExtractFinished(int returnCode)
checkDownloadedBinary(); checkDownloadedBinary();
} }
void MainWindow::onPackage() void MainWindow::onPackage() {
{
if (m_path.isEmpty()) if (m_path.isEmpty())
return; return;
m_ui->processOutput->clear(); m_ui->processOutput->clear();
@ -161,8 +150,7 @@ void MainWindow::onPackage()
m_heclProc.setProcessEnvironment(env); m_heclProc.setProcessEnvironment(env);
disconnect(&m_heclProc, SIGNAL(finished(int)), nullptr, nullptr); disconnect(&m_heclProc, SIGNAL(finished(int)), nullptr, nullptr);
connect(&m_heclProc, SIGNAL(finished(int)), this, SLOT(onPackageFinished(int))); connect(&m_heclProc, SIGNAL(finished(int)), this, SLOT(onPackageFinished(int)));
m_heclProc.start(m_heclPath, {"package", "-y", "-g"}, m_heclProc.start(m_heclPath, {"package", "-y", "-g"}, QIODevice::ReadOnly | QIODevice::Unbuffered);
QIODevice::ReadOnly | QIODevice::Unbuffered);
m_ui->heclTabs->setCurrentIndex(0); m_ui->heclTabs->setCurrentIndex(0);
@ -178,8 +166,7 @@ void MainWindow::onPackage()
resize(size); resize(size);
} }
void MainWindow::onPackageFinished(int returnCode) void MainWindow::onPackageFinished(int returnCode) {
{
m_cursor.movePosition(QTextCursor::End); m_cursor.movePosition(QTextCursor::End);
m_cursor.insertBlock(); m_cursor.insertBlock();
disconnect(m_ui->packageBtn, SIGNAL(clicked()), nullptr, nullptr); disconnect(m_ui->packageBtn, SIGNAL(clicked()), nullptr, nullptr);
@ -187,8 +174,7 @@ void MainWindow::onPackageFinished(int returnCode)
checkDownloadedBinary(); checkDownloadedBinary();
} }
void MainWindow::onLaunch() void MainWindow::onLaunch() {
{
if (m_path.isEmpty()) if (m_path.isEmpty())
return; return;
m_ui->processOutput->clear(); m_ui->processOutput->clear();
@ -201,38 +187,30 @@ void MainWindow::onLaunch()
m_heclProc.setProcessEnvironment(env); m_heclProc.setProcessEnvironment(env);
disconnect(&m_heclProc, SIGNAL(finished(int)), nullptr, nullptr); disconnect(&m_heclProc, SIGNAL(finished(int)), nullptr, nullptr);
connect(&m_heclProc, SIGNAL(finished(int)), this, SLOT(onLaunchFinished(int))); connect(&m_heclProc, SIGNAL(finished(int)), this, SLOT(onLaunchFinished(int)));
m_heclProc.start(m_urdePath, {"--no-shader-warmup", m_path + "/out"}, m_heclProc.start(m_urdePath, {"--no-shader-warmup", m_path + "/out"}, QIODevice::ReadOnly | QIODevice::Unbuffered);
QIODevice::ReadOnly | QIODevice::Unbuffered);
m_ui->heclTabs->setCurrentIndex(0); m_ui->heclTabs->setCurrentIndex(0);
disableOperations(); disableOperations();
} }
void MainWindow::onLaunchFinished(int returnCode) void MainWindow::onLaunchFinished(int returnCode) {
{
m_cursor.movePosition(QTextCursor::End); m_cursor.movePosition(QTextCursor::End);
m_cursor.insertBlock(); m_cursor.insertBlock();
checkDownloadedBinary(); checkDownloadedBinary();
} }
void MainWindow::doHECLTerminate() void MainWindow::doHECLTerminate() { KillProcessTree(m_heclProc); }
{
KillProcessTree(m_heclProc);
}
void MainWindow::onReturnPressed() void MainWindow::onReturnPressed() {
{
if (sender() == m_ui->pathEdit) if (sender() == m_ui->pathEdit)
setPath(m_ui->pathEdit->text()); setPath(m_ui->pathEdit->text());
} }
void MainWindow::onIndexDownloaded(const QStringList& index) void MainWindow::onIndexDownloaded(const QStringList& index) {
{
int bestVersion = 0; int bestVersion = 0;
m_ui->binaryComboBox->clear(); m_ui->binaryComboBox->clear();
for (const QString& str : index) for (const QString& str : index) {
{
URDEVersion version(str); URDEVersion version(str);
if (m_ui->sysReqTable->willRun(version)) if (m_ui->sysReqTable->willRun(version))
bestVersion = m_ui->binaryComboBox->count(); bestVersion = m_ui->binaryComboBox->count();
@ -243,15 +221,13 @@ void MainWindow::onIndexDownloaded(const QStringList& index)
m_ui->recommendedBinaryLabel->setText(m_recommendedVersion.fileString(false)); m_ui->recommendedBinaryLabel->setText(m_recommendedVersion.fileString(false));
m_ui->binaryComboBox->setEnabled(true); m_ui->binaryComboBox->setEnabled(true);
if (!m_path.isEmpty()) if (!m_path.isEmpty()) {
{
checkDownloadedBinary(); checkDownloadedBinary();
m_ui->downloadButton->setEnabled(true); m_ui->downloadButton->setEnabled(true);
} }
} }
void MainWindow::onDownloadPressed() void MainWindow::onDownloadPressed() {
{
m_updateURDEButton->hide(); m_updateURDEButton->hide();
QString filename = m_ui->binaryComboBox->currentData().value<URDEVersion>().fileString(true); QString filename = m_ui->binaryComboBox->currentData().value<URDEVersion>().fileString(true);
disableOperations(); disableOperations();
@ -259,14 +235,12 @@ void MainWindow::onDownloadPressed()
m_dlManager.fetchBinary(filename, m_path + '/' + filename); m_dlManager.fetchBinary(filename, m_path + '/' + filename);
} }
void MainWindow::onUpdateURDEPressed() void MainWindow::onUpdateURDEPressed() {
{
m_ui->heclTabs->setCurrentIndex(1); m_ui->heclTabs->setCurrentIndex(1);
onDownloadPressed(); onDownloadPressed();
} }
void MainWindow::onBinaryDownloaded(QuaZip& file) void MainWindow::onBinaryDownloaded(QuaZip& file) {
{
bool err = !ExtractZip::extractDir(file, m_path); bool err = !ExtractZip::extractDir(file, m_path);
if (err) if (err)
@ -284,14 +258,12 @@ void MainWindow::onBinaryDownloaded(QuaZip& file)
QStringLiteral("Blender 2.78+ must be installed. Please download via Steam or blender.org.")); QStringLiteral("Blender 2.78+ must be installed. Please download via Steam or blender.org."));
} }
void MainWindow::onBinaryFailed() void MainWindow::onBinaryFailed() {
{
m_ui->downloadButton->setEnabled(true); m_ui->downloadButton->setEnabled(true);
checkDownloadedBinary(); checkDownloadedBinary();
} }
void MainWindow::disableOperations() void MainWindow::disableOperations() {
{
m_ui->extractBtn->setEnabled(false); m_ui->extractBtn->setEnabled(false);
m_ui->packageBtn->setEnabled(false); m_ui->packageBtn->setEnabled(false);
m_ui->launchBtn->setEnabled(false); m_ui->launchBtn->setEnabled(false);
@ -300,8 +272,7 @@ void MainWindow::disableOperations()
m_ui->downloadButton->setEnabled(false); m_ui->downloadButton->setEnabled(false);
} }
void MainWindow::enableOperations() void MainWindow::enableOperations() {
{
disableOperations(); disableOperations();
m_ui->pathEdit->setEnabled(true); m_ui->pathEdit->setEnabled(true);
m_ui->browseBtn->setEnabled(true); m_ui->browseBtn->setEnabled(true);
@ -319,8 +290,7 @@ void MainWindow::enableOperations()
m_ui->launchBtn->setText(QStringLiteral("Launch")); m_ui->launchBtn->setText(QStringLiteral("Launch"));
m_ui->extractBtn->setEnabled(true); m_ui->extractBtn->setEnabled(true);
if (QFile::exists(m_path + "/MP1/!original_ids.yaml")) if (QFile::exists(m_path + "/MP1/!original_ids.yaml")) {
{
m_ui->packageBtn->setEnabled(true); m_ui->packageBtn->setEnabled(true);
if (isPackageComplete()) if (isPackageComplete())
m_ui->launchBtn->setEnabled(true); m_ui->launchBtn->setEnabled(true);
@ -336,38 +306,26 @@ void MainWindow::enableOperations()
insertContinueNote("Press 'Extract' to begin."); insertContinueNote("Press 'Extract' to begin.");
} }
bool MainWindow::isPackageComplete() const bool MainWindow::isPackageComplete() const {
{
return return
#if RUNTIME_ORIGINAL_IDS #if RUNTIME_ORIGINAL_IDS
QFile::exists(m_path + "/out/files/!original_ids.upak") && QFile::exists(m_path + "/out/files/!original_ids.upak") &&
#endif #endif
QFile::exists(m_path + "/out/files/AudioGrp.upak") && QFile::exists(m_path + "/out/files/AudioGrp.upak") && QFile::exists(m_path + "/out/files/GGuiSys.upak") &&
QFile::exists(m_path + "/out/files/GGuiSys.upak") && QFile::exists(m_path + "/out/files/Metroid1.upak") && QFile::exists(m_path + "/out/files/Metroid2.upak") &&
QFile::exists(m_path + "/out/files/Metroid1.upak") && QFile::exists(m_path + "/out/files/Metroid3.upak") && QFile::exists(m_path + "/out/files/Metroid4.upak") &&
QFile::exists(m_path + "/out/files/Metroid2.upak") && QFile::exists(m_path + "/out/files/metroid5.upak") && QFile::exists(m_path + "/out/files/Metroid6.upak") &&
QFile::exists(m_path + "/out/files/Metroid3.upak") && QFile::exists(m_path + "/out/files/Metroid7.upak") && QFile::exists(m_path + "/out/files/Metroid8.upak") &&
QFile::exists(m_path + "/out/files/Metroid4.upak") && QFile::exists(m_path + "/out/files/MidiData.upak") && QFile::exists(m_path + "/out/files/MiscData.upak") &&
QFile::exists(m_path + "/out/files/metroid5.upak") && QFile::exists(m_path + "/out/files/NoARAM.upak") && QFile::exists(m_path + "/out/files/SamGunFx.upak") &&
QFile::exists(m_path + "/out/files/Metroid6.upak") && QFile::exists(m_path + "/out/files/SamusGun.upak") && QFile::exists(m_path + "/out/files/SlideShow.upak") &&
QFile::exists(m_path + "/out/files/Metroid7.upak") && QFile::exists(m_path + "/out/files/TestAnim.upak") && QFile::exists(m_path + "/out/files/Tweaks.upak");
QFile::exists(m_path + "/out/files/Metroid8.upak") &&
QFile::exists(m_path + "/out/files/MidiData.upak") &&
QFile::exists(m_path + "/out/files/MiscData.upak") &&
QFile::exists(m_path + "/out/files/NoARAM.upak") &&
QFile::exists(m_path + "/out/files/SamGunFx.upak") &&
QFile::exists(m_path + "/out/files/SamusGun.upak") &&
QFile::exists(m_path + "/out/files/SlideShow.upak") &&
QFile::exists(m_path + "/out/files/TestAnim.upak") &&
QFile::exists(m_path + "/out/files/Tweaks.upak");
} }
static bool GetDLPackage(const QString& path, QString& dlPackage) static bool GetDLPackage(const QString& path, QString& dlPackage) {
{
QProcess proc; QProcess proc;
proc.start(path, {"--dlpackage"}, QIODevice::ReadOnly); proc.start(path, {"--dlpackage"}, QIODevice::ReadOnly);
if (proc.waitForStarted()) if (proc.waitForStarted()) {
{
proc.waitForFinished(); proc.waitForFinished();
if (proc.exitCode() == 100) if (proc.exitCode() == 100)
dlPackage = QString::fromUtf8(proc.readLine()).trimmed(); dlPackage = QString::fromUtf8(proc.readLine()).trimmed();
@ -376,15 +334,13 @@ static bool GetDLPackage(const QString& path, QString& dlPackage)
return false; return false;
} }
bool MainWindow::checkDownloadedBinary() bool MainWindow::checkDownloadedBinary() {
{
m_updateURDEButton->hide(); m_updateURDEButton->hide();
m_urdePath = QString(); m_urdePath = QString();
m_heclPath = QString(); m_heclPath = QString();
if (m_path.isEmpty()) if (m_path.isEmpty()) {
{
m_ui->heclTabs->setCurrentIndex(1); m_ui->heclTabs->setCurrentIndex(1);
m_ui->downloadErrorLabel->setText(QStringLiteral("Set working directory to continue."), true); m_ui->downloadErrorLabel->setText(QStringLiteral("Set working directory to continue."), true);
enableOperations(); enableOperations();
@ -409,24 +365,15 @@ bool MainWindow::checkDownloadedBinary()
visigenPath = QFileInfo(visigenPath).absoluteFilePath(); visigenPath = QFileInfo(visigenPath).absoluteFilePath();
QString urdeDlPackage, heclDlPackage, visigenDlPackage; QString urdeDlPackage, heclDlPackage, visigenDlPackage;
if (GetDLPackage(urdePath, urdeDlPackage) && if (GetDLPackage(urdePath, urdeDlPackage) && GetDLPackage(heclPath, heclDlPackage) &&
GetDLPackage(heclPath, heclDlPackage) && GetDLPackage(visigenPath, visigenDlPackage)) {
GetDLPackage(visigenPath, visigenDlPackage)) if (!urdeDlPackage.isEmpty() && urdeDlPackage == heclDlPackage && urdeDlPackage == visigenDlPackage) {
{
if (!urdeDlPackage.isEmpty() &&
urdeDlPackage == heclDlPackage &&
urdeDlPackage == visigenDlPackage)
{
URDEVersion v(urdeDlPackage); URDEVersion v(urdeDlPackage);
m_ui->currentBinaryLabel->setText(v.fileString(false)); m_ui->currentBinaryLabel->setText(v.fileString(false));
if (m_recommendedVersion.isValid() && v.isValid() && if (m_recommendedVersion.isValid() && v.isValid() && m_recommendedVersion.getVersion() > v.getVersion()) {
m_recommendedVersion.getVersion() > v.getVersion())
{
m_updateURDEButton->show(); m_updateURDEButton->show();
} }
} } else {
else
{
m_ui->currentBinaryLabel->setText(QStringLiteral("unknown -- re-download recommended")); m_ui->currentBinaryLabel->setText(QStringLiteral("unknown -- re-download recommended"));
} }
@ -435,9 +382,7 @@ bool MainWindow::checkDownloadedBinary()
m_ui->downloadErrorLabel->setText({}, true); m_ui->downloadErrorLabel->setText({}, true);
enableOperations(); enableOperations();
return true; return true;
} } else {
else
{
m_ui->currentBinaryLabel->setText(QStringLiteral("none")); m_ui->currentBinaryLabel->setText(QStringLiteral("none"));
m_ui->heclTabs->setCurrentIndex(1); m_ui->heclTabs->setCurrentIndex(1);
m_ui->downloadErrorLabel->setText(QStringLiteral("Press 'Download' to fetch latest URDE binary."), true); m_ui->downloadErrorLabel->setText(QStringLiteral("Press 'Download' to fetch latest URDE binary."), true);
@ -447,14 +392,12 @@ bool MainWindow::checkDownloadedBinary()
return false; return false;
} }
void MainWindow::setPath(const QString& path) void MainWindow::setPath(const QString& path) {
{
QFileInfo finfo(path); QFileInfo finfo(path);
QString usePath; QString usePath;
if (!path.isEmpty()) if (!path.isEmpty())
usePath = finfo.absoluteFilePath(); usePath = finfo.absoluteFilePath();
if (!usePath.isEmpty() && !finfo.exists()) if (!usePath.isEmpty() && !finfo.exists()) {
{
if (QMessageBox::question(this, QStringLiteral("Make Directory"), if (QMessageBox::question(this, QStringLiteral("Make Directory"),
QStringLiteral("%1 does not exist. Create it now?").arg(usePath)) == QMessageBox::Yes) QStringLiteral("%1 does not exist. Create it now?").arg(usePath)) == QMessageBox::Yes)
QDir().mkpath(usePath); QDir().mkpath(usePath);
@ -462,10 +405,8 @@ void MainWindow::setPath(const QString& path)
usePath = QString(); usePath = QString();
} }
if (!usePath.isEmpty() && !finfo.isDir()) if (!usePath.isEmpty() && !finfo.isDir()) {
{ QMessageBox::warning(this, QStringLiteral("Directory Error"), QStringLiteral("%1 is not a directory").arg(usePath),
QMessageBox::warning(this, QStringLiteral("Directory Error"),
QStringLiteral("%1 is not a directory").arg(usePath),
QMessageBox::Ok, QMessageBox::NoButton); QMessageBox::Ok, QMessageBox::NoButton);
usePath = QString(); usePath = QString();
} }
@ -473,14 +414,11 @@ void MainWindow::setPath(const QString& path)
m_path = usePath; m_path = usePath;
m_settings.setValue(QStringLiteral("working_dir"), m_path); m_settings.setValue(QStringLiteral("working_dir"), m_path);
if (!m_path.isEmpty()) if (!m_path.isEmpty()) {
{
m_ui->pathEdit->setText(m_path); m_ui->pathEdit->setText(m_path);
m_ui->downloadButton->setToolTip(QString()); m_ui->downloadButton->setToolTip(QString());
m_ui->downloadButton->setEnabled(m_ui->binaryComboBox->isEnabled()); m_ui->downloadButton->setEnabled(m_ui->binaryComboBox->isEnabled());
} } else {
else
{
m_ui->downloadButton->setToolTip(QStringLiteral("Working directory must be set")); m_ui->downloadButton->setToolTip(QStringLiteral("Working directory must be set"));
m_ui->downloadButton->setEnabled(false); m_ui->downloadButton->setEnabled(false);
m_ui->currentBinaryLabel->setText(QStringLiteral("none")); m_ui->currentBinaryLabel->setText(QStringLiteral("none"));
@ -490,9 +428,8 @@ void MainWindow::setPath(const QString& path)
checkDownloadedBinary(); checkDownloadedBinary();
} }
void MainWindow::initSlots() void MainWindow::initSlots() {
{ connect(&m_heclProc, &QProcess::readyRead, [=]() {
connect(&m_heclProc, &QProcess::readyRead, [=](){
QByteArray bytes = m_heclProc.readAll(); QByteArray bytes = m_heclProc.readAll();
setTextTermFormatting(bytes); setTextTermFormatting(bytes);
}); });
@ -519,8 +456,7 @@ void MainWindow::initSlots()
connect(m_ui->downloadButton, SIGNAL(clicked()), this, SLOT(onDownloadPressed())); connect(m_ui->downloadButton, SIGNAL(clicked()), this, SLOT(onDownloadPressed()));
} }
void MainWindow::setTextTermFormatting(const QString& text) void MainWindow::setTextTermFormatting(const QString& text) {
{
m_inContinueNote = false; m_inContinueNote = false;
QRegExp const escapeSequenceExpression(R"(\x1B\[([\d;\?FA]+)([mlh]?))"); QRegExp const escapeSequenceExpression(R"(\x1B\[([\d;\?FA]+)([mlh]?))");
@ -531,8 +467,7 @@ void MainWindow::setTextTermFormatting(const QString& text)
while (offset >= 0) { while (offset >= 0) {
int previousOffset = offset + escapeSequenceExpression.matchedLength(); int previousOffset = offset + escapeSequenceExpression.matchedLength();
QStringList captures = escapeSequenceExpression.capturedTexts(); QStringList captures = escapeSequenceExpression.capturedTexts();
if (captures.size() >= 3 && captures[2] == "m") if (captures.size() >= 3 && captures[2] == "m") {
{
QStringList capturedTexts = captures[1].split(';'); QStringList capturedTexts = captures[1].split(';');
QListIterator<QString> i(capturedTexts); QListIterator<QString> i(capturedTexts);
while (i.hasNext()) { while (i.hasNext()) {
@ -541,14 +476,11 @@ void MainWindow::setTextTermFormatting(const QString& text)
Q_ASSERT(ok); Q_ASSERT(ok);
ParseEscapeSequence(attribute, i, textCharFormat, defaultTextCharFormat); ParseEscapeSequence(attribute, i, textCharFormat, defaultTextCharFormat);
} }
} } else if (captures.size() >= 2 && (captures[1].endsWith('F') || captures[1].endsWith('A'))) {
else if (captures.size() >= 2 && (captures[1].endsWith('F') || captures[1].endsWith('A')))
{
int lineCount = captures[1].chopped(1).toInt(); int lineCount = captures[1].chopped(1).toInt();
if (!lineCount) if (!lineCount)
lineCount = 1; lineCount = 1;
for (int i=0 ; i<lineCount ; ++i) for (int i = 0; i < lineCount; ++i) {
{
m_cursor.movePosition(QTextCursor::PreviousBlock); m_cursor.movePosition(QTextCursor::PreviousBlock);
m_cursor.select(QTextCursor::BlockUnderCursor); m_cursor.select(QTextCursor::BlockUnderCursor);
m_cursor.removeSelectedText(); m_cursor.removeSelectedText();
@ -566,15 +498,14 @@ void MainWindow::setTextTermFormatting(const QString& text)
m_ui->processOutput->ensureCursorVisible(); m_ui->processOutput->ensureCursorVisible();
} }
void MainWindow::insertContinueNote(const QString& text) void MainWindow::insertContinueNote(const QString& text) {
{
if (m_inContinueNote) if (m_inContinueNote)
return; return;
m_inContinueNote = true; m_inContinueNote = true;
m_cursor.movePosition(QTextCursor::End); m_cursor.movePosition(QTextCursor::End);
QTextCharFormat textCharFormat = m_cursor.charFormat(); QTextCharFormat textCharFormat = m_cursor.charFormat();
textCharFormat.setForeground(QColor(0,255,0)); textCharFormat.setForeground(QColor(0, 255, 0));
m_cursor.insertText(text, textCharFormat); m_cursor.insertText(text, textCharFormat);
m_cursor.insertBlock(); m_cursor.insertBlock();
m_ui->processOutput->ensureCursorVisible(); m_ui->processOutput->ensureCursorVisible();

View File

@ -18,8 +18,7 @@ namespace Ui {
class MainWindow; class MainWindow;
} }
class MainWindow : public QMainWindow class MainWindow : public QMainWindow {
{
Q_OBJECT Q_OBJECT
hecl::Runtime::FileStoreManager m_fileMgr; hecl::Runtime::FileStoreManager m_fileMgr;
hecl::CVarManager m_cvarManager; hecl::CVarManager m_cvarManager;
@ -36,8 +35,9 @@ class MainWindow : public QMainWindow
URDEVersion m_recommendedVersion; URDEVersion m_recommendedVersion;
QPushButton* m_updateURDEButton; QPushButton* m_updateURDEButton;
bool m_inContinueNote = false; bool m_inContinueNote = false;
public: public:
explicit MainWindow(QWidget *parent = 0); explicit MainWindow(QWidget* parent = 0);
~MainWindow(); ~MainWindow();
void setTextTermFormatting(const QString& text); void setTextTermFormatting(const QString& text);
void insertContinueNote(const QString& text); void insertContinueNote(const QString& text);
@ -52,6 +52,7 @@ private slots:
void onReturnPressed(); void onReturnPressed();
void onDownloadPressed(); void onDownloadPressed();
void onUpdateURDEPressed(); void onUpdateURDEPressed();
private: private:
bool checkDownloadedBinary(); bool checkDownloadedBinary();
void setPath(const QString& path); void setPath(const QString& path);
@ -63,4 +64,3 @@ private:
void enableOperations(); void enableOperations();
bool isPackageComplete() const; bool isPackageComplete() const;
}; };

View File

@ -21,8 +21,7 @@
#if __APPLE__ #if __APPLE__
#include "MacOSSystemVersion.hpp" #include "MacOSSystemVersion.hpp"
#elif _WIN32 #elif _WIN32
static QString GetWindowsVersionString() static QString GetWindowsVersionString() {
{
if (IsWindows10OrGreater()) if (IsWindows10OrGreater())
return QStringLiteral("Windows 10"); return QStringLiteral("Windows 10");
else if (IsWindows8Point1OrGreater()) else if (IsWindows8Point1OrGreater())
@ -42,13 +41,10 @@ static QString GetWindowsVersionString()
} }
#endif #endif
SysReqTableModel::SysReqTableModel(QObject* parent) SysReqTableModel::SysReqTableModel(QObject* parent) : QAbstractTableModel(parent) {
: QAbstractTableModel(parent)
{
#ifdef __linux__ #ifdef __linux__
QFile file("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"); QFile file("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
if (file.open(QFile::ReadOnly)) if (file.open(QFile::ReadOnly)) {
{
QString str(file.readAll()); QString str(file.readAll());
m_cpuSpeed = str.toInt() / 1000; m_cpuSpeed = str.toInt() / 1000;
m_cpuSpeedStr.sprintf("%g GHz", m_cpuSpeed / 1000.0); m_cpuSpeedStr.sprintf("%g GHz", m_cpuSpeed / 1000.0);
@ -63,13 +59,11 @@ SysReqTableModel::SysReqTableModel(QObject* parent)
QDomElement n = spDocElem.firstChildElement("array").firstChildElement("dict").firstChildElement("key"); QDomElement n = spDocElem.firstChildElement("array").firstChildElement("dict").firstChildElement("key");
while (!n.isNull() && n.text() != "_items") while (!n.isNull() && n.text() != "_items")
n = n.nextSiblingElement("key"); n = n.nextSiblingElement("key");
if (!n.isNull()) if (!n.isNull()) {
{
n = n.nextSiblingElement("array").firstChildElement("dict").firstChildElement("key"); n = n.nextSiblingElement("array").firstChildElement("dict").firstChildElement("key");
while (!n.isNull() && n.text() != "current_processor_speed") while (!n.isNull() && n.text() != "current_processor_speed")
n = n.nextSiblingElement("key"); n = n.nextSiblingElement("key");
if (!n.isNull()) if (!n.isNull()) {
{
n = n.nextSiblingElement("string"); n = n.nextSiblingElement("string");
double speed = n.text().split(' ').front().toDouble(); double speed = n.text().split(' ').front().toDouble();
m_cpuSpeed = uint64_t(speed * 1000.0); m_cpuSpeed = uint64_t(speed * 1000.0);
@ -78,15 +72,11 @@ SysReqTableModel::SysReqTableModel(QObject* parent)
} }
#elif _WIN32 #elif _WIN32
HKEY hkey; HKEY hkey;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _SYS_STR("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), 0,
_SYS_STR("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) {
0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS)
{
DWORD MHz; DWORD MHz;
DWORD size = sizeof(MHz); DWORD size = sizeof(MHz);
if (RegQueryValueEx(hkey, _SYS_STR("~MHz"), nullptr, nullptr, if (RegQueryValueEx(hkey, _SYS_STR("~MHz"), nullptr, nullptr, (LPBYTE)&MHz, &size) == ERROR_SUCCESS) {
(LPBYTE)&MHz, &size) == ERROR_SUCCESS)
{
m_cpuSpeed = uint64_t(MHz); m_cpuSpeed = uint64_t(MHz);
m_cpuSpeedStr.sprintf("%1.1f GHz", MHz / 1000.f); m_cpuSpeedStr.sprintf("%1.1f GHz", MHz / 1000.f);
} }
@ -96,8 +86,7 @@ SysReqTableModel::SysReqTableModel(QObject* parent)
/* This only works for Skylake+ */ /* This only works for Skylake+ */
int regs[4] = {}; int regs[4] = {};
zeus::getCpuInfo(0, regs); zeus::getCpuInfo(0, regs);
if (regs[0] >= 0x16) if (regs[0] >= 0x16) {
{
zeus::getCpuInfo(0x16, regs); zeus::getCpuInfo(0x16, regs);
m_cpuSpeed = uint64_t(regs[0]); m_cpuSpeed = uint64_t(regs[0]);
} }
@ -125,48 +114,34 @@ SysReqTableModel::SysReqTableModel(QObject* parent)
#endif #endif
hecl::blender::FindBlender(m_blendMajor, m_blendMinor); hecl::blender::FindBlender(m_blendMajor, m_blendMinor);
if (m_blendMajor) if (m_blendMajor)
m_blendVersionStr = QStringLiteral("Blender ") + QString::number(m_blendMajor) + m_blendVersionStr =
'.' + QString::number(m_blendMinor); QStringLiteral("Blender ") + QString::number(m_blendMajor) + '.' + QString::number(m_blendMinor);
else else
m_blendVersionStr = QStringLiteral("Not Found"); m_blendVersionStr = QStringLiteral("Not Found");
} }
void SysReqTableModel::updateFreeDiskSpace(const QString& path) void SysReqTableModel::updateFreeDiskSpace(const QString& path) {
{ if (path.isEmpty()) {
if (path.isEmpty())
{
m_freeDiskSpace = 0; m_freeDiskSpace = 0;
m_freeDiskSpaceStr = QStringLiteral("<Set Working Directory>"); m_freeDiskSpaceStr = QStringLiteral("<Set Working Directory>");
} } else {
else
{
m_freeDiskSpace = QStorageInfo(path).bytesFree(); m_freeDiskSpace = QStorageInfo(path).bytesFree();
m_freeDiskSpaceStr.sprintf("%1.1f GB", m_freeDiskSpace / 1000.f / 1000.f / 1000.f); m_freeDiskSpaceStr.sprintf("%1.1f GB", m_freeDiskSpace / 1000.f / 1000.f / 1000.f);
} }
emit dataChanged(index(3, 0), index(3, 0)); emit dataChanged(index(3, 0), index(3, 0));
} }
int SysReqTableModel::rowCount(const QModelIndex& parent) const int SysReqTableModel::rowCount(const QModelIndex& parent) const { return 7; }
{
return 7;
}
int SysReqTableModel::columnCount(const QModelIndex& parent) const int SysReqTableModel::columnCount(const QModelIndex& parent) const { return 2; }
{
return 2;
}
QVariant SysReqTableModel::data(const QModelIndex& index, int role) const QVariant SysReqTableModel::data(const QModelIndex& index, int role) const {
{ if (role != Qt::DisplayRole && role != Qt::UserRole) {
if (role != Qt::DisplayRole && role != Qt::UserRole)
{
return {}; return {};
} }
if (role == Qt::UserRole) if (role == Qt::UserRole) {
{ switch (index.row()) {
switch (index.row())
{
case 0: case 0:
return true; return true;
case 1: case 1:
@ -186,14 +161,10 @@ QVariant SysReqTableModel::data(const QModelIndex& index, int role) const
case 5: case 5:
return isBlenderVersionOk(); return isBlenderVersionOk();
} }
} } else {
else if (index.column() == 0) {
{
if (index.column() == 0)
{
/* Recommended */ /* Recommended */
switch (index.row()) switch (index.row()) {
{
case 0: case 0:
#if ZEUS_ARCH_X86 || ZEUS_ARCH_X86_64 #if ZEUS_ARCH_X86 || ZEUS_ARCH_X86_64
return QStringLiteral("x86_64"); return QStringLiteral("x86_64");
@ -219,12 +190,9 @@ QVariant SysReqTableModel::data(const QModelIndex& index, int role) const
case 5: case 5:
return QStringLiteral("Blender 2.78"); return QStringLiteral("Blender 2.78");
} }
} } else if (index.column() == 1) {
else if (index.column() == 1)
{
/* Your System */ /* Your System */
switch (index.row()) switch (index.row()) {
{
case 0: case 0:
#if ZEUS_ARCH_X86 || ZEUS_ARCH_X86_64 #if ZEUS_ARCH_X86 || ZEUS_ARCH_X86_64
return CurArchitectureString; return CurArchitectureString;
@ -247,28 +215,21 @@ QVariant SysReqTableModel::data(const QModelIndex& index, int role) const
return {}; return {};
} }
QVariant SysReqTableModel::headerData(int section, Qt::Orientation orientation, int role) const QVariant SysReqTableModel::headerData(int section, Qt::Orientation orientation, int role) const {
{ if (role != Qt::DisplayRole) {
if (role != Qt::DisplayRole)
{
return {}; return {};
} }
if (orientation == Qt::Horizontal) if (orientation == Qt::Horizontal) {
{ switch (section) {
switch (section)
{
case 0: case 0:
default: default:
return QStringLiteral("Recommended"); return QStringLiteral("Recommended");
case 1: case 1:
return QStringLiteral("Your System"); return QStringLiteral("Your System");
} }
} } else {
else switch (section) {
{
switch (section)
{
case 0: case 0:
default: default:
return QStringLiteral("Architecture"); return QStringLiteral("Architecture");
@ -288,13 +249,11 @@ QVariant SysReqTableModel::headerData(int section, Qt::Orientation orientation,
} }
} }
void SysReqTableView::paintEvent(QPaintEvent* e) void SysReqTableView::paintEvent(QPaintEvent* e) {
{
int tableWidth = columnWidth(0) + columnWidth(1); int tableWidth = columnWidth(0) + columnWidth(1);
int tableX = verticalHeader()->width() + columnViewportPosition(0); int tableX = verticalHeader()->width() + columnViewportPosition(0);
int tableY = horizontalHeader()->height(); int tableY = horizontalHeader()->height();
for (int i = 0; i < 6; ++i) for (int i = 0; i < 6; ++i) {
{
QWidget* w = std::get<0>(m_backgroundWidgets[i]); QWidget* w = std::get<0>(m_backgroundWidgets[i]);
QPalette pal = palette(); QPalette pal = palette();
@ -307,8 +266,7 @@ void SysReqTableView::paintEvent(QPaintEvent* e)
QSequentialAnimationGroup* animation = std::get<1>(m_backgroundWidgets[i]); QSequentialAnimationGroup* animation = std::get<1>(m_backgroundWidgets[i]);
QPropertyAnimation* pAnimation = static_cast<QPropertyAnimation*>(animation->animationAt(1)); QPropertyAnimation* pAnimation = static_cast<QPropertyAnimation*>(animation->animationAt(1));
bool& running = std::get<2>(m_backgroundWidgets[i]); bool& running = std::get<2>(m_backgroundWidgets[i]);
if (!running) if (!running) {
{
w->setGeometry(QRect(tableX, tableY + rowViewportPosition(i), 0, rowHeight(i))); w->setGeometry(QRect(tableX, tableY + rowViewportPosition(i), 0, rowHeight(i)));
pAnimation->setStartValue(QRect(tableX, tableY + rowViewportPosition(i), 0, rowHeight(i))); pAnimation->setStartValue(QRect(tableX, tableY + rowViewportPosition(i), 0, rowHeight(i)));
pAnimation->setEndValue(QRect(tableX, tableY + rowViewportPosition(i), tableWidth, rowHeight(i))); pAnimation->setEndValue(QRect(tableX, tableY + rowViewportPosition(i), tableWidth, rowHeight(i)));
@ -323,9 +281,7 @@ void SysReqTableView::paintEvent(QPaintEvent* e)
QTableView::paintEvent(e); QTableView::paintEvent(e);
} }
SysReqTableView::SysReqTableView(QWidget* parent) SysReqTableView::SysReqTableView(QWidget* parent) : QTableView(parent), m_vectorISATable(this) {
: QTableView(parent), m_vectorISATable(this)
{
setModel(&m_model); setModel(&m_model);
setIndexWidget(m_model.index(6, 0), &m_vectorISATable); setIndexWidget(m_model.index(6, 0), &m_vectorISATable);
setSpan(6, 0, 1, 2); setSpan(6, 0, 1, 2);
@ -335,8 +291,7 @@ SysReqTableView::SysReqTableView(QWidget* parent)
setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);
setFocusPolicy(Qt::NoFocus); setFocusPolicy(Qt::NoFocus);
for (int i = 0; i < 6; ++i) for (int i = 0; i < 6; ++i) {
{
QWidget* w = new QWidget(this); QWidget* w = new QWidget(this);
std::get<0>(m_backgroundWidgets[i]) = w; std::get<0>(m_backgroundWidgets[i]) = w;

View File

@ -5,8 +5,7 @@
class QSequentialAnimationGroup; class QSequentialAnimationGroup;
class SysReqTableModel : public QAbstractTableModel class SysReqTableModel : public QAbstractTableModel {
{
Q_OBJECT Q_OBJECT
uint64_t m_cpuSpeed = 0; uint64_t m_cpuSpeed = 0;
QString m_cpuSpeedStr; QString m_cpuSpeedStr;
@ -25,34 +24,32 @@ class SysReqTableModel : public QAbstractTableModel
int m_blendMajor = 0; int m_blendMajor = 0;
int m_blendMinor = 0; int m_blendMinor = 0;
QString m_blendVersionStr; QString m_blendVersionStr;
public: public:
SysReqTableModel(QObject* parent = Q_NULLPTR); SysReqTableModel(QObject* parent = Q_NULLPTR);
int rowCount(const QModelIndex& parent = QModelIndex()) const; int rowCount(const QModelIndex& parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex& parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
bool isBlenderVersionOk() const bool isBlenderVersionOk() const { return m_blendMajor > 2 || (m_blendMajor == 2 && m_blendMinor >= 78); }
{ return m_blendMajor > 2 || (m_blendMajor == 2 && m_blendMinor >= 78); }
void updateFreeDiskSpace(const QString& path); void updateFreeDiskSpace(const QString& path);
}; };
class SysReqTableView : public QTableView class SysReqTableView : public QTableView {
{
Q_OBJECT Q_OBJECT
SysReqTableModel m_model; SysReqTableModel m_model;
VectorISATableView m_vectorISATable; VectorISATableView m_vectorISATable;
std::tuple<QWidget*, QSequentialAnimationGroup*, bool> m_backgroundWidgets[6] = {}; std::tuple<QWidget*, QSequentialAnimationGroup*, bool> m_backgroundWidgets[6] = {};
public: public:
SysReqTableView(QWidget* parent = Q_NULLPTR); SysReqTableView(QWidget* parent = Q_NULLPTR);
void paintEvent(QPaintEvent* e) Q_DECL_OVERRIDE; void paintEvent(QPaintEvent* e) Q_DECL_OVERRIDE;
const SysReqTableModel& getModel() const { return m_model; } const SysReqTableModel& getModel() const { return m_model; }
const VectorISATableView& getVectorISATable() const { return m_vectorISATable; } const VectorISATableView& getVectorISATable() const { return m_vectorISATable; }
bool willRun(const URDEVersion& v) const bool willRun(const URDEVersion& v) const {
{
return v.getArchitecture() == CurArchitecture && v.getPlatform() == CurPlatform && return v.getArchitecture() == CurArchitecture && v.getPlatform() == CurPlatform &&
m_vectorISATable.willRun(v.getVectorISA()); m_vectorISATable.willRun(v.getVectorISA());
} }
bool isBlenderVersionOk() const { return m_model.isBlenderVersionOk(); } bool isBlenderVersionOk() const { return m_model.isBlenderVersionOk(); }
void updateFreeDiskSpace(const QString& path) { m_model.updateFreeDiskSpace(path); } void updateFreeDiskSpace(const QString& path) { m_model.updateFreeDiskSpace(path); }
}; };

View File

@ -3,13 +3,12 @@
#include <QTableView> #include <QTableView>
#include "zeus/Math.hpp" #include "zeus/Math.hpp"
class VectorISATableModel : public QAbstractTableModel class VectorISATableModel : public QAbstractTableModel {
{
Q_OBJECT Q_OBJECT
protected: protected:
const zeus::CPUInfo& m_features = zeus::cpuFeatures(); const zeus::CPUInfo& m_features = zeus::cpuFeatures();
public: public:
VectorISATableModel(QObject* parent = Q_NULLPTR) : QAbstractTableModel(parent) {} VectorISATableModel(QObject* parent = Q_NULLPTR) : QAbstractTableModel(parent) {}
int rowCount(const QModelIndex& parent = QModelIndex()) const { return 1; } int rowCount(const QModelIndex& parent = QModelIndex()) const { return 1; }
}; };

View File

@ -2,23 +2,19 @@
#include "VectorISATableModel.hpp" #include "VectorISATableModel.hpp"
class VectorISATableModelIntel : public VectorISATableModel class VectorISATableModelIntel : public VectorISATableModel {
{
Q_OBJECT Q_OBJECT
public: public:
VectorISATableModelIntel(QObject* parent = Q_NULLPTR) : VectorISATableModel(parent) {} VectorISATableModelIntel(QObject* parent = Q_NULLPTR) : VectorISATableModel(parent) {}
int columnCount(const QModelIndex &parent = QModelIndex()) const { return 7; } int columnCount(const QModelIndex& parent = QModelIndex()) const { return 7; }
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const {
{
if (role != Qt::DisplayRole && role != Qt::UserRole) if (role != Qt::DisplayRole && role != Qt::UserRole)
return {}; return {};
if (role == Qt::UserRole) if (role == Qt::UserRole) {
{ switch (index.column()) {
switch (index.column())
{
case 0: case 0:
default: default:
return true; return true;
@ -35,11 +31,8 @@ public:
case 6: case 6:
return m_features.AVX2; return m_features.AVX2;
} }
} } else {
else switch (index.column()) {
{
switch (index.column())
{
case 0: case 0:
default: default:
return QStringLiteral("x87"); return QStringLiteral("x87");
@ -59,10 +52,8 @@ public:
} }
} }
VectorISA getISA(int idx) const VectorISA getISA(int idx) const {
{ switch (idx) {
switch (idx)
{
default: default:
return VectorISA::Invalid; return VectorISA::Invalid;
case 0: case 0:
@ -82,10 +73,8 @@ public:
} }
} }
bool willRun(VectorISA visa) const bool willRun(VectorISA visa) const {
{ switch (visa) {
switch (visa)
{
default: default:
return false; return false;
case VectorISA::X87: case VectorISA::X87:
@ -105,4 +94,3 @@ public:
} }
} }
}; };

View File

@ -3,23 +3,18 @@
#include <QPropertyAnimation> #include <QPropertyAnimation>
#include <QSequentialAnimationGroup> #include <QSequentialAnimationGroup>
void VectorISATableView::paintEvent(QPaintEvent* e) void VectorISATableView::paintEvent(QPaintEvent* e) {
{
QTableView* p = static_cast<QTableView*>(parent()->parent()); QTableView* p = static_cast<QTableView*>(parent()->parent());
int tableY = p->horizontalHeader()->height() + p->rowViewportPosition(6); int tableY = p->horizontalHeader()->height() + p->rowViewportPosition(6);
int rHeight = rowHeight(0); int rHeight = rowHeight(0);
for (int i = 0; i < 2; ++i) for (int i = 0; i < 2; ++i) {
{
int tableX; int tableX;
int width = 0; int width = 0;
if (i == 0) if (i == 0) {
{
tableX = p->verticalHeader()->width() + columnViewportPosition(0); tableX = p->verticalHeader()->width() + columnViewportPosition(0);
for (int j = 0; j <= m_maxISA; ++j) for (int j = 0; j <= m_maxISA; ++j)
width += columnWidth(j); width += columnWidth(j);
} } else {
else
{
tableX = p->verticalHeader()->width() + columnViewportPosition(m_maxISA + 1); tableX = p->verticalHeader()->width() + columnViewportPosition(m_maxISA + 1);
for (int j = m_maxISA + 1; j < m_model.columnCount({}); ++j) for (int j = m_maxISA + 1; j < m_model.columnCount({}); ++j)
width += columnWidth(j); width += columnWidth(j);
@ -29,8 +24,7 @@ void VectorISATableView::paintEvent(QPaintEvent* e)
QSequentialAnimationGroup* animation = std::get<1>(m_backgroundWidgets[i]); QSequentialAnimationGroup* animation = std::get<1>(m_backgroundWidgets[i]);
QPropertyAnimation* pAnimation = static_cast<QPropertyAnimation*>(animation->animationAt(1)); QPropertyAnimation* pAnimation = static_cast<QPropertyAnimation*>(animation->animationAt(1));
bool& running = std::get<2>(m_backgroundWidgets[i]); bool& running = std::get<2>(m_backgroundWidgets[i]);
if (!running) if (!running) {
{
w->setGeometry(QRect(tableX, tableY, 0, rHeight)); w->setGeometry(QRect(tableX, tableY, 0, rHeight));
pAnimation->setStartValue(QRect(tableX, tableY, 0, rHeight)); pAnimation->setStartValue(QRect(tableX, tableY, 0, rHeight));
pAnimation->setEndValue(QRect(tableX, tableY, width, rHeight)); pAnimation->setEndValue(QRect(tableX, tableY, width, rHeight));
@ -45,13 +39,10 @@ void VectorISATableView::paintEvent(QPaintEvent* e)
QTableView::paintEvent(e); QTableView::paintEvent(e);
} }
VectorISATableView::VectorISATableView(QWidget* parent) VectorISATableView::VectorISATableView(QWidget* parent) : QTableView(parent) {
: QTableView(parent)
{
setModel(&m_model); setModel(&m_model);
for (int i = 0; i < m_model.columnCount({}); ++i) for (int i = 0; i < m_model.columnCount({}); ++i) {
{
if (m_model.data(m_model.index(0, i), Qt::UserRole).toBool()) if (m_model.data(m_model.index(0, i), Qt::UserRole).toBool())
m_maxISA = i; m_maxISA = i;
else else
@ -67,8 +58,7 @@ VectorISATableView::VectorISATableView(QWidget* parent)
setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);
setFocusPolicy(Qt::NoFocus); setFocusPolicy(Qt::NoFocus);
for (int i = 0; i < 2; ++i) for (int i = 0; i < 2; ++i) {
{
QWidget* w = new QWidget(parent); QWidget* w = new QWidget(parent);
std::get<0>(m_backgroundWidgets[i]) = w; std::get<0>(m_backgroundWidgets[i]) = w;

View File

@ -9,18 +9,17 @@
class QSequentialAnimationGroup; class QSequentialAnimationGroup;
class VectorISATableView : public QTableView class VectorISATableView : public QTableView {
{
Q_OBJECT Q_OBJECT
#if ZEUS_ARCH_X86_64 || ZEUS_ARCH_X86 #if ZEUS_ARCH_X86_64 || ZEUS_ARCH_X86
VectorISATableModelIntel m_model; VectorISATableModelIntel m_model;
#endif #endif
std::tuple<QWidget*, QSequentialAnimationGroup*, bool> m_backgroundWidgets[2] = {}; std::tuple<QWidget*, QSequentialAnimationGroup*, bool> m_backgroundWidgets[2] = {};
int m_maxISA = 0; int m_maxISA = 0;
public: public:
VectorISATableView(QWidget* parent = Q_NULLPTR); VectorISATableView(QWidget* parent = Q_NULLPTR);
void paintEvent(QPaintEvent* e) Q_DECL_OVERRIDE; void paintEvent(QPaintEvent* e) Q_DECL_OVERRIDE;
VectorISA getISA() const { return m_model.getISA(m_maxISA); } VectorISA getISA() const { return m_model.getISA(m_maxISA); }
bool willRun(VectorISA visa) const { return m_model.willRun(visa); } bool willRun(VectorISA visa) const { return m_model.willRun(visa); }
}; };

View File

@ -5,13 +5,11 @@
extern "C" const uint8_t MAINICON_QT[]; extern "C" const uint8_t MAINICON_QT[];
static QIcon MakeAppIcon() static QIcon MakeAppIcon() {
{
QIcon ret; QIcon ret;
const uint8_t* ptr = MAINICON_QT; const uint8_t* ptr = MAINICON_QT;
for (int i = 0; i < 6; ++i) for (int i = 0; i < 6; ++i) {
{
uint32_t size = *reinterpret_cast<const uint32_t*>(ptr); uint32_t size = *reinterpret_cast<const uint32_t*>(ptr);
ptr += 4; ptr += 4;
@ -24,8 +22,7 @@ static QIcon MakeAppIcon()
return ret; return ret;
} }
int main(int argc, char* argv[]) int main(int argc, char* argv[]) {
{
InitializePlatform(); InitializePlatform();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
@ -37,25 +34,25 @@ int main(int argc, char* argv[])
QApplication::setWindowIcon(MakeAppIcon()); QApplication::setWindowIcon(MakeAppIcon());
QPalette darkPalette; QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53,53,53)); darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(42,42,42)); darkPalette.setColor(QPalette::Base, QColor(42, 42, 42));
darkPalette.setColor(QPalette::Disabled, QPalette::Base, QColor(25,25,25,53)); darkPalette.setColor(QPalette::Disabled, QPalette::Base, QColor(25, 25, 25, 53));
darkPalette.setColor(QPalette::AlternateBase, QColor(53,53,53)); darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, QColor(42,42,42)); darkPalette.setColor(QPalette::ToolTipBase, QColor(42, 42, 42));
darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::Text, QColor(255,255,255,120)); darkPalette.setColor(QPalette::Disabled, QPalette::Text, QColor(255, 255, 255, 120));
darkPalette.setColor(QPalette::Button, QColor(53,53,53)); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::Disabled, QPalette::Button, QColor(53,53,53,53)); darkPalette.setColor(QPalette::Disabled, QPalette::Button, QColor(53, 53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(255,255,255,120)); darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(255, 255, 255, 120));
darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42,130,218)); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42,130,218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(42,130,218,53)); darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(42, 130, 218, 53));
darkPalette.setColor(QPalette::HighlightedText, Qt::white); darkPalette.setColor(QPalette::HighlightedText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, QColor(255,255,255,120)); darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, QColor(255, 255, 255, 120));
a.setPalette(darkPalette); a.setPalette(darkPalette);
MainWindow w; MainWindow w;