[Fix-Warnings] Local variable can be made const

This commit is contained in:
Brübach, Lukas 2025-11-29 15:11:22 +01:00
parent 8abd04dab1
commit f2d3e81331
214 changed files with 1375 additions and 1355 deletions

View file

@ -26,18 +26,18 @@ void DeckStatsInterface::queryFinished(QNetworkReply *reply)
return; return;
} }
QString data(reply->readAll()); const QString data(reply->readAll());
reply->deleteLater(); reply->deleteLater();
static const QRegularExpression rx("<meta property=\"og:url\" content=\"([^\"]+)\""); static const QRegularExpression rx("<meta property=\"og:url\" content=\"([^\"]+)\"");
auto match = rx.match(data); const auto match = rx.match(data);
if (!match.hasMatch()) { if (!match.hasMatch()) {
QMessageBox::critical(nullptr, tr("Error"), tr("The reply from the server could not be parsed.")); QMessageBox::critical(nullptr, tr("Error"), tr("The reply from the server could not be parsed."));
deleteLater(); deleteLater();
return; return;
} }
QString deckUrl = match.captured(1); const QString deckUrl = match.captured(1);
QDesktopServices::openUrl(deckUrl); QDesktopServices::openUrl(deckUrl);
deleteLater(); deleteLater();
@ -70,7 +70,7 @@ void DeckStatsInterface::analyzeDeck(DeckList *deck)
void DeckStatsInterface::copyDeckWithoutTokens(DeckList &source, DeckList &destination) void DeckStatsInterface::copyDeckWithoutTokens(DeckList &source, DeckList &destination)
{ {
auto copyIfNotAToken = [this, &destination](const auto node, const auto card) { auto copyIfNotAToken = [this, &destination](const auto node, const auto card) {
CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName()); const CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName());
if (dbCard && !dbCard->getIsToken()) { if (dbCard && !dbCard->getIsToken()) {
DecklistCardNode *addedCard = destination.addCard(card->getName(), node->getName(), -1); DecklistCardNode *addedCard = destination.addCard(card->getName(), node->getName(), -1);
addedCard->setNumber(card->getNumber()); addedCard->setNumber(card->getNumber());

View file

@ -26,13 +26,13 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply)
return; return;
} }
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); const int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (reply->hasRawHeader("Location")) { if (reply->hasRawHeader("Location")) {
/* /*
* If the reply contains a "Location" header, a relative URL to the deck on TappedOut * If the reply contains a "Location" header, a relative URL to the deck on TappedOut
* can be extracted from the header. The http status is a 302 "redirect". * can be extracted from the header. The http status is a 302 "redirect".
*/ */
QString deckUrl = reply->rawHeader("Location"); const QString deckUrl = reply->rawHeader("Location");
qCInfo(TappedOutInterfaceLog) << "Tappedout: good reply, http status" << httpStatus << "location" << deckUrl; qCInfo(TappedOutInterfaceLog) << "Tappedout: good reply, http status" << httpStatus << "location" << deckUrl;
QDesktopServices::openUrl("https://tappedout.net" + deckUrl); QDesktopServices::openUrl("https://tappedout.net" + deckUrl);
} else { } else {
@ -40,13 +40,13 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply)
* Otherwise, the deck has not been parsed correctly. Error messages can be extracted * Otherwise, the deck has not been parsed correctly. Error messages can be extracted
* from the html. Css pseudo selector for errors: $("div.alert-danger > ul > li") * from the html. Css pseudo selector for errors: $("div.alert-danger > ul > li")
*/ */
QString data(reply->readAll()); const QString data(reply->readAll());
QStringList errorMessageList = {tr("Unable to analyze the deck.")}; QStringList errorMessageList = {tr("Unable to analyze the deck.")};
static const QRegularExpression rx("<div class=\"alert alert-danger.*?<ul>(.*?)</ul>"); static const QRegularExpression rx("<div class=\"alert alert-danger.*?<ul>(.*?)</ul>");
auto match = rx.match(data); const auto match = rx.match(data);
if (match.hasMatch()) { if (match.hasMatch()) {
QString errors = match.captured(1); const QString errors = match.captured(1);
static const QRegularExpression rx2("<li>(.*?)</li>"); static const QRegularExpression rx2("<li>(.*?)</li>");
static const QRegularExpression rxremove("<[^>]*>"); static const QRegularExpression rxremove("<[^>]*>");
auto matchIterator = rx2.globalMatch(errors); auto matchIterator = rx2.globalMatch(errors);
@ -56,7 +56,7 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply)
} }
} }
QString errorMessage = errorMessageList.join("\n"); const QString errorMessage = errorMessageList.join("\n");
qCWarning(TappedOutInterfaceLog) << "Tappedout: bad reply, http status" << httpStatus << "size" << data.size() qCWarning(TappedOutInterfaceLog) << "Tappedout: bad reply, http status" << httpStatus << "size" << data.size()
<< "message" << errorMessage; << "message" << errorMessage;
@ -95,7 +95,7 @@ void TappedOutInterface::analyzeDeck(DeckList *deck)
void TappedOutInterface::copyDeckSplitMainAndSide(DeckList &source, DeckList &mainboard, DeckList &sideboard) void TappedOutInterface::copyDeckSplitMainAndSide(DeckList &source, DeckList &mainboard, DeckList &sideboard)
{ {
auto copyMainOrSide = [this, &mainboard, &sideboard](const auto node, const auto card) { auto copyMainOrSide = [this, &mainboard, &sideboard](const auto node, const auto card) {
CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName()); const CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName());
if (!dbCard || dbCard->getIsToken()) if (!dbCard || dbCard->getIsToken())
return; return;

View file

@ -26,28 +26,28 @@ bool parseDeckUrl(const QString &url, ParsedDeckInfo &outInfo)
QRegularExpressionMatch match; QRegularExpressionMatch match;
if ((match = rxTappedOut.match(url)).hasMatch()) { if ((match = rxTappedOut.match(url)).hasMatch()) {
QString slug = match.captured(1); const QString slug = match.captured(1);
outInfo = ParsedDeckInfo{.baseUrl = TAPPEDOUT_BASE, outInfo = ParsedDeckInfo{.baseUrl = TAPPEDOUT_BASE,
.deckID = slug, .deckID = slug,
.fullUrl = TAPPEDOUT_BASE + slug + TAPPEDOUT_SUFFIX, .fullUrl = TAPPEDOUT_BASE + slug + TAPPEDOUT_SUFFIX,
.provider = DeckProvider::TappedOut}; .provider = DeckProvider::TappedOut};
return true; return true;
} else if ((match = rxArchidekt.match(url)).hasMatch()) { } else if ((match = rxArchidekt.match(url)).hasMatch()) {
QString deckID = match.captured(1); const QString deckID = match.captured(1);
outInfo = ParsedDeckInfo{.baseUrl = ARCHIDEKT_BASE, outInfo = ParsedDeckInfo{.baseUrl = ARCHIDEKT_BASE,
.deckID = deckID, .deckID = deckID,
.fullUrl = ARCHIDEKT_BASE + deckID + ARCHIDEKT_SUFFIX, .fullUrl = ARCHIDEKT_BASE + deckID + ARCHIDEKT_SUFFIX,
.provider = DeckProvider::Archidekt}; .provider = DeckProvider::Archidekt};
return true; return true;
} else if ((match = rxMoxfield.match(url)).hasMatch()) { } else if ((match = rxMoxfield.match(url)).hasMatch()) {
QString deckID = match.captured(1); const QString deckID = match.captured(1);
outInfo = ParsedDeckInfo{.baseUrl = MOXFIELD_BASE, outInfo = ParsedDeckInfo{.baseUrl = MOXFIELD_BASE,
.deckID = deckID, .deckID = deckID,
.fullUrl = MOXFIELD_BASE + deckID + MOXFIELD_SUFFIX, .fullUrl = MOXFIELD_BASE + deckID + MOXFIELD_SUFFIX,
.provider = DeckProvider::Moxfield}; .provider = DeckProvider::Moxfield};
return true; return true;
} else if ((match = rxDeckstats.match(url)).hasMatch()) { } else if ((match = rxDeckstats.match(url)).hasMatch()) {
QString deckPath = match.captured(1); const QString deckPath = match.captured(1);
outInfo = ParsedDeckInfo{.baseUrl = "https://deckstats.net/decks/", outInfo = ParsedDeckInfo{.baseUrl = "https://deckstats.net/decks/",
.deckID = deckPath, .deckID = deckPath,
.fullUrl = "https://deckstats.net/decks/" + deckPath + DECKSTATS_SUFFIX, .fullUrl = "https://deckstats.net/decks/" + deckPath + DECKSTATS_SUFFIX,

View file

@ -26,8 +26,8 @@ public:
{ {
DeckLoader *loader = new DeckLoader(nullptr); DeckLoader *loader = new DeckLoader(nullptr);
QString deckName = obj.value("name").toString(); const QString deckName = obj.value("name").toString();
QString deckDescription = obj.value("description").toString(); const QString deckDescription = obj.value("description").toString();
loader->getDeckList()->setName(deckName); loader->getDeckList()->setName(deckName);
loader->getDeckList()->setComments(deckDescription); loader->getDeckList()->setComments(deckDescription);
@ -36,7 +36,7 @@ public:
QTextStream outStream(&outputText); QTextStream outStream(&outputText);
for (auto entry : obj.value("cards").toArray()) { for (auto entry : obj.value("cards").toArray()) {
auto quantity = entry.toObject().value("quantity").toInt(); const auto quantity = entry.toObject().value("quantity").toInt();
auto card = entry.toObject().value("card").toObject(); auto card = entry.toObject().value("card").toObject();
auto oracleCard = card.value("oracleCard").toObject(); auto oracleCard = card.value("oracleCard").toObject();

View file

@ -34,14 +34,14 @@ SpoilerBackgroundUpdater::SpoilerBackgroundUpdater(QObject *apParent) : QObject(
void SpoilerBackgroundUpdater::startSpoilerDownloadProcess(QString url, bool saveResults) void SpoilerBackgroundUpdater::startSpoilerDownloadProcess(QString url, bool saveResults)
{ {
auto spoilerURL = QUrl(url); const auto spoilerURL = QUrl(url);
downloadFromURL(spoilerURL, saveResults); downloadFromURL(spoilerURL, saveResults);
} }
void SpoilerBackgroundUpdater::downloadFromURL(QUrl url, bool saveResults) void SpoilerBackgroundUpdater::downloadFromURL(QUrl url, bool saveResults)
{ {
auto *nam = new QNetworkAccessManager(this); auto *nam = new QNetworkAccessManager(this);
QNetworkReply *reply = nam->get(QNetworkRequest(url)); const QNetworkReply *reply = nam->get(QNetworkRequest(url));
if (saveResults) { if (saveResults) {
// This will write out to the file (used for spoiler.xml) // This will write out to the file (used for spoiler.xml)
@ -56,7 +56,7 @@ void SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile()
{ {
// Check for server reply // Check for server reply
auto *reply = dynamic_cast<QNetworkReply *>(sender()); auto *reply = dynamic_cast<QNetworkReply *>(sender());
QNetworkReply::NetworkError errorCode = reply->error(); const QNetworkReply::NetworkError errorCode = reply->error();
if (errorCode == QNetworkReply::NoError) { if (errorCode == QNetworkReply::NoError) {
spoilerData = reply->readAll(); spoilerData = reply->readAll();
@ -74,8 +74,8 @@ void SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile()
bool SpoilerBackgroundUpdater::deleteSpoilerFile() bool SpoilerBackgroundUpdater::deleteSpoilerFile()
{ {
QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); const QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath();
QFileInfo fi(fileName); const QFileInfo fi(fileName);
QDir fileDir(fi.path()); QDir fileDir(fi.path());
QFile file(fileName); QFile file(fileName);
@ -91,8 +91,8 @@ bool SpoilerBackgroundUpdater::deleteSpoilerFile()
void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled() void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled()
{ {
auto *response = dynamic_cast<QNetworkReply *>(sender()); const auto *response = dynamic_cast<QNetworkReply *>(sender());
QNetworkReply::NetworkError errorCode = response->error(); const QNetworkReply::NetworkError errorCode = response->error();
if (errorCode == QNetworkReply::ContentNotFoundError) { if (errorCode == QNetworkReply::ContentNotFoundError) {
// Spoiler season is offline at this point, so the spoiler.xml file can be safely deleted // Spoiler season is offline at this point, so the spoiler.xml file can be safely deleted
@ -125,9 +125,9 @@ void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled()
bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data) bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data)
{ {
QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); const QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath();
QFileInfo fi(fileName); const QFileInfo fi(fileName);
QDir fileDir(fi.path()); const QDir fileDir(fi.path());
if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) { if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) {
return false; return false;
@ -179,7 +179,7 @@ bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data)
utcTime.setTimeSpec(Qt::UTC); utcTime.setTimeSpec(Qt::UTC);
#endif #endif
QString localTime = utcTime.toLocalTime().toString("MMM d, hh:mm"); const QString localTime = utcTime.toLocalTime().toString("MMM d, hh:mm");
trayIcon->showMessage(tr("Spoilers have been updated!"), tr("Last change:") + " " + localTime); trayIcon->showMessage(tr("Spoilers have been updated!"), tr("Last change:") + " " + localTime);
emit spoilersUpdatedSuccessfully(); emit spoilersUpdatedSuccessfully();

View file

@ -9,7 +9,7 @@ ClientUpdateChecker::ClientUpdateChecker(QObject *parent) : QObject(parent)
void ClientUpdateChecker::check() void ClientUpdateChecker::check()
{ {
auto releaseChannel = SettingsCache::instance().getUpdateReleaseChannel(); const auto releaseChannel = SettingsCache::instance().getUpdateReleaseChannel();
finishedCheckConnection = finishedCheckConnection =
connect(releaseChannel, &ReleaseChannel::finishedCheck, this, &ClientUpdateChecker::actFinishedCheck); connect(releaseChannel, &ReleaseChannel::finishedCheck, this, &ClientUpdateChecker::actFinishedCheck);

View file

@ -37,7 +37,7 @@ ReleaseChannel::~ReleaseChannel()
void ReleaseChannel::checkForUpdates() void ReleaseChannel::checkForUpdates()
{ {
QString releaseChannelUrl = getReleaseChannelUrl(); const QString releaseChannelUrl = getReleaseChannelUrl();
qCInfo(ReleaseChannelLog) << "Searching for updates on the channel: " << releaseChannelUrl; qCInfo(ReleaseChannelLog) << "Searching for updates on the channel: " << releaseChannelUrl;
response = netMan->get(QNetworkRequest(releaseChannelUrl)); response = netMan->get(QNetworkRequest(releaseChannelUrl));
connect(response, &QNetworkReply::finished, this, &ReleaseChannel::releaseListFinished); connect(response, &QNetworkReply::finished, this, &ReleaseChannel::releaseListFinished);
@ -113,7 +113,7 @@ void StableReleaseChannel::releaseListFinished()
{ {
auto *reply = static_cast<QNetworkReply *>(sender()); auto *reply = static_cast<QNetworkReply *>(sender());
QJsonParseError parseError{}; QJsonParseError parseError{};
QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); const QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError);
reply->deleteLater(); reply->deleteLater();
if (parseError.error != QJsonParseError::NoError) { if (parseError.error != QJsonParseError::NoError) {
qCWarning(ReleaseChannelLog) << "No reply received from the release update server."; qCWarning(ReleaseChannelLog) << "No reply received from the release update server.";
@ -141,7 +141,7 @@ void StableReleaseChannel::releaseListFinished()
for (const auto &rawAsset : rawAssets) { for (const auto &rawAsset : rawAssets) {
QVariantMap asset = rawAsset.toMap(); QVariantMap asset = rawAsset.toMap();
QString name = asset["name"].toString(); QString name = asset["name"].toString();
QString url = asset["browser_download_url"].toString(); const QString url = asset["browser_download_url"].toString();
if (downloadMatchesCurrentOS(name)) { if (downloadMatchesCurrentOS(name)) {
lastRelease->setDownloadUrl(url); lastRelease->setDownloadUrl(url);
@ -150,8 +150,8 @@ void StableReleaseChannel::releaseListFinished()
} }
} }
QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); const QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN);
QString myHash = QString(VERSION_COMMIT); const QString myHash = QString(VERSION_COMMIT);
qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash; qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash;
qCInfo(ReleaseChannelLog) << "Got reply from release server, name=" << lastRelease->getName() qCInfo(ReleaseChannelLog) << "Got reply from release server, name=" << lastRelease->getName()
@ -159,7 +159,7 @@ void StableReleaseChannel::releaseListFinished()
<< "url=" << lastRelease->getDownloadUrl(); << "url=" << lastRelease->getDownloadUrl();
const QString &tagName = resultMap["tag_name"].toString(); const QString &tagName = resultMap["tag_name"].toString();
QString url = QString(STABLETAG_URL) + tagName; const QString url = QString(STABLETAG_URL) + tagName;
qCInfo(ReleaseChannelLog) << "Searching for commit hash corresponding to stable channel tag: " << tagName; qCInfo(ReleaseChannelLog) << "Searching for commit hash corresponding to stable channel tag: " << tagName;
response = netMan->get(QNetworkRequest(url)); response = netMan->get(QNetworkRequest(url));
connect(response, &QNetworkReply::finished, this, &StableReleaseChannel::tagListFinished); connect(response, &QNetworkReply::finished, this, &StableReleaseChannel::tagListFinished);
@ -187,8 +187,8 @@ void StableReleaseChannel::tagListFinished()
lastRelease->setCommitHash(resultMap["object"].toMap()["sha"].toString()); lastRelease->setCommitHash(resultMap["object"].toMap()["sha"].toString());
qCInfo(ReleaseChannelLog) << "Got reply from tag server, commit=" << lastRelease->getCommitHash(); qCInfo(ReleaseChannelLog) << "Got reply from tag server, commit=" << lastRelease->getCommitHash();
QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); const QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN);
QString myHash = QString(VERSION_COMMIT); const QString myHash = QString(VERSION_COMMIT);
qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash; qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash;
const bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0); const bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0);
@ -218,11 +218,11 @@ QString BetaReleaseChannel::getReleaseChannelUrl() const
void BetaReleaseChannel::releaseListFinished() void BetaReleaseChannel::releaseListFinished()
{ {
auto *reply = static_cast<QNetworkReply *>(sender()); auto *reply = static_cast<QNetworkReply *>(sender());
QByteArray jsonData = reply->readAll(); const QByteArray jsonData = reply->readAll();
reply->deleteLater(); reply->deleteLater();
QJsonDocument doc = QJsonDocument::fromJson(jsonData); const QJsonDocument doc = QJsonDocument::fromJson(jsonData);
QJsonArray array = doc.array(); const QJsonArray array = doc.array();
/* /*
* Get the latest release on GitHub * Get the latest release on GitHub
@ -260,7 +260,7 @@ void BetaReleaseChannel::releaseListFinished()
<< "name=" << lastRelease->getName() << "desc=" << lastRelease->getDescriptionUrl() << "name=" << lastRelease->getName() << "desc=" << lastRelease->getDescriptionUrl()
<< "commit=" << lastRelease->getCommitHash() << "date=" << lastRelease->getPublishDate(); << "commit=" << lastRelease->getCommitHash() << "date=" << lastRelease->getPublishDate();
QString betaBuildDownloadUrl = resultMap["assets_url"].toString(); const QString betaBuildDownloadUrl = resultMap["assets_url"].toString();
qCInfo(ReleaseChannelLog) << "Searching for a corresponding file on the beta channel: " << betaBuildDownloadUrl; qCInfo(ReleaseChannelLog) << "Searching for a corresponding file on the beta channel: " << betaBuildDownloadUrl;
response = netMan->get(QNetworkRequest(betaBuildDownloadUrl)); response = netMan->get(QNetworkRequest(betaBuildDownloadUrl));
@ -271,7 +271,7 @@ void BetaReleaseChannel::fileListFinished()
{ {
auto *reply = static_cast<QNetworkReply *>(sender()); auto *reply = static_cast<QNetworkReply *>(sender());
QJsonParseError parseError{}; QJsonParseError parseError{};
QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); const QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError);
reply->deleteLater(); reply->deleteLater();
if (parseError.error != QJsonParseError::NoError) { if (parseError.error != QJsonParseError::NoError) {
qCWarning(ReleaseChannelLog) << "No reply received from the file update server."; qCWarning(ReleaseChannelLog) << "No reply received from the file update server.";
@ -280,11 +280,11 @@ void BetaReleaseChannel::fileListFinished()
} }
QVariantList resultList = jsonResponse.toVariant().toList(); QVariantList resultList = jsonResponse.toVariant().toList();
QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); const QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN);
QString myHash = QString(VERSION_COMMIT); const QString myHash = QString(VERSION_COMMIT);
qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash; qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash;
bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0); const bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0);
bool compatibleVersion = false; bool compatibleVersion = false;
QStringList resultUrlList{}; QStringList resultUrlList{};

View file

@ -31,7 +31,7 @@ void UpdateDownloader::downloadError(QNetworkReply::NetworkError)
void UpdateDownloader::fileFinished() void UpdateDownloader::fileFinished()
{ {
// If we finished but there's a redirect, follow it // If we finished but there's a redirect, follow it
QVariant redirect = response->attribute(QNetworkRequest::RedirectionTargetAttribute); const QVariant redirect = response->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (!redirect.isNull()) { if (!redirect.isNull()) {
beginDownload(redirect.toUrl()); beginDownload(redirect.toUrl());
return; return;
@ -44,7 +44,7 @@ void UpdateDownloader::fileFinished()
} }
// Work out the file name of the download // Work out the file name of the download
QString fileName = QDir::temp().path() + QDir::separator() + originalUrl.toString().section('/', -1); const QString fileName = QDir::temp().path() + QDir::separator() + originalUrl.toString().section('/', -1);
// Save the build in a temporary directory // Save the build in a temporary directory
QFile file(fileName); QFile file(fileName);

View file

@ -63,7 +63,7 @@ void SettingsCache::translateLegacySettings()
// Sets // Sets
legacySetting.beginGroup("sets"); legacySetting.beginGroup("sets");
QStringList setsGroups = legacySetting.childGroups(); const QStringList setsGroups = legacySetting.childGroups();
for (int i = 0; i < setsGroups.size(); i++) { for (int i = 0; i < setsGroups.size(); i++) {
legacySetting.beginGroup(setsGroups.at(i)); legacySetting.beginGroup(setsGroups.at(i));
cardDatabase()->setEnabled(setsGroups.at(i), legacySetting.value("enabled").toBool()); cardDatabase()->setEnabled(setsGroups.at(i), legacySetting.value("enabled").toBool());
@ -71,7 +71,7 @@ void SettingsCache::translateLegacySettings()
cardDatabase()->setSortKey(setsGroups.at(i), legacySetting.value("sortkey").toUInt()); cardDatabase()->setSortKey(setsGroups.at(i), legacySetting.value("sortkey").toUInt());
legacySetting.endGroup(); legacySetting.endGroup();
} }
QStringList setsKeys = legacySetting.allKeys(); const QStringList setsKeys = legacySetting.allKeys();
for (int i = 0; i < setsKeys.size(); ++i) { for (int i = 0; i < setsKeys.size(); ++i) {
usedKeys.append("sets/" + setsKeys.at(i)); usedKeys.append("sets/" + setsKeys.at(i));
} }
@ -86,7 +86,7 @@ void SettingsCache::translateLegacySettings()
servers().setFPPort(legacySetting.value("fpport").toString()); servers().setFPPort(legacySetting.value("fpport").toString());
servers().setFPPlayerName(legacySetting.value("fpplayername").toString()); servers().setFPPlayerName(legacySetting.value("fpplayername").toString());
usedKeys.append(legacySetting.allKeys()); usedKeys.append(legacySetting.allKeys());
QStringList allKeysServer = legacySetting.allKeys(); const QStringList allKeysServer = legacySetting.allKeys();
for (int i = 0; i < allKeysServer.size(); ++i) { for (int i = 0; i < allKeysServer.size(); ++i) {
usedKeys.append("server/" + allKeysServer.at(i)); usedKeys.append("server/" + allKeysServer.at(i));
} }
@ -94,16 +94,16 @@ void SettingsCache::translateLegacySettings()
// Messages // Messages
legacySetting.beginGroup("messages"); legacySetting.beginGroup("messages");
QStringList allMessages = legacySetting.allKeys(); const QStringList allMessages = legacySetting.allKeys();
for (int i = 0; i < allMessages.size(); ++i) { for (int i = 0; i < allMessages.size(); ++i) {
if (allMessages.at(i) != "count") { if (allMessages.at(i) != "count") {
QString temp = allMessages.at(i); QString temp = allMessages.at(i);
int index = temp.remove("msg").toInt(); const int index = temp.remove("msg").toInt();
messages().setMessageAt(index, legacySetting.value(allMessages.at(i)).toString()); messages().setMessageAt(index, legacySetting.value(allMessages.at(i)).toString());
} }
} }
messages().setCount(legacySetting.value("count").toInt()); messages().setCount(legacySetting.value("count").toInt());
QStringList allKeysmessages = legacySetting.allKeys(); const QStringList allKeysmessages = legacySetting.allKeys();
for (int i = 0; i < allKeysmessages.size(); ++i) { for (int i = 0; i < allKeysmessages.size(); ++i) {
usedKeys.append("messages/" + allKeysmessages.at(i)); usedKeys.append("messages/" + allKeysmessages.at(i));
} }
@ -120,19 +120,19 @@ void SettingsCache::translateLegacySettings()
else else
gameFilters().setMaxPlayers(99); // This prevents a bug where no games will show if max was not set before gameFilters().setMaxPlayers(99); // This prevents a bug where no games will show if max was not set before
QStringList allFilters = legacySetting.allKeys(); const QStringList allFilters = legacySetting.allKeys();
for (int i = 0; i < allFilters.size(); ++i) { for (int i = 0; i < allFilters.size(); ++i) {
if (allFilters.at(i).startsWith("game_type")) { if (allFilters.at(i).startsWith("game_type")) {
gameFilters().setGameHashedTypeEnabled(allFilters.at(i), legacySetting.value(allFilters.at(i)).toBool()); gameFilters().setGameHashedTypeEnabled(allFilters.at(i), legacySetting.value(allFilters.at(i)).toBool());
} }
} }
QStringList allKeysfilter_games = legacySetting.allKeys(); const QStringList allKeysfilter_games = legacySetting.allKeys();
for (int i = 0; i < allKeysfilter_games.size(); ++i) { for (int i = 0; i < allKeysfilter_games.size(); ++i) {
usedKeys.append("filter_games/" + allKeysfilter_games.at(i)); usedKeys.append("filter_games/" + allKeysfilter_games.at(i));
} }
legacySetting.endGroup(); legacySetting.endGroup();
QStringList allLegacyKeys = legacySetting.allKeys(); const QStringList allLegacyKeys = legacySetting.allKeys();
for (int i = 0; i < allLegacyKeys.size(); ++i) { for (int i = 0; i < allLegacyKeys.size(); ++i) {
if (usedKeys.contains(allLegacyKeys.at(i))) if (usedKeys.contains(allLegacyKeys.at(i)))
continue; continue;
@ -173,7 +173,7 @@ SettingsCache::SettingsCache()
// define a dummy context that will be used where needed // define a dummy context that will be used where needed
QString dummy = QT_TRANSLATE_NOOP("i18n", "English"); QString dummy = QT_TRANSLATE_NOOP("i18n", "English");
QString settingsPath = getSettingsPath(); const QString settingsPath = getSettingsPath();
settings = new QSettings(settingsPath + "global.ini", QSettings::IniFormat, this); settings = new QSettings(settingsPath + "global.ini", QSettings::IniFormat, this);
shortcutsSettings = new ShortcutsSettings(settingsPath, this); shortcutsSettings = new ShortcutsSettings(settingsPath, this);
cardDatabaseSettings = new CardDatabaseSettings(settingsPath, this); cardDatabaseSettings = new CardDatabaseSettings(settingsPath, this);
@ -234,7 +234,7 @@ SettingsCache::SettingsCache()
tabLogOpen = settings->value("tabs/log", true).toBool(); tabLogOpen = settings->value("tabs/log", true).toBool();
// we only want to reset the cache once, then its up to the user // we only want to reset the cache once, then its up to the user
bool updateCache = settings->value("revert/pixmapCacheSize", false).toBool(); const bool updateCache = settings->value("revert/pixmapCacheSize", false).toBool();
if (!updateCache) { if (!updateCache) {
pixmapCacheSize = PIXMAPCACHE_SIZE_DEFAULT; pixmapCacheSize = PIXMAPCACHE_SIZE_DEFAULT;
settings->setValue("personal/pixmapCacheSize", pixmapCacheSize); settings->setValue("personal/pixmapCacheSize", pixmapCacheSize);
@ -485,7 +485,7 @@ void SettingsCache::setSeenTips(const QList<int> &_seenTips)
{ {
seenTips = _seenTips; seenTips = _seenTips;
QList<QVariant> storedTipList; QList<QVariant> storedTipList;
for (auto tipNumber : seenTips) { for (const auto tipNumber : seenTips) {
storedTipList.append(tipNumber); storedTipList.append(tipNumber);
} }
settings->setValue("tipOfDay/seenTips", storedTipList); settings->setValue("tipOfDay/seenTips", storedTipList);
@ -1510,7 +1510,7 @@ void SettingsCache::setRoundCardCorners(bool _roundCardCorners)
void SettingsCache::loadPaths() void SettingsCache::loadPaths()
{ {
QString dataPath = getDataPath(); const QString dataPath = getDataPath();
deckPath = getSafeConfigPath("paths/decks", dataPath + "/decks/"); deckPath = getSafeConfigPath("paths/decks", dataPath + "/decks/");
filtersPath = getSafeConfigPath("paths/filters", dataPath + "/filters/"); filtersPath = getSafeConfigPath("paths/filters", dataPath + "/filters/");
replaysPath = getSafeConfigPath("paths/replays", dataPath + "/replays/"); replaysPath = getSafeConfigPath("paths/replays", dataPath + "/replays/");
@ -1532,8 +1532,8 @@ void SettingsCache::loadPaths()
void SettingsCache::resetPaths() void SettingsCache::resetPaths()
{ {
QStringList databasePaths{customCardDatabasePath, cardDatabasePath, spoilerDatabasePath, tokenDatabasePath}; const QStringList databasePaths{customCardDatabasePath, cardDatabasePath, spoilerDatabasePath, tokenDatabasePath};
QString picsPath_ = picsPath; const QString picsPath_ = picsPath;
settings->remove("paths"); // removes all keys in paths/* settings->remove("paths"); // removes all keys in paths/*
loadPaths(); loadPaths();
if (databasePaths != if (databasePaths !=

View file

@ -11,7 +11,7 @@ CardCounterSettings::CardCounterSettings(const QString &settingsPath, QObject *p
void CardCounterSettings::setColor(int counterId, const QColor &color) void CardCounterSettings::setColor(int counterId, const QColor &color)
{ {
QString key = QString("cards/counters/%1/color").arg(counterId); const QString key = QString("cards/counters/%1/color").arg(counterId);
if (settings.value(key).value<QColor>() == color) if (settings.value(key).value<QColor>() == color)
return; return;
@ -29,9 +29,9 @@ QColor CardCounterSettings::color(int counterId) const
defaultColor = QColor::fromHsv(counterId * 60, 150, 255); defaultColor = QColor::fromHsv(counterId * 60, 150, 255);
} else { } else {
// Future-proof support for more counters with pseudo-random colors // Future-proof support for more counters with pseudo-random colors
int h = (counterId * 37) % 360; const int h = (counterId * 37) % 360;
int s = 128 + 64 * qSin((counterId * 97) * 0.1); // 64-192 const int s = 128 + 64 * qSin((counterId * 97) * 0.1); // 64-192
int v = 196 + 32 * qSin((counterId * 101) * 0.07); // 164-228 const int v = 196 + 32 * qSin((counterId * 101) * 0.07); // 164-228
defaultColor = QColor::fromHsv(h, s, v); defaultColor = QColor::fromHsv(h, s, v);
} }
@ -43,7 +43,7 @@ QString CardCounterSettings::displayName(int counterId) const
{ {
// Currently, card counters name are fixed to A, B, ..., Z, AA, AB, ... // Currently, card counters name are fixed to A, B, ..., Z, AA, AB, ...
auto nChars = 1 + counterId / 26; const auto nChars = 1 + counterId / 26;
QString str; QString str;
str.resize(nChars); str.resize(nChars);

View file

@ -14,13 +14,13 @@ ShortcutFilterProxyModel::ShortcutFilterProxyModel(QObject *parent) : QSortFilte
*/ */
bool ShortcutFilterProxyModel::filterAcceptsRow(const int sourceRow, const QModelIndex &sourceParent) const bool ShortcutFilterProxyModel::filterAcceptsRow(const int sourceRow, const QModelIndex &sourceParent) const
{ {
QModelIndex nameIndex = sourceModel()->index(sourceRow, filterKeyColumn(), sourceParent); const QModelIndex nameIndex = sourceModel()->index(sourceRow, filterKeyColumn(), sourceParent);
QModelIndex parentIndex = sourceModel()->index(sourceParent.row(), filterKeyColumn(), sourceParent.parent()); const QModelIndex parentIndex = sourceModel()->index(sourceParent.row(), filterKeyColumn(), sourceParent.parent());
QString name = sourceModel()->data(nameIndex).toString(); const QString name = sourceModel()->data(nameIndex).toString();
QString parentName = sourceModel()->data(parentIndex).toString(); const QString parentName = sourceModel()->data(parentIndex).toString();
QString searchedString = parentName + " " + name; const QString searchedString = parentName + " " + name;
return searchedString.contains(filterRegularExpression()); return searchedString.contains(filterRegularExpression());
} }
@ -136,7 +136,7 @@ void ShortcutTreeView::currentChanged(const QModelIndex &current, const QModelIn
{ {
QTreeView::scrollTo(current, QAbstractItemView::EnsureVisible); QTreeView::scrollTo(current, QAbstractItemView::EnsureVisible);
if (current.parent().isValid()) { if (current.parent().isValid()) {
auto shortcutName = model()->data(model()->index(current.row(), 2, current.parent())).toString(); const auto shortcutName = model()->data(model()->index(current.row(), 2, current.parent())).toString();
emit currentItemChanged(shortcutName); emit currentItemChanged(shortcutName);
} else { } else {
// emit empty string if the selection is a category header // emit empty string if the selection is a category header
@ -160,7 +160,7 @@ void ShortcutTreeView::updateSearchString(const QString &searchString)
auto escapeRegex = [](const QString &s) { return QRegularExpression::escape(s); }; auto escapeRegex = [](const QString &s) { return QRegularExpression::escape(s); };
std::transform(searchWords.begin(), searchWords.end(), searchWords.begin(), escapeRegex); std::transform(searchWords.begin(), searchWords.end(), searchWords.begin(), escapeRegex);
auto regex = QRegularExpression(searchWords.join(".*"), QRegularExpression::CaseInsensitiveOption); const auto regex = QRegularExpression(searchWords.join(".*"), QRegularExpression::CaseInsensitiveOption);
proxyModel->setFilterRegularExpression(regex); proxyModel->setFilterRegularExpression(regex);
expandAll(); expandAll();

View file

@ -17,7 +17,7 @@ ShortcutsSettings::ShortcutsSettings(const QString &settingsPath, QObject *paren
settingsFilePath = settingsPath; settingsFilePath = settingsPath;
settingsFilePath.append("shortcuts.ini"); settingsFilePath.append("shortcuts.ini");
bool exists = QFile(settingsFilePath).exists(); const bool exists = QFile(settingsFilePath).exists();
QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat); QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat);
@ -76,7 +76,7 @@ void ShortcutsSettings::migrateShortcuts()
if (shortCutsFile.contains("Textbox/unfocusTextBox")) { if (shortCutsFile.contains("Textbox/unfocusTextBox")) {
qCInfo(ShortcutsSettingsLog) qCInfo(ShortcutsSettingsLog)
<< "[ShortcutsSettings] Textbox/unfocusTextBox shortcut found. Migrating to Player/unfocusTextBox."; << "[ShortcutsSettings] Textbox/unfocusTextBox shortcut found. Migrating to Player/unfocusTextBox.";
QString unfocusTextBox = shortCutsFile.value("Textbox/unfocusTextBox", "").toString(); const QString unfocusTextBox = shortCutsFile.value("Textbox/unfocusTextBox", "").toString();
this->setShortcuts("Player/unfocusTextBox", unfocusTextBox); this->setShortcuts("Player/unfocusTextBox", unfocusTextBox);
shortCutsFile.remove("Textbox/unfocusTextBox"); shortCutsFile.remove("Textbox/unfocusTextBox");
} }
@ -84,7 +84,7 @@ void ShortcutsSettings::migrateShortcuts()
if (shortCutsFile.contains("tab_game/aFocusChat")) { if (shortCutsFile.contains("tab_game/aFocusChat")) {
qCInfo(ShortcutsSettingsLog) qCInfo(ShortcutsSettingsLog)
<< "[ShortcutsSettings] tab_game/aFocusChat shortcut found. Migrating to Player/aFocusChat."; << "[ShortcutsSettings] tab_game/aFocusChat shortcut found. Migrating to Player/aFocusChat.";
QString aFocusChat = shortCutsFile.value("tab_game/aFocusChat", "").toString(); const QString aFocusChat = shortCutsFile.value("tab_game/aFocusChat", "").toString();
this->setShortcuts("Player/aFocusChat", aFocusChat); this->setShortcuts("Player/aFocusChat", aFocusChat);
shortCutsFile.remove("tab_game/aFocusChat"); shortCutsFile.remove("tab_game/aFocusChat");
} }
@ -92,7 +92,7 @@ void ShortcutsSettings::migrateShortcuts()
// PR #5564 changes "MainWindow/aDeckEditor" to "Tabs/aTabDeckEditor" // PR #5564 changes "MainWindow/aDeckEditor" to "Tabs/aTabDeckEditor"
if (shortCutsFile.contains("MainWindow/aDeckEditor")) { if (shortCutsFile.contains("MainWindow/aDeckEditor")) {
qCInfo(ShortcutsSettingsLog) << "MainWindow/aDeckEditor shortcut found. Migrating to Tabs/aTabDeckEditor."; qCInfo(ShortcutsSettingsLog) << "MainWindow/aDeckEditor shortcut found. Migrating to Tabs/aTabDeckEditor.";
QString keySequence = shortCutsFile.value("MainWindow/aDeckEditor", "").toString(); const QString keySequence = shortCutsFile.value("MainWindow/aDeckEditor", "").toString();
this->setShortcuts("Tabs/aTabDeckEditor", keySequence); this->setShortcuts("Tabs/aTabDeckEditor", keySequence);
shortCutsFile.remove("MainWindow/aDeckEditor"); shortCutsFile.remove("MainWindow/aDeckEditor");
} }
@ -217,9 +217,9 @@ bool ShortcutsSettings::isKeyAllowed(const QString &name, const QString &sequenc
if (name.startsWith("Player") || name.startsWith("Replays")) { if (name.startsWith("Player") || name.startsWith("Replays")) {
return true; return true;
} }
QString checkSequence = sequences.split(sep).last(); const QString checkSequence = sequences.split(sep).last();
QStringList forbiddenKeys{"Del", "Backspace", "Down", "Up", "Left", "Right", const QStringList forbiddenKeys{"Del", "Backspace", "Down", "Up", "Left", "Right",
"Return", "Enter", "Menu", "Ctrl+Alt+-", "Ctrl+Alt+=", "Ctrl+Alt+[", "Return", "Enter", "Menu", "Ctrl+Alt+-", "Ctrl+Alt+=", "Ctrl+Alt+[",
"Ctrl+Alt+]", "Tab", "Space", "Shift+S", "Shift+Left", "Shift+Right"}; "Ctrl+Alt+]", "Tab", "Space", "Shift+S", "Shift+Left", "Shift+Right"};
return !forbiddenKeys.contains(checkSequence); return !forbiddenKeys.contains(checkSequence);
} }
@ -246,8 +246,8 @@ static bool isAlwaysActiveShortcut(const QString &shortcutName)
QStringList ShortcutsSettings::findOverlaps(const QString &name, const QString &sequences) const QStringList ShortcutsSettings::findOverlaps(const QString &name, const QString &sequences) const
{ {
QString checkSequence = sequences.split(sep).last(); const QString checkSequence = sequences.split(sep).last();
QString checkKey = name.left(name.indexOf("/")); const QString checkKey = name.left(name.indexOf("/"));
QStringList overlaps; QStringList overlaps;
for (const auto &key : shortCuts.keys()) { for (const auto &key : shortCuts.keys()) {

View file

@ -130,10 +130,10 @@ QStringMap &SoundEngine::getAvailableThemes()
void SoundEngine::themeChangedSlot() void SoundEngine::themeChangedSlot()
{ {
QString themeName = SettingsCache::instance().getSoundThemeName(); const QString themeName = SettingsCache::instance().getSoundThemeName();
qCInfo(SoundEngineLog) << "Sound theme changed:" << themeName; qCInfo(SoundEngineLog) << "Sound theme changed:" << themeName;
QDir dir = getAvailableThemes().value(themeName); const QDir dir = getAvailableThemes().value(themeName);
audioData.clear(); audioData.clear();

View file

@ -112,13 +112,14 @@ static void setupParserRules()
// actual functionality // actual functionality
search["DeckContentQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { search["DeckContentQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter {
auto cardFilter = FilterString(std::any_cast<QString>(sv[0])); const auto cardFilter = FilterString(std::any_cast<QString>(sv[0]));
auto numberMatcher = sv.size() > 1 ? std::any_cast<NumberMatcher>(sv[1]) : [](int count) { return count > 0; }; const auto numberMatcher =
sv.size() > 1 ? std::any_cast<NumberMatcher>(sv[1]) : [](int count) { return count > 0; };
return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) -> bool { return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) -> bool {
int count = 0; int count = 0;
deck->deckLoader->getDeckList()->forEachCard([&](InnerDecklistNode *, const DecklistCardNode *node) { deck->deckLoader->getDeckList()->forEachCard([&](InnerDecklistNode *, const DecklistCardNode *node) {
auto cardInfoPtr = CardDatabaseManager::query()->getCardInfo(node->getName()); const auto cardInfoPtr = CardDatabaseManager::query()->getCardInfo(node->getName());
if (!cardInfoPtr.isNull() && cardFilter.check(cardInfoPtr)) { if (!cardInfoPtr.isNull() && cardFilter.check(cardInfoPtr)) {
count += node->getNumber(); count += node->getNumber();
} }
@ -134,29 +135,29 @@ static void setupParserRules()
}; };
search["DeckNameQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { search["DeckNameQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter {
auto name = std::any_cast<QString>(sv[0]); const auto name = std::any_cast<QString>(sv[0]);
return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) { return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) {
return deck->deckLoader->getDeckList()->getName().contains(name, Qt::CaseInsensitive); return deck->deckLoader->getDeckList()->getName().contains(name, Qt::CaseInsensitive);
}; };
}; };
search["FileNameQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { search["FileNameQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter {
auto name = std::any_cast<QString>(sv[0]); const auto name = std::any_cast<QString>(sv[0]);
return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) { return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) {
auto filename = QFileInfo(deck->filePath).fileName(); const auto filename = QFileInfo(deck->filePath).fileName();
return filename.contains(name, Qt::CaseInsensitive); return filename.contains(name, Qt::CaseInsensitive);
}; };
}; };
search["PathQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { search["PathQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter {
auto name = std::any_cast<QString>(sv[0]); const auto name = std::any_cast<QString>(sv[0]);
return [=](const DeckPreviewWidget *, const ExtraDeckSearchInfo &info) { return [=](const DeckPreviewWidget *, const ExtraDeckSearchInfo &info) {
return info.relativeFilePath.contains(name, Qt::CaseInsensitive); return info.relativeFilePath.contains(name, Qt::CaseInsensitive);
}; };
}; };
search["GenericQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { search["GenericQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter {
auto name = std::any_cast<QString>(sv[0]); const auto name = std::any_cast<QString>(sv[0]);
return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) { return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) {
return deck->getDisplayName().contains(name, Qt::CaseInsensitive); return deck->getDisplayName().contains(name, Qt::CaseInsensitive);
}; };

View file

@ -216,7 +216,7 @@ bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, i
if (node == NULL || node == fTree) if (node == NULL || node == fTree)
return false; return false;
Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt()); const Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
if (state == Qt::Checked) if (state == Qt::Checked)
node->enable(); node->enable();
else else
@ -288,7 +288,7 @@ QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const
parent = node->parent(); parent = node->parent();
if (parent) { if (parent) {
int row = parent->index(); const int row = parent->index();
if (row < 0) if (row < 0)
return QModelIndex(); return QModelIndex();
idx = createIndex(row, 0, parent); idx = createIndex(row, 0, parent);

View file

@ -23,7 +23,7 @@ static QTextBrowser *createBrowser(const QString &helpFile)
file.close(); file.close();
// --- Remove @page declarations at the top of the file --- // --- Remove @page declarations at the top of the file ---
auto opts = QRegularExpression::MultilineOption; const auto opts = QRegularExpression::MultilineOption;
text = text.replace(QRegularExpression(R"(^\s*@page[^\n]*\n)", opts), ""); text = text.replace(QRegularExpression(R"(^\s*@page[^\n]*\n)", opts), "");
// Poor Markdown Converter // Poor Markdown Converter
@ -33,7 +33,7 @@ static QTextBrowser *createBrowser(const QString &helpFile)
.replace(QRegularExpression("^------*", opts), "<hr />") .replace(QRegularExpression("^------*", opts), "<hr />")
.replace(QRegularExpression(R"(\[([^[]+)\]\(([^\)]+)\))", opts), R"(<a href='\2'>\1</a>)"); .replace(QRegularExpression(R"(\[([^[]+)\]\(([^\)]+)\))", opts), R"(<a href='\2'>\1</a>)");
auto browser = new QTextBrowser(); const auto browser = new QTextBrowser();
browser->setParent(nullptr, Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | browser->setParent(nullptr, Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint |
Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint |
Qt::WindowFullscreenButtonHint); Qt::WindowFullscreenButtonHint);
@ -41,7 +41,7 @@ static QTextBrowser *createBrowser(const QString &helpFile)
browser->setReadOnly(true); browser->setReadOnly(true);
browser->setMinimumSize({500, 600}); browser->setMinimumSize({500, 600});
QString sheet = QString("a { text-decoration: underline; color: rgb(71,158,252) };"); const QString sheet = QString("a { text-decoration: underline; color: rgb(71,158,252) };");
browser->document()->setDefaultStyleSheet(sheet); browser->document()->setDefaultStyleSheet(sheet);
browser->setHtml(text); browser->setHtml(text);
@ -58,7 +58,7 @@ static QTextBrowser *createBrowser(const QString &helpFile)
*/ */
QTextBrowser *createSearchSyntaxHelpWindow(QLineEdit *lineEdit) QTextBrowser *createSearchSyntaxHelpWindow(QLineEdit *lineEdit)
{ {
auto browser = createBrowser("theme:help/search.md"); const auto browser = createBrowser("theme:help/search.md");
QObject::connect(browser, &QTextBrowser::anchorClicked, QObject::connect(browser, &QTextBrowser::anchorClicked,
[lineEdit](const QUrl &link) { lineEdit->setText(link.fragment()); }); [lineEdit](const QUrl &link) { lineEdit->setText(link.fragment()); });
QObject::connect(lineEdit, &QObject::destroyed, browser, &QTextBrowser::close); QObject::connect(lineEdit, &QObject::destroyed, browser, &QTextBrowser::close);
@ -73,7 +73,7 @@ QTextBrowser *createSearchSyntaxHelpWindow(QLineEdit *lineEdit)
*/ */
QTextBrowser *createDeckSearchSyntaxHelpWindow(QLineEdit *lineEdit) QTextBrowser *createDeckSearchSyntaxHelpWindow(QLineEdit *lineEdit)
{ {
auto browser = createBrowser("theme:help/deck_search.md"); const auto browser = createBrowser("theme:help/deck_search.md");
QObject::connect(browser, &QTextBrowser::anchorClicked, [lineEdit](const QUrl &link) { QObject::connect(browser, &QTextBrowser::anchorClicked, [lineEdit](const QUrl &link) {
if (link.fragment() == "cardSearchSyntaxHelp") { if (link.fragment() == "cardSearchSyntaxHelp") {
createSearchSyntaxHelpWindow(lineEdit); createSearchSyntaxHelpWindow(lineEdit);

View file

@ -42,7 +42,7 @@ void AbstractGame::setActiveCard(CardItem *card)
CardItem *AbstractGame::getCard(int playerId, const QString &zoneName, int cardId) const CardItem *AbstractGame::getCard(int playerId, const QString &zoneName, int cardId) const
{ {
Player *player = playerManager->getPlayer(playerId); const Player *player = playerManager->getPlayer(playerId);
if (!player) if (!player)
return nullptr; return nullptr;

View file

@ -47,7 +47,7 @@ AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item,
QPainterPath AbstractCardDragItem::shape() const QPainterPath AbstractCardDragItem::shape() const
{ {
QPainterPath shape; QPainterPath shape;
qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; const qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0;
shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius); shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius);
return shape; return shape;
} }

View file

@ -44,7 +44,7 @@ QRectF AbstractCardItem::boundingRect() const
QPainterPath AbstractCardItem::shape() const QPainterPath AbstractCardItem::shape() const
{ {
QPainterPath shape; QPainterPath shape;
qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; const qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0;
shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius); shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius);
return shape; return shape;
} }
@ -60,8 +60,8 @@ void AbstractCardItem::refreshCardInfo()
exactCard = CardDatabaseManager::query()->getCard(cardRef); exactCard = CardDatabaseManager::query()->getCard(cardRef);
if (!exactCard && !cardRef.name.isEmpty()) { if (!exactCard && !cardRef.name.isEmpty()) {
CardInfo::UiAttributes attributes = {.tableRow = -1}; const CardInfo::UiAttributes attributes = {.tableRow = -1};
auto info = CardInfo::newInstance(cardRef.name, "", true, {}, {}, {}, {}, attributes); const auto info = CardInfo::newInstance(cardRef.name, "", true, {}, {}, {}, {}, attributes);
exactCard = ExactCard(info); exactCard = ExactCard(info);
} }
if (exactCard) { if (exactCard) {
@ -98,9 +98,9 @@ void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &transla
const int MAX_FONT_SIZE = SettingsCache::instance().getMaxFontSize(); const int MAX_FONT_SIZE = SettingsCache::instance().getMaxFontSize();
const int fontSize = std::max(9, MAX_FONT_SIZE); const int fontSize = std::max(9, MAX_FONT_SIZE);
QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); const QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect());
int scale = resetPainterTransform(painter); const int scale = resetPainterTransform(painter);
painter->translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2); painter->translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2);
painter->rotate(angle); painter->rotate(angle);
@ -114,7 +114,7 @@ void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &transla
void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle) void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle)
{ {
qreal scaleFactor = translatedSize.width() / boundingRect().width(); const qreal scaleFactor = translatedSize.width() / boundingRect().width();
QPixmap translatedPixmap; QPixmap translatedPixmap;
bool paintImage = true; bool paintImage = true;
@ -173,7 +173,7 @@ void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *
{ {
painter->save(); painter->save();
QSizeF translatedSize = getTranslatedSize(painter); const QSizeF translatedSize = getTranslatedSize(painter);
paintPicture(painter, translatedSize, tapAngle); paintPicture(painter, translatedSize, tapAngle);
painter->setRenderHint(QPainter::Antialiasing, false); painter->setRenderHint(QPainter::Antialiasing, false);

View file

@ -29,7 +29,7 @@ void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
void CardDragItem::updatePosition(const QPointF &cursorScenePos) void CardDragItem::updatePosition(const QPointF &cursorScenePos)
{ {
QList<QGraphicsItem *> colliding = const QList<QGraphicsItem *> colliding =
scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder,
static_cast<GameScene *>(scene())->getViewTransform()); static_cast<GameScene *>(scene())->getViewTransform());
@ -55,7 +55,7 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
if (!cursorZone) { if (!cursorZone) {
// Avoid the cards getting stuck visually when not over // Avoid the cards getting stuck visually when not over
// any zone. // any zone.
QPointF newPos = cursorScenePos - hotSpot; const QPointF newPos = cursorScenePos - hotSpot;
if (newPos != pos()) { if (newPos != pos()) {
for (int i = 0; i < childDrags.size(); i++) for (int i = 0; i < childDrags.size(); i++)
@ -66,8 +66,8 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
return; return;
} }
QPointF zonePos = currentZone->scenePos(); const QPointF zonePos = currentZone->scenePos();
QPointF cursorPosInZone = cursorScenePos - zonePos; const QPointF cursorPosInZone = cursorScenePos - zonePos;
// If we are on a Table, we center the card around the cursor, because we // If we are on a Table, we center the card around the cursor, because we
// snap it into place and no longer see it being dragged. // snap it into place and no longer see it being dragged.
@ -82,7 +82,7 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
else else
closestGridPoint = cursorPosInZone - hotSpot; closestGridPoint = cursorPosInZone - hotSpot;
QPointF newPos = zonePos + closestGridPoint; const QPointF newPos = zonePos + closestGridPoint;
if (newPos != pos()) { if (newPos != pos()) {
for (int i = 0; i < childDrags.size(); i++) for (int i = 0; i < childDrags.size(); i++)
@ -90,7 +90,7 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
setPos(newPos); setPos(newPos);
bool newOccupied = false; bool newOccupied = false;
TableZone *table = qobject_cast<TableZone *>(cursorZone); const TableZone *table = qobject_cast<TableZone *>(cursorZone);
if (table) if (table)
if (table->getCardFromCoords(closestGridPoint)) if (table->getCardFromCoords(closestGridPoint))
newOccupied = true; newOccupied = true;
@ -105,7 +105,7 @@ void CardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
setCursor(Qt::OpenHandCursor); setCursor(Qt::OpenHandCursor);
QGraphicsScene *sc = scene(); QGraphicsScene *sc = scene();
QPointF sp = pos(); const QPointF sp = pos();
sc->removeItem(this); sc->removeItem(this);
QList<CardDragItem *> dragItemList; QList<CardDragItem *> dragItemList;

View file

@ -47,7 +47,7 @@ void CardList::sortBy(const QList<SortOption> &option)
} }
auto comparator = [&option](CardItem *a, CardItem *b) { auto comparator = [&option](CardItem *a, CardItem *b) {
for (auto prop : option) { for (const auto prop : option) {
auto extractor = getExtractorFor(prop); auto extractor = getExtractorFor(prop);
QString t1 = extractor(a); QString t1 = extractor(a);
QString t2 = extractor(b); QString t2 = extractor(b);
@ -79,7 +79,7 @@ void CardList::sortBy(const QList<SortOption> &option)
*/ */
static QString getColorSortString(const CardInfo &c, bool appendAtEnd) static QString getColorSortString(const CardInfo &c, bool appendAtEnd)
{ {
QString colors = c.getColors(); const QString colors = c.getColors();
switch (colors.size()) { switch (colors.size()) {
case 0: { case 0: {
if (c.getCardType().contains("Land")) { if (c.getCardType().contains("Land")) {
@ -135,7 +135,7 @@ std::function<QString(CardItem *)> CardList::getExtractorFor(SortOption option)
return QString(); return QString();
} }
auto info = c->getCardInfo(); const auto info = c->getCardInfo();
// calculation copied from CardDatabaseModel. // calculation copied from CardDatabaseModel.
// we pad the cmc and also append the mana cost to the end so same cmc cards still have a sort order // we pad the cmc and also append the mana cost to the end so same cmc cards still have a sort order

View file

@ -25,10 +25,10 @@ QRectF GeneralCounter::boundingRect() const
void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); const QRectF mapRect = painter->combinedTransform().mapRect(boundingRect());
int translatedHeight = mapRect.size().height(); const int translatedHeight = mapRect.size().height();
qreal scaleFactor = translatedHeight / boundingRect().height(); const qreal scaleFactor = translatedHeight / boundingRect().height();
QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); const QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered);
painter->save(); painter->save();
resetPainterTransform(painter); resetPainterTransform(painter);

View file

@ -21,7 +21,7 @@ DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item,
void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos) void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos)
{ {
QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos); const QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos);
DeckViewCardContainer *cursorZone = 0; DeckViewCardContainer *cursorZone = 0;
for (int i = colliding.size() - 1; i >= 0; i--) for (int i = colliding.size() - 1; i >= 0; i--)
@ -31,7 +31,7 @@ void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos)
return; return;
currentZone = cursorZone; currentZone = cursorZone;
QPointF newPos = cursorScenePos; const QPointF newPos = cursorScenePos;
if (newPos != pos()) { if (newPos != pos()) {
for (int i = 0; i < childDrags.size(); i++) for (int i = 0; i < childDrags.size(); i++)
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
@ -95,7 +95,7 @@ void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
pen.setJoinStyle(Qt::MiterJoin); pen.setJoinStyle(Qt::MiterJoin);
pen.setColor(originZone == DECK_ZONE_MAIN ? Qt::green : Qt::red); pen.setColor(originZone == DECK_ZONE_MAIN ? Qt::green : Qt::red);
painter->setPen(pen); painter->setPen(pen);
qreal cardRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * (CARD_WIDTH - 3) : 0.0; const qreal cardRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * (CARD_WIDTH - 3) : 0.0;
painter->drawRoundedRect(QRectF(1.5, 1.5, CARD_WIDTH - 3., CARD_HEIGHT - 3.), cardRadius, cardRadius); painter->drawRoundedRect(QRectF(1.5, 1.5, CARD_WIDTH - 3., CARD_HEIGHT - 3.), cardRadius, cardRadius);
painter->restore(); painter->restore();
} }
@ -115,7 +115,7 @@ void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
dragItem->updatePosition(event->scenePos()); dragItem->updatePosition(event->scenePos());
dragItem->grabMouse(); dragItem->grabMouse();
QList<QGraphicsItem *> sel = scene()->selectedItems(); const QList<QGraphicsItem *> sel = scene()->selectedItems();
int j = 0; int j = 0;
for (int i = 0; i < sel.size(); i++) { for (int i = 0; i < sel.size(); i++) {
auto *c = static_cast<DeckViewCard *>(sel.at(i)); auto *c = static_cast<DeckViewCard *>(sel.at(i));
@ -137,11 +137,11 @@ void DeckView::mouseDoubleClickEvent(QMouseEvent *event)
if (event->button() == Qt::LeftButton) { if (event->button() == Qt::LeftButton) {
QList<MoveCard_ToZone> result; QList<MoveCard_ToZone> result;
QList<QGraphicsItem *> sel = scene()->selectedItems(); const QList<QGraphicsItem *> sel = scene()->selectedItems();
for (int i = 0; i < sel.size(); i++) { for (int i = 0; i < sel.size(); i++) {
auto *c = static_cast<DeckViewCard *>(sel.at(i)); const auto *c = static_cast<DeckViewCard *>(sel.at(i));
auto *zone = static_cast<DeckViewCardContainer *>(c->parentItem()); const auto *zone = static_cast<DeckViewCardContainer *>(c->parentItem());
MoveCard_ToZone m; MoveCard_ToZone m;
m.set_card_name(c->getName().toStdString()); m.set_card_name(c->getName().toStdString());
m.set_start_zone(zone->getName().toStdString()); m.set_start_zone(zone->getName().toStdString());
@ -180,7 +180,7 @@ QRectF DeckViewCardContainer::boundingRect() const
void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
qreal totalTextWidth = getCardTypeTextWidth(); const qreal totalTextWidth = getCardTypeTextWidth();
painter->fillRect(boundingRect(), themeManager->getBgBrush(ThemeManager::Table)); painter->fillRect(boundingRect(), themeManager->getBgBrush(ThemeManager::Table));
painter->setPen(QColor(255, 255, 255, 100)); painter->setPen(QColor(255, 255, 255, 100));
@ -204,7 +204,7 @@ void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsI
painter->setPen(QColor(255, 255, 255, 100)); painter->setPen(QColor(255, 255, 255, 100));
painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2)); painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2));
} }
qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; const qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first;
QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight); QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight);
yUntilNow += thisRowHeight + paddingY; yUntilNow += thisRowHeight + paddingY;
@ -242,7 +242,7 @@ int DeckViewCardContainer::getCardTypeTextWidth() const
f.setStyleHint(QFont::Serif); f.setStyleHint(QFont::Serif);
f.setPixelSize(16); f.setPixelSize(16);
f.setWeight(QFont::Bold); f.setWeight(QFont::Bold);
QFontMetrics fm(f); const QFontMetrics fm(f);
int maxCardTypeWidth = 0; int maxCardTypeWidth = 0;
for (const auto &key : cardsByType.keys()) { for (const auto &key : cardsByType.keys()) {
@ -280,7 +280,7 @@ void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int>> &rowsAnd
currentRowsAndCols = rowsAndCols; currentRowsAndCols = rowsAndCols;
qreal yUntilNow = separatorY + paddingY; qreal yUntilNow = separatorY + paddingY;
qreal x = (qreal)getCardTypeTextWidth(); const qreal x = (qreal)getCardTypeTextWidth();
for (int i = 0; i < rowsAndCols.size(); ++i) { for (int i = 0; i < rowsAndCols.size(); ++i) {
const int tempRows = rowsAndCols[i].first; const int tempRows = rowsAndCols[i].first;
const int tempCols = rowsAndCols[i].second; const int tempCols = rowsAndCols[i].second;
@ -295,7 +295,7 @@ void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int>> &rowsAnd
} }
prepareGeometryChange(); prepareGeometryChange();
QSizeF bRect = calculateBoundingRect(rowsAndCols); const QSizeF bRect = calculateBoundingRect(rowsAndCols);
width = bRect.width(); width = bRect.width();
height = bRect.height(); height = bRect.height();
} }
@ -343,9 +343,9 @@ void DeckViewScene::rebuildTree()
if (!deck) if (!deck)
return; return;
InnerDecklistNode *listRoot = deck->getRoot(); const InnerDecklistNode *listRoot = deck->getRoot();
for (int i = 0; i < listRoot->size(); i++) { for (int i = 0; i < listRoot->size(); i++) {
auto *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i)); const auto *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0);
if (!container) { if (!container) {
@ -355,7 +355,7 @@ void DeckViewScene::rebuildTree()
} }
for (int j = 0; j < currentZone->size(); j++) { for (int j = 0; j < currentZone->size(); j++) {
auto *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j)); const auto *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
if (!currentCard) if (!currentCard)
continue; continue;
@ -469,7 +469,7 @@ QList<MoveCard_ToZone> DeckViewScene::getSideboardPlan() const
QList<MoveCard_ToZone> result; QList<MoveCard_ToZone> result;
QMapIterator<QString, DeckViewCardContainer *> containerIterator(cardContainers); QMapIterator<QString, DeckViewCardContainer *> containerIterator(cardContainers);
while (containerIterator.hasNext()) { while (containerIterator.hasNext()) {
DeckViewCardContainer *cont = containerIterator.next().value(); const DeckViewCardContainer *cont = containerIterator.next().value();
const QList<DeckViewCard *> cardList = cont->getCards(); const QList<DeckViewCard *> cardList = cont->getCards();
for (int i = 0; i < cardList.size(); ++i) for (int i = 0; i < cardList.size(); ++i)
if (cardList[i]->getOriginZone() != cont->getName()) { if (cardList[i]->getOriginZone() != cont->getName()) {

View file

@ -10,7 +10,7 @@ TabbedDeckViewContainer::TabbedDeckViewContainer(int _playerId, TabGame *parent)
connect(this, &QTabWidget::tabCloseRequested, this, &TabbedDeckViewContainer::closeTab); connect(this, &QTabWidget::tabCloseRequested, this, &TabbedDeckViewContainer::closeTab);
playerDeckView = new DeckViewContainer(playerId, parentGame); playerDeckView = new DeckViewContainer(playerId, parentGame);
int playerTabIndex = addTab(playerDeckView, "Your Deck"); const int playerTabIndex = addTab(playerDeckView, "Your Deck");
tabBar()->setTabButton(playerTabIndex, QTabBar::RightSide, nullptr); tabBar()->setTabButton(playerTabIndex, QTabBar::RightSide, nullptr);
updateTabBarVisibility(); updateTabBarVisibility();
} }

View file

@ -91,7 +91,7 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa
chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck")); chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck"));
connect(chooseTokenFromDeckRadioButton, &QRadioButton::toggled, this, &DlgCreateToken::actChooseTokenFromDeck); connect(chooseTokenFromDeckRadioButton, &QRadioButton::toggled, this, &DlgCreateToken::actChooseTokenFromDeck);
QByteArray deckHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState(); const QByteArray deckHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState();
chooseTokenView = new QTreeView; chooseTokenView = new QTreeView;
chooseTokenView->setModel(cardDatabaseDisplayModel); chooseTokenView->setModel(cardDatabaseDisplayModel);
chooseTokenView->setUniformRowHeights(true); chooseTokenView->setUniformRowHeights(true);

View file

@ -104,7 +104,7 @@ void DlgMoveTopCardsUntil::validateAndAccept()
// move currently selected text to top of history list // move currently selected text to top of history list
if (exprComboBox->currentIndex() != 0) { if (exprComboBox->currentIndex() != 0) {
QString currentExpr = exprComboBox->currentText(); const QString currentExpr = exprComboBox->currentText();
exprComboBox->removeItem(exprComboBox->currentIndex()); exprComboBox->removeItem(exprComboBox->currentIndex());
exprComboBox->insertItem(0, currentExpr); exprComboBox->insertItem(0, currentExpr);
exprComboBox->setCurrentIndex(0); exprComboBox->setCurrentIndex(0);

View file

@ -122,8 +122,8 @@ void GameScene::rearrange()
auto playersPlaying = collectActivePlayers(firstPlayerIndex); auto playersPlaying = collectActivePlayers(firstPlayerIndex);
playersPlaying = rotatePlayers(playersPlaying, firstPlayerIndex); playersPlaying = rotatePlayers(playersPlaying, firstPlayerIndex);
int columns = determineColumnCount(playersPlaying.size()); const int columns = determineColumnCount(playersPlaying.size());
QSizeF sceneSize = computeSceneSizeAndPlayerLayout(playersPlaying, columns); const QSizeF sceneSize = computeSceneSizeAndPlayerLayout(playersPlaying, columns);
phasesToolbar->setHeight(sceneSize.height()); phasesToolbar->setHeight(sceneSize.height());
setSceneRect(0, 0, sceneSize.width(), sceneSize.height()); setSceneRect(0, 0, sceneSize.width(), sceneSize.height());
@ -147,9 +147,9 @@ void GameScene::processViewSizeChange(const QSize &newSize)
viewSize = newSize; viewSize = newSize;
QList<qreal> minWidthByColumn = calculateMinWidthByColumn(); QList<qreal> minWidthByColumn = calculateMinWidthByColumn();
qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth()); const qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth());
qreal newWidth = calculateNewSceneWidth(newSize, minWidth); const qreal newWidth = calculateNewSceneWidth(newSize, minWidth);
setSceneRect(0, 0, newWidth, sceneRect().height()); setSceneRect(0, 0, newWidth, sceneRect().height());
resizeColumnsAndPlayers(minWidthByColumn, newWidth); resizeColumnsAndPlayers(minWidthByColumn, newWidth);
@ -170,7 +170,7 @@ QList<Player *> GameScene::collectActivePlayers(int &firstPlayerIndex) const
firstPlayerIndex = 0; firstPlayerIndex = 0;
bool firstPlayerFound = false; bool firstPlayerFound = false;
for (auto *pgItem : players) { for (const auto *pgItem : players) {
Player *p = pgItem->getPlayer(); Player *p = pgItem->getPlayer();
if (p && !p->getConceded()) { if (p && !p->getConceded()) {
activePlayers.append(p); activePlayers.append(p);
@ -226,7 +226,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList<Player *> &players
{ {
playersByColumn.clear(); playersByColumn.clear();
int rows = qCeil((qreal)playersPlaying.size() / columns); const int rows = qCeil((qreal)playersPlaying.size() / columns);
qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing; qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing;
QList<int> columnWidth; QList<int> columnWidth;
@ -235,7 +235,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList<Player *> &players
playersByColumn.append(QList<PlayerGraphicsItem *>()); playersByColumn.append(QList<PlayerGraphicsItem *>());
columnWidth.append(0); columnWidth.append(0);
qreal thisColumnHeight = -playerAreaSpacing; qreal thisColumnHeight = -playerAreaSpacing;
int rowsInColumn = rows - (playersPlaying.size() % columns) * col; // Adjust rows for uneven columns const int rowsInColumn = rows - (playersPlaying.size() % columns) * col; // Adjust rows for uneven columns
for (int j = 0; j < rowsInColumn; ++j) { for (int j = 0; j < rowsInColumn; ++j) {
Player *player = playersIter.next(); Player *player = playersIter.next();
@ -244,7 +244,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList<Player *> &players
else else
playersByColumn[col].append(player->getGraphicsItem()); playersByColumn[col].append(player->getGraphicsItem());
auto *pgItem = player->getGraphicsItem(); const auto *pgItem = player->getGraphicsItem();
thisColumnHeight += pgItem->boundingRect().height() + playerAreaSpacing; thisColumnHeight += pgItem->boundingRect().height() + playerAreaSpacing;
columnWidth[col] = std::max(columnWidth[col], (int)pgItem->boundingRect().width()); columnWidth[col] = std::max(columnWidth[col], (int)pgItem->boundingRect().width());
} }
@ -253,7 +253,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList<Player *> &players
sceneWidth += columnWidth[col] + playerAreaSpacing; sceneWidth += columnWidth[col] + playerAreaSpacing;
} }
qreal phasesWidth = phasesToolbar->getWidth(); const qreal phasesWidth = phasesToolbar->getWidth();
sceneWidth += phasesWidth; sceneWidth += phasesWidth;
// Position players horizontally and vertically // Position players horizontally and vertically
@ -281,7 +281,7 @@ QList<qreal> GameScene::calculateMinWidthByColumn() const
QList<qreal> minWidthByColumn; QList<qreal> minWidthByColumn;
for (const auto &col : playersByColumn) { for (const auto &col : playersByColumn) {
qreal maxWidth = 0; qreal maxWidth = 0;
for (PlayerGraphicsItem *player : col) for (const PlayerGraphicsItem *player : col)
maxWidth = std::max(maxWidth, player->getMinimumWidth()); maxWidth = std::max(maxWidth, player->getMinimumWidth());
minWidthByColumn.append(maxWidth); minWidthByColumn.append(maxWidth);
} }
@ -296,8 +296,8 @@ QList<qreal> GameScene::calculateMinWidthByColumn() const
*/ */
qreal GameScene::calculateNewSceneWidth(const QSize &newSize, qreal minWidth) const qreal GameScene::calculateNewSceneWidth(const QSize &newSize, qreal minWidth) const
{ {
qreal newRatio = (qreal)newSize.width() / newSize.height(); const qreal newRatio = (qreal)newSize.width() / newSize.height();
qreal minRatio = minWidth / sceneRect().height(); const qreal minRatio = minWidth / sceneRect().height();
if (minRatio > newRatio) { if (minRatio > newRatio) {
return minWidth; // Table dominates width return minWidth; // Table dominates width
@ -316,9 +316,9 @@ qreal GameScene::calculateNewSceneWidth(const QSize &newSize, qreal minWidth) co
*/ */
void GameScene::resizeColumnsAndPlayers(const QList<qreal> &minWidthByColumn, qreal newWidth) void GameScene::resizeColumnsAndPlayers(const QList<qreal> &minWidthByColumn, qreal newWidth)
{ {
qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth()); const qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth());
qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); const qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size();
qreal newx = phasesToolbar->getWidth(); qreal newx = phasesToolbar->getWidth();
for (int col = 0; col < playersByColumn.size(); ++col) { for (int col = 0; col < playersByColumn.size(); ++col) {
@ -334,7 +334,7 @@ void GameScene::resizeColumnsAndPlayers(const QList<qreal> &minWidthByColumn, qr
void GameScene::updateHover(const QPointF &scenePos) void GameScene::updateHover(const QPointF &scenePos)
{ {
auto itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); const auto itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform());
CardZone *zone = findTopmostZone(itemList); CardZone *zone = findTopmostZone(itemList);
CardItem *topCard = zone ? findTopmostCardInZone(itemList, zone) : nullptr; CardItem *topCard = zone ? findTopmostCardInZone(itemList, zone) : nullptr;
@ -396,8 +396,8 @@ CardItem *GameScene::findTopmostCardInZone(const QList<QGraphicsItem *> &items,
*/ */
void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numberCards, bool isReversed) void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numberCards, bool isReversed)
{ {
for (auto &view : zoneViews) { for (const auto &view : zoneViews) {
ZoneViewZone *temp = view->getZone(); const ZoneViewZone *temp = view->getZone();
if (temp->getLogic()->getName() == zoneName && temp->getLogic()->getPlayer() == player && if (temp->getLogic()->getName() == zoneName && temp->getLogic()->getPlayer() == player &&
qobject_cast<ZoneViewZoneLogic *>(temp->getLogic())->getNumberCards() == numberCards) { qobject_cast<ZoneViewZoneLogic *>(temp->getLogic())->getNumberCards() == numberCards) {
view->close(); view->close();

View file

@ -32,7 +32,7 @@ void GameState::setGameTime(int _secondsElapsed)
int seconds = _secondsElapsed; int seconds = _secondsElapsed;
int minutes = seconds / 60; int minutes = seconds / 60;
seconds -= minutes * 60; seconds -= minutes * 60;
int hours = minutes / 60; const int hours = minutes / 60;
minutes -= hours * 60; minutes -= hours * 60;
emit updateTimeElapsedLabel(QString::number(hours).rightJustified(2, '0') + ":" + emit updateTimeElapsedLabel(QString::number(hours).rightJustified(2, '0') + ":" +

View file

@ -29,7 +29,7 @@ QRectF HandCounter::boundingRect() const
void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
painter->save(); painter->save();
QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize(); const QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize();
QPixmap cachedPixmap; QPixmap cachedPixmap;
if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) { if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) {
cachedPixmap = QPixmap("theme:hand").scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); cachedPixmap = QPixmap("theme:hand").scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);

View file

@ -16,11 +16,11 @@
CardMenu::CardMenu(Player *_player, const CardItem *_card, bool _shortcutsActive) CardMenu::CardMenu(Player *_player, const CardItem *_card, bool _shortcutsActive)
: player(_player), card(_card), shortcutsActive(_shortcutsActive) : player(_player), card(_card), shortcutsActive(_shortcutsActive)
{ {
auto playerActions = player->getPlayerActions(); const auto playerActions = player->getPlayerActions();
const QList<Player *> &players = player->getGame()->getPlayerManager()->getPlayers().values(); const QList<Player *> &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto playerToAdd : players) { for (const auto playerToAdd : players) {
if (playerToAdd == player) { if (playerToAdd == player) {
continue; continue;
} }
@ -95,7 +95,7 @@ CardMenu::CardMenu(Player *_player, const CardItem *_card, bool _shortcutsActive
bool revealedCard = false; bool revealedCard = false;
bool writeableCard = player->getPlayerInfo()->getLocalOrJudge(); bool writeableCard = player->getPlayerInfo()->getLocalOrJudge();
if (auto *view = qobject_cast<ZoneViewZoneLogic *>(card->getZone())) { if (const auto *view = qobject_cast<ZoneViewZoneLogic *>(card->getZone())) {
if (view->getRevealZone()) { if (view->getRevealZone()) {
if (view->getWriteableRevealZone()) { if (view->getWriteableRevealZone()) {
writeableCard = true; writeableCard = true;
@ -155,7 +155,7 @@ void CardMenu::removePlayer(Player *playerToRemove)
void CardMenu::createTableMenu() void CardMenu::createTableMenu()
{ {
// Card is on the battlefield // Card is on the battlefield
bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; const bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player;
if (!canModifyCard) { if (!canModifyCard) {
addRelatedCardView(); addRelatedCardView();
@ -213,7 +213,7 @@ void CardMenu::createTableMenu()
void CardMenu::createStackMenu() void CardMenu::createStackMenu()
{ {
bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; const bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player;
// Card is on the stack // Card is on the stack
if (canModifyCard) { if (canModifyCard) {
@ -238,7 +238,7 @@ void CardMenu::createStackMenu()
void CardMenu::createGraveyardOrExileMenu() void CardMenu::createGraveyardOrExileMenu()
{ {
bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; const bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player;
// Card is in the graveyard or exile // Card is in the graveyard or exile
if (canModifyCard) { if (canModifyCard) {
@ -328,7 +328,7 @@ void CardMenu::addRelatedCardView()
if (!card) { if (!card) {
return; return;
} }
auto exactCard = card->getCard(); const auto exactCard = card->getCard();
if (!exactCard) { if (!exactCard) {
return; return;
} }
@ -348,12 +348,12 @@ void CardMenu::addRelatedCardView()
} }
addSeparator(); addSeparator();
auto viewRelatedCards = new QMenu(tr("View related cards")); const auto viewRelatedCards = new QMenu(tr("View related cards"));
addMenu(viewRelatedCards); addMenu(viewRelatedCards);
for (const CardRelation *relatedCard : relatedCards) { for (const CardRelation *relatedCard : relatedCards) {
QString relatedCardName = relatedCard->getName(); QString relatedCardName = relatedCard->getName();
CardRef cardRef = {relatedCardName, exactCard.getPrinting().getUuid()}; CardRef cardRef = {relatedCardName, exactCard.getPrinting().getUuid()};
QAction *viewCard = viewRelatedCards->addAction(relatedCardName); const QAction *viewCard = viewRelatedCards->addAction(relatedCardName);
Q_UNUSED(viewCard); Q_UNUSED(viewCard);
connect(viewCard, &QAction::triggered, player->getGame(), connect(viewCard, &QAction::triggered, player->getGame(),
@ -366,7 +366,7 @@ void CardMenu::addRelatedCardActions()
if (!card) { if (!card) {
return; return;
} }
auto exactCard = card->getCard(); const auto exactCard = card->getCard();
if (!exactCard) { if (!exactCard) {
return; return;
} }
@ -460,7 +460,7 @@ void CardMenu::retranslateUi()
mCardCounters->setTitle(tr("Ca&rd counters")); mCardCounters->setTitle(tr("Ca&rd counters"));
auto &cardCounterSettings = SettingsCache::instance().cardCounters(); const auto &cardCounterSettings = SettingsCache::instance().cardCounters();
for (int i = 0; i < aAddCounter.size(); ++i) { for (int i = 0; i < aAddCounter.size(); ++i) {
aAddCounter[i]->setText(tr("&Add counter (%1)").arg(cardCounterSettings.displayName(i))); aAddCounter[i]->setText(tr("&Add counter (%1)").arg(cardCounterSettings.displayName(i)));
@ -475,7 +475,7 @@ void CardMenu::retranslateUi()
void CardMenu::setShortcutsActive() void CardMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aHide->setShortcuts(shortcuts.getShortcut("Player/aHide")); aHide->setShortcuts(shortcuts.getShortcut("Player/aHide"));
aPlay->setShortcuts(shortcuts.getShortcut("Player/aPlay")); aPlay->setShortcuts(shortcuts.getShortcut("Player/aPlay"));

View file

@ -19,7 +19,7 @@ void CustomZoneMenu::retranslateUi()
if (player->getPlayerInfo()->getLocalOrJudge()) { if (player->getPlayerInfo()->getLocalOrJudge()) {
for (auto aViewZone : actions()) { for (const auto aViewZone : actions()) {
aViewZone->setText(tr("View custom zone '%1'").arg(aViewZone->data().toString())); aViewZone->setText(tr("View custom zone '%1'").arg(aViewZone->data().toString()));
} }
} }

View file

@ -36,7 +36,7 @@ GraveyardMenu::GraveyardMenu(Player *_player, QWidget *parent) : TearOffMenu(par
void GraveyardMenu::createMoveActions() void GraveyardMenu::createMoveActions()
{ {
auto grave = player->getGraveZone(); const auto grave = player->getGraveZone();
if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) {
aMoveGraveToTopLibrary = new QAction(this); aMoveGraveToTopLibrary = new QAction(this);
@ -60,7 +60,7 @@ void GraveyardMenu::createMoveActions()
void GraveyardMenu::createViewActions() void GraveyardMenu::createViewActions()
{ {
PlayerActions *playerActions = player->getPlayerActions(); const PlayerActions *playerActions = player->getPlayerActions();
aViewGraveyard = new QAction(this); aViewGraveyard = new QAction(this);
connect(aViewGraveyard, &QAction::triggered, playerActions, &PlayerActions::actViewGraveyard); connect(aViewGraveyard, &QAction::triggered, playerActions, &PlayerActions::actViewGraveyard);
@ -77,7 +77,7 @@ void GraveyardMenu::populateRevealRandomMenuWithActivePlayers()
mRevealRandomGraveyardCard->addSeparator(); mRevealRandomGraveyardCard->addSeparator();
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (const auto *other : players) {
if (other == player) if (other == player)
continue; continue;
QAction *a = mRevealRandomGraveyardCard->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealRandomGraveyardCard->addAction(other->getPlayerInfo()->getName());
@ -88,7 +88,7 @@ void GraveyardMenu::populateRevealRandomMenuWithActivePlayers()
void GraveyardMenu::onRevealRandomTriggered() void GraveyardMenu::onRevealRandomTriggered()
{ {
if (auto *a = qobject_cast<QAction *>(sender())) { if (const auto *a = qobject_cast<QAction *>(sender())) {
player->getPlayerActions()->actRevealRandomGraveyardCard(a->data().toInt()); player->getPlayerActions()->actRevealRandomGraveyardCard(a->data().toInt());
} }
} }
@ -112,7 +112,7 @@ void GraveyardMenu::retranslateUi()
void GraveyardMenu::setShortcutsActive() void GraveyardMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aViewGraveyard->setShortcuts(shortcuts.getShortcut("Player/aViewGraveyard")); aViewGraveyard->setShortcuts(shortcuts.getShortcut("Player/aViewGraveyard"));
} }

View file

@ -74,7 +74,7 @@ HandMenu::HandMenu(Player *_player, PlayerActions *actions, QWidget *parent) : T
aMoveHandToRfg = new QAction(this); aMoveHandToRfg = new QAction(this);
aMoveHandToRfg->setData(QList<QVariant>() << "rfg" << 0); aMoveHandToRfg->setData(QList<QVariant>() << "rfg" << 0);
auto hand = player->getHandZone(); const auto hand = player->getHandZone();
connect(aMoveHandToTopLibrary, &QAction::triggered, hand, &HandZoneLogic::moveAllToZone); connect(aMoveHandToTopLibrary, &QAction::triggered, hand, &HandZoneLogic::moveAllToZone);
connect(aMoveHandToBottomLibrary, &QAction::triggered, hand, &HandZoneLogic::moveAllToZone); connect(aMoveHandToBottomLibrary, &QAction::triggered, hand, &HandZoneLogic::moveAllToZone);
@ -122,7 +122,7 @@ void HandMenu::retranslateUi()
void HandMenu::setShortcutsActive() void HandMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aViewHand->setShortcuts(shortcuts.getShortcut("Player/aViewHand")); aViewHand->setShortcuts(shortcuts.getShortcut("Player/aViewHand"));
aSortHandByName->setShortcuts(shortcuts.getShortcut("Player/aSortHandByName")); aSortHandByName->setShortcuts(shortcuts.getShortcut("Player/aSortHandByName"));
aSortHandByType->setShortcuts(shortcuts.getShortcut("Player/aSortHandByType")); aSortHandByType->setShortcuts(shortcuts.getShortcut("Player/aSortHandByType"));
@ -152,7 +152,7 @@ void HandMenu::populateRevealHandMenuWithActivePlayers()
mRevealHand->addSeparator(); mRevealHand->addSeparator();
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (const auto *other : players) {
if (other == player) if (other == player)
continue; continue;
QAction *a = mRevealHand->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealHand->addAction(other->getPlayerInfo()->getName());
@ -170,7 +170,7 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers()
mRevealRandomHandCard->addSeparator(); mRevealRandomHandCard->addSeparator();
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (const auto *other : players) {
if (other == player) if (other == player)
continue; continue;
QAction *a = mRevealRandomHandCard->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealRandomHandCard->addAction(other->getPlayerInfo()->getName());
@ -181,7 +181,7 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers()
void HandMenu::onRevealHandTriggered() void HandMenu::onRevealHandTriggered()
{ {
auto *action = qobject_cast<QAction *>(sender()); const auto *action = qobject_cast<QAction *>(sender());
if (!action) if (!action)
return; return;
@ -191,7 +191,7 @@ void HandMenu::onRevealHandTriggered()
void HandMenu::onRevealRandomHandCardTriggered() void HandMenu::onRevealRandomHandCardTriggered()
{ {
auto *action = qobject_cast<QAction *>(sender()); const auto *action = qobject_cast<QAction *>(sender());
if (!action) if (!action)
return; return;

View file

@ -90,7 +90,7 @@ void LibraryMenu::resetTopCardMenuActions()
void LibraryMenu::createDrawActions() void LibraryMenu::createDrawActions()
{ {
PlayerActions *playerActions = player->getPlayerActions(); const PlayerActions *playerActions = player->getPlayerActions();
if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) {
aDrawCard = new QAction(this); aDrawCard = new QAction(this);
@ -108,7 +108,7 @@ void LibraryMenu::createDrawActions()
void LibraryMenu::createShuffleActions() void LibraryMenu::createShuffleActions()
{ {
PlayerActions *playerActions = player->getPlayerActions(); const PlayerActions *playerActions = player->getPlayerActions();
if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) {
aShuffle = new QAction(this); aShuffle = new QAction(this);
@ -122,7 +122,7 @@ void LibraryMenu::createShuffleActions()
void LibraryMenu::createMoveActions() void LibraryMenu::createMoveActions()
{ {
PlayerActions *playerActions = player->getPlayerActions(); const PlayerActions *playerActions = player->getPlayerActions();
if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) {
aMoveTopToPlay = new QAction(this); aMoveTopToPlay = new QAction(this);
@ -165,7 +165,7 @@ void LibraryMenu::createMoveActions()
void LibraryMenu::createViewActions() void LibraryMenu::createViewActions()
{ {
PlayerActions *playerActions = player->getPlayerActions(); const PlayerActions *playerActions = player->getPlayerActions();
if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) {
aViewLibrary = new QAction(this); aViewLibrary = new QAction(this);
@ -244,7 +244,7 @@ void LibraryMenu::populateRevealLibraryMenuWithActivePlayers()
mRevealLibrary->addSeparator(); mRevealLibrary->addSeparator();
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (const auto *other : players) {
if (other == player) if (other == player)
continue; continue;
QAction *a = mRevealLibrary->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealLibrary->addAction(other->getPlayerInfo()->getName());
@ -258,7 +258,7 @@ void LibraryMenu::populateLendLibraryMenuWithActivePlayers()
mLendLibrary->clear(); mLendLibrary->clear();
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (const auto *other : players) {
if (other == player) if (other == player)
continue; continue;
QAction *a = mLendLibrary->addAction(other->getPlayerInfo()->getName()); QAction *a = mLendLibrary->addAction(other->getPlayerInfo()->getName());
@ -278,7 +278,7 @@ void LibraryMenu::populateRevealTopCardMenuWithActivePlayers()
mRevealTopCard->addSeparator(); mRevealTopCard->addSeparator();
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (const auto *other : players) {
if (other == player) if (other == player)
continue; continue;
QAction *a = mRevealTopCard->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealTopCard->addAction(other->getPlayerInfo()->getName());
@ -289,26 +289,26 @@ void LibraryMenu::populateRevealTopCardMenuWithActivePlayers()
void LibraryMenu::onRevealLibraryTriggered() void LibraryMenu::onRevealLibraryTriggered()
{ {
if (auto *a = qobject_cast<QAction *>(sender())) { if (const auto *a = qobject_cast<QAction *>(sender())) {
player->getPlayerActions()->actRevealLibrary(a->data().toInt()); player->getPlayerActions()->actRevealLibrary(a->data().toInt());
} }
} }
void LibraryMenu::onLendLibraryTriggered() void LibraryMenu::onLendLibraryTriggered()
{ {
if (auto *a = qobject_cast<QAction *>(sender())) { if (const auto *a = qobject_cast<QAction *>(sender())) {
player->getPlayerActions()->actLendLibrary(a->data().toInt()); player->getPlayerActions()->actLendLibrary(a->data().toInt());
} }
} }
void LibraryMenu::onRevealTopCardTriggered() void LibraryMenu::onRevealTopCardTriggered()
{ {
if (auto *a = qobject_cast<QAction *>(sender())) { if (const auto *a = qobject_cast<QAction *>(sender())) {
int deckSize = player->getDeckZone()->getCards().size(); const int deckSize = player->getDeckZone()->getCards().size();
bool ok; bool ok;
int number = QInputDialog::getInt(player->getGame()->getTab(), tr("Reveal top cards of library"), const int number = QInputDialog::getInt(player->getGame()->getTab(), tr("Reveal top cards of library"),
tr("Number of cards: (max. %1)").arg(deckSize), defaultNumberTopCards, 1, tr("Number of cards: (max. %1)").arg(deckSize), defaultNumberTopCards,
deckSize, 1, &ok); 1, deckSize, 1, &ok);
if (ok) { if (ok) {
player->getPlayerActions()->actRevealTopCards(a->data().toInt(), number); player->getPlayerActions()->actRevealTopCards(a->data().toInt(), number);
defaultNumberTopCards = number; defaultNumberTopCards = number;
@ -318,7 +318,7 @@ void LibraryMenu::onRevealTopCardTriggered()
void LibraryMenu::setShortcutsActive() void LibraryMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aViewLibrary->setShortcuts(shortcuts.getShortcut("Player/aViewLibrary")); aViewLibrary->setShortcuts(shortcuts.getShortcut("Player/aViewLibrary"));
aViewTopCards->setShortcuts(shortcuts.getShortcut("Player/aViewTopCards")); aViewTopCards->setShortcuts(shortcuts.getShortcut("Player/aViewTopCards"));

View file

@ -43,7 +43,7 @@ MoveMenu::MoveMenu(Player *player) : QMenu(tr("Move to"))
void MoveMenu::setShortcutsActive() void MoveMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aMoveToTopLibrary->setShortcuts(shortcuts.getShortcut("Player/aMoveToTopLibrary")); aMoveToTopLibrary->setShortcuts(shortcuts.getShortcut("Player/aMoveToTopLibrary"));
aMoveToBottomLibrary->setShortcuts(shortcuts.getShortcut("Player/aMoveToBottomLibrary")); aMoveToBottomLibrary->setShortcuts(shortcuts.getShortcut("Player/aMoveToBottomLibrary"));

View file

@ -63,7 +63,7 @@ void PtMenu::retranslateUi()
void PtMenu::setShortcutsActive() void PtMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aIncP->setShortcuts(shortcuts.getShortcut("Player/aIncP")); aIncP->setShortcuts(shortcuts.getShortcut("Player/aIncP"));
aDecP->setShortcuts(shortcuts.getShortcut("Player/aDecP")); aDecP->setShortcuts(shortcuts.getShortcut("Player/aDecP"));

View file

@ -27,7 +27,7 @@ RfgMenu::RfgMenu(Player *_player, QWidget *parent) : TearOffMenu(parent), player
void RfgMenu::createMoveActions() void RfgMenu::createMoveActions()
{ {
if (player->getPlayerInfo()->getLocalOrJudge()) { if (player->getPlayerInfo()->getLocalOrJudge()) {
auto rfg = player->getRfgZone(); const auto rfg = player->getRfgZone();
aMoveRfgToTopLibrary = new QAction(this); aMoveRfgToTopLibrary = new QAction(this);
aMoveRfgToTopLibrary->setData(QList<QVariant>() << "deck" << 0); aMoveRfgToTopLibrary->setData(QList<QVariant>() << "deck" << 0);
@ -47,7 +47,7 @@ void RfgMenu::createMoveActions()
void RfgMenu::createViewActions() void RfgMenu::createViewActions()
{ {
PlayerActions *playerActions = player->getPlayerActions(); const PlayerActions *playerActions = player->getPlayerActions();
aViewRfg = new QAction(this); aViewRfg = new QAction(this);
connect(aViewRfg, &QAction::triggered, playerActions, &PlayerActions::actViewRfg); connect(aViewRfg, &QAction::triggered, playerActions, &PlayerActions::actViewRfg);

View file

@ -14,7 +14,7 @@ void SayMenu::initSayMenu()
{ {
clear(); clear();
int count = SettingsCache::instance().messages().getCount(); const int count = SettingsCache::instance().messages().getCount();
setEnabled(count > 0); setEnabled(count > 0);
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {

View file

@ -22,7 +22,7 @@ void SideboardMenu::retranslateUi()
void SideboardMenu::setShortcutsActive() void SideboardMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aViewSideboard->setShortcuts(shortcuts.getShortcut("Player/aViewSideboard")); aViewSideboard->setShortcuts(shortcuts.getShortcut("Player/aViewSideboard"));
} }

View file

@ -6,7 +6,7 @@
UtilityMenu::UtilityMenu(Player *_player, QMenu *playerMenu) : QMenu(playerMenu), player(_player) UtilityMenu::UtilityMenu(Player *_player, QMenu *playerMenu) : QMenu(playerMenu), player(_player)
{ {
PlayerActions *playerActions = player->getPlayerActions(); const PlayerActions *playerActions = player->getPlayerActions();
if (player->getPlayerInfo()->getLocalOrJudge()) { if (player->getPlayerInfo()->getLocalOrJudge()) {
aUntapAll = new QAction(this); aUntapAll = new QAction(this);
@ -62,7 +62,7 @@ void UtilityMenu::populatePredefinedTokensMenu()
return; return;
} }
InnerDecklistNode *tokenZone = const InnerDecklistNode *tokenZone =
dynamic_cast<InnerDecklistNode *>(_deck->getDeckList()->getRoot()->findChild(DECK_ZONE_TOKENS)); dynamic_cast<InnerDecklistNode *>(_deck->getDeckList()->getRoot()->findChild(DECK_ZONE_TOKENS));
if (tokenZone) { if (tokenZone) {
@ -95,7 +95,7 @@ void UtilityMenu::retranslateUi()
void UtilityMenu::setShortcutsActive() void UtilityMenu::setShortcutsActive()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
if (player->getPlayerInfo()->getLocalOrJudge()) { if (player->getPlayerInfo()->getLocalOrJudge()) {
aIncrementAllCardCounters->setShortcuts(shortcuts.getShortcut("Player/aIncrementAllCardCounters")); aIncrementAllCardCounters->setShortcuts(shortcuts.getShortcut("Player/aIncrementAllCardCounters"));

View file

@ -18,7 +18,7 @@ void PlayerArea::updateBg()
void PlayerArea::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void PlayerArea::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Player, playerZoneId); const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Player, playerZoneId);
painter->fillRect(boundingRect(), brush); painter->fillRect(boundingRect(), brush);
} }

View file

@ -14,7 +14,7 @@ PlayerGraphicsItem::PlayerGraphicsItem(Player *_player) : player(_player)
playerArea = new PlayerArea(this); playerArea = new PlayerArea(this);
playerTarget = new PlayerTarget(player, playerArea); playerTarget = new PlayerTarget(player, playerArea);
qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0; const qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0;
playerTarget->setPos(QPointF(avatarMargin, avatarMargin)); playerTarget->setPos(QPointF(avatarMargin, avatarMargin));
initializeZones(); initializeZones();
@ -50,18 +50,18 @@ void PlayerGraphicsItem::onPlayerActiveChanged(bool _active)
void PlayerGraphicsItem::initializeZones() void PlayerGraphicsItem::initializeZones()
{ {
deckZoneGraphicsItem = new PileZone(player->getDeckZone(), this); deckZoneGraphicsItem = new PileZone(player->getDeckZone(), this);
auto base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0, const auto base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0,
10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0); 10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0);
deckZoneGraphicsItem->setPos(base); deckZoneGraphicsItem->setPos(base);
qreal h = deckZoneGraphicsItem->boundingRect().width() + 5; const qreal h = deckZoneGraphicsItem->boundingRect().width() + 5;
sideboardGraphicsItem = new PileZone(player->getSideboardZone(), this); sideboardGraphicsItem = new PileZone(player->getSideboardZone(), this);
player->getSideboardZone()->setGraphicsVisibility(false); player->getSideboardZone()->setGraphicsVisibility(false);
auto *handCounter = new HandCounter(playerArea); auto *handCounter = new HandCounter(playerArea);
handCounter->setPos(base + QPointF(0, h + 10)); handCounter->setPos(base + QPointF(0, h + 10));
qreal h2 = handCounter->boundingRect().height(); const qreal h2 = handCounter->boundingRect().height();
graveyardZoneGraphicsItem = new PileZone(player->getGraveZone(), this); graveyardZoneGraphicsItem = new PileZone(player->getGraveZone(), this);
graveyardZoneGraphicsItem->setPos(base + QPointF(0, h + h2 + 10)); graveyardZoneGraphicsItem->setPos(base + QPointF(0, h + h2 + 10));
@ -127,7 +127,7 @@ void PlayerGraphicsItem::setMirrored(bool _mirrored)
void PlayerGraphicsItem::rearrangeCounters() void PlayerGraphicsItem::rearrangeCounters()
{ {
qreal marginTop = 80; const qreal marginTop = 80;
const qreal padding = 5; const qreal padding = 5;
qreal ySize = boundingRect().y() + marginTop; qreal ySize = boundingRect().y() + marginTop;
@ -198,9 +198,9 @@ void PlayerGraphicsItem::rearrangeZones()
void PlayerGraphicsItem::updateBoundingRect() void PlayerGraphicsItem::updateBoundingRect()
{ {
prepareGeometryChange(); prepareGeometryChange();
qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stackZoneGraphicsItem->boundingRect().width(); const qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stackZoneGraphicsItem->boundingRect().width();
if (SettingsCache::instance().getHorizontalHand()) { if (SettingsCache::instance().getHorizontalHand()) {
qreal handHeight = const qreal handHeight =
player->getPlayerInfo()->getHandVisible() ? handZoneGraphicsItem->boundingRect().height() : 0; player->getPlayerInfo()->getHandVisible() ? handZoneGraphicsItem->boundingRect().height() : 0;
bRect = QRectF(0, 0, width + tableZoneGraphicsItem->boundingRect().width(), bRect = QRectF(0, 0, width + tableZoneGraphicsItem->boundingRect().width(),
tableZoneGraphicsItem->boundingRect().height() + handHeight); tableZoneGraphicsItem->boundingRect().height() + handHeight);

View file

@ -14,7 +14,7 @@ PlayerManager::PlayerManager(AbstractGame *_game,
bool PlayerManager::isMainPlayerConceded() const bool PlayerManager::isMainPlayerConceded() const
{ {
Player *player = players.value(localPlayerId, nullptr); const Player *player = players.value(localPlayerId, nullptr);
return player && player->getConceded(); return player && player->getConceded();
} }

View file

@ -95,7 +95,7 @@ public:
void removeSpectator(int spectatorId) void removeSpectator(int spectatorId)
{ {
ServerInfo_User spectatorInfo = spectators.value(spectatorId); const ServerInfo_User spectatorInfo = spectators.value(spectatorId);
spectators.remove(spectatorId); spectators.remove(spectatorId);
emit spectatorRemoved(spectatorId, spectatorInfo); emit spectatorRemoved(spectatorId, spectatorInfo);
} }

View file

@ -37,8 +37,8 @@ void PlayerCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*
painter->drawPath(path); painter->drawPath(path);
QRectF translatedRect = path.controlPointRect(); const QRectF translatedRect = path.controlPointRect();
QSize translatedSize = translatedRect.size().toSize(); const QSize translatedSize = translatedRect.size().toSize();
QFont font("Serif"); QFont font("Serif");
font.setWeight(QFont::Bold); font.setWeight(QFont::Bold);
font.setPixelSize(qMax(qRound(translatedSize.height() / 1.3), 9)); font.setPixelSize(qMax(qRound(translatedSize.height() / 1.3), 9));

View file

@ -26,7 +26,7 @@ void HandZone::handleDropEvent(const QList<CardDragItem *> &dragItems,
CardZoneLogic *startZone, CardZoneLogic *startZone,
const QPoint &dropPoint) const QPoint &dropPoint)
{ {
QPoint point = dropPoint + scenePos().toPoint(); const QPoint point = dropPoint + scenePos().toPoint();
int x = -1; int x = -1;
if (SettingsCache::instance().getHorizontalHand()) { if (SettingsCache::instance().getHorizontalHand()) {
for (x = 0; x < getLogic()->getCards().size(); x++) for (x = 0; x < getLogic()->getCards().size(); x++)
@ -62,7 +62,7 @@ QRectF HandZone::boundingRect() const
void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Hand, getLogic()->getPlayer()->getZoneId()); const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Hand, getLogic()->getPlayer()->getZoneId());
painter->fillRect(boundingRect(), brush); painter->fillRect(boundingRect(), brush);
} }
@ -71,10 +71,10 @@ void HandZone::reorganizeCards()
if (!getLogic()->getCards().isEmpty()) { if (!getLogic()->getCards().isEmpty()) {
const int cardCount = getLogic()->getCards().size(); const int cardCount = getLogic()->getCards().size();
if (SettingsCache::instance().getHorizontalHand()) { if (SettingsCache::instance().getHorizontalHand()) {
bool leftJustified = SettingsCache::instance().getLeftJustified(); const bool leftJustified = SettingsCache::instance().getLeftJustified();
qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); const qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width();
const int xPadding = leftJustified ? cardWidth * 1.4 : 5; const int xPadding = leftJustified ? cardWidth * 1.4 : 5;
qreal totalWidth = const qreal totalWidth =
leftJustified ? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding; leftJustified ? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding;
for (int i = 0; i < cardCount; i++) { for (int i = 0; i < cardCount; i++) {
@ -84,7 +84,7 @@ void HandZone::reorganizeCards()
if (cardWidth * cardCount > totalWidth) if (cardWidth * cardCount > totalWidth)
c->setPos(xPadding + ((qreal)i) * (totalWidth - cardWidth) / (cardCount - 1), 5); c->setPos(xPadding + ((qreal)i) * (totalWidth - cardWidth) / (cardCount - 1), 5);
else { else {
qreal xPosition = const qreal xPosition =
leftJustified ? xPadding + ((qreal)i) * cardWidth leftJustified ? xPadding + ((qreal)i) * cardWidth
: xPadding + ((qreal)i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2; : xPadding + ((qreal)i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2;
c->setPos(xPosition, 5); c->setPos(xPosition, 5);
@ -92,17 +92,17 @@ void HandZone::reorganizeCards()
c->setRealZValue(i); c->setRealZValue(i);
} }
} else { } else {
qreal totalWidth = boundingRect().width(); const qreal totalWidth = boundingRect().width();
qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); const qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width();
qreal xspace = 5; const qreal xspace = 5;
qreal x1 = xspace; const qreal x1 = xspace;
qreal x2 = totalWidth - xspace - cardWidth; const qreal x2 = totalWidth - xspace - cardWidth;
for (int i = 0; i < cardCount; i++) { for (int i = 0; i < cardCount; i++) {
CardItem *card = getLogic()->getCards().at(i); CardItem *card = getLogic()->getCards().at(i);
qreal x = (i % 2) ? x2 : x1; const qreal x = (i % 2) ? x2 : x1;
qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(), const qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(),
getLogic()->getCards().at(0)->boundingRect().height()); getLogic()->getCards().at(0)->boundingRect().height());
card->setPos(x, y); card->setPos(x, y);
card->setRealZValue(i); card->setRealZValue(i);
} }

View file

@ -44,8 +44,8 @@ bool ZoneViewZoneLogic::prepareAddCard(int x)
} }
} else { } else {
// map x (which is in origZone indexes) to this viewZone's cardList index // map x (which is in origZone indexes) to this viewZone's cardList index
int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId(); const int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId();
int insertionIndex = x - firstId; const int insertionIndex = x - firstId;
if (insertionIndex >= 0) { if (insertionIndex >= 0) {
// card was put into a portion of the deck that's in the view // card was put into a portion of the deck that's in the view
doInsert = true; doInsert = true;
@ -79,8 +79,8 @@ void ZoneViewZoneLogic::addCardImpl(CardItem *card, int x, int /*y*/)
cards.insert(x, card); cards.insert(x, card);
} else { } else {
// map x (which is in origZone indexes) to this viewZone's cardList index // map x (which is in origZone indexes) to this viewZone's cardList index
int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId(); const int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId();
int insertionIndex = x - firstId; const int insertionIndex = x - firstId;
// qMin to prevent out-of-bounds error when bottoming a card that is already in the view // qMin to prevent out-of-bounds error when bottoming a card that is already in the view
cards.insert(qMin(insertionIndex, cards.size()), card); cards.insert(qMin(insertionIndex, cards.size()), card);
} }
@ -99,7 +99,7 @@ void ZoneViewZoneLogic::updateCardIds(CardAction action)
return; return;
} }
int cardCount = cards.size(); const int cardCount = cards.size();
auto startId = 0; auto startId = 0;

View file

@ -38,7 +38,7 @@ QRectF PileZone::boundingRect() const
QPainterPath PileZone::shape() const QPainterPath PileZone::shape() const
{ {
QPainterPath shape; QPainterPath shape;
qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; const qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0;
shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius); shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius);
return shape; return shape;
} }
@ -100,8 +100,8 @@ void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
if (getLogic()->getCards().isEmpty()) if (getLogic()->getCards().isEmpty())
return; return;
bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier); const bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier);
bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); const bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier);
CardItem *card = bottomCard ? getLogic()->getCards().last() : getLogic()->getCards().first(); CardItem *card = bottomCard ? getLogic()->getCards().last() : getLogic()->getCards().first();
const int cardid = const int cardid =
getLogic()->contentsKnown() ? card->getId() : (bottomCard ? getLogic()->getCards().size() - 1 : 0); getLogic()->contentsKnown() ? card->getId() : (bottomCard ? getLogic()->getCards().size() - 1 : 0);

View file

@ -9,8 +9,8 @@
qreal divideCardSpaceInZone(qreal index, int cardCount, qreal totalHeight, qreal cardHeight, bool reverse) qreal divideCardSpaceInZone(qreal index, int cardCount, qreal totalHeight, qreal cardHeight, bool reverse)
{ {
qreal cardMinOverlap = cardHeight * SettingsCache::instance().getStackCardOverlapPercent() / 100; const qreal cardMinOverlap = cardHeight * SettingsCache::instance().getStackCardOverlapPercent() / 100;
qreal desiredHeight = cardHeight * cardCount - cardMinOverlap * (cardCount - 1); const qreal desiredHeight = cardHeight * cardCount - cardMinOverlap * (cardCount - 1);
qreal y; qreal y;
if (desiredHeight > totalHeight) { if (desiredHeight > totalHeight) {
if (reverse) { if (reverse) {
@ -19,7 +19,7 @@ qreal divideCardSpaceInZone(qreal index, int cardCount, qreal totalHeight, qreal
y = index * (totalHeight - cardHeight) / (cardCount - 1); y = index * (totalHeight - cardHeight) / (cardCount - 1);
} }
} else { } else {
qreal start = (totalHeight - desiredHeight) / 2; const qreal start = (totalHeight - desiredHeight) / 2;
if (reverse) { if (reverse) {
if (index <= start) { if (index <= start) {
return 0; return 0;
@ -42,7 +42,7 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
QPointF pos = event->pos(); QPointF pos = event->pos();
if (pos.x() < 0) if (pos.x() < 0)
pos.setX(0); pos.setX(0);
QRectF br = boundingRect(); const QRectF br = boundingRect();
if (pos.x() > br.width()) if (pos.x() > br.width())
pos.setX(br.width()); pos.setX(br.width());
if (pos.y() < 0) if (pos.y() < 0)
@ -50,13 +50,13 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
if (pos.y() > br.height()) if (pos.y() > br.height())
pos.setY(br.height()); pos.setY(br.height());
QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); const QRectF selectionRect = QRectF(selectionOrigin, pos).normalized();
for (auto card : getLogic()->getCards()) { for (auto card : getLogic()->getCards()) {
if (card->getAttachedTo() && card->getAttachedTo()->getZone() != getLogic()) { if (card->getAttachedTo() && card->getAttachedTo()->getZone() != getLogic()) {
continue; continue;
} }
bool inRect = selectionRect.intersects(card->mapRectToParent(card->boundingRect())); const bool inRect = selectionRect.intersects(card->mapRectToParent(card->boundingRect()));
if (inRect && !cardsInSelectionRect.contains(card)) { if (inRect && !cardsInSelectionRect.contains(card)) {
// selection has just expanded to cover the card // selection has just expanded to cover the card
cardsInSelectionRect.insert(card); cardsInSelectionRect.insert(card);

View file

@ -32,7 +32,7 @@ QRectF StackZone::boundingRect() const
void StackZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void StackZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Stack, getLogic()->getPlayer()->getZoneId()); const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Stack, getLogic()->getPlayer()->getZoneId());
painter->fillRect(boundingRect(), brush); painter->fillRect(boundingRect(), brush);
} }
@ -76,7 +76,7 @@ void StackZone::handleDropEvent(const QList<CardDragItem *> &dragItems,
cmd.set_x(index); cmd.set_x(index);
cmd.set_y(0); cmd.set_y(0);
for (CardDragItem *item : dragItems) { for (const CardDragItem *item : dragItems) {
if (item) { if (item) {
cmd.mutable_cards_to_move()->add_card()->set_card_id(item->getId()); cmd.mutable_cards_to_move()->add_card()->set_card_id(item->getId());
} }
@ -89,17 +89,17 @@ void StackZone::reorganizeCards()
{ {
if (!getLogic()->getCards().isEmpty()) { if (!getLogic()->getCards().isEmpty()) {
const auto cardCount = static_cast<int>(getLogic()->getCards().size()); const auto cardCount = static_cast<int>(getLogic()->getCards().size());
qreal totalWidth = boundingRect().width(); const qreal totalWidth = boundingRect().width();
qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); const qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width();
qreal xspace = 5; const qreal xspace = 5;
qreal x1 = xspace; const qreal x1 = xspace;
qreal x2 = totalWidth - xspace - cardWidth; const qreal x2 = totalWidth - xspace - cardWidth;
for (int i = 0; i < cardCount; i++) { for (int i = 0; i < cardCount; i++) {
CardItem *card = getLogic()->getCards().at(i); CardItem *card = getLogic()->getCards().at(i);
qreal x = (i % 2) ? x2 : x1; const qreal x = (i % 2) ? x2 : x1;
qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(), const qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(),
getLogic()->getCards().at(0)->boundingRect().height()); getLogic()->getCards().at(0)->boundingRect().height());
card->setPos(x, y); card->setPos(x, y);
card->setRealZValue(i); card->setRealZValue(i);
} }

View file

@ -58,7 +58,7 @@ bool TableZone::isInverted() const
void TableZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void TableZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Table, getLogic()->getPlayer()->getZoneId()); const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Table, getLogic()->getPlayer()->getZoneId());
painter->fillRect(boundingRect(), brush); painter->fillRect(boundingRect(), brush);
if (active) { if (active) {
@ -157,11 +157,11 @@ void TableZone::reorganizeCards()
continue; continue;
QPointF mapPoint = mapFromGrid(gridPoint); QPointF mapPoint = mapFromGrid(gridPoint);
qreal x = mapPoint.x(); const qreal x = mapPoint.x();
qreal y = mapPoint.y(); const qreal y = mapPoint.y();
int numberAttachedCards = getLogic()->getCards()[i]->getAttachedCards().size(); const int numberAttachedCards = getLogic()->getCards()[i]->getAttachedCards().size();
qreal actualX = x + numberAttachedCards * STACKED_CARD_OFFSET_X; const qreal actualX = x + numberAttachedCards * STACKED_CARD_OFFSET_X;
qreal actualY = y; qreal actualY = y;
if (numberAttachedCards) if (numberAttachedCards)
actualY += 15; actualY += 15;
@ -174,8 +174,8 @@ void TableZone::reorganizeCards()
while (attachedCardIterator.hasNext()) { while (attachedCardIterator.hasNext()) {
++j; ++j;
CardItem *attachedCard = attachedCardIterator.next(); CardItem *attachedCard = attachedCardIterator.next();
qreal childX = actualX - j * STACKED_CARD_OFFSET_X; const qreal childX = actualX - j * STACKED_CARD_OFFSET_X;
qreal childY = y + 5; const qreal childY = y + 5;
attachedCard->setPos(childX, childY); attachedCard->setPos(childX, childY);
attachedCard->setRealZValue((childY + CARD_HEIGHT) * 100000 + (childX + 1) * 100); attachedCard->setRealZValue((childY + CARD_HEIGHT) * 100000 + (childX + 1) * 100);
} }
@ -191,7 +191,7 @@ void TableZone::toggleTapped()
QList<QGraphicsItem *> selectedItems; QList<QGraphicsItem *> selectedItems;
auto isCardOnTable = [](const QGraphicsItem *item) { auto isCardOnTable = [](const QGraphicsItem *item) {
if (auto card = qgraphicsitem_cast<const CardItem *>(item)) { if (const auto card = qgraphicsitem_cast<const CardItem *>(item)) {
return card->getZone()->getName() == "table"; return card->getZone()->getName() == "table";
} }
return false; return false;
@ -199,12 +199,12 @@ void TableZone::toggleTapped()
std::copy_if(selectedItemsRaw.begin(), selectedItemsRaw.end(), std::back_inserter(selectedItems), isCardOnTable); std::copy_if(selectedItemsRaw.begin(), selectedItemsRaw.end(), std::back_inserter(selectedItems), isCardOnTable);
bool tapAll = std::any_of(selectedItems.begin(), selectedItems.end(), [](const QGraphicsItem *item) { const bool tapAll = std::any_of(selectedItems.begin(), selectedItems.end(), [](const QGraphicsItem *item) {
return !qgraphicsitem_cast<const CardItem *>(item)->getTapped(); return !qgraphicsitem_cast<const CardItem *>(item)->getTapped();
}); });
QList<const ::google::protobuf::Message *> cmdList; QList<const ::google::protobuf::Message *> cmdList;
for (const auto &selectedItem : selectedItems) { for (const auto &selectedItem : selectedItems) {
CardItem *temp = qgraphicsitem_cast<CardItem *>(selectedItem); const CardItem *temp = qgraphicsitem_cast<CardItem *>(selectedItem);
if (temp->getTapped() != tapAll) { if (temp->getTapped() != tapAll) {
Command_SetCardAttr *cmd = new Command_SetCardAttr; Command_SetCardAttr *cmd = new Command_SetCardAttr;
cmd->set_zone(getLogic()->getName().toStdString()); cmd->set_zone(getLogic()->getName().toStdString());
@ -251,7 +251,7 @@ CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const
CardItem *TableZone::getCardFromCoords(const QPointF &point) const CardItem *TableZone::getCardFromCoords(const QPointF &point) const
{ {
QPoint gridPoint = mapToGrid(point); const QPoint gridPoint = mapToGrid(point);
return getCardFromGrid(gridPoint); return getCardFromGrid(gridPoint);
} }
@ -318,7 +318,7 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const
// used for the x-coordinate. // used for the x-coordinate.
// Offset point by the margin amount to reference point within grid area. // Offset point by the margin amount to reference point within grid area.
int y = mapPoint.y() - MARGIN_TOP; const int y = mapPoint.y() - MARGIN_TOP;
// Below calculation effectively rounds to the nearest grid point. // Below calculation effectively rounds to the nearest grid point.
const int gridPointHeight = CARD_HEIGHT + PADDING_Y; const int gridPointHeight = CARD_HEIGHT + PADDING_Y;
@ -333,7 +333,7 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const
// widths of each card stack along the row. // widths of each card stack along the row.
// Offset point by the margin amount to reference point within grid area. // Offset point by the margin amount to reference point within grid area.
int x = mapPoint.x() - MARGIN_LEFT + PADDING_X / 2; const int x = mapPoint.x() - MARGIN_LEFT + PADDING_X / 2;
// Maximum value is a card width from the right margin, referenced to the // Maximum value is a card width from the right margin, referenced to the
// grid area. // grid area.
@ -348,13 +348,13 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const
xNextStack += cardStackWidth.value(key, CARD_WIDTH) + PADDING_X; xNextStack += cardStackWidth.value(key, CARD_WIDTH) + PADDING_X;
nextStackCol++; nextStackCol++;
} }
int stackCol = qMax(nextStackCol - 1, 0); const int stackCol = qMax(nextStackCol - 1, 0);
// Have the stack column, need to refine to the grid column. Take the // Have the stack column, need to refine to the grid column. Take the
// difference between the point and the stack point and divide by stacked // difference between the point and the stack point and divide by stacked
// card offsets. // card offsets.
int xDiff = x - xStack; const int xDiff = x - xStack;
int gridPointX = stackCol * 3 + qMin(xDiff / STACKED_CARD_OFFSET_X, 2); const int gridPointX = stackCol * 3 + qMin(xDiff / STACKED_CARD_OFFSET_X, 2);
return QPoint(gridPointX, gridPointY); return QPoint(gridPointX, gridPointY);
} }

View file

@ -68,10 +68,10 @@ void ZoneViewZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o
void ZoneViewZone::initializeCards(const QList<const ServerInfo_Card *> &cardList) void ZoneViewZone::initializeCards(const QList<const ServerInfo_Card *> &cardList)
{ {
int numberCards = qobject_cast<ZoneViewZoneLogic *>(getLogic())->getNumberCards(); const int numberCards = qobject_cast<ZoneViewZoneLogic *>(getLogic())->getNumberCards();
if (!cardList.isEmpty()) { if (!cardList.isEmpty()) {
for (int i = 0; i < cardList.size(); ++i) { for (int i = 0; i < cardList.size(); ++i) {
auto card = cardList[i]; const auto card = cardList[i];
CardRef cardRef = {QString::fromStdString(card->name()), QString::fromStdString(card->provider_id())}; CardRef cardRef = {QString::fromStdString(card->name()), QString::fromStdString(card->provider_id())};
getLogic()->addCard(new CardItem(getLogic()->getPlayer(), this, cardRef, card->id()), false, i); getLogic()->addCard(new CardItem(getLogic()->getPlayer(), this, cardRef, card->id()), false, i);
} }
@ -88,9 +88,9 @@ void ZoneViewZone::initializeCards(const QList<const ServerInfo_Card *> &cardLis
getLogic()->getPlayer()->getPlayerActions()->sendGameCommand(pend); getLogic()->getPlayer()->getPlayerActions()->sendGameCommand(pend);
} else { } else {
const CardList &c = qobject_cast<ZoneViewZoneLogic *>(getLogic())->getOriginalZone()->getCards(); const CardList &c = qobject_cast<ZoneViewZoneLogic *>(getLogic())->getOriginalZone()->getCards();
int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size()); const int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size());
for (int i = 0; i < number; i++) { for (int i = 0; i < number; i++) {
CardItem *card = c.at(i); const CardItem *card = c.at(i);
getLogic()->addCard(new CardItem(getLogic()->getPlayer(), this, card->getCardRef(), card->getId()), false, getLogic()->addCard(new CardItem(getLogic()->getPlayer(), this, card->getCardRef(), card->getId()), false,
i); i);
} }
@ -104,9 +104,10 @@ void ZoneViewZone::zoneDumpReceived(const Response &r)
const int respCardListSize = resp.zone_info().card_list_size(); const int respCardListSize = resp.zone_info().card_list_size();
for (int i = 0; i < respCardListSize; ++i) { for (int i = 0; i < respCardListSize; ++i) {
const ServerInfo_Card &cardInfo = resp.zone_info().card_list(i); const ServerInfo_Card &cardInfo = resp.zone_info().card_list(i);
auto cardName = QString::fromStdString(cardInfo.name()); const auto cardName = QString::fromStdString(cardInfo.name());
auto cardProviderId = QString::fromStdString(cardInfo.provider_id()); const auto cardProviderId = QString::fromStdString(cardInfo.provider_id());
auto card = new CardItem(getLogic()->getPlayer(), this, {cardName, cardProviderId}, cardInfo.id(), getLogic()); const auto card =
new CardItem(getLogic()->getPlayer(), this, {cardName, cardProviderId}, cardInfo.id(), getLogic());
getLogic()->rawInsertCard(card, i); getLogic()->rawInsertCard(card, i);
} }
@ -120,7 +121,7 @@ void ZoneViewZone::reorganizeCards()
{ {
// filter cards // filter cards
CardList cardsToDisplay = CardList(getLogic()->getCards().getContentsKnown()); CardList cardsToDisplay = CardList(getLogic()->getCards().getContentsKnown());
for (auto card : getLogic()->getCards()) { for (const auto card : getLogic()->getCards()) {
if (filterString.check(card->getCard().getCardPtr())) { if (filterString.check(card->getCard().getCardPtr())) {
card->show(); card->show();
cardsToDisplay.append(card); cardsToDisplay.append(card);
@ -158,10 +159,10 @@ void ZoneViewZone::reorganizeCards()
} }
// determine bounding rect // determine bounding rect
qreal aleft = 0; const qreal aleft = 0;
qreal atop = 0; const qreal atop = 0;
qreal awidth = gridSize.cols * CARD_WIDTH + (CARD_WIDTH / 2) + HORIZONTAL_PADDING; const qreal awidth = gridSize.cols * CARD_WIDTH + (CARD_WIDTH / 2) + HORIZONTAL_PADDING;
qreal aheight = (gridSize.rows * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3; const qreal aheight = (gridSize.rows * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3;
optimumRect = QRectF(aleft, atop, awidth, aheight); optimumRect = QRectF(aleft, atop, awidth, aheight);
updateGeometry(); updateGeometry();
@ -179,7 +180,7 @@ void ZoneViewZone::reorganizeCards()
*/ */
ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, CardList::SortOption pileOption) ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, CardList::SortOption pileOption)
{ {
int cardCount = cards.size(); const int cardCount = cards.size();
if (pileOption != CardList::NoSort) { if (pileOption != CardList::NoSort) {
int row = 0; int row = 0;
@ -204,8 +205,8 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca
} }
lastColumnProp = columnProp; lastColumnProp = columnProp;
qreal x = col * CARD_WIDTH; const qreal x = col * CARD_WIDTH;
qreal y = row * CARD_HEIGHT / 3; const qreal y = row * CARD_HEIGHT / 3;
c->setPos(HORIZONTAL_PADDING + x, VERTICAL_PADDING + y); c->setPos(HORIZONTAL_PADDING + x, VERTICAL_PADDING + y);
c->setRealZValue(i); c->setRealZValue(i);
longestRow = qMax(row, longestRow); longestRow = qMax(row, longestRow);
@ -232,8 +233,8 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca
for (int i = 0; i < cardCount; i++) { for (int i = 0; i < cardCount; i++) {
CardItem *c = cards.at(i); CardItem *c = cards.at(i);
qreal x = (i / rows) * CARD_WIDTH; const qreal x = (i / rows) * CARD_WIDTH;
qreal y = (i % rows) * CARD_HEIGHT / 3; const qreal y = (i % rows) * CARD_HEIGHT / 3;
c->setPos(HORIZONTAL_PADDING + x, VERTICAL_PADDING + y); c->setPos(HORIZONTAL_PADDING + x, VERTICAL_PADDING + y);
c->setRealZValue(i); c->setRealZValue(i);
} }

View file

@ -52,7 +52,7 @@ ZoneViewWidget::ZoneViewWidget(Player *_player,
searchEdit.setPlaceholderText(tr("Search by card name (or search expressions)")); searchEdit.setPlaceholderText(tr("Search by card name (or search expressions)"));
searchEdit.setClearButtonEnabled(true); searchEdit.setClearButtonEnabled(true);
searchEdit.addAction(loadColorAdjustedPixmap("theme:icons/search"), QLineEdit::LeadingPosition); searchEdit.addAction(loadColorAdjustedPixmap("theme:icons/search"), QLineEdit::LeadingPosition);
auto help = searchEdit.addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition); const auto help = searchEdit.addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition);
connect(help, &QAction::triggered, this, [this] { createSearchSyntaxHelpWindow(&searchEdit); }); connect(help, &QAction::triggered, this, [this] { createSearchSyntaxHelpWindow(&searchEdit); });
@ -175,7 +175,7 @@ ZoneViewWidget::ZoneViewWidget(Player *_player,
void ZoneViewWidget::processGroupBy(int index) void ZoneViewWidget::processGroupBy(int index)
{ {
auto option = static_cast<CardList::SortOption>(groupBySelector.itemData(index).toInt()); const auto option = static_cast<CardList::SortOption>(groupBySelector.itemData(index).toInt());
SettingsCache::instance().setZoneViewGroupByIndex(index); SettingsCache::instance().setZoneViewGroupByIndex(index);
zone->setGroupBy(option); zone->setGroupBy(option);
@ -191,7 +191,7 @@ void ZoneViewWidget::processGroupBy(int index)
void ZoneViewWidget::processSortBy(int index) void ZoneViewWidget::processSortBy(int index)
{ {
auto option = static_cast<CardList::SortOption>(sortBySelector.itemData(index).toInt()); const auto option = static_cast<CardList::SortOption>(sortBySelector.itemData(index).toInt());
// set to SortByName instead if it has the same value as groupBy // set to SortByName instead if it has the same value as groupBy
if (option != CardList::NoSort && if (option != CardList::NoSort &&
@ -215,7 +215,7 @@ void ZoneViewWidget::retranslateUi()
setWindowTitle(zone->getLogic()->getTranslatedName(false, CaseNominative)); setWindowTitle(zone->getLogic()->getTranslatedName(false, CaseNominative));
{ // We can't change the strings after they're put into the QComboBox, so this is our workaround { // We can't change the strings after they're put into the QComboBox, so this is our workaround
int oldIndex = groupBySelector.currentIndex(); const int oldIndex = groupBySelector.currentIndex();
groupBySelector.clear(); groupBySelector.clear();
groupBySelector.addItem(tr("Ungrouped"), CardList::NoSort); groupBySelector.addItem(tr("Ungrouped"), CardList::NoSort);
groupBySelector.addItem(tr("Group by Type"), CardList::SortByMainType); groupBySelector.addItem(tr("Group by Type"), CardList::SortByMainType);
@ -225,7 +225,7 @@ void ZoneViewWidget::retranslateUi()
} }
{ {
int oldIndex = sortBySelector.currentIndex(); const int oldIndex = sortBySelector.currentIndex();
sortBySelector.clear(); sortBySelector.clear();
sortBySelector.addItem(tr("Unsorted"), CardList::NoSort); sortBySelector.addItem(tr("Unsorted"), CardList::NoSort);
sortBySelector.addItem(tr("Sort by Name"), CardList::SortByName); sortBySelector.addItem(tr("Sort by Name"), CardList::SortByName);
@ -246,14 +246,14 @@ void ZoneViewWidget::moveEvent(QGraphicsSceneMoveEvent * /* event */)
if (!scene()) if (!scene())
return; return;
int titleBarHeight = 24; const int titleBarHeight = 24;
QPointF scenePos = pos(); QPointF scenePos = pos();
if (scenePos.x() < 0) { if (scenePos.x() < 0) {
scenePos.setX(0); scenePos.setX(0);
} else { } else {
qreal maxw = scene()->sceneRect().width() - 100; const qreal maxw = scene()->sceneRect().width() - 100;
if (scenePos.x() > maxw) if (scenePos.x() > maxw)
scenePos.setX(maxw); scenePos.setX(maxw);
} }
@ -261,7 +261,7 @@ void ZoneViewWidget::moveEvent(QGraphicsSceneMoveEvent * /* event */)
if (scenePos.y() < titleBarHeight) { if (scenePos.y() < titleBarHeight) {
scenePos.setY(titleBarHeight); scenePos.setY(titleBarHeight);
} else { } else {
qreal maxh = scene()->sceneRect().height() - titleBarHeight; const qreal maxh = scene()->sceneRect().height() - titleBarHeight;
if (scenePos.y() > maxh) if (scenePos.y() > maxh)
scenePos.setY(maxh); scenePos.setY(maxh);
} }
@ -278,8 +278,8 @@ void ZoneViewWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
void ZoneViewWidget::resizeScrollbar(const qreal newZoneHeight) void ZoneViewWidget::resizeScrollbar(const qreal newZoneHeight)
{ {
qreal totalZoneHeight = zone->getOptimumRect().height(); const qreal totalZoneHeight = zone->getOptimumRect().height();
qreal newMax = qMax(totalZoneHeight - newZoneHeight, 0.0); const qreal newMax = qMax(totalZoneHeight - newZoneHeight, 0.0);
scrollBar->setMaximum(newMax); scrollBar->setMaximum(newMax);
} }
@ -320,18 +320,18 @@ static qreal determineNewZoneHeight(qreal oldZoneHeight)
void ZoneViewWidget::resizeToZoneContents(bool forceInitialHeight) void ZoneViewWidget::resizeToZoneContents(bool forceInitialHeight)
{ {
QRectF zoneRect = zone->getOptimumRect(); const QRectF zoneRect = zone->getOptimumRect();
qreal totalZoneHeight = zoneRect.height(); const qreal totalZoneHeight = zoneRect.height();
qreal width = qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), const qreal width = qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(),
zoneRect.width() + scrollBar->width() + 10); zoneRect.width() + scrollBar->width() + 10);
QSizeF maxSize(width, zoneRect.height() + extraHeight + 10); const QSizeF maxSize(width, zoneRect.height() + extraHeight + 10);
qreal currentZoneHeight = rect().height() - extraHeight - 10; const qreal currentZoneHeight = rect().height() - extraHeight - 10;
qreal newZoneHeight = forceInitialHeight ? calcMaxInitialHeight() : determineNewZoneHeight(currentZoneHeight); const qreal newZoneHeight = forceInitialHeight ? calcMaxInitialHeight() : determineNewZoneHeight(currentZoneHeight);
QSizeF initialSize(width, newZoneHeight + extraHeight + 10); const QSizeF initialSize(width, newZoneHeight + extraHeight + 10);
setMaximumSize(maxSize); setMaximumSize(maxSize);
resize(initialSize); resize(initialSize);
@ -378,13 +378,13 @@ void ZoneViewWidget::initStyleOption(QStyleOption *option) const
*/ */
void ZoneViewWidget::expandWindow() void ZoneViewWidget::expandWindow()
{ {
qreal maxInitialHeight = calcMaxInitialHeight(); const qreal maxInitialHeight = calcMaxInitialHeight();
qreal maxExpandedHeight = rowsToHeight(SettingsCache::instance().getCardViewExpandedRowsMax()); const qreal maxExpandedHeight = rowsToHeight(SettingsCache::instance().getCardViewExpandedRowsMax());
qreal height = rect().height() - extraHeight - 10; const qreal height = rect().height() - extraHeight - 10;
qreal maxHeight = maximumHeight() - extraHeight - 10; const qreal maxHeight = maximumHeight() - extraHeight - 10;
// reset window to initial max height if... // reset window to initial max height if...
bool doResetSize = const bool doResetSize =
// current height is less than that // current height is less than that
(height < maxInitialHeight) || (height < maxInitialHeight) ||
// current height is at expanded max height // current height is at expanded max height

View file

@ -23,7 +23,7 @@ void AbstractGraphicsItem::paintNumberEllipse(int number,
#else #else
fm.width(numStr); fm.width(numStr);
#endif #endif
double h = fm.height() * 1.3; const double h = fm.height() * 1.3;
if (w < h) if (w < h)
w = h; w = h;
@ -34,9 +34,9 @@ void AbstractGraphicsItem::paintNumberEllipse(int number,
if (position == -1) if (position == -1)
textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h);
else { else {
qreal xOffset = 10; const qreal xOffset = 10;
qreal yOffset = 20; const qreal yOffset = 20;
qreal spacing = 2; const qreal spacing = 2;
if (position < 2) if (position < 2)
textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0)
: (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)),
@ -59,7 +59,7 @@ void AbstractGraphicsItem::paintNumberEllipse(int number,
int resetPainterTransform(QPainter *painter) int resetPainterTransform(QPainter *painter)
{ {
painter->resetTransform(); painter->resetTransform();
auto tx = painter->deviceTransform().inverted(); const auto tx = painter->deviceTransform().inverted();
painter->setTransform(tx); painter->setTransform(tx);
return tx.isScaling() ? 1.0 / tx.m11() : 1; return tx.isScaling() ? 1.0 / tx.m11() : 1;
} }

View file

@ -32,7 +32,7 @@ CardPictureLoader::CardPictureLoader() : QObject(nullptr)
connect(worker, &CardPictureLoaderWorker::imageLoaded, this, &CardPictureLoader::imageLoaded); connect(worker, &CardPictureLoaderWorker::imageLoaded, this, &CardPictureLoader::imageLoaded);
statusBar = new CardPictureLoaderStatusBar(nullptr); statusBar = new CardPictureLoaderStatusBar(nullptr);
QMainWindow *mainWindow = qobject_cast<QMainWindow *>(QApplication::activeWindow()); const QMainWindow *mainWindow = qobject_cast<QMainWindow *>(QApplication::activeWindow());
if (mainWindow) { if (mainWindow) {
mainWindow->statusBar()->addPermanentWidget(statusBar); mainWindow->statusBar()->addPermanentWidget(statusBar);
} }
@ -50,7 +50,8 @@ CardPictureLoader::~CardPictureLoader()
void CardPictureLoader::getCardBackPixmap(QPixmap &pixmap, QSize size) void CardPictureLoader::getCardBackPixmap(QPixmap &pixmap, QSize size)
{ {
QString backCacheKey = "_trice_card_back_" + QString::number(size.width()) + "x" + QString::number(size.height()); const QString backCacheKey =
"_trice_card_back_" + QString::number(size.width()) + "x" + QString::number(size.height());
if (!QPixmapCache::find(backCacheKey, &pixmap)) { if (!QPixmapCache::find(backCacheKey, &pixmap)) {
qCDebug(CardPictureLoaderLog) << "PictureLoader: cache miss for" << backCacheKey; qCDebug(CardPictureLoaderLog) << "PictureLoader: cache miss for" << backCacheKey;
QPixmap tmpPixmap("theme:cardback"); QPixmap tmpPixmap("theme:cardback");
@ -70,7 +71,7 @@ void CardPictureLoader::getCardBackPixmap(QPixmap &pixmap, QSize size)
void CardPictureLoader::getCardBackLoadingInProgressPixmap(QPixmap &pixmap, QSize size) void CardPictureLoader::getCardBackLoadingInProgressPixmap(QPixmap &pixmap, QSize size)
{ {
QString backCacheKey = const QString backCacheKey =
"_trice_card_back_inprogress_" + QString::number(size.width()) + "x" + QString::number(size.height()); "_trice_card_back_inprogress_" + QString::number(size.width()) + "x" + QString::number(size.height());
if (!QPixmapCache::find(backCacheKey, &pixmap)) { if (!QPixmapCache::find(backCacheKey, &pixmap)) {
qCDebug(CardPictureLoaderCardBackCacheFailLog) << "PictureLoader: cache miss for" << backCacheKey; qCDebug(CardPictureLoaderCardBackCacheFailLog) << "PictureLoader: cache miss for" << backCacheKey;
@ -92,7 +93,7 @@ void CardPictureLoader::getCardBackLoadingInProgressPixmap(QPixmap &pixmap, QSiz
void CardPictureLoader::getCardBackLoadingFailedPixmap(QPixmap &pixmap, QSize size) void CardPictureLoader::getCardBackLoadingFailedPixmap(QPixmap &pixmap, QSize size)
{ {
QString backCacheKey = const QString backCacheKey =
"_trice_card_back_failed_" + QString::number(size.width()) + "x" + QString::number(size.height()); "_trice_card_back_failed_" + QString::number(size.width()) + "x" + QString::number(size.height());
if (!QPixmapCache::find(backCacheKey, &pixmap)) { if (!QPixmapCache::find(backCacheKey, &pixmap)) {
qCDebug(CardPictureLoaderCardBackCacheFailLog) << "PictureLoader: cache miss for" << backCacheKey; qCDebug(CardPictureLoaderCardBackCacheFailLog) << "PictureLoader: cache miss for" << backCacheKey;
@ -118,8 +119,9 @@ void CardPictureLoader::getPixmap(QPixmap &pixmap, const ExactCard &card, QSize
return; return;
} }
QString key = card.getPixmapCacheKey(); const QString key = card.getPixmapCacheKey();
QString sizeKey = key + QLatin1Char('_') + QString::number(size.width()) + "x" + QString::number(size.height()); const QString sizeKey =
key + QLatin1Char('_') + QString::number(size.width()) + "x" + QString::number(size.height());
if (QPixmapCache::find(sizeKey, &pixmap)) { if (QPixmapCache::find(sizeKey, &pixmap)) {
return; // Use cached version return; // Use cached version
@ -133,8 +135,8 @@ void CardPictureLoader::getPixmap(QPixmap &pixmap, const ExactCard &card, QSize
return; return;
} }
QScreen *screen = qApp->primaryScreen(); const QScreen *screen = qApp->primaryScreen();
qreal dpr = screen ? screen->devicePixelRatio() : 1.0; const qreal dpr = screen ? screen->devicePixelRatio() : 1.0;
qCDebug(CardPictureLoaderLog) << "Scaling cached image for" << card.getName(); qCDebug(CardPictureLoaderLog) << "Scaling cached image for" << card.getName();
pixmap = bigPixmap.scaled(size * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); pixmap = bigPixmap.scaled(size * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation);
@ -156,7 +158,7 @@ void CardPictureLoader::imageLoaded(const ExactCard &card, const QImage &image)
} else { } else {
if (card.getInfo().getUiAttributes().upsideDownArt) { if (card.getInfo().getUiAttributes().upsideDownArt) {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 9, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(6, 9, 0))
QImage mirrorImage = image.flipped(Qt::Horizontal | Qt::Vertical); const QImage mirrorImage = image.flipped(Qt::Horizontal | Qt::Vertical);
#else #else
QImage mirrorImage = image.mirrored(true, true); QImage mirrorImage = image.mirrored(true, true);
#endif #endif
@ -188,7 +190,7 @@ void CardPictureLoader::clearNetworkCache()
void CardPictureLoader::cacheCardPixmaps(const QList<ExactCard> &cards) void CardPictureLoader::cacheCardPixmaps(const QList<ExactCard> &cards)
{ {
QPixmap tmp; QPixmap tmp;
int max = qMin(cards.size(), CACHED_CARD_PER_DECK_MAX); const int max = qMin(cards.size(), CACHED_CARD_PER_DECK_MAX);
for (int i = 0; i < max; ++i) { for (int i = 0; i < max; ++i) {
const ExactCard &card = cards.at(i); const ExactCard &card = cards.at(i);
if (!card) { if (!card) {
@ -216,7 +218,7 @@ void CardPictureLoader::picsPathChanged()
bool CardPictureLoader::hasCustomArt() bool CardPictureLoader::hasCustomArt()
{ {
auto picsPath = SettingsCache::instance().getPicsPath(); const auto picsPath = SettingsCache::instance().getPicsPath();
QDirIterator it(picsPath, QDir::Dirs | QDir::NoDotAndDotDot); QDirIterator it(picsPath, QDir::Dirs | QDir::NoDotAndDotDot);
// Check if there is at least one non-directory file in the pics path, other // Check if there is at least one non-directory file in the pics path, other

View file

@ -49,10 +49,10 @@ void CardPictureLoaderLocal::refreshIndex()
QImage CardPictureLoaderLocal::tryLoad(const ExactCard &toLoad) const QImage CardPictureLoaderLocal::tryLoad(const ExactCard &toLoad) const
{ {
PrintingInfo setInstance = toLoad.getPrinting(); const PrintingInfo setInstance = toLoad.getPrinting();
QString cardName = toLoad.getName(); const QString cardName = toLoad.getName();
QString correctedCardName = toLoad.getInfo().getCorrectedName(); const QString correctedCardName = toLoad.getInfo().getCorrectedName();
QString setName, collectorNumber, providerId; QString setName, collectorNumber, providerId;

View file

@ -64,7 +64,7 @@ public:
int queryElapsedSeconds() int queryElapsedSeconds()
{ {
if (!getFinished()) { if (!getFinished()) {
int elapsedSeconds = QDateTime::fromString(startTime->text()).secsTo(QDateTime::currentDateTime()); const int elapsedSeconds = QDateTime::fromString(startTime->text()).secsTo(QDateTime::currentDateTime());
elapsedTime->setText(QString::number(elapsedSeconds)); elapsedTime->setText(QString::number(elapsedSeconds));
update(); update();
repaint(); repaint();

View file

@ -64,7 +64,7 @@ CardPictureLoaderWorker::~CardPictureLoaderWorker()
void CardPictureLoaderWorker::queueRequest(const QUrl &url, CardPictureLoaderWorkerWork *worker) void CardPictureLoaderWorker::queueRequest(const QUrl &url, CardPictureLoaderWorkerWork *worker)
{ {
QUrl cachedRedirect = getCachedRedirect(url); const QUrl cachedRedirect = getCachedRedirect(url);
if (!cachedRedirect.isEmpty()) { if (!cachedRedirect.isEmpty()) {
queueRequest(cachedRedirect, worker); queueRequest(cachedRedirect, worker);
} else if (cache->metaData(url).isValid()) { } else if (cache->metaData(url).isValid()) {
@ -80,7 +80,7 @@ void CardPictureLoaderWorker::queueRequest(const QUrl &url, CardPictureLoaderWor
QNetworkReply *CardPictureLoaderWorker::makeRequest(const QUrl &url, CardPictureLoaderWorkerWork *worker) QNetworkReply *CardPictureLoaderWorker::makeRequest(const QUrl &url, CardPictureLoaderWorkerWork *worker)
{ {
// Check for cached redirects // Check for cached redirects
QUrl cachedRedirect = getCachedRedirect(url); const QUrl cachedRedirect = getCachedRedirect(url);
if (!cachedRedirect.isEmpty()) { if (!cachedRedirect.isEmpty()) {
emit imageRequestSucceeded(url); emit imageRequestSucceeded(url);
return makeRequest(cachedRedirect, worker); return makeRequest(cachedRedirect, worker);
@ -115,7 +115,7 @@ void CardPictureLoaderWorker::processQueuedRequests()
bool CardPictureLoaderWorker::processSingleRequest() bool CardPictureLoaderWorker::processSingleRequest()
{ {
if (!requestLoadQueue.isEmpty()) { if (!requestLoadQueue.isEmpty()) {
auto request = requestLoadQueue.takeFirst(); const auto request = requestLoadQueue.takeFirst();
makeRequest(request.first, request.second); makeRequest(request.first, request.second);
return true; return true;
} }
@ -139,7 +139,7 @@ void CardPictureLoaderWorker::handleImageLoadEnqueued(const ExactCard &card)
currentlyLoading.insert(card.getPixmapCacheKey()); currentlyLoading.insert(card.getPixmapCacheKey());
// try to load image from local first // try to load image from local first
QImage image = localLoader->tryLoad(card); const QImage image = localLoader->tryLoad(card);
if (!image.isNull()) { if (!image.isNull()) {
handleImageLoaded(card, image); handleImageLoaded(card, image);
} else { } else {
@ -181,7 +181,7 @@ void CardPictureLoaderWorker::loadRedirectCache()
QSettings settings(cacheFilePath, QSettings::IniFormat); QSettings settings(cacheFilePath, QSettings::IniFormat);
redirectCache.clear(); redirectCache.clear();
int size = settings.beginReadArray(REDIRECT_HEADER_NAME); const int size = settings.beginReadArray(REDIRECT_HEADER_NAME);
for (int i = 0; i < size; ++i) { for (int i = 0; i < size; ++i) {
settings.setArrayIndex(i); settings.setArrayIndex(i);
QUrl originalUrl = settings.value(REDIRECT_ORIGINAL_URL).toUrl(); QUrl originalUrl = settings.value(REDIRECT_ORIGINAL_URL).toUrl();
@ -212,7 +212,7 @@ void CardPictureLoaderWorker::saveRedirectCache() const
void CardPictureLoaderWorker::cleanStaleEntries() void CardPictureLoaderWorker::cleanStaleEntries()
{ {
QDateTime now = QDateTime::currentDateTimeUtc(); const QDateTime now = QDateTime::currentDateTimeUtc();
auto it = redirectCache.begin(); auto it = redirectCache.begin();
while (it != redirectCache.end()) { while (it != redirectCache.end()) {

View file

@ -37,12 +37,12 @@ CardPictureLoaderWorkerWork::CardPictureLoaderWorkerWork(const CardPictureLoader
void CardPictureLoaderWorkerWork::startNextPicDownload() void CardPictureLoaderWorkerWork::startNextPicDownload()
{ {
QString picUrl = cardToDownload.getCurrentUrl(); const QString picUrl = cardToDownload.getCurrentUrl();
if (picUrl.isEmpty()) { if (picUrl.isEmpty()) {
picDownloadFailed(); picDownloadFailed();
} else { } else {
QUrl url(picUrl); const QUrl url(picUrl);
qCDebug(CardPictureLoaderWorkerWorkLog).nospace() qCDebug(CardPictureLoaderWorkerWorkLog).nospace()
<< "PictureLoader: [card: " << cardToDownload.getCard().getInfo().getCorrectedName() << "PictureLoader: [card: " << cardToDownload.getCard().getInfo().getCorrectedName()
<< " set: " << cardToDownload.getSetName() << "]: Trying to fetch picture from url " << " set: " << cardToDownload.getSetName() << "]: Trying to fetch picture from url "
@ -71,9 +71,9 @@ void CardPictureLoaderWorkerWork::picDownloadFailed()
void CardPictureLoaderWorkerWork::handleNetworkReply(QNetworkReply *reply) void CardPictureLoaderWorkerWork::handleNetworkReply(QNetworkReply *reply)
{ {
QVariant redirectTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); const QVariant redirectTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (redirectTarget.isValid()) { if (redirectTarget.isValid()) {
QUrl url = reply->request().url(); const QUrl url = reply->request().url();
QUrl redirectUrl = redirectTarget.toUrl(); QUrl redirectUrl = redirectTarget.toUrl();
if (redirectUrl.isRelative()) { if (redirectUrl.isRelative()) {
redirectUrl = url.resolved(redirectUrl); redirectUrl = url.resolved(redirectUrl);
@ -93,7 +93,7 @@ void CardPictureLoaderWorkerWork::handleNetworkReply(QNetworkReply *reply)
static bool imageIsBlackListed(const QByteArray &picData) static bool imageIsBlackListed(const QByteArray &picData)
{ {
QString md5sum = QCryptographicHash::hash(picData, QCryptographicHash::Md5).toHex(); const QString md5sum = QCryptographicHash::hash(picData, QCryptographicHash::Md5).toHex();
return MD5_BLACKLIST.contains(md5sum); return MD5_BLACKLIST.contains(md5sum);
} }
@ -102,7 +102,7 @@ void CardPictureLoaderWorkerWork::handleFailedReply(const QNetworkReply *reply)
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 429) { if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 429) {
qCWarning(CardPictureLoaderWorkerWorkLog) << "Too many requests."; qCWarning(CardPictureLoaderWorkerWorkLog) << "Too many requests.";
} else { } else {
bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); const bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
if (isFromCache) { if (isFromCache) {
qCDebug(CardPictureLoaderWorkerWorkLog).nospace() qCDebug(CardPictureLoaderWorkerWorkLog).nospace()
@ -126,13 +126,13 @@ void CardPictureLoaderWorkerWork::handleFailedReply(const QNetworkReply *reply)
void CardPictureLoaderWorkerWork::handleSuccessfulReply(QNetworkReply *reply) void CardPictureLoaderWorkerWork::handleSuccessfulReply(QNetworkReply *reply)
{ {
bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); const bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool();
// List of status codes from https://doc.qt.io/qt-6/qnetworkreply.html#redirected // List of status codes from https://doc.qt.io/qt-6/qnetworkreply.html#redirected
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 305 || statusCode == 307 || if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 305 || statusCode == 307 ||
statusCode == 308) { statusCode == 308) {
QUrl redirectUrl = reply->header(QNetworkRequest::LocationHeader).toUrl(); const QUrl redirectUrl = reply->header(QNetworkRequest::LocationHeader).toUrl();
qCDebug(CardPictureLoaderWorkerWorkLog).nospace() qCDebug(CardPictureLoaderWorkerWorkLog).nospace()
<< "PictureLoader: [card: " << cardToDownload.getCard().getName() << " set: " << cardToDownload.getSetName() << "PictureLoader: [card: " << cardToDownload.getCard().getName() << " set: " << cardToDownload.getSetName()
<< "]: following " << (isFromCache ? "cached redirect" : "redirect") << " to " << "]: following " << (isFromCache ? "cached redirect" : "redirect") << " to "
@ -153,7 +153,7 @@ void CardPictureLoaderWorkerWork::handleSuccessfulReply(QNetworkReply *reply)
return; return;
} }
QImage image = tryLoadImageFromReply(reply); const QImage image = tryLoadImageFromReply(reply);
if (image.isNull()) { if (image.isNull()) {
qCDebug(CardPictureLoaderWorkerWorkLog).nospace() qCDebug(CardPictureLoaderWorkerWorkLog).nospace()
@ -175,7 +175,7 @@ void CardPictureLoaderWorkerWork::handleSuccessfulReply(QNetworkReply *reply)
QImage CardPictureLoaderWorkerWork::tryLoadImageFromReply(QNetworkReply *reply) QImage CardPictureLoaderWorkerWork::tryLoadImageFromReply(QNetworkReply *reply)
{ {
static constexpr int riffHeaderSize = 12; // RIFF_HEADER_SIZE from webp/format_constants.h static constexpr int riffHeaderSize = 12; // RIFF_HEADER_SIZE from webp/format_constants.h
auto replyHeader = reply->peek(riffHeaderSize); const auto replyHeader = reply->peek(riffHeaderSize);
if (replyHeader.startsWith("RIFF") && replyHeader.endsWith("WEBP")) { if (replyHeader.startsWith("RIFF") && replyHeader.endsWith("WEBP")) {
auto imgBuf = QBuffer(this); auto imgBuf = QBuffer(this);

View file

@ -36,9 +36,9 @@ QList<CardSetPtr> CardPictureToLoad::extractSetsSorted(const ExactCard &card)
// If the user hasn't disabled arts other than their personal preference... // If the user hasn't disabled arts other than their personal preference...
if (!SettingsCache::instance().getOverrideAllCardArtWithPersonalPreference()) { if (!SettingsCache::instance().getOverrideAllCardArtWithPersonalPreference()) {
// If the pixmapCacheKey corresponds to a specific set, we have to try to load it first. // If the pixmapCacheKey corresponds to a specific set, we have to try to load it first.
qsizetype setIndex = sortedSets.indexOf(card.getPrinting().getSet()); const qsizetype setIndex = sortedSets.indexOf(card.getPrinting().getSet());
if (setIndex > 0) { // we don't need to move the set if it's already first if (setIndex > 0) { // we don't need to move the set if it's already first
CardSetPtr setForCardProviderID = sortedSets.takeAt(setIndex); const CardSetPtr setForCardProviderID = sortedSets.takeAt(setIndex);
sortedSets.prepend(setForCardProviderID); sortedSets.prepend(setForCardProviderID);
} }
} }
@ -83,7 +83,7 @@ void CardPictureToLoad::populateSetUrls()
currentSetUrls.clear(); currentSetUrls.clear();
if (card && currentSet) { if (card && currentSet) {
QString setCustomURL = findPrintingForSet(card, currentSet->getShortName()).getProperty("picurl"); const QString setCustomURL = findPrintingForSet(card, currentSet->getShortName()).getProperty("picurl");
if (!setCustomURL.isEmpty()) { if (!setCustomURL.isEmpty()) {
currentSetUrls.append(setCustomURL); currentSetUrls.append(setCustomURL);
@ -191,7 +191,7 @@ static int parse(const QString &urlTemplate,
} }
if (!fillWith.isEmpty()) { if (!fillWith.isEmpty()) {
int fillLength = fillWith.length(); const int fillLength = fillWith.length();
if (fillLength < propLength) { if (fillLength < propLength) {
qCDebug(CardPictureToLoadLog).nospace() qCDebug(CardPictureToLoadLog).nospace()
<< "PictureLoader: [card: " << cardName << " set: " << setName << "]: Requested " << propType << "PictureLoader: [card: " << cardName << " set: " << setName << "]: Requested " << propType
@ -217,13 +217,13 @@ QString CardPictureToLoad::transformUrl(const QString &urlTemplate) const
for downloading images. If information is requested by the template that is for downloading images. If information is requested by the template that is
not populated for this specific card/set combination, an empty string is returned.*/ not populated for this specific card/set combination, an empty string is returned.*/
CardSetPtr set = getCurrentSet(); const CardSetPtr set = getCurrentSet();
QMap<QString, QString> transformMap = QMap<QString, QString>(); QMap<QString, QString> transformMap = QMap<QString, QString>();
QString setName = getSetName(); const QString setName = getSetName();
// name // name
QString cardName = card.getName(); const QString cardName = card.getName();
transformMap["!name!"] = cardName; transformMap["!name!"] = cardName;
transformMap["!name_lower!"] = card.getName().toLower(); transformMap["!name_lower!"] = card.getName().toLower();
transformMap["!corrected_name!"] = card.getInfo().getCorrectedName(); transformMap["!corrected_name!"] = card.getInfo().getCorrectedName();

View file

@ -99,7 +99,7 @@ bool DeckLoader::loadFromFileAsync(const QString &fileName, FileFormat fmt, bool
emit loadFinished(result); emit loadFinished(result);
}); });
QFuture<bool> future = QtConcurrent::run([=, this]() { const QFuture<bool> future = QtConcurrent::run([=, this]() {
QFile file(fileName); QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return false; return false;
@ -129,7 +129,7 @@ bool DeckLoader::loadFromFileAsync(const QString &fileName, FileFormat fmt, bool
bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId)
{ {
bool result = deckList->loadFromString_Native(nativeString); const bool result = deckList->loadFromString_Native(nativeString);
if (result) { if (result) {
lastLoadInfo = { lastLoadInfo = {
.remoteDeckId = remoteDeckId, .remoteDeckId = remoteDeckId,
@ -174,13 +174,13 @@ bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt)
bool DeckLoader::updateLastLoadedTimestamp(const QString &fileName, FileFormat fmt) bool DeckLoader::updateLastLoadedTimestamp(const QString &fileName, FileFormat fmt)
{ {
QFileInfo fileInfo(fileName); const QFileInfo fileInfo(fileName);
if (!fileInfo.exists()) { if (!fileInfo.exists()) {
qCWarning(DeckLoaderLog) << "File does not exist:" << fileName; qCWarning(DeckLoaderLog) << "File does not exist:" << fileName;
return false; return false;
} }
QDateTime originalTimestamp = fileInfo.lastModified(); const QDateTime originalTimestamp = fileInfo.lastModified();
// Open the file for writing // Open the file for writing
QFile file(fileName); QFile file(fileName);
@ -285,7 +285,7 @@ QString DeckLoader::exportDeckToDecklist(const DeckList *deckList, DecklistWebsi
// Set up the function to call // Set up the function to call
auto formatDeckListForExport = [&mainBoardCards, &sideBoardCards](const auto *node, const auto *card) { auto formatDeckListForExport = [&mainBoardCards, &sideBoardCards](const auto *node, const auto *card) {
// Get the card name // Get the card name
CardInfoPtr dbCard = CardDatabaseManager::query()->getCardInfo(card->getName()); const CardInfoPtr dbCard = CardDatabaseManager::query()->getCardInfo(card->getName());
if (!dbCard || dbCard->getIsToken()) { if (!dbCard || dbCard->getIsToken()) {
// If it's a token, we don't care about the card. // If it's a token, we don't care about the card.
return; return;
@ -328,10 +328,10 @@ struct SetProviderIdToPreferred
void operator()(const InnerDecklistNode *node, DecklistCardNode *card) const void operator()(const InnerDecklistNode *node, DecklistCardNode *card) const
{ {
Q_UNUSED(node); Q_UNUSED(node);
PrintingInfo preferredPrinting = CardDatabaseManager::query()->getPreferredPrinting(card->getName()); const PrintingInfo preferredPrinting = CardDatabaseManager::query()->getPreferredPrinting(card->getName());
QString providerId = preferredPrinting.getUuid(); const QString providerId = preferredPrinting.getUuid();
QString setShortName = preferredPrinting.getSet()->getShortName(); const QString setShortName = preferredPrinting.getSet()->getShortName();
QString collectorNumber = preferredPrinting.getProperty("num"); const QString collectorNumber = preferredPrinting.getProperty("num");
card->setCardProviderId(providerId); card->setCardProviderId(providerId);
card->setCardCollectorNumber(collectorNumber); card->setCardCollectorNumber(collectorNumber);
@ -481,7 +481,7 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out,
for (int j = 0; j < zoneNode->size(); j++) { for (int j = 0; j < zoneNode->size(); j++) {
auto *card = dynamic_cast<DecklistCardNode *>(zoneNode->at(j)); auto *card = dynamic_cast<DecklistCardNode *>(zoneNode->at(j));
CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(card->getName()); const CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(card->getName());
QString cardType = info ? info->getMainCardType() : "unknown"; QString cardType = info ? info->getMainCardType() : "unknown";
cardsByType.insert(cardType, card); cardsByType.insert(cardType, card);
@ -505,7 +505,7 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out,
out << "// " << cardTotalByType[cardType] << " " << cardType << "\n"; out << "// " << cardTotalByType[cardType] << " " << cardType << "\n";
} }
QList<DecklistCardNode *> cards = cardsByType.values(cardType); const QList<DecklistCardNode *> cards = cardsByType.values(cardType);
saveToStream_DeckZoneCards(out, zoneNode, cards, addComments, addSetNameAndNumber); saveToStream_DeckZoneCards(out, zoneNode, cards, addComments, addSetNameAndNumber);
@ -523,7 +523,7 @@ void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out,
{ {
// QMultiMap sorts values in reverse order // QMultiMap sorts values in reverse order
for (int i = cards.size() - 1; i >= 0; --i) { for (int i = cards.size() - 1; i >= 0; --i) {
DecklistCardNode *card = cards[i]; const DecklistCardNode *card = cards[i];
if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) { if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) {
out << "SB: "; out << "SB: ";
@ -551,8 +551,8 @@ void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out,
bool DeckLoader::convertToCockatriceFormat(QString fileName) bool DeckLoader::convertToCockatriceFormat(QString fileName)
{ {
// Change the file extension to .cod // Change the file extension to .cod
QFileInfo fileInfo(fileName); const QFileInfo fileInfo(fileName);
QString newFileName = QDir::toNativeSeparators(fileInfo.path() + "/" + fileInfo.completeBaseName() + ".cod"); const QString newFileName = QDir::toNativeSeparators(fileInfo.path() + "/" + fileInfo.completeBaseName() + ".cod");
// Open the new file for writing // Open the new file for writing
QFile file(newFileName); QFile file(newFileName);
@ -599,7 +599,7 @@ bool DeckLoader::convertToCockatriceFormat(QString fileName)
QString DeckLoader::getCardZoneFromName(const QString &cardName, QString currentZoneName) QString DeckLoader::getCardZoneFromName(const QString &cardName, QString currentZoneName)
{ {
CardInfoPtr card = CardDatabaseManager::query()->getCardInfo(cardName); const CardInfoPtr card = CardDatabaseManager::query()->getCardInfo(cardName);
if (card && card->getIsToken()) { if (card && card->getIsToken()) {
return DECK_ZONE_TOKENS; return DECK_ZONE_TOKENS;
@ -611,7 +611,7 @@ QString DeckLoader::getCardZoneFromName(const QString &cardName, QString current
QString DeckLoader::getCompleteCardName(const QString &cardName) QString DeckLoader::getCompleteCardName(const QString &cardName)
{ {
if (CardDatabaseManager::getInstance()) { if (CardDatabaseManager::getInstance()) {
ExactCard temp = CardDatabaseManager::query()->guessCard({cardName}); const ExactCard temp = CardDatabaseManager::query()->guessCard({cardName});
if (temp) { if (temp) {
return temp.getName(); return temp.getName();
} }
@ -625,7 +625,7 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node)
const int totalColumns = 2; const int totalColumns = 2;
if (node->height() == 1) { if (node->height() == 1) {
QTextBlockFormat blockFormat; const QTextBlockFormat blockFormat;
QTextCharFormat charFormat; QTextCharFormat charFormat;
charFormat.setFontPointSize(11); charFormat.setFontPointSize(11);
charFormat.setFontWeight(QFont::Bold); charFormat.setFontWeight(QFont::Bold);
@ -635,9 +635,9 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node)
tableFormat.setCellPadding(0); tableFormat.setCellPadding(0);
tableFormat.setCellSpacing(0); tableFormat.setCellSpacing(0);
tableFormat.setBorder(0); tableFormat.setBorder(0);
QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); const QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat);
for (int i = 0; i < node->size(); i++) { for (int i = 0; i < node->size(); i++) {
auto *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i)); const auto *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i));
QTextCharFormat cellCharFormat; QTextCharFormat cellCharFormat;
cellCharFormat.setFontPointSize(9); cellCharFormat.setFontPointSize(9);
@ -653,7 +653,7 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node)
cellCursor.insertText(card->getName()); cellCursor.insertText(card->getName());
} }
} else if (node->height() == 2) { } else if (node->height() == 2) {
QTextBlockFormat blockFormat; const QTextBlockFormat blockFormat;
QTextCharFormat charFormat; QTextCharFormat charFormat;
charFormat.setFontPointSize(14); charFormat.setFontPointSize(14);
charFormat.setFontWeight(QFont::Bold); charFormat.setFontWeight(QFont::Bold);
@ -670,7 +670,7 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node)
} }
tableFormat.setColumnWidthConstraints(constraints); tableFormat.setColumnWidthConstraints(constraints);
QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); const QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat);
for (int i = 0; i < node->size(); i++) { for (int i = 0; i < node->size(); i++) {
QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition();
printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i))); printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i)));
@ -690,7 +690,7 @@ void DeckLoader::printDeckList(QPrinter *printer, const DeckList *deckList)
QTextCursor cursor(&doc); QTextCursor cursor(&doc);
QTextBlockFormat headerBlockFormat; const QTextBlockFormat headerBlockFormat;
QTextCharFormat headerCharFormat; QTextCharFormat headerCharFormat;
headerCharFormat.setFontPointSize(16); headerCharFormat.setFontPointSize(16);
headerCharFormat.setFontWeight(QFont::Bold); headerCharFormat.setFontWeight(QFont::Bold);

View file

@ -76,7 +76,7 @@ int FlowLayout::heightForWidth(const int width) const
continue; continue;
} }
int itemWidth = item->sizeHint().width() + horizontalSpacing(); const int itemWidth = item->sizeHint().width() + horizontalSpacing();
if (rowWidth + itemWidth > width) { if (rowWidth + itemWidth > width) {
height += rowHeight + verticalSpacing(); height += rowHeight + verticalSpacing();
rowWidth = itemWidth; rowWidth = itemWidth;
@ -98,7 +98,7 @@ int FlowLayout::heightForWidth(const int width) const
continue; continue;
} }
int itemHeight = item->sizeHint().height(); const int itemHeight = item->sizeHint().height();
if (colHeight + itemHeight > width) { if (colHeight + itemHeight > width) {
width += colWidth; width += colWidth;
colHeight = itemHeight; colHeight = itemHeight;
@ -163,7 +163,7 @@ int FlowLayout::layoutAllRows(const int originX, const int originY, const int av
} }
QSize itemSize = item->sizeHint(); // The suggested size for the current item QSize itemSize = item->sizeHint(); // The suggested size for the current item
int itemWidth = itemSize.width() + horizontalSpacing(); // Item width plus spacing const int itemWidth = itemSize.width() + horizontalSpacing(); // Item width plus spacing
// Check if the current item fits in the remaining width of the current row // Check if the current item fits in the remaining width of the current row
if (currentXPosition + itemWidth > availableWidth) { if (currentXPosition + itemWidth > availableWidth) {
@ -279,7 +279,7 @@ void FlowLayout::layoutSingleColumn(const QVector<QLayoutItem *> &colItems, cons
} }
// Debugging: Print the item's widget class name and size hint // Debugging: Print the item's widget class name and size hint
QWidget *widget = item->widget(); const QWidget *widget = item->widget();
if (widget) { if (widget) {
qCDebug(FlowLayoutLog) << "Widget class:" << widget->metaObject()->className(); qCDebug(FlowLayoutLog) << "Widget class:" << widget->metaObject()->className();
qCDebug(FlowLayoutLog) << "Widget size hint:" << widget->sizeHint(); qCDebug(FlowLayoutLog) << "Widget size hint:" << widget->sizeHint();
@ -290,7 +290,7 @@ void FlowLayout::layoutSingleColumn(const QVector<QLayoutItem *> &colItems, cons
const QObjectList &children = widget->children(); const QObjectList &children = widget->children();
qCDebug(FlowLayoutLog) << "Child widgets:"; qCDebug(FlowLayoutLog) << "Child widgets:";
for (QObject *child : children) { for (QObject *child : children) {
if (QWidget *childWidget = qobject_cast<QWidget *>(child)) { if (const QWidget *childWidget = qobject_cast<QWidget *>(child)) {
qCDebug(FlowLayoutLog) << " - Child widget class:" << childWidget->metaObject()->className(); qCDebug(FlowLayoutLog) << " - Child widget class:" << childWidget->metaObject()->className();
qCDebug(FlowLayoutLog) << " Size hint:" << childWidget->sizeHint(); qCDebug(FlowLayoutLog) << " Size hint:" << childWidget->sizeHint();
qCDebug(FlowLayoutLog) << " Maximum size:" << childWidget->maximumSize(); qCDebug(FlowLayoutLog) << " Maximum size:" << childWidget->maximumSize();
@ -365,7 +365,7 @@ QSize FlowLayout::calculateSizeHintHorizontal() const
} }
QSize itemSize = item->sizeHint(); QSize itemSize = item->sizeHint();
int itemWidth = itemSize.width() + horizontalSpacing(); const int itemWidth = itemSize.width() + horizontalSpacing();
qCDebug(FlowLayoutLog) << "Processing item. Size:" << itemSize << "Width with spacing:" << itemWidth; qCDebug(FlowLayoutLog) << "Processing item. Size:" << itemSize << "Width with spacing:" << itemWidth;
if (currentWidth + itemWidth > availableWidth) { if (currentWidth + itemWidth > availableWidth) {
@ -413,7 +413,7 @@ QSize FlowLayout::calculateMinimumSizeHorizontal() const
} }
QSize itemMinSize = item->minimumSize(); QSize itemMinSize = item->minimumSize();
int itemWidth = itemMinSize.width() + horizontalSpacing(); const int itemWidth = itemMinSize.width() + horizontalSpacing();
qCDebug(FlowLayoutLog) << "Processing item. Minimum size:" << itemMinSize << "Width with spacing:" << itemWidth; qCDebug(FlowLayoutLog) << "Processing item. Minimum size:" << itemMinSize << "Width with spacing:" << itemWidth;
if (currentWidth + itemWidth > availableWidth) { if (currentWidth + itemWidth > availableWidth) {
@ -509,7 +509,7 @@ QSize FlowLayout::calculateMinimumSizeVertical() const
} }
QSize itemMinSize = item->minimumSize(); QSize itemMinSize = item->minimumSize();
int itemHeight = itemMinSize.height() + verticalSpacing(); const int itemHeight = itemMinSize.height() + verticalSpacing();
qCDebug(FlowLayoutLog) << "Processing item. Minimum size:" << itemMinSize qCDebug(FlowLayoutLog) << "Processing item. Minimum size:" << itemMinSize
<< "Height with spacing:" << itemHeight; << "Height with spacing:" << itemHeight;
@ -553,7 +553,7 @@ void FlowLayout::insertWidgetAtIndex(QWidget *toInsert, int index)
addChildWidget(toInsert); addChildWidget(toInsert);
// We don't want to fail on an index that violates the bounds, so we just clamp it. // We don't want to fail on an index that violates the bounds, so we just clamp it.
int boundedIndex = qBound(0, index, qMax(0, static_cast<int>(items.size()))); const int boundedIndex = qBound(0, index, qMax(0, static_cast<int>(items.size())));
items.insert(boundedIndex, new QWidgetItem(toInsert)); items.insert(boundedIndex, new QWidgetItem(toInsert));
invalidate(); invalidate();

View file

@ -57,7 +57,7 @@ OverlapLayout::~OverlapLayout()
void OverlapLayout::insertWidgetAtIndex(QWidget *toInsert, int index) void OverlapLayout::insertWidgetAtIndex(QWidget *toInsert, int index)
{ {
addChildWidget(toInsert); addChildWidget(toInsert);
int clampedIndex = qBound(0, index, qMax(0, static_cast<int>(itemList.size()))); const int clampedIndex = qBound(0, index, qMax(0, static_cast<int>(itemList.size())));
itemList.insert(clampedIndex, new QWidgetItem(toInsert)); itemList.insert(clampedIndex, new QWidgetItem(toInsert));
for (int i = clampedIndex; i < itemList.size(); ++i) { for (int i = clampedIndex; i < itemList.size(); ++i) {
@ -154,7 +154,7 @@ void OverlapLayout::setGeometry(const QRect &rect)
// Determine the maximum item width and height among all layout items. // Determine the maximum item width and height among all layout items.
int maxItemWidth = 0; int maxItemWidth = 0;
int maxItemHeight = 0; int maxItemHeight = 0;
for (QLayoutItem *item : itemList) { for (const QLayoutItem *item : itemList) {
if (item != nullptr && item->widget()) { if (item != nullptr && item->widget()) {
QSize itemSize = item->widget()->sizeHint(); QSize itemSize = item->widget()->sizeHint();
maxItemWidth = qMax(maxItemWidth, itemSize.width()); maxItemWidth = qMax(maxItemWidth, itemSize.width());
@ -266,7 +266,7 @@ QSize OverlapLayout::calculatePreferredSize() const
// Determine the maximum item width and height among all layout items. // Determine the maximum item width and height among all layout items.
int maxItemWidth = 0; int maxItemWidth = 0;
int maxItemHeight = 0; int maxItemHeight = 0;
for (QLayoutItem *item : itemList) { for (const QLayoutItem *item : itemList) {
if (item != nullptr && item->widget()) { if (item != nullptr && item->widget()) {
QSize itemSize = item->widget()->sizeHint(); QSize itemSize = item->widget()->sizeHint();
maxItemWidth = qMax(maxItemWidth, itemSize.width()); maxItemWidth = qMax(maxItemWidth, itemSize.width());
@ -406,7 +406,7 @@ int OverlapLayout::calculateMaxColumns() const
// Determine maximum item width // Determine maximum item width
int maxItemWidth = 0; int maxItemWidth = 0;
for (QLayoutItem *item : itemList) { for (const QLayoutItem *item : itemList) {
if (item == nullptr || !item->widget()) { if (item == nullptr || !item->widget()) {
continue; continue;
} }
@ -457,7 +457,7 @@ int OverlapLayout::calculateMaxRows() const
// Determine maximum item height // Determine maximum item height
int maxItemHeight = 0; int maxItemHeight = 0;
for (QLayoutItem *item : itemList) { for (const QLayoutItem *item : itemList) {
if (item == nullptr || !item->widget()) { if (item == nullptr || !item->widget()) {
continue; continue;
} }

View file

@ -140,7 +140,7 @@ QString Logger::getSystemLocale()
QString Logger::getClientInstallInfo() QString Logger::getClientInstallInfo()
{ {
// don't rely on settingsCache->getIsPortableBuild() since the logger is initialized earlier // don't rely on settingsCache->getIsPortableBuild() since the logger is initialized earlier
bool isPortable = QFile::exists(qApp->applicationDirPath() + "/portable.dat"); const bool isPortable = QFile::exists(qApp->applicationDirPath() + "/portable.dat");
QString result(QString("Install Mode: ") + (isPortable ? "Portable" : "Standard")); QString result(QString("Install Mode: ") + (isPortable ? "Portable" : "Standard"));
return result; return result;
} }

View file

@ -77,7 +77,7 @@ QStringMap &ThemeManager::getAvailableThemes()
QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor) QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor)
{ {
QBrush brush; QBrush brush;
QPixmap tmp = QPixmap("theme:zones/" + fileName); const QPixmap tmp = QPixmap("theme:zones/" + fileName);
if (tmp.isNull()) { if (tmp.isNull()) {
brush.setColor(fallbackColor); brush.setColor(fallbackColor);
brush.setStyle(Qt::SolidPattern); brush.setStyle(Qt::SolidPattern);
@ -91,7 +91,7 @@ QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor)
QBrush ThemeManager::loadExtraBrush(QString fileName, QBrush &fallbackBrush) QBrush ThemeManager::loadExtraBrush(QString fileName, QBrush &fallbackBrush)
{ {
QBrush brush; QBrush brush;
QPixmap tmp = QPixmap("theme:zones/" + fileName); const QPixmap tmp = QPixmap("theme:zones/" + fileName);
if (tmp.isNull()) { if (tmp.isNull()) {
brush = fallbackBrush; brush = fallbackBrush;
@ -104,10 +104,10 @@ QBrush ThemeManager::loadExtraBrush(QString fileName, QBrush &fallbackBrush)
void ThemeManager::themeChangedSlot() void ThemeManager::themeChangedSlot()
{ {
QString themeName = SettingsCache::instance().getThemeName(); const QString themeName = SettingsCache::instance().getThemeName();
qCInfo(ThemeManagerLog) << "Theme changed:" << themeName; qCInfo(ThemeManagerLog) << "Theme changed:" << themeName;
QString dirPath = getAvailableThemes().value(themeName); const QString dirPath = getAvailableThemes().value(themeName);
QDir dir = dirPath; QDir dir = dirPath;
// css // css

View file

@ -83,14 +83,14 @@ void ColorIdentityWidget::resizeEvent(QResizeEvent *event)
QList<ManaSymbolWidget *> manaSymbols = findChildren<ManaSymbolWidget *>(); QList<ManaSymbolWidget *> manaSymbols = findChildren<ManaSymbolWidget *>();
if (!manaSymbols.isEmpty()) { if (!manaSymbols.isEmpty()) {
int totalWidth = event->size().width(); const int totalWidth = event->size().width();
int totalHeight = totalWidth / 6; // Set height to 1/4 of the width const int totalHeight = totalWidth / 6; // Set height to 1/4 of the width
setFixedHeight(totalHeight); setFixedHeight(totalHeight);
int spacing = layout->spacing(); const int spacing = layout->spacing();
int count = manaSymbols.size(); const int count = manaSymbols.size();
int availableWidth = totalWidth - (spacing * (count - 1)); const int availableWidth = totalWidth - (spacing * (count - 1));
int iconSize = qMin(availableWidth / count, totalHeight); // Ensure icons fit within the new height const int iconSize = qMin(availableWidth / count, totalHeight); // Ensure icons fit within the new height
for (ManaSymbolWidget *manaSymbol : manaSymbols) { for (ManaSymbolWidget *manaSymbol : manaSymbols) {
manaSymbol->setFixedSize(iconSize, iconSize); manaSymbol->setFixedSize(iconSize, iconSize);

View file

@ -19,7 +19,7 @@ ManaCostWidget::ManaCostWidget(QWidget *parent, CardInfoPtr _card) : QWidget(par
setFixedHeight(50); // Fixed height setFixedHeight(50); // Fixed height
if (card) { if (card) {
QString manaCost = card->getManaCost(); // Get mana cost string const QString manaCost = card->getManaCost(); // Get mana cost string
QStringList symbols = parseManaCost(manaCost); // Parse mana cost string QStringList symbols = parseManaCost(manaCost); // Parse mana cost string
for (const QString &symbol : symbols) { for (const QString &symbol : symbols) {
@ -35,13 +35,13 @@ void ManaCostWidget::resizeEvent(QResizeEvent *event)
QList<ManaSymbolWidget *> manaSymbols = findChildren<ManaSymbolWidget *>(); QList<ManaSymbolWidget *> manaSymbols = findChildren<ManaSymbolWidget *>();
if (!manaSymbols.isEmpty()) { if (!manaSymbols.isEmpty()) {
int totalWidth = event->size().width(); const int totalWidth = event->size().width();
int spacing = layout->spacing(); const int spacing = layout->spacing();
int count = manaSymbols.size(); const int count = manaSymbols.size();
// Available width minus total spacing // Available width minus total spacing
int availableWidth = totalWidth - (spacing * (count - 1)); const int availableWidth = totalWidth - (spacing * (count - 1));
int iconSize = qMin(50, availableWidth / count); const int iconSize = qMin(50, availableWidth / count);
for (ManaSymbolWidget *manaSymbol : manaSymbols) { for (ManaSymbolWidget *manaSymbol : manaSymbols) {
manaSymbol->setFixedSize(iconSize, iconSize); manaSymbol->setFixedSize(iconSize, iconSize);

View file

@ -39,7 +39,7 @@ CardGroupDisplayWidget::CardGroupDisplayWidget(QWidget *parent,
void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{ {
auto proxyModel = qobject_cast<QAbstractProxyModel *>(selectionModel->model()); const auto proxyModel = qobject_cast<QAbstractProxyModel *>(selectionModel->model());
for (auto &range : selected) { for (auto &range : selected) {
for (int row = range.top(); row <= range.bottom(); ++row) { for (int row = range.top(); row <= range.bottom(); ++row) {
@ -51,7 +51,7 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected,
auto it = indexToWidgetMap.find(QPersistentModelIndex(idx)); auto it = indexToWidgetMap.find(QPersistentModelIndex(idx));
if (it != indexToWidgetMap.end()) { if (it != indexToWidgetMap.end()) {
if (auto displayWidget = qobject_cast<CardInfoPictureWithTextOverlayWidget *>(it.value())) { if (const auto displayWidget = qobject_cast<CardInfoPictureWithTextOverlayWidget *>(it.value())) {
displayWidget->setHighlighted(true); displayWidget->setHighlighted(true);
} }
} }
@ -66,7 +66,7 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected,
auto it = indexToWidgetMap.find(QPersistentModelIndex(idx)); auto it = indexToWidgetMap.find(QPersistentModelIndex(idx));
if (it != indexToWidgetMap.end()) { if (it != indexToWidgetMap.end()) {
if (auto displayWidget = qobject_cast<CardInfoPictureWithTextOverlayWidget *>(it.value())) { if (const auto displayWidget = qobject_cast<CardInfoPictureWithTextOverlayWidget *>(it.value())) {
displayWidget->setHighlighted(false); displayWidget->setHighlighted(false);
} }
} }
@ -77,7 +77,7 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected,
void CardGroupDisplayWidget::clearAllDisplayWidgets() void CardGroupDisplayWidget::clearAllDisplayWidgets()
{ {
for (auto idx : indexToWidgetMap.keys()) { for (auto idx : indexToWidgetMap.keys()) {
auto displayWidget = indexToWidgetMap.value(idx); const auto displayWidget = indexToWidgetMap.value(idx);
removeFromLayout(displayWidget); removeFromLayout(displayWidget);
indexToWidgetMap.remove(idx); indexToWidgetMap.remove(idx);
delete displayWidget; delete displayWidget;
@ -89,10 +89,10 @@ QWidget *CardGroupDisplayWidget::constructWidgetForIndex(QPersistentModelIndex i
if (indexToWidgetMap.contains(index)) { if (indexToWidgetMap.contains(index)) {
return indexToWidgetMap[index]; return indexToWidgetMap[index];
} }
auto cardName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString(); const auto cardName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString();
auto cardProviderId = deckListModel->data(index.sibling(index.row(), 4), Qt::EditRole).toString(); const auto cardProviderId = deckListModel->data(index.sibling(index.row(), 4), Qt::EditRole).toString();
auto widget = new CardInfoPictureWithTextOverlayWidget(getLayoutParent(), true); const auto widget = new CardInfoPictureWithTextOverlayWidget(getLayoutParent(), true);
widget->setScaleFactor(cardSizeWidget->getSlider()->value()); widget->setScaleFactor(cardSizeWidget->getSlider()->value());
widget->setCard(CardDatabaseManager::query()->getCard({cardName, cardProviderId})); widget->setCard(CardDatabaseManager::query()->getCard({cardName, cardProviderId}));
@ -115,7 +115,7 @@ void CardGroupDisplayWidget::updateCardDisplays()
proxy.sort(1, Qt::AscendingOrder); proxy.sort(1, Qt::AscendingOrder);
// 1. trackedIndex is a source index → map it to proxy space // 1. trackedIndex is a source index → map it to proxy space
QModelIndex proxyParent = proxy.mapFromSource(trackedIndex); const QModelIndex proxyParent = proxy.mapFromSource(trackedIndex);
// 2. iterate children under the proxy parent // 2. iterate children under the proxy parent
for (int i = 0; i < proxy.rowCount(proxyParent); ++i) { for (int i = 0; i < proxy.rowCount(proxyParent); ++i) {
@ -125,7 +125,7 @@ void CardGroupDisplayWidget::updateCardDisplays()
QModelIndex sourceIndex = proxy.mapToSource(proxyIndex); QModelIndex sourceIndex = proxy.mapToSource(proxyIndex);
// 4. persist the source index // 4. persist the source index
QPersistentModelIndex persistent(sourceIndex); const QPersistentModelIndex persistent(sourceIndex);
addToLayout(constructWidgetForIndex(persistent)); addToLayout(constructWidgetForIndex(persistent));
} }
@ -143,7 +143,7 @@ void CardGroupDisplayWidget::onCardAddition(const QModelIndex &parent, int first
QModelIndex child = deckListModel->index(row, 0, parent); QModelIndex child = deckListModel->index(row, 0, parent);
// Persist the index // Persist the index
QPersistentModelIndex persistent(child); const QPersistentModelIndex persistent(child);
insertIntoLayout(constructWidgetForIndex(persistent), row); insertIntoLayout(constructWidgetForIndex(persistent), row);
} }

View file

@ -31,8 +31,8 @@ CardInfoDisplayWidget::CardInfoDisplayWidget(const CardRef &cardRef, QWidget *pa
setFrameStyle(QFrame::Panel | QFrame::Raised); setFrameStyle(QFrame::Panel | QFrame::Raised);
int pixmapHeight = QGuiApplication::primaryScreen()->geometry().height() / 3; const int pixmapHeight = QGuiApplication::primaryScreen()->geometry().height() / 3;
int pixmapWidth = static_cast<int>(pixmapHeight / aspectRatio); const int pixmapWidth = static_cast<int>(pixmapHeight / aspectRatio);
pic->setFixedWidth(pixmapWidth); pic->setFixedWidth(pixmapWidth);
pic->setFixedHeight(pixmapHeight); pic->setFixedHeight(pixmapHeight);
setFixedWidth(pixmapWidth + 150); setFixedWidth(pixmapWidth + 150);

View file

@ -25,16 +25,16 @@ QPixmap CardInfoPictureArtCropWidget::getProcessedBackground(const QSize &target
const QSize sz = fullResPixmap.size(); const QSize sz = fullResPixmap.size();
int marginX = sz.width() * 0.07; const int marginX = sz.width() * 0.07;
int topMargin = sz.height() * 0.11; const int topMargin = sz.height() * 0.11;
int bottomMargin = sz.height() * 0.45; const int bottomMargin = sz.height() * 0.45;
QRect foilRect(marginX, topMargin, sz.width() - 2 * marginX, sz.height() - topMargin - bottomMargin); QRect foilRect(marginX, topMargin, sz.width() - 2 * marginX, sz.height() - topMargin - bottomMargin);
foilRect = foilRect.intersected(fullResPixmap.rect()); // always clamp to source bounds foilRect = foilRect.intersected(fullResPixmap.rect()); // always clamp to source bounds
// Crop first, then scale for best quality // Crop first, then scale for best quality
QPixmap cropped = fullResPixmap.copy(foilRect); const QPixmap cropped = fullResPixmap.copy(foilRect);
QPixmap scaled = cropped.scaled(targetSize, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); QPixmap scaled = cropped.scaled(targetSize, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
return scaled; return scaled;

View file

@ -79,14 +79,14 @@ void CardInfoPictureEnlargedWidget::paintEvent(QPaintEvent *event)
} }
// Scale the size of the pixmap to fit the widget while maintaining the aspect ratio // Scale the size of the pixmap to fit the widget while maintaining the aspect ratio
QSize scaledSize = enlargedPixmap.size().scaled(size().width(), size().height(), Qt::KeepAspectRatio); const QSize scaledSize = enlargedPixmap.size().scaled(size().width(), size().height(), Qt::KeepAspectRatio);
// Calculate the position to center the scaled pixmap // Calculate the position to center the scaled pixmap
QPoint topLeft{(width() - scaledSize.width()) / 2, (height() - scaledSize.height()) / 2}; const QPoint topLeft{(width() - scaledSize.width()) / 2, (height() - scaledSize.height()) / 2};
// Define the radius for rounded corners // Define the radius for rounded corners
// Adjust the radius as needed for rounded corners // Adjust the radius as needed for rounded corners
qreal radius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * scaledSize.width() : 0.; const qreal radius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * scaledSize.width() : 0.;
QStylePainter painter(this); QStylePainter painter(this);
// Fill the background with transparent color to ensure rounded corners are rendered properly // Fill the background with transparent color to ensure rounded corners are rendered properly

View file

@ -192,27 +192,28 @@ void CardInfoPictureWidget::paintEvent(QPaintEvent *event)
} }
// Handle DPI scaling // Handle DPI scaling
qreal dpr = devicePixelRatio(); // Get the actual scaling factor const qreal dpr = devicePixelRatio(); // Get the actual scaling factor
QSize availableSize = size() * dpr; // Convert to physical pixel size const QSize availableSize = size() * dpr; // Convert to physical pixel size
// Compute final scaled size // Compute final scaled size
QSize pixmapSize = transformedPixmap.size(); const QSize pixmapSize = transformedPixmap.size();
QSize scaledSize = pixmapSize.scaled(availableSize, Qt::KeepAspectRatio); const QSize scaledSize = pixmapSize.scaled(availableSize, Qt::KeepAspectRatio);
// Pre-scale the pixmap once before drawing // Pre-scale the pixmap once before drawing
QPixmap finalPixmap = transformedPixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPixmap finalPixmap = transformedPixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
finalPixmap.setDevicePixelRatio(dpr); // Ensure correct display on high-DPI screens finalPixmap.setDevicePixelRatio(dpr); // Ensure correct display on high-DPI screens
// Compute target rectangle with explicit integer conversion // Compute target rectangle with explicit integer conversion
int targetX = static_cast<int>((availableSize.width() - scaledSize.width()) / (2 * dpr)); const int targetX = static_cast<int>((availableSize.width() - scaledSize.width()) / (2 * dpr));
int targetY = static_cast<int>((availableSize.height() - scaledSize.height()) / (2 * dpr)); const int targetY = static_cast<int>((availableSize.height() - scaledSize.height()) / (2 * dpr));
int targetW = static_cast<int>(scaledSize.width() / dpr); const int targetW = static_cast<int>(scaledSize.width() / dpr);
int targetH = static_cast<int>(scaledSize.height() / dpr); const int targetH = static_cast<int>(scaledSize.height() / dpr);
QRect targetRect{targetX, targetY, targetW, targetH}; const QRect targetRect{targetX, targetY, targetW, targetH};
// Compute rounded corner radius // Compute rounded corner radius
// Ensure consistent rounding // Ensure consistent rounding
qreal radius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * static_cast<qreal>(targetRect.width()) : 0.; const qreal radius =
SettingsCache::instance().getRoundCardCorners() ? 0.05 * static_cast<qreal>(targetRect.width()) : 0.;
// Draw the pixmap with rounded corners // Draw the pixmap with rounded corners
QStylePainter painter(this); QStylePainter painter(this);
@ -364,7 +365,7 @@ QMenu *CardInfoPictureWidget::createRightClickMenu()
QMenu *CardInfoPictureWidget::createViewRelatedCardsMenu() QMenu *CardInfoPictureWidget::createViewRelatedCardsMenu()
{ {
auto viewRelatedCards = new QMenu(tr("View related cards")); const auto viewRelatedCards = new QMenu(tr("View related cards"));
QList<CardRelation *> relatedCards = exactCard.getInfo().getAllRelatedCards(); QList<CardRelation *> relatedCards = exactCard.getInfo().getAllRelatedCards();
@ -372,7 +373,7 @@ QMenu *CardInfoPictureWidget::createViewRelatedCardsMenu()
return CardDatabaseManager::query()->getCardInfo(cardRelation->getName()) != nullptr; return CardDatabaseManager::query()->getCardInfo(cardRelation->getName()) != nullptr;
}; };
bool atLeastOneGoodRelationFound = std::any_of(relatedCards.begin(), relatedCards.end(), relatedCardExists); const bool atLeastOneGoodRelationFound = std::any_of(relatedCards.begin(), relatedCards.end(), relatedCardExists);
if (!atLeastOneGoodRelationFound) { if (!atLeastOneGoodRelationFound) {
viewRelatedCards->setEnabled(false); viewRelatedCards->setEnabled(false);
@ -397,8 +398,8 @@ QMenu *CardInfoPictureWidget::createViewRelatedCardsMenu()
*/ */
static MainWindow *findMainWindow() static MainWindow *findMainWindow()
{ {
for (auto widget : QApplication::topLevelWidgets()) { for (const auto widget : QApplication::topLevelWidgets()) {
if (auto mainWindow = qobject_cast<MainWindow *>(widget)) { if (const auto mainWindow = qobject_cast<MainWindow *>(widget)) {
return mainWindow; return mainWindow;
} }
} }
@ -409,9 +410,9 @@ static MainWindow *findMainWindow()
QMenu *CardInfoPictureWidget::createAddToOpenDeckMenu() QMenu *CardInfoPictureWidget::createAddToOpenDeckMenu()
{ {
auto addToOpenDeckMenu = new QMenu(tr("Add card to deck")); const auto addToOpenDeckMenu = new QMenu(tr("Add card to deck"));
auto mainWindow = findMainWindow(); const auto mainWindow = findMainWindow();
QList<AbstractTabDeckEditor *> deckEditorTabs = mainWindow->getTabSupervisor()->getDeckEditorTabs(); QList<AbstractTabDeckEditor *> deckEditorTabs = mainWindow->getTabSupervisor()->getDeckEditorTabs();
if (deckEditorTabs.isEmpty()) { if (deckEditorTabs.isEmpty()) {
@ -422,13 +423,13 @@ QMenu *CardInfoPictureWidget::createAddToOpenDeckMenu()
for (auto &deckEditorTab : deckEditorTabs) { for (auto &deckEditorTab : deckEditorTabs) {
auto *addCardMenu = addToOpenDeckMenu->addMenu(deckEditorTab->getTabText()); auto *addCardMenu = addToOpenDeckMenu->addMenu(deckEditorTab->getTabText());
QAction *addCard = addCardMenu->addAction(tr("Mainboard")); const QAction *addCard = addCardMenu->addAction(tr("Mainboard"));
connect(addCard, &QAction::triggered, this, [this, deckEditorTab] { connect(addCard, &QAction::triggered, this, [this, deckEditorTab] {
deckEditorTab->updateCard(exactCard); deckEditorTab->updateCard(exactCard);
deckEditorTab->actAddCard(exactCard); deckEditorTab->actAddCard(exactCard);
}); });
QAction *addCardSideboard = addCardMenu->addAction(tr("Sideboard")); const QAction *addCardSideboard = addCardMenu->addAction(tr("Sideboard"));
connect(addCardSideboard, &QAction::triggered, this, [this, deckEditorTab] { connect(addCardSideboard, &QAction::triggered, this, [this, deckEditorTab] {
deckEditorTab->updateCard(exactCard); deckEditorTab->updateCard(exactCard);
deckEditorTab->actAddCardToSideboard(exactCard); deckEditorTab->actAddCardToSideboard(exactCard);

View file

@ -75,7 +75,7 @@ void CardInfoTextWidget::setCard(CardInfoPtr card)
if (!relatedCards.empty()) { if (!relatedCards.empty()) {
text += QString("<tr><td>%1</td><td width=\"5\"></td><td>").arg(tr("Related cards:")); text += QString("<tr><td>%1</td><td width=\"5\"></td><td>").arg(tr("Related cards:"));
for (auto *relatedCard : relatedCards) { for (const auto *relatedCard : relatedCards) {
QString tmp = relatedCard->getName().toHtmlEscaped(); QString tmp = relatedCard->getName().toHtmlEscaped();
text += "<a href=\"" + tmp + "\">" + tmp + "</a><br>"; text += "<a href=\"" + tmp + "\">" + tmp + "</a><br>";
} }

View file

@ -81,7 +81,7 @@ void DeckCardZoneDisplayWidget::cleanupInvalidCardGroup(CardGroupDisplayWidget *
void DeckCardZoneDisplayWidget::constructAppropriateWidget(QPersistentModelIndex index) void DeckCardZoneDisplayWidget::constructAppropriateWidget(QPersistentModelIndex index)
{ {
auto categoryName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString(); const auto categoryName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString();
if (indexToWidgetMap.contains(index)) { if (indexToWidgetMap.contains(index)) {
return; return;
} }
@ -122,7 +122,7 @@ void DeckCardZoneDisplayWidget::displayCards()
proxy.sort(1, Qt::AscendingOrder); proxy.sort(1, Qt::AscendingOrder);
// 1. trackedIndex is a source index → map it to proxy space // 1. trackedIndex is a source index → map it to proxy space
QModelIndex proxyParent = proxy.mapFromSource(trackedIndex); const QModelIndex proxyParent = proxy.mapFromSource(trackedIndex);
// 2. iterate children under the proxy parent // 2. iterate children under the proxy parent
for (int i = 0; i < proxy.rowCount(proxyParent); ++i) { for (int i = 0; i < proxy.rowCount(proxyParent); ++i) {
@ -132,7 +132,7 @@ void DeckCardZoneDisplayWidget::displayCards()
QModelIndex sourceIndex = proxy.mapToSource(proxyIndex); QModelIndex sourceIndex = proxy.mapToSource(proxyIndex);
// 4. persist the source index // 4. persist the source index
QPersistentModelIndex persistent(sourceIndex); const QPersistentModelIndex persistent(sourceIndex);
constructAppropriateWidget(persistent); constructAppropriateWidget(persistent);
} }
@ -146,7 +146,7 @@ void DeckCardZoneDisplayWidget::onCategoryAddition(const QModelIndex &parent, in
} }
if (parent == trackedIndex) { if (parent == trackedIndex) {
for (int i = first; i <= last; i++) { for (int i = first; i <= last; i++) {
QPersistentModelIndex index = QPersistentModelIndex(deckListModel->index(i, 0, trackedIndex)); const QPersistentModelIndex index = QPersistentModelIndex(deckListModel->index(i, 0, trackedIndex));
constructAppropriateWidget(index); constructAppropriateWidget(index);
} }
@ -206,7 +206,7 @@ void DeckCardZoneDisplayWidget::refreshDisplayType(const DisplayType &_displayTy
// We gotta wait for all the deleteLater's to finish so we fire after the next event cycle // We gotta wait for all the deleteLater's to finish so we fire after the next event cycle
auto timer = new QTimer(this); const auto timer = new QTimer(this);
timer->setSingleShot(true); timer->setSingleShot(true);
connect(timer, &QTimer::timeout, this, [this]() { displayCards(); }); connect(timer, &QTimer::timeout, this, [this]() { displayCards(); });
timer->start(); timer->start();

View file

@ -51,7 +51,7 @@ void ManaBaseWidget::updateDisplay()
} }
int highestEntry = 0; int highestEntry = 0;
for (auto entry : manaBaseMap) { for (const auto entry : manaBaseMap) {
if (entry > highestEntry) { if (entry > highestEntry) {
highestEntry = entry; highestEntry = entry;
} }
@ -67,7 +67,7 @@ void ManaBaseWidget::updateDisplay()
manaColors.insert("C", QColor(150, 150, 150)); manaColors.insert("C", QColor(150, 150, 150));
for (auto manaColor : manaBaseMap.keys()) { for (auto manaColor : manaBaseMap.keys()) {
QColor barColor = manaColors.value(manaColor, Qt::gray); const QColor barColor = manaColors.value(manaColor, Qt::gray);
BarWidget *barWidget = new BarWidget(QString(manaColor), manaBaseMap[manaColor], highestEntry, barColor, this); BarWidget *barWidget = new BarWidget(QString(manaColor), manaBaseMap[manaColor], highestEntry, barColor, this);
barLayout->addWidget(barWidget); barLayout->addWidget(barWidget);
} }
@ -80,7 +80,7 @@ QHash<QString, int> ManaBaseWidget::analyzeManaBase()
manaBaseMap.clear(); manaBaseMap.clear();
QList<DecklistCardNode *> cardsInDeck = deckListModel->getDeckList()->getCardNodes(); QList<DecklistCardNode *> cardsInDeck = deckListModel->getDeckList()->getCardNodes();
for (auto currentCard : cardsInDeck) { for (const auto currentCard : cardsInDeck) {
for (int k = 0; k < currentCard->getNumber(); ++k) { for (int k = 0; k < currentCard->getNumber(); ++k) {
CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName());
if (info) { if (info) {
@ -98,7 +98,7 @@ QHash<QString, int> ManaBaseWidget::determineManaProduction(const QString &rules
{ {
QHash<QString, int> manaCounts = {{"W", 0}, {"U", 0}, {"B", 0}, {"R", 0}, {"G", 0}, {"C", 0}}; QHash<QString, int> manaCounts = {{"W", 0}, {"U", 0}, {"B", 0}, {"R", 0}, {"G", 0}, {"C", 0}};
QString text = rulesText.toLower(); // Normalize case for matching const QString text = rulesText.toLower(); // Normalize case for matching
// Quick keyword-based checks for any color and colorless mana // Quick keyword-based checks for any color and colorless mana
if (text.contains("{t}: add one mana of any color") || text.contains("add one mana of any color")) { if (text.contains("{t}: add one mana of any color") || text.contains("add one mana of any color")) {
@ -113,7 +113,7 @@ QHash<QString, int> ManaBaseWidget::determineManaProduction(const QString &rules
// Optimized regex for specific mana symbols // Optimized regex for specific mana symbols
static const QRegularExpression specificColorRegex(R"(\{T\}:\s*Add\s*\{([WUBRG])\})"); static const QRegularExpression specificColorRegex(R"(\{T\}:\s*Add\s*\{([WUBRG])\})");
QRegularExpressionMatch match = specificColorRegex.match(rulesText); const QRegularExpressionMatch match = specificColorRegex.match(rulesText);
if (match.hasMatch()) { if (match.hasMatch()) {
manaCounts[match.captured(1)]++; manaCounts[match.captured(1)]++;
} }

View file

@ -47,7 +47,7 @@ std::unordered_map<int, int> ManaCurveWidget::analyzeManaCurve()
QList<DecklistCardNode *> cardsInDeck = deckListModel->getDeckList()->getCardNodes(); QList<DecklistCardNode *> cardsInDeck = deckListModel->getDeckList()->getCardNodes();
for (auto currentCard : cardsInDeck) { for (const auto currentCard : cardsInDeck) {
for (int k = 0; k < currentCard->getNumber(); ++k) { for (int k = 0; k < currentCard->getNumber(); ++k) {
CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName());
if (info) { if (info) {
@ -81,7 +81,7 @@ void ManaCurveWidget::updateDisplay()
} }
// Convert unordered_map to ordered map to ensure sorting by CMC // Convert unordered_map to ordered map to ensure sorting by CMC
std::map<int, int> sortedManaCurve(manaCurveMap.begin(), manaCurveMap.end()); const std::map<int, int> sortedManaCurve(manaCurveMap.begin(), manaCurveMap.end());
// Add new widgets to the layout in sorted order // Add new widgets to the layout in sorted order
for (const auto &entry : sortedManaCurve) { for (const auto &entry : sortedManaCurve) {

View file

@ -49,7 +49,7 @@ std::unordered_map<char, int> ManaDevotionWidget::analyzeManaDevotion()
QList<DecklistCardNode *> cardsInDeck = deckListModel->getDeckList()->getCardNodes(); QList<DecklistCardNode *> cardsInDeck = deckListModel->getDeckList()->getCardNodes();
for (auto currentCard : cardsInDeck) { for (const auto currentCard : cardsInDeck) {
for (int k = 0; k < currentCard->getNumber(); ++k) { for (int k = 0; k < currentCard->getNumber(); ++k) {
CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName());
if (info) { if (info) {
@ -73,7 +73,7 @@ void ManaDevotionWidget::updateDisplay()
} }
int highestEntry = 0; int highestEntry = 0;
for (auto entry : manaDevotionMap) { for (const auto entry : manaDevotionMap) {
if (highestEntry < entry.second) { if (highestEntry < entry.second) {
highestEntry = entry.second; highestEntry = entry.second;
} }
@ -85,7 +85,7 @@ void ManaDevotionWidget::updateDisplay()
{'G', QColor(0, 115, 62)}, {'C', QColor(150, 150, 150)}}; {'G', QColor(0, 115, 62)}, {'C', QColor(150, 150, 150)}};
for (auto entry : manaDevotionMap) { for (auto entry : manaDevotionMap) {
QColor barColor = manaColors.count(entry.first) ? manaColors[entry.first] : Qt::gray; const QColor barColor = manaColors.count(entry.first) ? manaColors[entry.first] : Qt::gray;
BarWidget *barWidget = new BarWidget(QString(entry.first), entry.second, highestEntry, barColor, this); BarWidget *barWidget = new BarWidget(QString(entry.first), entry.second, highestEntry, barColor, this);
barLayout->addWidget(barWidget); barLayout->addWidget(barWidget);
} }
@ -97,7 +97,7 @@ std::unordered_map<char, int> ManaDevotionWidget::countManaSymbols(const QString
{ {
std::unordered_map<char, int> manaCounts = {{'W', 0}, {'U', 0}, {'B', 0}, {'R', 0}, {'G', 0}}; std::unordered_map<char, int> manaCounts = {{'W', 0}, {'U', 0}, {'B', 0}, {'R', 0}, {'G', 0}};
int len = manaString.length(); const int len = manaString.length();
for (int i = 0; i < len; ++i) { for (int i = 0; i < len; ++i) {
if (manaString[i] == '{') { if (manaString[i] == '{') {
++i; // Move past '{' ++i; // Move past '{'

View file

@ -37,7 +37,7 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(AbstractTabDeck
searchEdit->setPlaceholderText(tr("Search by card name (or search expressions)")); searchEdit->setPlaceholderText(tr("Search by card name (or search expressions)"));
searchEdit->setClearButtonEnabled(true); searchEdit->setClearButtonEnabled(true);
searchEdit->addAction(loadColorAdjustedPixmap("theme:icons/search"), QLineEdit::LeadingPosition); searchEdit->addAction(loadColorAdjustedPixmap("theme:icons/search"), QLineEdit::LeadingPosition);
auto help = searchEdit->addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition); const auto help = searchEdit->addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition);
searchEdit->installEventFilter(&searchKeySignals); searchEdit->installEventFilter(&searchKeySignals);
setFocusProxy(searchEdit); setFocusProxy(searchEdit);
@ -83,7 +83,7 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(AbstractTabDeck
&DeckEditorDatabaseDisplayWidget::updateCard); &DeckEditorDatabaseDisplayWidget::updateCard);
connect(databaseView, &QTreeView::doubleClicked, this, &DeckEditorDatabaseDisplayWidget::actAddCardToMainDeck); connect(databaseView, &QTreeView::doubleClicked, this, &DeckEditorDatabaseDisplayWidget::actAddCardToMainDeck);
QByteArray dbHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState(); const QByteArray dbHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState();
if (dbHeaderState.isNull()) { if (dbHeaderState.isNull()) {
// first run // first run
databaseView->setColumnWidth(0, 200); databaseView->setColumnWidth(0, 200);
@ -122,7 +122,7 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(AbstractTabDeck
void DeckEditorDatabaseDisplayWidget::updateSearch(const QString &search) void DeckEditorDatabaseDisplayWidget::updateSearch(const QString &search)
{ {
databaseDisplayModel->setStringFilter(search); databaseDisplayModel->setStringFilter(search);
QModelIndexList sel = databaseView->selectionModel()->selectedRows(); const QModelIndexList sel = databaseView->selectionModel()->selectedRows();
if (sel.isEmpty() && databaseDisplayModel->rowCount()) if (sel.isEmpty() && databaseDisplayModel->rowCount())
databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0),
QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
@ -214,7 +214,7 @@ void DeckEditorDatabaseDisplayWidget::databaseCustomMenu(QPoint point)
} else { } else {
for (const CardRelation *rel : relatedCards) { for (const CardRelation *rel : relatedCards) {
const QString &relatedCardName = rel->getName(); const QString &relatedCardName = rel->getName();
QAction *relatedCard = relatedMenu->addAction(relatedCardName); const QAction *relatedCard = relatedMenu->addAction(relatedCardName);
connect( connect(
relatedCard, &QAction::triggered, deckEditor->cardInfoDockWidget->cardInfo, relatedCard, &QAction::triggered, deckEditor->cardInfoDockWidget->cardInfo,
[this, relatedCardName] { deckEditor->cardInfoDockWidget->cardInfo->setCard(relatedCardName); }); [this, relatedCardName] { deckEditor->cardInfoDockWidget->cardInfo->setCard(relatedCardName); });
@ -226,7 +226,7 @@ void DeckEditorDatabaseDisplayWidget::databaseCustomMenu(QPoint point)
void DeckEditorDatabaseDisplayWidget::copyDatabaseCellContents() void DeckEditorDatabaseDisplayWidget::copyDatabaseCellContents()
{ {
auto _data = databaseView->selectionModel()->currentIndex().data(); const auto _data = databaseView->selectionModel()->currentIndex().data();
QApplication::clipboard()->setText(_data.toString()); QApplication::clipboard()->setText(_data.toString());
} }

View file

@ -265,7 +265,7 @@ void DeckEditorDeckDockWidget::createDeckDock()
ExactCard DeckEditorDeckDockWidget::getCurrentCard() ExactCard DeckEditorDeckDockWidget::getCurrentCard()
{ {
QModelIndex current = deckView->selectionModel()->currentIndex(); const QModelIndex current = deckView->selectionModel()->currentIndex();
if (!current.isValid()) if (!current.isValid())
return {}; return {};
const QString cardName = current.sibling(current.row(), 1).data().toString(); const QString cardName = current.sibling(current.row(), 1).data().toString();
@ -288,7 +288,7 @@ ExactCard DeckEditorDeckDockWidget::getCurrentCard()
void DeckEditorDeckDockWidget::updateCard(const QModelIndex /*&current*/, const QModelIndex & /*previous*/) void DeckEditorDeckDockWidget::updateCard(const QModelIndex /*&current*/, const QModelIndex & /*previous*/)
{ {
if (ExactCard card = getCurrentCard()) { if (const ExactCard card = getCurrentCard()) {
emit cardChanged(card); emit cardChanged(card);
} }
} }
@ -325,10 +325,10 @@ void DeckEditorDeckDockWidget::updateHash()
void DeckEditorDeckDockWidget::updateBannerCardComboBox() void DeckEditorDeckDockWidget::updateBannerCardComboBox()
{ {
// Store current banner card identity // Store current banner card identity
CardRef wanted = deckModel->getDeckList()->getBannerCard(); const CardRef wanted = deckModel->getDeckList()->getBannerCard();
// Block signals temporarily // Block signals temporarily
bool wasBlocked = bannerCardComboBox->blockSignals(true); const bool wasBlocked = bannerCardComboBox->blockSignals(true);
// Clear the existing items in the combo box // Clear the existing items in the combo box
bannerCardComboBox->clear(); bannerCardComboBox->clear();
@ -337,7 +337,7 @@ void DeckEditorDeckDockWidget::updateBannerCardComboBox()
QSet<QPair<QString, QString>> bannerCardSet; QSet<QPair<QString, QString>> bannerCardSet;
QList<DecklistCardNode *> cardsInDeck = deckModel->getDeckList()->getCardNodes(); QList<DecklistCardNode *> cardsInDeck = deckModel->getDeckList()->getCardNodes();
for (auto currentCard : cardsInDeck) { for (const auto currentCard : cardsInDeck) {
if (!CardDatabaseManager::query()->getCard(currentCard->toCardRef())) { if (!CardDatabaseManager::query()->getCard(currentCard->toCardRef())) {
continue; continue;
} }
@ -359,7 +359,7 @@ void DeckEditorDeckDockWidget::updateBannerCardComboBox()
} }
// Try to find an index with a matching card // Try to find an index with a matching card
int restoreIndex = findRestoreIndex(wanted, bannerCardComboBox); const int restoreIndex = findRestoreIndex(wanted, bannerCardComboBox);
// Handle results // Handle results
if (restoreIndex != -1) { if (restoreIndex != -1) {
@ -576,9 +576,10 @@ bool DeckEditorDeckDockWidget::swapCard(const QModelIndex &currentIndex)
offsetCountAtIndex(currentIndex, -1); offsetCountAtIndex(currentIndex, -1);
const QString otherZoneName = zoneName == DECK_ZONE_MAIN ? DECK_ZONE_SIDE : DECK_ZONE_MAIN; const QString otherZoneName = zoneName == DECK_ZONE_MAIN ? DECK_ZONE_SIDE : DECK_ZONE_MAIN;
ExactCard card = CardDatabaseManager::query()->getCard({cardName, cardProviderID}); const ExactCard card = CardDatabaseManager::query()->getCard({cardName, cardProviderID});
QModelIndex newCardIndex = card ? deckModel->addCard(card, otherZoneName) const QModelIndex newCardIndex = card
// Third argument (true) says create the card no matter what, even if not in DB ? deckModel->addCard(card, otherZoneName)
// Third argument (true) says create the card no matter what, even if not in DB
: deckModel->addPreferredPrintingCard(cardName, otherZoneName, true); : deckModel->addPreferredPrintingCard(cardName, otherZoneName, true);
recursiveExpand(proxy->mapToSource(newCardIndex)); recursiveExpand(proxy->mapToSource(newCardIndex));
@ -592,10 +593,10 @@ void DeckEditorDeckDockWidget::actDecrementCard(const ExactCard &card, QString z
if (card.getInfo().getIsToken()) if (card.getInfo().getIsToken())
zoneName = DECK_ZONE_TOKENS; zoneName = DECK_ZONE_TOKENS;
QString providerId = card.getPrinting().getUuid(); const QString providerId = card.getPrinting().getUuid();
QString collectorNumber = card.getPrinting().getProperty("num"); const QString collectorNumber = card.getPrinting().getProperty("num");
QModelIndex idx = deckModel->findCard(card.getName(), zoneName, providerId, collectorNumber); const QModelIndex idx = deckModel->findCard(card.getName(), zoneName, providerId, collectorNumber);
if (!idx.isValid()) { if (!idx.isValid()) {
return; return;
} }
@ -659,7 +660,7 @@ void DeckEditorDeckDockWidget::offsetCountAtIndex(const QModelIndex &idx, int of
return; return;
} }
QModelIndex sourceIndex = proxy->mapToSource(idx); const QModelIndex sourceIndex = proxy->mapToSource(idx);
const QModelIndex numberIndex = sourceIndex.sibling(sourceIndex.row(), 0); const QModelIndex numberIndex = sourceIndex.sibling(sourceIndex.row(), 0);
const QModelIndex nameIndex = sourceIndex.sibling(sourceIndex.row(), 1); const QModelIndex nameIndex = sourceIndex.sibling(sourceIndex.row(), 1);
@ -691,7 +692,7 @@ void DeckEditorDeckDockWidget::decklistCustomMenu(QPoint point)
if (!SettingsCache::instance().getOverrideAllCardArtWithPersonalPreference()) { if (!SettingsCache::instance().getOverrideAllCardArtWithPersonalPreference()) {
QMenu menu; QMenu menu;
QAction *selectPrinting = menu.addAction(tr("Select Printing")); const QAction *selectPrinting = menu.addAction(tr("Select Printing"));
connect(selectPrinting, &QAction::triggered, deckEditor, &AbstractTabDeckEditor::showPrintingSelector); connect(selectPrinting, &QAction::triggered, deckEditor, &AbstractTabDeckEditor::showPrintingSelector);
menu.exec(deckView->mapToGlobal(point)); menu.exec(deckView->mapToGlobal(point));
@ -700,7 +701,7 @@ void DeckEditorDeckDockWidget::decklistCustomMenu(QPoint point)
void DeckEditorDeckDockWidget::refreshShortcuts() void DeckEditorDeckDockWidget::refreshShortcuts()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aRemoveCard->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aRemoveCard")); aRemoveCard->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aRemoveCard"));
aIncrement->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aIncrement")); aIncrement->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aIncrement"));
aDecrement->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aDecrement")); aDecrement->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aDecrement"));

View file

@ -128,7 +128,7 @@ void DeckEditorFilterDockWidget::actClearFilterOne()
void DeckEditorFilterDockWidget::refreshShortcuts() void DeckEditorFilterDockWidget::refreshShortcuts()
{ {
ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts();
aClearFilterAll->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aClearFilterAll")); aClearFilterAll->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aClearFilterAll"));
aClearFilterOne->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aClearFilterOne")); aClearFilterOne->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aClearFilterOne"));

View file

@ -70,7 +70,7 @@ void DeckListHistoryManagerWidget::refreshList()
// Fill redo section first (oldest redo at top, newest redo closest to divider) // Fill redo section first (oldest redo at top, newest redo closest to divider)
const auto redoStack = historyManager->getRedoStack(); const auto redoStack = historyManager->getRedoStack();
for (int i = 0; i < redoStack.size(); ++i) { // iterate forward for (int i = 0; i < redoStack.size(); ++i) { // iterate forward
auto item = new QListWidgetItem(tr("[redo] ") + redoStack[i].getReason(), historyList); const auto item = new QListWidgetItem(tr("[redo] ") + redoStack[i].getReason(), historyList);
item->setData(Qt::UserRole, QVariant("redo")); item->setData(Qt::UserRole, QVariant("redo"));
item->setData(Qt::UserRole + 1, i); // index in redo stack item->setData(Qt::UserRole + 1, i); // index in redo stack
item->setForeground(Qt::gray); item->setForeground(Qt::gray);
@ -79,7 +79,7 @@ void DeckListHistoryManagerWidget::refreshList()
// Divider // Divider
if (!historyManager->getUndoStack().isEmpty() && !historyManager->getRedoStack().isEmpty()) { if (!historyManager->getUndoStack().isEmpty() && !historyManager->getRedoStack().isEmpty()) {
auto divider = new QListWidgetItem("──────────", historyList); const auto divider = new QListWidgetItem("──────────", historyList);
divider->setFlags(Qt::NoItemFlags); // not selectable divider->setFlags(Qt::NoItemFlags); // not selectable
historyList->addItem(divider); historyList->addItem(divider);
} }
@ -87,7 +87,7 @@ void DeckListHistoryManagerWidget::refreshList()
// Fill undo section // Fill undo section
const auto undoStack = historyManager->getUndoStack(); const auto undoStack = historyManager->getUndoStack();
for (int i = undoStack.size() - 1; i >= 0; --i) { for (int i = undoStack.size() - 1; i >= 0; --i) {
auto item = new QListWidgetItem(tr("[undo] ") + undoStack[i].getReason(), historyList); const auto item = new QListWidgetItem(tr("[undo] ") + undoStack[i].getReason(), historyList);
item->setData(Qt::UserRole, QVariant("undo")); item->setData(Qt::UserRole, QVariant("undo"));
item->setData(Qt::UserRole + 1, i); // index in undo stack item->setData(Qt::UserRole + 1, i); // index in undo stack
historyList->addItem(item); historyList->addItem(item);
@ -135,17 +135,17 @@ void DeckListHistoryManagerWidget::onListClicked(QListWidgetItem *item)
} }
const QString mode = item->data(Qt::UserRole).toString(); const QString mode = item->data(Qt::UserRole).toString();
int index = item->data(Qt::UserRole + 1).toInt(); const int index = item->data(Qt::UserRole + 1).toInt();
if (mode == "redo") { if (mode == "redo") {
const auto redoStack = historyManager->getRedoStack(); const auto redoStack = historyManager->getRedoStack();
int steps = redoStack.size() - index; const int steps = redoStack.size() - index;
for (int i = 0; i < steps; ++i) { for (int i = 0; i < steps; ++i) {
historyManager->redo(deckListModel->getDeckList()); historyManager->redo(deckListModel->getDeckList());
} }
} else if (mode == "undo") { } else if (mode == "undo") {
const auto undoStack = historyManager->getUndoStack(); const auto undoStack = historyManager->getUndoStack();
int steps = undoStack.size() - 1 - index; const int steps = undoStack.size() - 1 - index;
for (int i = 0; i < steps + 1; ++i) { for (int i = 0; i < steps + 1; ++i) {
historyManager->undo(deckListModel->getDeckList()); historyManager->undo(deckListModel->getDeckList());
} }

View file

@ -7,13 +7,13 @@
QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const
{ {
QModelIndex src = mapToSource(index); const QModelIndex src = mapToSource(index);
if (!src.isValid()) if (!src.isValid())
return {}; return {};
QVariant value = QIdentityProxyModel::data(index, role); QVariant value = QIdentityProxyModel::data(index, role);
bool isCard = src.data(DeckRoles::IsCardRole).toBool(); const bool isCard = src.data(DeckRoles::IsCardRole).toBool();
if (role == Qt::FontRole && !isCard) { if (role == Qt::FontRole && !isCard) {
QFont f; QFont f;
@ -25,11 +25,11 @@ QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const
if (isCard) { if (isCard) {
const bool legal = const bool legal =
true; // TODO: Not implemented yet. QIdentityProxyModel::data(index, DeckRoles::IsLegalRole).toBool(); true; // TODO: Not implemented yet. QIdentityProxyModel::data(index, DeckRoles::IsLegalRole).toBool();
int base = 255 - (index.row() % 2) * 30; const int base = 255 - (index.row() % 2) * 30;
return legal ? QBrush(QColor(base, base, base)) : QBrush(QColor(255, base / 3, base / 3)); return legal ? QBrush(QColor(base, base, base)) : QBrush(QColor(255, base / 3, base / 3));
} else { } else {
int depth = src.data(DeckRoles::DepthRole).toInt(); const int depth = src.data(DeckRoles::DepthRole).toInt();
int color = 90 + 60 * depth; const int color = 90 + 60 * depth;
return QBrush(QColor(color, 255, color)); return QBrush(QColor(color, 255, color));
} }
} }

View file

@ -214,9 +214,9 @@ void DlgConnect::rebuildComboBoxList(int failure)
savedHostList = uci.getServerInfo(); savedHostList = uci.getServerInfo();
auto &servers = SettingsCache::instance().servers(); auto &servers = SettingsCache::instance().servers();
bool autoConnectEnabled = servers.getAutoConnect() > 0; const bool autoConnectEnabled = servers.getAutoConnect() > 0;
QString previousHostName = servers.getPrevioushostName(); const QString previousHostName = servers.getPrevioushostName();
QString autoConnectSaveName = servers.getSaveName(); const QString autoConnectSaveName = servers.getSaveName();
int index = 0; int index = 0;
@ -272,7 +272,7 @@ void DlgConnect::updateDisplayInfo(const QString &saveName)
<< ""; << "";
} }
bool savePasswordStatus = (_data.at(5) == "1"); const bool savePasswordStatus = (_data.at(5) == "1");
saveEdit->setText(_data.at(0)); saveEdit->setText(_data.at(0));
hostEdit->setText(_data.at(1)); hostEdit->setText(_data.at(1));
@ -285,7 +285,7 @@ void DlgConnect::updateDisplayInfo(const QString &saveName)
} }
if (!_data.at(6).isEmpty()) { if (!_data.at(6).isEmpty()) {
QString formattedLink = "<a href=\"" + _data.at(6) + "\">" + _data.at(6) + "</a>"; const QString formattedLink = "<a href=\"" + _data.at(6) + "\">" + _data.at(6) + "</a>";
serverContactLabel->setText(tr("Webpage") + ":"); serverContactLabel->setText(tr("Webpage") + ":");
serverContactLink->setText(formattedLink); serverContactLink->setText(formattedLink);
} else { } else {

View file

@ -85,7 +85,7 @@ void DlgDefaultTagsEditor::loadStringList()
void DlgDefaultTagsEditor::addItem() void DlgDefaultTagsEditor::addItem()
{ {
QString newTag = inputField->text().trimmed(); const QString newTag = inputField->text().trimmed();
if (newTag.isEmpty()) { if (newTag.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Input"), tr("Tag name cannot be empty!")); QMessageBox::warning(this, tr("Invalid Input"), tr("Tag name cannot be empty!"));
return; return;
@ -93,10 +93,10 @@ void DlgDefaultTagsEditor::addItem()
// Prevent duplicate tags // Prevent duplicate tags
for (int i = 0; i < listWidget->count(); ++i) { for (int i = 0; i < listWidget->count(); ++i) {
QWidget *widget = listWidget->itemWidget(listWidget->item(i)); const QWidget *widget = listWidget->itemWidget(listWidget->item(i));
if (!widget) if (!widget)
continue; continue;
QLineEdit *lineEdit = widget->findChild<QLineEdit *>(); const QLineEdit *lineEdit = widget->findChild<QLineEdit *>();
if (lineEdit && lineEdit->text() == newTag) { if (lineEdit && lineEdit->text() == newTag) {
QMessageBox::warning(this, tr("Duplicate Tag"), tr("This tag already exists.")); QMessageBox::warning(this, tr("Duplicate Tag"), tr("This tag already exists."));
return; return;
@ -136,10 +136,10 @@ void DlgDefaultTagsEditor::confirmChanges()
{ {
QStringList updatedList; QStringList updatedList;
for (int i = 0; i < listWidget->count(); ++i) { for (int i = 0; i < listWidget->count(); ++i) {
QWidget *widget = listWidget->itemWidget(listWidget->item(i)); const QWidget *widget = listWidget->itemWidget(listWidget->item(i));
if (!widget) if (!widget)
continue; continue;
QLineEdit *lineEdit = widget->findChild<QLineEdit *>(); const QLineEdit *lineEdit = widget->findChild<QLineEdit *>();
if (lineEdit) { if (lineEdit) {
updatedList.append(lineEdit->text()); updatedList.append(lineEdit->text());
} }

View file

@ -49,7 +49,7 @@ void DlgEditAvatar::actOk()
void DlgEditAvatar::actBrowse() void DlgEditAvatar::actBrowse()
{ {
QString fileName = const QString fileName =
QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)")); QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)"));
if (fileName.isEmpty()) { if (fileName.isEmpty()) {
imageLabel->setText(tr("No image chosen.")); imageLabel->setText(tr("No image chosen."));

View file

@ -162,11 +162,11 @@ void DlgEditTokens::actAddToken()
} }
} }
QString setName = CardSet::TOKENS_SETNAME; const QString setName = CardSet::TOKENS_SETNAME;
SetToPrintingsMap sets; SetToPrintingsMap sets;
sets[setName].append(PrintingInfo(databaseModel->getDatabase()->getSet(setName))); sets[setName].append(PrintingInfo(databaseModel->getDatabase()->getSet(setName)));
CardInfo::UiAttributes attributes = {.tableRow = -1}; const CardInfo::UiAttributes attributes = {.tableRow = -1};
CardInfoPtr card = CardInfo::newInstance(name, "", true, {}, {}, {}, sets, attributes); const CardInfoPtr card = CardInfo::newInstance(name, "", true, {}, {}, {}, sets, attributes);
card->setCardType("Token"); card->setCardType("Token");
databaseModel->getDatabase()->addCard(card); databaseModel->getDatabase()->addCard(card);
@ -175,7 +175,7 @@ void DlgEditTokens::actAddToken()
void DlgEditTokens::actRemoveToken() void DlgEditTokens::actRemoveToken()
{ {
if (currentCard) { if (currentCard) {
CardInfoPtr cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() const CardInfoPtr cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard()
currentCard.clear(); currentCard.clear();
databaseModel->getDatabase()->removeCard(cardToRemove); databaseModel->getDatabase()->removeCard(cardToRemove);
} }

View file

@ -261,7 +261,7 @@ int DlgFilterGames::getMaxPlayersFilterMax() const
QTime DlgFilterGames::getMaxGameAge() const QTime DlgFilterGames::getMaxGameAge() const
{ {
int index = maxGameAgeComboBox->currentIndex(); const int index = maxGameAgeComboBox->currentIndex();
if (index < 0 || index >= gameAgeMap.size()) { // index is out of bounds if (index < 0 || index >= gameAgeMap.size()) { // index is out of bounds
return gamesProxyModel->getMaxGameAge(); // leave the setting unchanged return gamesProxyModel->getMaxGameAge(); // leave the setting unchanged
} }

View file

@ -56,7 +56,7 @@ void DlgLoadDeckFromWebsite::accept()
if (DeckLinkToApiTransformer::parseDeckUrl(urlEdit->text(), info)) { if (DeckLinkToApiTransformer::parseDeckUrl(urlEdit->text(), info)) {
qCInfo(DlgLoadDeckFromWebsiteLog) << info.baseUrl << info.deckID << info.fullUrl; qCInfo(DlgLoadDeckFromWebsiteLog) << info.baseUrl << info.deckID << info.fullUrl;
auto jsonParser = createParserForProvider(info.provider); const auto jsonParser = createParserForProvider(info.provider);
if (!jsonParser && info.provider != DeckProvider::Deckstats && info.provider != DeckProvider::TappedOut) { if (!jsonParser && info.provider != DeckProvider::Deckstats && info.provider != DeckProvider::TappedOut) {
qCWarning(DlgLoadDeckFromWebsiteLog) << "No parser found for provider"; qCWarning(DlgLoadDeckFromWebsiteLog) << "No parser found for provider";
QMessageBox::warning(this, tr("Load Deck from Website"), QMessageBox::warning(this, tr("Load Deck from Website"),
@ -66,7 +66,7 @@ void DlgLoadDeckFromWebsite::accept()
return; return;
} }
QNetworkRequest request(QUrl(info.fullUrl)); const QNetworkRequest request(QUrl(info.fullUrl));
QNetworkReply *reply = nam->get(request); QNetworkReply *reply = nam->get(request);
QEventLoop loop; QEventLoop loop;
@ -81,7 +81,7 @@ void DlgLoadDeckFromWebsite::accept()
return; return;
} }
QByteArray responseData = reply->readAll(); const QByteArray responseData = reply->readAll();
reply->deleteLater(); reply->deleteLater();
// Special handling for Deckstats and TappedOut .txt // Special handling for Deckstats and TappedOut .txt
@ -107,7 +107,7 @@ void DlgLoadDeckFromWebsite::accept()
// Normal JSON parsing for other providers // Normal JSON parsing for other providers
QJsonParseError parseError; QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError); const QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);
if (parseError.error != QJsonParseError::NoError) { if (parseError.error != QJsonParseError::NoError) {
qCWarning(DlgLoadDeckFromWebsiteLog) << "JSON parse error:" << parseError.errorString(); qCWarning(DlgLoadDeckFromWebsiteLog) << "JSON parse error:" << parseError.errorString();
QMessageBox::warning(this, tr("Load Deck from Website"), QMessageBox::warning(this, tr("Load Deck from Website"),

View file

@ -326,19 +326,19 @@ void WndSets::actDisableSortButtons(int index)
void WndSets::actToggleButtons(const QItemSelection &selected, const QItemSelection &) void WndSets::actToggleButtons(const QItemSelection &selected, const QItemSelection &)
{ {
bool emptySelection = selected.empty(); const bool emptySelection = selected.empty();
aTop->setDisabled(emptySelection || setOrderIsSorted); aTop->setDisabled(emptySelection || setOrderIsSorted);
aUp->setDisabled(emptySelection || setOrderIsSorted); aUp->setDisabled(emptySelection || setOrderIsSorted);
aDown->setDisabled(emptySelection || setOrderIsSorted); aDown->setDisabled(emptySelection || setOrderIsSorted);
aBottom->setDisabled(emptySelection || setOrderIsSorted); aBottom->setDisabled(emptySelection || setOrderIsSorted);
int rows = view->selectionModel()->selectedRows().size(); const int rows = view->selectionModel()->selectedRows().size();
rebuildMainLayout((rows > 1) ? SOME_SETS_SELECTED : NO_SETS_SELECTED); rebuildMainLayout((rows > 1) ? SOME_SETS_SELECTED : NO_SETS_SELECTED);
} }
void WndSets::selectRows(QSet<int> rows) void WndSets::selectRows(QSet<int> rows)
{ {
for (auto i : rows) { for (const auto i : rows) {
QModelIndex idx = model->index(i, 0); QModelIndex idx = model->index(i, 0);
view->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); view->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows);
view->scrollTo(idx, QAbstractItemView::EnsureVisible); view->scrollTo(idx, QAbstractItemView::EnsureVisible);
@ -385,7 +385,7 @@ void WndSets::actUp()
for (auto i : rows) { for (auto i : rows) {
if (i.row() <= 0) if (i.row() <= 0)
continue; continue;
int oldRow = displayModel->mapToSource(i).row(); const int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() - 1; int newRow = i.row() - 1;
model->swapRows(oldRow, displayModel->mapToSource(displayModel->index(newRow, 0)).row()); model->swapRows(oldRow, displayModel->mapToSource(displayModel->index(newRow, 0)).row());
@ -408,7 +408,7 @@ void WndSets::actDown()
for (auto i : rows) { for (auto i : rows) {
if (i.row() >= displayModel->rowCount() - 1) if (i.row() >= displayModel->rowCount() - 1)
continue; continue;
int oldRow = displayModel->mapToSource(i).row(); const int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() + 1; int newRow = i.row() + 1;
model->swapRows(oldRow, displayModel->mapToSource(displayModel->index(newRow, 0)).row()); model->swapRows(oldRow, displayModel->mapToSource(displayModel->index(newRow, 0)).row());
@ -429,7 +429,7 @@ void WndSets::actTop()
return; return;
for (int i = 0; i < rows.length(); i++) { for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row(); const int oldRow = displayModel->mapToSource(rows.at(i)).row();
if (oldRow <= 0) { if (oldRow <= 0) {
newRow++; newRow++;
@ -455,7 +455,7 @@ void WndSets::actBottom()
return; return;
for (int i = 0; i < rows.length(); i++) { for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row(); const int oldRow = displayModel->mapToSource(rows.at(i)).row();
if (oldRow >= newRow) { if (oldRow >= newRow) {
newRow--; newRow--;

View file

@ -144,7 +144,7 @@ void DlgSelectSetForCards::retranslateUi()
void DlgSelectSetForCards::actOK() void DlgSelectSetForCards::actOK()
{ {
QMap<QString, QStringList> modifiedSetsAndCardsMap = getModifiedCards(); const QMap<QString, QStringList> modifiedSetsAndCardsMap = getModifiedCards();
for (QString modifiedSet : modifiedSetsAndCardsMap.keys()) { for (QString modifiedSet : modifiedSetsAndCardsMap.keys()) {
for (QString card : modifiedSetsAndCardsMap.value(modifiedSet)) { for (QString card : modifiedSetsAndCardsMap.value(modifiedSet)) {
QModelIndex find_card = model->findCard(card, DECK_ZONE_MAIN); QModelIndex find_card = model->findCard(card, DECK_ZONE_MAIN);
@ -205,13 +205,13 @@ QMap<QString, int> DlgSelectSetForCards::getSetsForCards()
if (!model) if (!model)
return setCounts; return setCounts;
DeckList *decklist = model->getDeckList(); const DeckList *decklist = model->getDeckList();
if (!decklist) if (!decklist)
return setCounts; return setCounts;
QList<DecklistCardNode *> cardsInDeck = decklist->getCardNodes(); QList<DecklistCardNode *> cardsInDeck = decklist->getCardNodes();
for (auto currentCard : cardsInDeck) { for (const auto currentCard : cardsInDeck) {
CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(currentCard->getName());
if (!infoPtr) if (!infoPtr)
continue; continue;
@ -248,13 +248,13 @@ void DlgSelectSetForCards::updateCardLists()
} }
} }
DeckList *decklist = model->getDeckList(); const DeckList *decklist = model->getDeckList();
if (!decklist) if (!decklist)
return; return;
QList<DecklistCardNode *> cardsInDeck = decklist->getCardNodes(); QList<DecklistCardNode *> cardsInDeck = decklist->getCardNodes();
for (auto currentCard : cardsInDeck) { for (const auto currentCard : cardsInDeck) {
bool found = false; bool found = false;
QString foundSetName; QString foundSetName;
@ -298,16 +298,16 @@ void DlgSelectSetForCards::dragEnterEvent(QDragEnterEvent *event)
void DlgSelectSetForCards::dropEvent(QDropEvent *event) void DlgSelectSetForCards::dropEvent(QDropEvent *event)
{ {
QByteArray itemData = event->mimeData()->data("application/x-setentrywidget"); const QByteArray itemData = event->mimeData()->data("application/x-setentrywidget");
QString draggedSetName = QString::fromUtf8(itemData); const QString draggedSetName = QString::fromUtf8(itemData);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QPoint adjustedPos = event->position().toPoint() + QPoint(0, scrollArea->verticalScrollBar()->value()); const QPoint adjustedPos = event->position().toPoint() + QPoint(0, scrollArea->verticalScrollBar()->value());
#else #else
QPoint adjustedPos = event->pos() + QPoint(0, scrollArea->verticalScrollBar()->value()); QPoint adjustedPos = event->pos() + QPoint(0, scrollArea->verticalScrollBar()->value());
#endif #endif
int dropIndex = -1; int dropIndex = -1;
for (int i = 0; i < listLayout->count(); ++i) { for (int i = 0; i < listLayout->count(); ++i) {
QWidget *widget = listLayout->itemAt(i)->widget(); const QWidget *widget = listLayout->itemAt(i)->widget();
if (widget && widget->geometry().contains(adjustedPos)) { if (widget && widget->geometry().contains(adjustedPos)) {
dropIndex = i; dropIndex = i;
break; break;
@ -337,13 +337,13 @@ QMap<QString, QStringList> DlgSelectSetForCards::getCardsForSets()
if (!model) if (!model)
return setCards; return setCards;
DeckList *decklist = model->getDeckList(); const DeckList *decklist = model->getDeckList();
if (!decklist) if (!decklist)
return setCards; return setCards;
QList<DecklistCardNode *> cardsInDeck = decklist->getCardNodes(); QList<DecklistCardNode *> cardsInDeck = decklist->getCardNodes();
for (auto currentCard : cardsInDeck) { for (const auto currentCard : cardsInDeck) {
CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(currentCard->getName());
if (!infoPtr) if (!infoPtr)
continue; continue;
@ -362,7 +362,7 @@ QMap<QString, QStringList> DlgSelectSetForCards::getModifiedCards()
QMap<QString, QStringList> modifiedCards; QMap<QString, QStringList> modifiedCards;
for (int i = 0; i < listLayout->count(); ++i) { for (int i = 0; i < listLayout->count(); ++i) {
QWidget *widget = listLayout->itemAt(i)->widget(); QWidget *widget = listLayout->itemAt(i)->widget();
if (auto entry = qobject_cast<SetEntryWidget *>(widget)) { if (const auto entry = qobject_cast<SetEntryWidget *>(widget)) {
if (entry->isChecked()) { if (entry->isChecked()) {
QStringList cardsInSet = entry->getAllCardsForSet(); QStringList cardsInSet = entry->getAllCardsForSet();
@ -388,7 +388,7 @@ void DlgSelectSetForCards::updateLayoutOrder()
entry_widgets.clear(); entry_widgets.clear();
for (int i = 0; i < listLayout->count(); ++i) { for (int i = 0; i < listLayout->count(); ++i) {
QWidget *widget = listLayout->itemAt(i)->widget(); QWidget *widget = listLayout->itemAt(i)->widget();
if (auto entry = qobject_cast<SetEntryWidget *>(widget)) { if (const auto entry = qobject_cast<SetEntryWidget *>(widget)) {
entry_widgets.append(entry); entry_widgets.append(entry);
} }
} }
@ -403,7 +403,7 @@ SetEntryWidget::SetEntryWidget(DlgSelectSetForCards *_parent, const QString &_se
setLayout(layout); setLayout(layout);
QHBoxLayout *headerLayout = new QHBoxLayout(); QHBoxLayout *headerLayout = new QHBoxLayout();
CardSetPtr set = CardDatabaseManager::getInstance()->getSet(setName); const CardSetPtr set = CardDatabaseManager::getInstance()->getSet(setName);
checkBox = new QCheckBox("(" + set->getShortName() + ") - " + set->getLongName(), this); checkBox = new QCheckBox("(" + set->getShortName() + ") - " + set->getLongName(), this);
connect(checkBox, &QCheckBox::toggled, parent, &DlgSelectSetForCards::updateLayoutOrder); connect(checkBox, &QCheckBox::toggled, parent, &DlgSelectSetForCards::updateLayoutOrder);
expandButton = new QPushButton("+", this); expandButton = new QPushButton("+", this);
@ -510,7 +510,7 @@ void SetEntryWidget::dragMoveEvent(QDragMoveEvent *event)
// For now, we will just highlight the widget when dragged. // For now, we will just highlight the widget when dragged.
QPainter painter(this); QPainter painter(this);
QColor highlightColor(255, 255, 255, 128); // Semi-transparent white const QColor highlightColor(255, 255, 255, 128); // Semi-transparent white
painter.setBrush(QBrush(highlightColor)); painter.setBrush(QBrush(highlightColor));
painter.setPen(Qt::NoPen); painter.setPen(Qt::NoPen);
painter.drawRect(this->rect()); // Highlight the widget area painter.drawRect(this->rect()); // Highlight the widget area
@ -594,14 +594,16 @@ void SetEntryWidget::updateCardDisplayWidgets()
for (const QString &cardName : possibleCards) { for (const QString &cardName : possibleCards) {
CardInfoPictureWidget *picture_widget = new CardInfoPictureWidget(cardListContainer); CardInfoPictureWidget *picture_widget = new CardInfoPictureWidget(cardListContainer);
QString providerId = CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid(); const QString providerId =
CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid();
picture_widget->setCard(CardDatabaseManager::query()->getCard({cardName, providerId})); picture_widget->setCard(CardDatabaseManager::query()->getCard({cardName, providerId}));
cardListContainer->addWidget(picture_widget); cardListContainer->addWidget(picture_widget);
} }
for (const QString &cardName : unusedCards) { for (const QString &cardName : unusedCards) {
CardInfoPictureWidget *picture_widget = new CardInfoPictureWidget(alreadySelectedCardListContainer); CardInfoPictureWidget *picture_widget = new CardInfoPictureWidget(alreadySelectedCardListContainer);
QString providerId = CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid(); const QString providerId =
CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid();
picture_widget->setCard(CardDatabaseManager::query()->getCard({cardName, providerId})); picture_widget->setCard(CardDatabaseManager::query()->getCard({cardName, providerId}));
alreadySelectedCardListContainer->addWidget(picture_widget); alreadySelectedCardListContainer->addWidget(picture_widget);
} }

View file

@ -68,8 +68,8 @@ GeneralSettingsPage::GeneralSettingsPage()
languageBox.addItem(langName, code); languageBox.addItem(langName, code);
} }
QString setLanguage = QCoreApplication::translate("i18n", DEFAULT_LANG_NAME); const QString setLanguage = QCoreApplication::translate("i18n", DEFAULT_LANG_NAME);
int index = languageBox.findText(setLanguage, Qt::MatchExactly); const int index = languageBox.findText(setLanguage, Qt::MatchExactly);
if (index == -1) { if (index == -1) {
qWarning() << "could not find language" << setLanguage; qWarning() << "could not find language" << setLanguage;
} else { } else {
@ -77,7 +77,7 @@ GeneralSettingsPage::GeneralSettingsPage()
} }
// updates // updates
SettingsCache &settings = SettingsCache::instance(); const SettingsCache &settings = SettingsCache::instance();
startupUpdateCheckCheckBox.setChecked(settings.getCheckUpdatesOnStartup()); startupUpdateCheckCheckBox.setChecked(settings.getCheckUpdatesOnStartup());
startupCardUpdateCheckBehaviorSelector.addItem(""); // these will be set in retranslateUI startupCardUpdateCheckBehaviorSelector.addItem(""); // these will be set in retranslateUI
@ -178,7 +178,7 @@ GeneralSettingsPage::GeneralSettingsPage()
// Required init here to avoid crashing on Portable builds // Required init here to avoid crashing on Portable builds
resetAllPathsButton = new QPushButton; resetAllPathsButton = new QPushButton;
bool isPortable = settings.getIsPortableBuild(); const bool isPortable = settings.getIsPortableBuild();
if (isPortable) { if (isPortable) {
deckPathEdit->setEnabled(false); deckPathEdit->setEnabled(false);
filtersPathEdit->setEnabled(false); filtersPathEdit->setEnabled(false);
@ -249,7 +249,7 @@ GeneralSettingsPage::GeneralSettingsPage()
QStringList GeneralSettingsPage::findQmFiles() QStringList GeneralSettingsPage::findQmFiles()
{ {
QDir dir(translationPath); const QDir dir(translationPath);
QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name); QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name);
fileNames.replaceInStrings(QRegularExpression(translationPrefix + "_(.*)\\.qm"), "\\1"); fileNames.replaceInStrings(QRegularExpression(translationPrefix + "_(.*)\\.qm"), "\\1");
return fileNames; return fileNames;
@ -259,8 +259,8 @@ QString GeneralSettingsPage::languageName(const QString &lang)
{ {
QTranslator qTranslator; QTranslator qTranslator;
QString appNameHint = translationPrefix + "_" + lang; const QString appNameHint = translationPrefix + "_" + lang;
bool appTranslationLoaded = qTranslator.load(appNameHint, translationPath); const bool appTranslationLoaded = qTranslator.load(appNameHint, translationPath);
if (!appTranslationLoaded) { if (!appTranslationLoaded) {
qCWarning(DlgSettingsLog) << "Unable to load" << translationPrefix << "translation" << appNameHint << "at" qCWarning(DlgSettingsLog) << "Unable to load" << translationPrefix << "translation" << appNameHint << "at"
<< translationPath; << translationPath;
@ -271,7 +271,7 @@ QString GeneralSettingsPage::languageName(const QString &lang)
void GeneralSettingsPage::deckPathButtonClicked() void GeneralSettingsPage::deckPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), deckPathEdit->text()); const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), deckPathEdit->text());
if (path.isEmpty()) if (path.isEmpty())
return; return;
@ -281,7 +281,7 @@ void GeneralSettingsPage::deckPathButtonClicked()
void GeneralSettingsPage::filtersPathButtonClicked() void GeneralSettingsPage::filtersPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), filtersPathEdit->text()); const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), filtersPathEdit->text());
if (path.isEmpty()) if (path.isEmpty())
return; return;
@ -291,7 +291,7 @@ void GeneralSettingsPage::filtersPathButtonClicked()
void GeneralSettingsPage::replaysPathButtonClicked() void GeneralSettingsPage::replaysPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), replaysPathEdit->text()); const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), replaysPathEdit->text());
if (path.isEmpty()) if (path.isEmpty())
return; return;
@ -301,7 +301,7 @@ void GeneralSettingsPage::replaysPathButtonClicked()
void GeneralSettingsPage::picsPathButtonClicked() void GeneralSettingsPage::picsPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), picsPathEdit->text()); const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), picsPathEdit->text());
if (path.isEmpty()) if (path.isEmpty())
return; return;
@ -311,7 +311,7 @@ void GeneralSettingsPage::picsPathButtonClicked()
void GeneralSettingsPage::cardDatabasePathButtonClicked() void GeneralSettingsPage::cardDatabasePathButtonClicked()
{ {
QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), cardDatabasePathEdit->text()); const QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), cardDatabasePathEdit->text());
if (path.isEmpty()) if (path.isEmpty())
return; return;
@ -321,7 +321,7 @@ void GeneralSettingsPage::cardDatabasePathButtonClicked()
void GeneralSettingsPage::customCardDatabaseButtonClicked() void GeneralSettingsPage::customCardDatabaseButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), customCardDatabasePathEdit->text()); const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), customCardDatabasePathEdit->text());
if (path.isEmpty()) if (path.isEmpty())
return; return;
@ -331,7 +331,7 @@ void GeneralSettingsPage::customCardDatabaseButtonClicked()
void GeneralSettingsPage::tokenDatabasePathButtonClicked() void GeneralSettingsPage::tokenDatabasePathButtonClicked()
{ {
QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), tokenDatabasePathEdit->text()); const QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), tokenDatabasePathEdit->text());
if (path.isEmpty()) if (path.isEmpty())
return; return;
@ -393,16 +393,16 @@ void GeneralSettingsPage::retranslateUi()
const auto &settings = SettingsCache::instance(); const auto &settings = SettingsCache::instance();
QDate lastCheckDate = settings.getLastCardUpdateCheck(); const QDate lastCheckDate = settings.getLastCardUpdateCheck();
int daysAgo = lastCheckDate.daysTo(QDate::currentDate()); const int daysAgo = lastCheckDate.daysTo(QDate::currentDate());
lastCardUpdateCheckDateLabel.setText( lastCardUpdateCheckDateLabel.setText(
tr("Last update check on %1 (%2 days ago)").arg(lastCheckDate.toString()).arg(daysAgo)); tr("Last update check on %1 (%2 days ago)").arg(lastCheckDate.toString()).arg(daysAgo));
// We can't change the strings after they're put into the QComboBox, so this is our workaround // We can't change the strings after they're put into the QComboBox, so this is our workaround
int oldIndex = updateReleaseChannelBox.currentIndex(); const int oldIndex = updateReleaseChannelBox.currentIndex();
updateReleaseChannelBox.clear(); updateReleaseChannelBox.clear();
for (ReleaseChannel *chan : settings.getUpdateReleaseChannels()) { for (const ReleaseChannel *chan : settings.getUpdateReleaseChannels()) {
updateReleaseChannelBox.addItem(tr(chan->getName().toUtf8())); updateReleaseChannelBox.addItem(tr(chan->getName().toUtf8()));
} }
updateReleaseChannelBox.setCurrentIndex(oldIndex); updateReleaseChannelBox.setCurrentIndex(oldIndex);
@ -410,10 +410,10 @@ void GeneralSettingsPage::retranslateUi()
AppearanceSettingsPage::AppearanceSettingsPage() AppearanceSettingsPage::AppearanceSettingsPage()
{ {
SettingsCache &settings = SettingsCache::instance(); const SettingsCache &settings = SettingsCache::instance();
// Theme settings // Theme settings
QString themeName = SettingsCache::instance().getThemeName(); const QString themeName = SettingsCache::instance().getThemeName();
QStringList themeDirs = themeManager->getAvailableThemes().keys(); QStringList themeDirs = themeManager->getAvailableThemes().keys();
for (int i = 0; i < themeDirs.size(); i++) { for (int i = 0; i < themeDirs.size(); i++) {
@ -429,15 +429,15 @@ AppearanceSettingsPage::AppearanceSettingsPage()
homeTabBackgroundSourceBox.addItem(QObject::tr(entry.trKey), QVariant::fromValue(entry.type)); homeTabBackgroundSourceBox.addItem(QObject::tr(entry.trKey), QVariant::fromValue(entry.type));
} }
QString homeTabBackgroundSource = SettingsCache::instance().getHomeTabBackgroundSource(); const QString homeTabBackgroundSource = SettingsCache::instance().getHomeTabBackgroundSource();
int homeTabBackgroundSourceId = const int homeTabBackgroundSourceId =
homeTabBackgroundSourceBox.findData(BackgroundSources::fromId(homeTabBackgroundSource)); homeTabBackgroundSourceBox.findData(BackgroundSources::fromId(homeTabBackgroundSource));
if (homeTabBackgroundSourceId != -1) { if (homeTabBackgroundSourceId != -1) {
homeTabBackgroundSourceBox.setCurrentIndex(homeTabBackgroundSourceId); homeTabBackgroundSourceBox.setCurrentIndex(homeTabBackgroundSourceId);
} }
connect(&homeTabBackgroundSourceBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this]() { connect(&homeTabBackgroundSourceBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this]() {
auto type = homeTabBackgroundSourceBox.currentData().value<BackgroundSources::Type>(); const auto type = homeTabBackgroundSourceBox.currentData().value<BackgroundSources::Type>();
SettingsCache::instance().setHomeTabBackgroundSource(BackgroundSources::toId(type)); SettingsCache::instance().setHomeTabBackgroundSource(BackgroundSources::toId(type));
}); });
@ -545,7 +545,7 @@ AppearanceSettingsPage::AppearanceSettingsPage()
connect(pushButton, &QPushButton::clicked, this, [index, this]() { connect(pushButton, &QPushButton::clicked, this, [index, this]() {
auto &cardCounterSettings = SettingsCache::instance().cardCounters(); auto &cardCounterSettings = SettingsCache::instance().cardCounters();
auto newColor = QColorDialog::getColor(cardCounterSettings.color(index), this); const auto newColor = QColorDialog::getColor(cardCounterSettings.color(index), this);
if (!newColor.isValid()) if (!newColor.isValid())
return; return;
@ -555,8 +555,8 @@ AppearanceSettingsPage::AppearanceSettingsPage()
auto *colorName = new QLabel; auto *colorName = new QLabel;
cardCounterNames.append(colorName); cardCounterNames.append(colorName);
int row = index / 3; const int row = index / 3;
int column = 2 * (index % 3); const int column = 2 * (index % 3);
cardCounterColorsLayout->addWidget(pushButton, row, column); cardCounterColorsLayout->addWidget(pushButton, row, column);
cardCounterColorsLayout->addWidget(colorName, row, column + 1); cardCounterColorsLayout->addWidget(colorName, row, column + 1);
@ -628,14 +628,14 @@ AppearanceSettingsPage::AppearanceSettingsPage()
void AppearanceSettingsPage::themeBoxChanged(int index) void AppearanceSettingsPage::themeBoxChanged(int index)
{ {
QStringList themeDirs = themeManager->getAvailableThemes().keys(); const QStringList themeDirs = themeManager->getAvailableThemes().keys();
if (index >= 0 && index < themeDirs.count()) if (index >= 0 && index < themeDirs.count())
SettingsCache::instance().setThemeName(themeDirs.at(index)); SettingsCache::instance().setThemeName(themeDirs.at(index));
} }
void AppearanceSettingsPage::openThemeLocation() void AppearanceSettingsPage::openThemeLocation()
{ {
QString dir = SettingsCache::instance().getThemesPath(); const QString dir = SettingsCache::instance().getThemesPath();
QDir dirDir = dir; QDir dirDir = dir;
dirDir.cdUp(); dirDir.cdUp();
// open if dir exists, create if parent dir does exist // open if dir exists, create if parent dir does exist
@ -673,7 +673,7 @@ void AppearanceSettingsPage::overrideAllCardArtWithPersonalPreferenceToggled(QT_
"Are you sure you would like to disable this feature?"); "Are you sure you would like to disable this feature?");
} }
QMessageBox::StandardButton result = const QMessageBox::StandardButton result =
QMessageBox::question(this, tr("Confirm Change"), message, QMessageBox::Yes | QMessageBox::No); QMessageBox::question(this, tr("Confirm Change"), message, QMessageBox::Yes | QMessageBox::No);
if (result == QMessageBox::Yes) { if (result == QMessageBox::Yes) {
@ -747,7 +747,7 @@ void AppearanceSettingsPage::retranslateUi()
cardCountersGroupBox->setTitle(tr("Card counters")); cardCountersGroupBox->setTitle(tr("Card counters"));
auto &cardCounterSettings = SettingsCache::instance().cardCounters(); const auto &cardCounterSettings = SettingsCache::instance().cardCounters();
for (int index = 0; index < cardCounterNames.size(); ++index) { for (int index = 0; index < cardCounterNames.size(); ++index) {
cardCounterNames[index]->setText(tr("Counter %1").arg(cardCounterSettings.displayName(index))); cardCounterNames[index]->setText(tr("Counter %1").arg(cardCounterSettings.displayName(index)));
} }
@ -1059,17 +1059,17 @@ DeckEditorSettingsPage::DeckEditorSettingsPage()
networkRedirectCacheTtlEdit.setSingleStep(1); networkRedirectCacheTtlEdit.setSingleStep(1);
networkRedirectCacheTtlEdit.setValue(SettingsCache::instance().getRedirectCacheTtl()); networkRedirectCacheTtlEdit.setValue(SettingsCache::instance().getRedirectCacheTtl());
auto networkCacheLayout = new QHBoxLayout; const auto networkCacheLayout = new QHBoxLayout;
networkCacheLayout->addStretch(); networkCacheLayout->addStretch();
networkCacheLayout->addWidget(&networkCacheLabel); networkCacheLayout->addWidget(&networkCacheLabel);
networkCacheLayout->addWidget(&networkCacheEdit); networkCacheLayout->addWidget(&networkCacheEdit);
auto networkRedirectCacheLayout = new QHBoxLayout; const auto networkRedirectCacheLayout = new QHBoxLayout;
networkRedirectCacheLayout->addStretch(); networkRedirectCacheLayout->addStretch();
networkRedirectCacheLayout->addWidget(&networkRedirectCacheTtlLabel); networkRedirectCacheLayout->addWidget(&networkRedirectCacheTtlLabel);
networkRedirectCacheLayout->addWidget(&networkRedirectCacheTtlEdit); networkRedirectCacheLayout->addWidget(&networkRedirectCacheTtlEdit);
auto pixmapCacheLayout = new QHBoxLayout; const auto pixmapCacheLayout = new QHBoxLayout;
pixmapCacheLayout->addStretch(); pixmapCacheLayout->addStretch();
pixmapCacheLayout->addWidget(&pixmapCacheLabel); pixmapCacheLayout->addWidget(&pixmapCacheLabel);
pixmapCacheLayout->addWidget(&pixmapCacheEdit); pixmapCacheLayout->addWidget(&pixmapCacheEdit);
@ -1135,7 +1135,7 @@ void DeckEditorSettingsPage::clearDownloadedPicsButtonClicked()
// These are not used anymore, but we don't delete them automatically, so // These are not used anymore, but we don't delete them automatically, so
// we should do it here lest we leave pictures hanging around on users' // we should do it here lest we leave pictures hanging around on users'
// machines. // machines.
QString picsPath = SettingsCache::instance().getPicsPath() + "/downloadedPics/"; const QString picsPath = SettingsCache::instance().getPicsPath() + "/downloadedPics/";
QStringList dirs = QDir(picsPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot); QStringList dirs = QDir(picsPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
bool outerSuccessRemove = true; bool outerSuccessRemove = true;
for (const auto &dir : dirs) { for (const auto &dir : dirs) {
@ -1152,7 +1152,7 @@ void DeckEditorSettingsPage::clearDownloadedPicsButtonClicked()
} }
if (innerSuccessRemove) { if (innerSuccessRemove) {
bool success = QDir(picsPath).rmdir(dir); const bool success = QDir(picsPath).rmdir(dir);
if (!success) { if (!success) {
qInfo() << "Failed to remove inner directory" << picsPath; qInfo() << "Failed to remove inner directory" << picsPath;
} else { } else {
@ -1171,7 +1171,7 @@ void DeckEditorSettingsPage::clearDownloadedPicsButtonClicked()
void DeckEditorSettingsPage::actAddURL() void DeckEditorSettingsPage::actAddURL()
{ {
bool ok; bool ok;
QString msg = QInputDialog::getText(this, tr("Add URL"), tr("URL:"), QLineEdit::Normal, QString(), &ok); const QString msg = QInputDialog::getText(this, tr("Add URL"), tr("URL:"), QLineEdit::Normal, QString(), &ok);
if (ok) { if (ok) {
urlList->addItem(msg); urlList->addItem(msg);
storeSettings(); storeSettings();
@ -1189,9 +1189,9 @@ void DeckEditorSettingsPage::actRemoveURL()
void DeckEditorSettingsPage::actEditURL() void DeckEditorSettingsPage::actEditURL()
{ {
if (urlList->currentItem()) { if (urlList->currentItem()) {
QString oldText = urlList->currentItem()->text(); const QString oldText = urlList->currentItem()->text();
bool ok; bool ok;
QString msg = QInputDialog::getText(this, tr("Edit URL"), tr("URL:"), QLineEdit::Normal, oldText, &ok); const QString msg = QInputDialog::getText(this, tr("Edit URL"), tr("URL:"), QLineEdit::Normal, oldText, &ok);
if (ok) { if (ok) {
urlList->currentItem()->setText(msg); urlList->currentItem()->setText(msg);
storeSettings(); storeSettings();
@ -1223,7 +1223,7 @@ void DeckEditorSettingsPage::updateSpoilers()
updateNowButton->setText(tr("Updating...")); updateNowButton->setText(tr("Updating..."));
// Create a new SBU that will act as if the client was just reloaded // Create a new SBU that will act as if the client was just reloaded
auto *sbu = new SpoilerBackgroundUpdater(); const auto *sbu = new SpoilerBackgroundUpdater();
connect(sbu, &SpoilerBackgroundUpdater::spoilerCheckerDone, this, &DeckEditorSettingsPage::unlockSettings); connect(sbu, &SpoilerBackgroundUpdater::spoilerCheckerDone, this, &DeckEditorSettingsPage::unlockSettings);
connect(sbu, &SpoilerBackgroundUpdater::spoilersUpdatedSuccessfully, this, &DeckEditorSettingsPage::unlockSettings); connect(sbu, &SpoilerBackgroundUpdater::spoilersUpdatedSuccessfully, this, &DeckEditorSettingsPage::unlockSettings);
} }
@ -1236,10 +1236,10 @@ void DeckEditorSettingsPage::unlockSettings()
QString DeckEditorSettingsPage::getLastUpdateTime() QString DeckEditorSettingsPage::getLastUpdateTime()
{ {
QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); const QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath();
QFileInfo fi(fileName); const QFileInfo fi(fileName);
QDir fileDir(fi.path()); QDir fileDir(fi.path());
QFile file(fileName); const QFile file(fileName);
if (file.exists()) { if (file.exists()) {
return fi.lastModified().toString("MMM d, hh:mm"); return fi.lastModified().toString("MMM d, hh:mm");
@ -1250,7 +1250,8 @@ QString DeckEditorSettingsPage::getLastUpdateTime()
void DeckEditorSettingsPage::spoilerPathButtonClicked() void DeckEditorSettingsPage::spoilerPathButtonClicked()
{ {
QString lsPath = QFileDialog::getExistingDirectory(this, tr("Choose path"), mpSpoilerSavePathLineEdit->text()); const QString lsPath =
QFileDialog::getExistingDirectory(this, tr("Choose path"), mpSpoilerSavePathLineEdit->text());
if (lsPath.isEmpty()) { if (lsPath.isEmpty()) {
return; return;
} }
@ -1378,7 +1379,7 @@ MessagesSettingsPage::MessagesSettingsPage()
messageList = new QListWidget; messageList = new QListWidget;
int count = SettingsCache::instance().messages().getCount(); const int count = SettingsCache::instance().messages().getCount();
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
messageList->addItem(SettingsCache::instance().messages().getMessageAt(i)); messageList->addItem(SettingsCache::instance().messages().getMessageAt(i));
@ -1426,7 +1427,7 @@ MessagesSettingsPage::MessagesSettingsPage()
void MessagesSettingsPage::updateColor(const QString &value) void MessagesSettingsPage::updateColor(const QString &value)
{ {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0))
QColor colorToSet = QColor::fromString("#" + value); const QColor colorToSet = QColor::fromString("#" + value);
#else #else
QColor colorToSet; QColor colorToSet;
colorToSet.setNamedColor("#" + value); colorToSet.setNamedColor("#" + value);
@ -1440,7 +1441,7 @@ void MessagesSettingsPage::updateColor(const QString &value)
void MessagesSettingsPage::updateHighlightColor(const QString &value) void MessagesSettingsPage::updateHighlightColor(const QString &value)
{ {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0))
QColor colorToSet = QColor::fromString("#" + value); const QColor colorToSet = QColor::fromString("#" + value);
#else #else
QColor colorToSet; QColor colorToSet;
colorToSet.setNamedColor("#" + value); colorToSet.setNamedColor("#" + value);
@ -1488,7 +1489,7 @@ void MessagesSettingsPage::storeSettings()
void MessagesSettingsPage::actAdd() void MessagesSettingsPage::actAdd()
{ {
bool ok; bool ok;
QString msg = const QString msg =
getTextWithMax(this, tr("Add message"), tr("Message:"), QLineEdit::Normal, QString(), &ok, MAX_TEXT_LENGTH); getTextWithMax(this, tr("Add message"), tr("Message:"), QLineEdit::Normal, QString(), &ok, MAX_TEXT_LENGTH);
if (ok) { if (ok) {
messageList->addItem(msg); messageList->addItem(msg);
@ -1499,9 +1500,9 @@ void MessagesSettingsPage::actAdd()
void MessagesSettingsPage::actEdit() void MessagesSettingsPage::actEdit()
{ {
if (messageList->currentItem()) { if (messageList->currentItem()) {
QString oldText = messageList->currentItem()->text(); const QString oldText = messageList->currentItem()->text();
bool ok; bool ok;
QString msg = const QString msg =
getTextWithMax(this, tr("Edit message"), tr("Message:"), QLineEdit::Normal, oldText, &ok, MAX_TEXT_LENGTH); getTextWithMax(this, tr("Edit message"), tr("Message:"), QLineEdit::Normal, oldText, &ok, MAX_TEXT_LENGTH);
if (ok) { if (ok) {
messageList->currentItem()->setText(msg); messageList->currentItem()->setText(msg);
@ -1549,7 +1550,7 @@ SoundSettingsPage::SoundSettingsPage()
connect(&soundEnabledCheckBox, &QCheckBox::QT_STATE_CHANGED, &SettingsCache::instance(), connect(&soundEnabledCheckBox, &QCheckBox::QT_STATE_CHANGED, &SettingsCache::instance(),
&SettingsCache::setSoundEnabled); &SettingsCache::setSoundEnabled);
QString themeName = SettingsCache::instance().getSoundThemeName(); const QString themeName = SettingsCache::instance().getSoundThemeName();
QStringList themeDirs = soundEngine->getAvailableThemes().keys(); QStringList themeDirs = soundEngine->getAvailableThemes().keys();
for (int i = 0; i < themeDirs.size(); i++) { for (int i = 0; i < themeDirs.size(); i++) {
@ -1602,7 +1603,7 @@ SoundSettingsPage::SoundSettingsPage()
void SoundSettingsPage::themeBoxChanged(int index) void SoundSettingsPage::themeBoxChanged(int index)
{ {
QStringList themeDirs = soundEngine->getAvailableThemes().keys(); const QStringList themeDirs = soundEngine->getAvailableThemes().keys();
if (index >= 0 && index < themeDirs.count()) if (index >= 0 && index < themeDirs.count())
SettingsCache::instance().setSoundThemeName(themeDirs.at(index)); SettingsCache::instance().setSoundThemeName(themeDirs.at(index));
} }
@ -1702,8 +1703,8 @@ void ShortcutSettingsPage::currentItemChanged(const QString &key)
currentActionName->setText(""); currentActionName->setText("");
editTextBox->setShortcutName(""); editTextBox->setShortcutName("");
} else { } else {
QString group = SettingsCache::instance().shortcuts().getShortcut(key).getGroupName(); const QString group = SettingsCache::instance().shortcuts().getShortcut(key).getGroupName();
QString action = SettingsCache::instance().shortcuts().getShortcut(key).getName(); const QString action = SettingsCache::instance().shortcuts().getShortcut(key).getName();
currentActionGroupName->setText(group); currentActionGroupName->setText(group);
currentActionName->setText(action); currentActionName->setText(action);
editTextBox->setShortcutName(key); editTextBox->setShortcutName(key);
@ -1755,7 +1756,7 @@ static QScrollArea *makeScrollable(QWidget *widget)
DlgSettings::DlgSettings(QWidget *parent) : QDialog(parent) DlgSettings::DlgSettings(QWidget *parent) : QDialog(parent)
{ {
auto rec = QGuiApplication::primaryScreen()->availableGeometry(); const auto rec = QGuiApplication::primaryScreen()->availableGeometry();
this->setMinimumSize(qMin(700, rec.width()), qMin(700, rec.height())); this->setMinimumSize(qMin(700, rec.width()), qMin(700, rec.height()));
connect(&SettingsCache::instance(), &SettingsCache::langChanged, this, &DlgSettings::updateLanguage); connect(&SettingsCache::instance(), &SettingsCache::langChanged, this, &DlgSettings::updateLanguage);
@ -1865,7 +1866,7 @@ void DlgSettings::closeEvent(QCloseEvent *event)
{ {
bool showLoadError = true; bool showLoadError = true;
QString loadErrorMessage = tr("Unknown Error loading card database"); QString loadErrorMessage = tr("Unknown Error loading card database");
LoadStatus loadStatus = CardDatabaseManager::getInstance()->getLoadStatus(); const LoadStatus loadStatus = CardDatabaseManager::getInstance()->getLoadStatus();
qCInfo(DlgSettingsLog) << "Card Database load status: " << loadStatus; qCInfo(DlgSettingsLog) << "Card Database load status: " << loadStatus;
switch (loadStatus) { switch (loadStatus) {
case Ok: case Ok:

View file

@ -10,8 +10,8 @@ DlgStartupCardCheck::DlgStartupCardCheck(QWidget *parent) : QDialog(parent)
layout = new QVBoxLayout(this); layout = new QVBoxLayout(this);
QDate lastCheckDate = SettingsCache::instance().getLastCardUpdateCheck(); const QDate lastCheckDate = SettingsCache::instance().getLastCardUpdateCheck();
int daysAgo = lastCheckDate.daysTo(QDate::currentDate()); const int daysAgo = lastCheckDate.daysTo(QDate::currentDate());
instructionLabel = new QLabel( instructionLabel = new QLabel(
tr("It has been more than %2 days since you last checked your card database for updates.\nChoose how you would " tr("It has been more than %2 days since you last checked your card database for updates.\nChoose how you would "

View file

@ -19,7 +19,7 @@
DlgTipOfTheDay::DlgTipOfTheDay(QWidget *parent) : QDialog(parent) DlgTipOfTheDay::DlgTipOfTheDay(QWidget *parent) : QDialog(parent)
{ {
successfulInit = false; successfulInit = false;
QString xmlPath = "theme:tips/tips_of_the_day.xml"; const QString xmlPath = "theme:tips/tips_of_the_day.xml";
tipDatabase = new TipsOfTheDay(xmlPath, this); tipDatabase = new TipsOfTheDay(xmlPath, this);
if (tipDatabase->rowCount() == 0) { if (tipDatabase->rowCount() == 0) {
@ -42,7 +42,7 @@ DlgTipOfTheDay::DlgTipOfTheDay(QWidget *parent) : QDialog(parent)
tipNumber = new QLabel(); tipNumber = new QLabel();
tipNumber->setAlignment(Qt::AlignCenter); tipNumber->setAlignment(Qt::AlignCenter);
QList<int> seenTips = SettingsCache::instance().getSeenTips(); const QList<int> seenTips = SettingsCache::instance().getSeenTips();
newTipsAvailable = false; newTipsAvailable = false;
currentTip = 0; currentTip = 0;
for (int i = 0; i < tipDatabase->rowCount(); i++) { for (int i = 0; i < tipDatabase->rowCount(); i++) {
@ -137,7 +137,7 @@ void DlgTipOfTheDay::updateTip(int tipId)
SettingsCache::instance().setSeenTips(seenTips); SettingsCache::instance().setSeenTips(seenTips);
} }
TipOfTheDay tip = tipDatabase->getTip(tipId); const TipOfTheDay tip = tipDatabase->getTip(tipId);
titleText = tip.getTitle(); titleText = tip.getTitle();
contentText = tip.getContent(); contentText = tip.getContent();
imagePath = tip.getImagePath(); imagePath = tip.getImagePath();
@ -150,8 +150,8 @@ void DlgTipOfTheDay::updateTip(int tipId)
qCWarning(DlgTipOfTheDayLog) << "Image failed to load from" << imagePath; qCWarning(DlgTipOfTheDayLog) << "Image failed to load from" << imagePath;
imageLabel->clear(); imageLabel->clear();
} else { } else {
int h = std::min(std::max(imageLabel->height(), MIN_TIP_IMAGE_HEIGHT), MAX_TIP_IMAGE_HEIGHT); const int h = std::min(std::max(imageLabel->height(), MIN_TIP_IMAGE_HEIGHT), MAX_TIP_IMAGE_HEIGHT);
int w = std::min(std::max(imageLabel->width(), MIN_TIP_IMAGE_WIDTH), MAX_TIP_IMAGE_WIDTH); const int w = std::min(std::max(imageLabel->width(), MIN_TIP_IMAGE_WIDTH), MAX_TIP_IMAGE_WIDTH);
imageLabel->setPixmap(image->scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation)); imageLabel->setPixmap(image->scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation));
} }

View file

@ -108,7 +108,7 @@ void DlgUpdate::beginUpdateCheck()
progress->setMaximum(0); progress->setMaximum(0);
setLabel(tr("Checking for updates...")); setLabel(tr("Checking for updates..."));
auto checker = new ClientUpdateChecker(this); const auto checker = new ClientUpdateChecker(this);
connect(checker, &ClientUpdateChecker::finishedCheck, this, &DlgUpdate::finishedUpdateCheck); connect(checker, &ClientUpdateChecker::finishedCheck, this, &DlgUpdate::finishedUpdateCheck);
connect(checker, &ClientUpdateChecker::error, this, &DlgUpdate::updateCheckError); connect(checker, &ClientUpdateChecker::error, this, &DlgUpdate::updateCheckError);
checker->check(); checker->check();

View file

@ -76,7 +76,7 @@ QVariant TipsOfTheDay::data(const QModelIndex &index, int /*role*/) const
if (!index.isValid() || index.row() >= tipList->size() || index.column() >= TIPDDBMODEL_COLUMNS) if (!index.isValid() || index.row() >= tipList->size() || index.column() >= TIPDDBMODEL_COLUMNS)
return QVariant(); return QVariant();
TipOfTheDay tip = tipList->at(index.row()); const TipOfTheDay tip = tipList->at(index.row());
switch (index.column()) { switch (index.column()) {
case TitleColumn: case TitleColumn:
return tip.getTitle(); return tip.getTitle();

View file

@ -10,7 +10,7 @@
BannerWidget::BannerWidget(QWidget *parent, const QString &text, Qt::Orientation orientation, int transparency) BannerWidget::BannerWidget(QWidget *parent, const QString &text, Qt::Orientation orientation, int transparency)
: QWidget(parent), gradientOrientation(orientation), transparency(qBound(0, transparency, 100)) : QWidget(parent), gradientOrientation(orientation), transparency(qBound(0, transparency, 100))
{ {
auto layout = new QHBoxLayout(this); const auto layout = new QHBoxLayout(this);
iconLabel = new QLabel(this); iconLabel = new QLabel(this);
iconLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); iconLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
@ -82,7 +82,7 @@ void BannerWidget::paintEvent(QPaintEvent *event)
QPainter painter(this); QPainter painter(this);
// Calculate alpha based on transparency percentage // Calculate alpha based on transparency percentage
int alpha = (255 * transparency) / 100; const int alpha = (255 * transparency) / 100;
// Determine gradient direction // Determine gradient direction
QLinearGradient gradient; QLinearGradient gradient;

View file

@ -11,14 +11,14 @@ BarWidget::BarWidget(QString label, int value, int total, QColor barColor, QWidg
QSize BarWidget::sizeHint() const QSize BarWidget::sizeHint() const
{ {
QFontMetrics metrics(font()); const QFontMetrics metrics(font());
int labelHeight = metrics.height(); const int labelHeight = metrics.height();
int valueHeight = metrics.height(); const int valueHeight = metrics.height();
// Calculate the height dynamically based on the total // Calculate the height dynamically based on the total
int barHeight = (total > 0) ? (value * 200 / total) : 20; // Scale height proportionally const int barHeight = (total > 0) ? (value * 200 / total) : 20; // Scale height proportionally
int totalHeight = barHeight + labelHeight + valueHeight + 30; // Extra space for text const int totalHeight = barHeight + labelHeight + valueHeight + 30; // Extra space for text
return QSize(60, totalHeight); // Allow width to expand return QSize(60, totalHeight); // Allow width to expand
} }
void BarWidget::paintEvent(QPaintEvent *event) void BarWidget::paintEvent(QPaintEvent *event)
@ -26,13 +26,13 @@ void BarWidget::paintEvent(QPaintEvent *event)
QPainter painter(this); QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::Antialiasing);
int widgetWidth = width(); const int widgetWidth = width();
int widgetHeight = height(); const int widgetHeight = height();
// Calculate bar dimensions // Calculate bar dimensions
int barWidth = widgetWidth * 0.8; // Use 80% of the available width const int barWidth = widgetWidth * 0.8; // Use 80% of the available width
int fullBarHeight = widgetHeight - 40; // Leave space for labels const int fullBarHeight = widgetHeight - 40; // Leave space for labels
int valueBarHeight = (total > 0) ? (value * fullBarHeight / total) : 0; const int valueBarHeight = (total > 0) ? (value * fullBarHeight / total) : 0;
// Draw full bar background (gray) // Draw full bar background (gray)
painter.setBrush(QColor(200, 200, 200)); painter.setBrush(QColor(200, 200, 200));
@ -44,12 +44,12 @@ void BarWidget::paintEvent(QPaintEvent *event)
// Draw the CMC label // Draw the CMC label
painter.setPen(Qt::white); painter.setPen(Qt::white);
QRect textRect(0, widgetHeight - 30, widgetWidth, 20); const QRect textRect(0, widgetHeight - 30, widgetWidth, 20);
painter.drawText(textRect, Qt::AlignCenter, label); painter.drawText(textRect, Qt::AlignCenter, label);
// Draw the value count // Draw the value count
painter.setPen(Qt::black); painter.setPen(Qt::black);
QRect valueRect(0, 10, widgetWidth, 20); const QRect valueRect(0, 10, widgetWidth, 20);
painter.drawText(valueRect, Qt::AlignCenter, QString::number(value)); painter.drawText(valueRect, Qt::AlignCenter, QString::number(value));
(void)event; // Suppress unused parameter warning (void)event; // Suppress unused parameter warning

View file

@ -21,7 +21,7 @@ void DynamicFontSizeLabel::paintEvent(QPaintEvent *event)
// timer.start(); // timer.start();
QFont newFont = font(); QFont newFont = font();
float fontSize = getWidgetMaximumFontSize(this, this->text()); const float fontSize = getWidgetMaximumFontSize(this, this->text());
newFont.setPointSizeF(fontSize); newFont.setPointSizeF(fontSize);
setFont(newFont); setFont(newFont);
// qDebug() << "Font size set to" << fontSize; // qDebug() << "Font size set to" << fontSize;
@ -70,7 +70,7 @@ float DynamicFontSizeLabel::getWidgetMaximumFontSize(QWidget *widget, const QStr
QFontMetricsF fm(font); QFontMetricsF fm(font);
/* Check if widget is QLabel */ /* Check if widget is QLabel */
QLabel *label = qobject_cast<QLabel *>(widget); const QLabel *label = qobject_cast<QLabel *>(widget);
if (label) { if (label) {
newFontSizeRect = newFontSizeRect =
fm.boundingRect(widgetRect, (label->wordWrap() ? Qt::TextWordWrap : 0) | label->alignment(), text); fm.boundingRect(widgetRect, (label->wordWrap() ? Qt::TextWordWrap : 0) | label->alignment(), text);

View file

@ -16,7 +16,7 @@ void DynamicFontSizePushButton::paintEvent(QPaintEvent *event)
// Adjust the font size dynamically based on the text // Adjust the font size dynamically based on the text
QFont newFont = font(); QFont newFont = font();
float fontSize = DynamicFontSizeLabel::getWidgetMaximumFontSize(this, this->text()); const float fontSize = DynamicFontSizeLabel::getWidgetMaximumFontSize(this, this->text());
newFont.setPointSizeF(fontSize); newFont.setPointSizeF(fontSize);
setFont(newFont); setFont(newFont);

View file

@ -10,7 +10,7 @@ void PercentBarWidget::paintEvent(QPaintEvent *event)
Q_UNUSED(event); Q_UNUSED(event);
QPainter painter(this); QPainter painter(this);
QRect rect = this->rect(); const QRect rect = this->rect();
const int midX = rect.width() / 2; const int midX = rect.width() / 2;
const int height = rect.height(); const int height = rect.height();
@ -40,7 +40,7 @@ void PercentBarWidget::paintEvent(QPaintEvent *event)
const int tickHeight = 4; const int tickHeight = 4;
for (int percent = -100; percent <= 100; percent += 10) { for (int percent = -100; percent <= 100; percent += 10) {
int x = midX + static_cast<int>((percent / 100.0) * halfWidth); const int x = midX + static_cast<int>((percent / 100.0) * halfWidth);
painter.drawLine(x, height - tickHeight, x, height); painter.drawLine(x, height - tickHeight, x, height);
} }
} }

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