Compare commits

..

3 commits

Author SHA1 Message Date
Lukas Brübach
bd4bc62dfd [Replay] Add a clickable replay history sidebar
Render the event index as a scrollable list of event boxes. Selecting an entry seeks the replay to that event and keeps the current event highlighted while playback advances.
2026-11-03 18:08:52 +01:00
Lukas Brübach
93f4575048 [Replay] Build a compact event history index
Turn replay protocol events into short localized summaries with an actor, badge, and time so the history UI can render them without retaining the replay or duplicating the chat log.
2026-11-03 00:44:29 +01:00
Lukas Brübach
fecf10e2b1 [Replay] Seek to the exact time of an event
Timeline seeks only expose whole timer intervals, so jumping to an event could leave that event unprocessed until the next tick. Add an event-time seek that also applies events at the target timestamp.
2026-11-02 15:40:58 +01:00
42 changed files with 243 additions and 1494 deletions

View file

@ -71,8 +71,6 @@ if(WIN32 OR USE_VCPKG)
)
# Qt path set by user or env var
if(QTDIR
OR QTDIR32
OR QTDIR64
OR DEFINED ENV{QTDIR}
OR DEFINED ENV{QTDIR32}
OR DEFINED ENV{QTDIR64}
@ -238,13 +236,13 @@ else()
set(_lib_suffix 32)
endif()
if(NOT "${QTDIR${_lib_suffix}}" STREQUAL "")
if(DEFINED QTDIR${_lib_suffix})
list(APPEND CMAKE_PREFIX_PATH "${QTDIR${_lib_suffix}}")
elseif(NOT "${QTDIR}" STREQUAL "")
elseif(DEFINED QTDIR)
list(APPEND CMAKE_PREFIX_PATH "${QTDIR}")
elseif(NOT "$ENV{QTDIR${_lib_suffix}}" STREQUAL "")
elseif(DEFINED ENV{QTDIR${_lib_suffix}})
list(APPEND CMAKE_PREFIX_PATH "$ENV{QTDIR${_lib_suffix}}")
elseif(NOT "$ENV{QTDIR}" STREQUAL "")
elseif(DEFINED ENV{QTDIR})
list(APPEND CMAKE_PREFIX_PATH "$ENV{QTDIR}")
endif()

View file

@ -1,6 +1,6 @@
# Find a compatible Qt version
# Inputs: WITH_SERVER, WITH_CLIENT, WITH_ORACLE
# Optional Input: Qt6_DIR -- Directory containing Qt6Config.cmake
# Optional Input: QT6_DIR -- Hint as to where Qt6 lives on the system
# Output: COCKATRICE_QT_VERSION_NAME -- Example values: Qt6
# Output: SERVATRICE_QT_MODULES
# Output: COCKATRICE_QT_MODULES
@ -57,17 +57,7 @@ find_package(
QUIET HINTS ${Qt6_DIR}
)
if(NOT Qt6_FOUND)
set(_QT_DIAGNOSTIC "")
if(Qt6_NOT_FOUND_MESSAGE)
set(_QT_DIAGNOSTIC "\nQt package diagnostic: ${Qt6_NOT_FOUND_MESSAGE}")
endif()
message(FATAL_ERROR
"No suitable version of Qt was found. Qt 6.4.2 or newer with these components is required: "
"${REQUIRED_QT_COMPONENTS};Linguist.\n"
"Set QTDIR or CMAKE_PREFIX_PATH to the Qt installation prefix, or Qt6_DIR to the directory "
"containing Qt6Config.cmake."
"${_QT_DIAGNOSTIC}"
)
message(FATAL_ERROR "No suitable version of Qt was found")
endif()
set(COCKATRICE_QT_VERSION_NAME Qt6)

View file

@ -451,8 +451,6 @@ set(cockatrice_SOURCES
src/interface/intents/intent_open_shared_deck.h
src/interface/intents/url_parser.cpp
src/interface/intents/url_parser.h
src/interface/widgets/server/user/user_games_model.cpp
src/interface/widgets/server/user/user_games_model.h
src/interface/widgets/server/user/user_info_popup.cpp
src/interface/widgets/server/user/user_info_popup.h
)

View file

@ -15,18 +15,14 @@ static const QString ARCHIDEKT_SUFFIX = "/?format=json";
static const QString MOXFIELD_BASE = "https://api.moxfield.com/v2/decks/all/";
static const QString MOXFIELD_SUFFIX = "/";
static const QString DECKSTATS_BASE = "https://deckstats.net/decks/";
static const QString DECKSTATS_SUFFIX = "?include_comments=1&export_mtgarena=1";
static const QString MANABOX_BASE = "https://cloud.manabox.app/decks/";
bool parseDeckUrl(const QString &url, ParsedDeckInfo &outInfo)
{
static QRegularExpression rxTappedOut("tappedout\\.net/(?:mtg-decks/)?([^/?#]+)");
static QRegularExpression rxArchidekt("archidekt\\.com/decks/(\\d+)");
static QRegularExpression rxMoxfield("moxfield\\.com/decks/([a-zA-Z0-9_-]+)");
static QRegularExpression rxDeckstats("deckstats\\.net/decks/(\\d+/[a-zA-Z0-9_-]+)");
static QRegularExpression rxManabox("manabox\\.app/decks/([a-zA-Z0-9_-]+)");
QRegularExpressionMatch match;
@ -53,18 +49,11 @@ bool parseDeckUrl(const QString &url, ParsedDeckInfo &outInfo)
return true;
} else if ((match = rxDeckstats.match(url)).hasMatch()) {
QString deckPath = match.captured(1);
outInfo = ParsedDeckInfo{.baseUrl = DECKSTATS_BASE,
outInfo = ParsedDeckInfo{.baseUrl = "https://deckstats.net/decks/",
.deckID = deckPath,
.fullUrl = DECKSTATS_BASE + deckPath + DECKSTATS_SUFFIX,
.fullUrl = "https://deckstats.net/decks/" + deckPath + DECKSTATS_SUFFIX,
.provider = DeckProvider::Deckstats};
return true;
} else if ((match = rxManabox.match(url)).hasMatch()) {
QString deckPath = match.captured(1);
outInfo = ParsedDeckInfo{.baseUrl = MANABOX_BASE,
.deckID = deckPath,
.fullUrl = MANABOX_BASE + deckPath,
.provider = DeckProvider::Manabox};
return true;
}
return false;

View file

@ -15,7 +15,6 @@ enum class DeckProvider
Archidekt,
Moxfield,
Deckstats,
Manabox,
Unknown
};

View file

@ -8,19 +8,12 @@
#define INTERFACE_JSON_DECK_PARSER_H
#include "../../../interface/deck_loader/card_node_function.h"
#include "libcockatrice/deck_list/tree/inner_deck_list_node.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QList>
#include <QLoggingCategory>
#include <QString>
#include <QTextStream>
#include <libcockatrice/card/import/card_name_normalizer.h>
#include <libcockatrice/deck_list/deck_list.h>
inline Q_LOGGING_CATEGORY(InterfaceJsonDeckParserLog, "interface_json_deck_parser");
class IJsonDeckParser
{
public:
@ -39,6 +32,9 @@ public:
QString deckName = obj.value("name").toString();
QString deckDescription = obj.value("description").toString();
deckList.setName(deckName);
deckList.setComments(deckDescription);
QString outputText;
QTextStream outStream(&outputText);
@ -54,14 +50,8 @@ public:
outStream << quantity << ' ' << cardName << " (" << setName << ") " << collectorNumber << '\n';
}
outStream.flush();
outStream.seek(0);
deckList.loadFromStream_Plain(outStream, false, CardNameNormalizer());
deckList.setName(deckName);
deckList.setComments(deckDescription);
deckList.forEachCard(CardNodeFunction::ResolveProviderId());
deckList.setName(deckName);
deckList.setComments(deckDescription);
return deckList;
}
@ -77,6 +67,9 @@ public:
QString deckName = obj.value("name").toString();
QString deckDescription = obj.value("description").toString();
deckList.setName(deckName);
deckList.setComments(deckDescription);
QString outputText;
QTextStream outStream(&outputText);
@ -104,14 +97,8 @@ public:
outStream << quantity << ' ' << cardName << " (" << setName << ") " << collectorNumber << '\n';
}
outStream.flush();
outStream.seek(0);
deckList.loadFromStream_Plain(outStream, false, CardNameNormalizer());
deckList.setName(deckName);
deckList.setComments(deckDescription);
deckList.forEachCard(CardNodeFunction::ResolveProviderId());
deckList.setName(deckName);
deckList.setComments(deckDescription);
QJsonObject commandersObj = obj.value("commanders").toObject();
if (!commandersObj.isEmpty()) {
@ -127,113 +114,6 @@ public:
}
}
// Moxfield stores Oathbreaker signature spells in their own board,
// separate from both mainboard and commanders. They are playable deck
// cards, but must not replace the Oathbreaker as the banner card.
const QJsonObject signatureSpells = obj.value("signatureSpells").toObject();
for (auto it = signatureSpells.begin(); it != signatureSpells.end(); ++it) {
const QJsonObject entry = it.value().toObject();
const QJsonObject card = entry.value("card").toObject();
const QString name = card.value("name").toString();
const int quantity = entry.value("quantity").toInt();
if (name.isEmpty() || quantity <= 0) {
continue;
}
const QString set = card.value("set").toString().toUpper();
const QString collectorNumber = card.value("cn").toString();
const QString providerId = card.value("scryfall_id").toString();
deckList.addCards(name, quantity, DECK_ZONE_MAIN, -1, set, collectorNumber, providerId);
}
return deckList;
}
};
class ManaboxJsonParser : public IJsonDeckParser
{
enum BoardType : quint32
{
MainBoard = 0,
SideBoard = 1,
Commander = 2,
MaybeBoard = 3,
};
public:
DeckList parse(const QJsonObject &obj) override
{
DeckList deckList;
QString deckName = obj.value("name").toString();
QString outputText;
QString mainboardText;
QString sideboardText;
QTextStream mainboardStream(&mainboardText);
QTextStream sideboardStream(&sideboardText);
QTextStream outStream(&outputText);
auto commanderList = QList<QJsonObject>();
auto maybeboardList = QList<QJsonObject>();
for (auto entry : obj.value("cards").toArray()) {
auto card = entry.toObject();
auto collectorNumber = card.value("collectorNumber").toString();
auto cardName = card.value("name").toString();
auto boardType = static_cast<BoardType>(card.value("boardCategory").toInt());
auto setName = card.value("setId").toString();
auto quantity = card.value("quantity").toInt();
auto providerId = card.value("scryfallId").toString();
switch (boardType) {
case MainBoard:
mainboardStream << quantity << ' ' << cardName << " (" << setName << ") " << collectorNumber
<< '\n';
break;
case SideBoard:
sideboardStream << "SB: " << quantity << ' ' << cardName << " (" << setName << ") "
<< collectorNumber << '\n';
break;
case MaybeBoard:
maybeboardList.append(card);
break;
case Commander:
commanderList.append(card);
break;
default:
qCWarning(InterfaceJsonDeckParserLog)
<< "Unknown ManaBox Zone" << card.value("boardCategory").toInt() << "for" << cardName;
break;
}
}
outStream << mainboardText << sideboardText;
deckList.loadFromStream_Plain(outStream, false, CardNameNormalizer());
deckList.setName(deckName);
deckList.forEachCard(CardNodeFunction::ResolveProviderId());
for (const auto &maybeboardCard : maybeboardList) {
QString cardName = maybeboardCard.value("name").toString();
QString setName = maybeboardCard.value("setId").toString().toUpper();
QString collectorNumber = maybeboardCard.value("collectorNumber").toString();
QString providerId = maybeboardCard.value("scryfallId").toString();
for (int x = 0; x < maybeboardCard.value("quantity").toInt(); x++) {
deckList.addCard(cardName, DECK_ZONE_MAYBEBOARD, -1, setName, collectorNumber, providerId);
}
}
for (const auto &commanderCard : commanderList) {
QString commanderName = commanderCard.value("name").toString();
QString setName = commanderCard.value("setId").toString().toUpper();
QString collectorNumber = commanderCard.value("collectorNumber").toString();
QString providerId = commanderCard.value("scryfallId").toString();
deckList.setBannerCard({commanderName, providerId});
deckList.addCard(commanderName, DECK_ZONE_MAIN, -1, setName, collectorNumber, providerId);
}
return deckList;
}
};

View file

@ -11,7 +11,6 @@
#include <QSharedPointer>
#include <QTimer>
#include <QUrl>
#include <QtGlobal>
class ExactCard;
@ -39,94 +38,32 @@ void CardPictureLoaderStatusBar::cleanOldEntries()
if (!loadLog || !loadLog->popup) {
return;
}
const QDateTime now = QDateTime::currentDateTime();
// Removing an entry mutates the log, so walk a copy of it.
const QList<CardPictureLoaderRequestStatusDisplayWidget *> entries = logEntries;
for (CardPictureLoaderRequestStatusDisplayWidget *statusDisplayWidget : entries) {
for (CardPictureLoaderRequestStatusDisplayWidget *statusDisplayWidget :
loadLog->popup->findChildren<CardPictureLoaderRequestStatusDisplayWidget *>()) {
statusDisplayWidget->queryElapsedSeconds();
if (!statusDisplayWidget->getFinished()) {
continue;
}
if (QDateTime::fromString(statusDisplayWidget->getStartTime()).secsTo(now) > LOG_ENTRY_LIFETIME_SECS) {
removeLogEntry(statusDisplayWidget);
if (statusDisplayWidget->getFinished() &&
QDateTime::fromString(statusDisplayWidget->getStartTime()).secsTo(QDateTime::currentDateTime()) > 10) {
loadLog->removeSettingsWidget(statusDisplayWidget);
progressBar->setMaximum(progressBar->maximum() - 1);
progressBar->setValue(progressBar->value() - 1);
}
}
}
void CardPictureLoaderStatusBar::addQueuedImageLoad(const QUrl &url, const ExactCard &card, const QString &setName)
{
if (logEntries.size() >= MAX_LOG_ENTRIES) {
trimLog();
}
auto *entry = new CardPictureLoaderRequestStatusDisplayWidget(loadLog, url, card, setName);
loadLog->addSettingsWidget(entry);
logEntries.append(entry);
entriesByUrl.insert(entry->getUrl(), entry);
loadLog->addSettingsWidget(new CardPictureLoaderRequestStatusDisplayWidget(loadLog, url, card, setName));
progressBar->setMaximum(progressBar->maximum() + 1);
}
void CardPictureLoaderStatusBar::addSuccessfulImageLoad(const QUrl &url)
{
const QList<CardPictureLoaderRequestStatusDisplayWidget *> entries = entriesByUrl.values(url.toString());
if (entries.isEmpty()) {
// The entry may already have been dropped from the log; the download
// itself still succeeded, there is just nothing left to mark.
return;
}
int finishedEntries = 0;
for (CardPictureLoaderRequestStatusDisplayWidget *statusDisplayWidget : entries) {
if (statusDisplayWidget->getFinished()) {
continue;
}
statusDisplayWidget->queryElapsedSeconds();
statusDisplayWidget->setFinished();
++finishedEntries;
}
// The bar counts the entries currently in the log, so only entries that are
// still listed move it.
progressBar->setValue(progressBar->value() + finishedEntries);
}
void CardPictureLoaderStatusBar::trimLog()
{
if (logEntries.isEmpty()) {
return;
}
// Prefer evicting an entry that has already finished; only fall back to an
// in-flight request when the whole log is still pending.
CardPictureLoaderRequestStatusDisplayWidget *toRemove = nullptr;
for (CardPictureLoaderRequestStatusDisplayWidget *entry : logEntries) {
if (entry->getFinished()) {
toRemove = entry;
break;
progressBar->setValue(progressBar->value() + 1);
for (CardPictureLoaderRequestStatusDisplayWidget *statusDisplayWidget :
loadLog->popup->findChildren<CardPictureLoaderRequestStatusDisplayWidget *>()) {
if (statusDisplayWidget->getUrl() == url.toString()) {
statusDisplayWidget->queryElapsedSeconds();
statusDisplayWidget->setFinished();
}
}
removeLogEntry(toRemove != nullptr ? toRemove : logEntries.constFirst());
}
void CardPictureLoaderStatusBar::removeLogEntry(CardPictureLoaderRequestStatusDisplayWidget *entry)
{
if (entry == nullptr) {
return;
}
logEntries.removeOne(entry);
entriesByUrl.remove(entry->getUrl(), entry);
// The progress bar's maximum counts the entries currently in the log and
// its value the finished ones, so dropping an entry moves both counters back.
// Move the value first: a maximum of 0 turns the bar into a busy indicator and
// resets its value.
if (entry->getFinished()) {
progressBar->setValue(qMax(0, progressBar->value() - 1));
}
progressBar->setMaximum(qMax(0, progressBar->maximum() - 1));
loadLog->removeSettingsWidget(entry);
}
}

View file

@ -1,13 +1,10 @@
#ifndef PICTURE_LOADER_STATUS_BAR_H
#define PICTURE_LOADER_STATUS_BAR_H
#include <QList>
#include <QMultiHash>
#include <QString>
#include <QWidget>
#include <qtmetamacros.h>
class CardPictureLoaderRequestStatusDisplayWidget;
class ExactCard;
class QHBoxLayout;
class QProgressBar;
@ -24,20 +21,11 @@ class SettingsButtonWidget;
* - Shows overall progress of image downloads.
* - Maintains a log of individual requests via a popup (SettingsButtonWidget).
* - Cleans up finished request entries automatically after a delay.
*
* The log is a diagnostic view, not a queue: it keeps at most MAX_LOG_ENTRIES
* entries and indexes them by URL, so a burst of requests stays O(1) per event
* instead of scanning every entry the popup holds.
*/
class CardPictureLoaderStatusBar : public QWidget
{
Q_OBJECT
public:
/** Entries kept in the log; older ones are evicted as new requests arrive. */
static constexpr int MAX_LOG_ENTRIES = 50;
/** Seconds a finished entry stays in the log before it is cleaned up. */
static constexpr int LOG_ENTRY_LIFETIME_SECS = 10;
/**
* @brief Constructs a status bar with progress bar and log button.
* @param parent Parent widget
@ -67,28 +55,10 @@ public slots:
void cleanOldEntries();
private:
/**
* @brief Evicts the oldest finished entry (or the oldest entry if none finished)
* until the log fits within MAX_LOG_ENTRIES.
*/
void trimLog();
/**
* @brief Removes one entry from the log, its URL index and the popup, and keeps
* the progress bar counters in step with the entries that remain.
* @param entry Entry to remove
*/
void removeLogEntry(CardPictureLoaderRequestStatusDisplayWidget *entry);
QHBoxLayout *layout; ///< Horizontal layout containing progress bar and log button
QProgressBar *progressBar; ///< Progress bar showing overall download progress
SettingsButtonWidget *loadLog; ///< Popup log showing individual request statuses
QTimer *cleaner; ///< Timer for periodically cleaning old log entries
QList<CardPictureLoaderRequestStatusDisplayWidget *> logEntries; ///< Logged requests, oldest first
// A URL can back several live entries: a request parked for a deferred retry is re-queued while
// its first entry is still pending, so a completion must finish every entry for that URL.
QMultiHash<QString, CardPictureLoaderRequestStatusDisplayWidget *>
entriesByUrl; ///< Log entries indexed by their URL for O(1) completion lookup
};
#endif // PICTURE_LOADER_STATUS_BAR_H

View file

@ -49,7 +49,6 @@
#include <QPushButton>
#include <QSet>
#include <QSharedPointer>
#include <QSignalBlocker>
#include <QSize>
#include <QSizePolicy>
#include <QSplitter>
@ -188,17 +187,10 @@ void DeckEditorDeckDockWidget::createDeckDock()
formatLabel = new QLabel(this);
formatComboBox = new QComboBox(this);
formatComboBox->setObjectName("deckFormatComboBox");
formatComboBox->addItem(tr("Loading Database..."));
formatComboBox->setEnabled(false); // Disable until loaded
commanderBracketWidget = new CommanderBracketWidget(this);
connect(formatComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index) {
formatComboBox->setPlaceholderText(QString());
formatComboBox->setToolTip(QString());
deckStateManager->setFormat(index >= 0 ? formatComboBox->itemData(index).toString() : QString());
commanderBracketWidget->setDeck(deckStateManager->getDeckListShared());
});
commentsLabel = new QLabel();
commentsLabel->setObjectName("commentsLabel");
@ -363,9 +355,6 @@ void DeckEditorDeckDockWidget::initializeFormats()
{
QStringList allFormats = CardDatabaseManager::query()->getAllFormatsWithCount().keys();
// Rebuilding the list is a view update, not a user edit. In particular,
// clear() emits currentIndexChanged(-1), which must not clear the deck.
const QSignalBlocker blocker(formatComboBox);
formatComboBox->clear(); // Remove "Loading Database..."
formatComboBox->setEnabled(true);
@ -375,25 +364,28 @@ void DeckEditorDeckDockWidget::initializeFormats()
formatComboBox->addItem(formatName, formatName); // store the raw key in itemData
}
syncFormatSelection();
QString format = deckStateManager->getMetadata().gameFormat;
if (!format.isEmpty()) {
formatComboBox->setCurrentIndex(formatComboBox->findData(format));
} else {
// Ensure no selection is visible initially
formatComboBox->setCurrentIndex(-1);
}
connect(formatComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index) {
QString formatKey;
if (index >= 0) {
formatKey = formatComboBox->itemData(index).toString();
deckStateManager->setFormat(formatKey);
} else {
deckStateManager->setFormat(""); // clear format if deselected
}
commanderBracketWidget->setDeck(deckStateManager->getDeckListShared());
});
commanderBracketWidget->setDeck(deckStateManager->getDeckListShared());
}
void DeckEditorDeckDockWidget::syncFormatSelection()
{
if (!formatComboBox->isEnabled()) {
return;
}
const QSignalBlocker blocker(formatComboBox);
const QString format = deckStateManager->getMetadata().gameFormat;
const int index = format.isEmpty() ? -1 : formatComboBox->findData(format);
const QString unavailable = index < 0 && !format.isEmpty() ? tr("Unavailable: %1").arg(format) : QString();
formatComboBox->setPlaceholderText(unavailable);
formatComboBox->setToolTip(unavailable);
formatComboBox->setCurrentIndex(index);
}
ExactCard DeckEditorDeckDockWidget::getCurrentCard()
{
QModelIndex current = deckView->selectionModel()->currentIndex();
@ -604,7 +596,9 @@ void DeckEditorDeckDockWidget::syncDisplayWidgetsToModel()
updatePlaymatLabel();
updateHash();
syncFormatSelection();
formatComboBox->blockSignals(true);
formatComboBox->setCurrentIndex(formatComboBox->findData(deckStateManager->getMetadata().gameFormat));
formatComboBox->blockSignals(false);
commanderBracketWidget->setDeck(deckStateManager->getDeckListShared());
@ -768,6 +762,18 @@ void DeckEditorDeckDockWidget::actSwapSelection()
update();
}
void DeckEditorDeckDockWidget::actDecrementCard(const ExactCard &card, QString zoneName)
{
if (!card) {
return;
}
if (card.getInfo().getIsToken()) {
zoneName = DECK_ZONE_TOKENS;
}
deckStateManager->decrementCard(card, zoneName);
}
void DeckEditorDeckDockWidget::actDecrementSelection()
{
auto selectedRows = getSelectedCardNodeSourceIndices();
@ -1048,7 +1054,6 @@ void DeckEditorDeckDockWidget::retranslateUi()
commentsLabel->setText(tr("&Comments:"));
activeGroupCriteriaLabel->setText(tr("Group by:"));
formatLabel->setText(tr("Format:"));
syncFormatSelection();
commanderBracketWidget->retranslateUi();
hashLabel1->setText(tr("Hash:"));

View file

@ -70,6 +70,7 @@ public slots:
void syncDisplayWidgetsToModel();
void actAddCard(const ExactCard &card, const QString &zoneName);
void actIncrementSelection();
void actDecrementCard(const ExactCard &card, QString zoneName);
void actDecrementSelection();
void actSwapCard(const ExactCard &card, const QString &zoneName);
void actSwapSelection();
@ -110,7 +111,6 @@ private:
DeckListModel *getModel() const;
[[nodiscard]] QModelIndexList getSelectedCardNodeSourceIndices() const;
void offsetCountAtIndex(const QModelIndex &idx, bool isIncrement);
void syncFormatSelection();
void addMoveToZoneMenu(QMenu *menu, const QModelIndex &sourceCardIndex, const QString &currentBoardName);
void addChangeBoardMenu(QMenu *menu, const QString &zoneName);

View file

@ -211,15 +211,15 @@ QModelIndex DeckStateManager::addCard(const ExactCard &card, const QString &zone
return {};
}
QString targetZone = card.getInfo().getIsToken() ? DECK_ZONE_TOKENS : zoneName;
QString zone = card.getInfo().getIsToken() ? DECK_ZONE_TOKENS : zoneName;
CardSetPtr set = card.getPrinting().getSet();
QString setName = set ? set->getCorrectedShortName() : "";
QString reason =
tr("Added (%1): %2 (%3) %4").arg(targetZone, card.getName(), setName, card.getPrinting().getProperty("num"));
tr("Added (%1): %2 (%3) %4").arg(zone, card.getName(), setName, card.getPrinting().getProperty("num"));
QModelIndex idx = modifyDeck(reason, [&card, &targetZone](auto model) { return model->addCard(card, targetZone); });
QModelIndex idx = modifyDeck(reason, [&card, &zone](auto model) { return model->addCard(card, zone); });
if (idx.isValid()) {
emit focusIndexChanged(idx, true);
@ -234,22 +234,10 @@ QModelIndex DeckStateManager::decrementCard(const ExactCard &card, const QString
return {};
}
QString targetZone = zoneName;
QString providerId = card.getPrinting().getUuid();
QString collectorNumber = card.getPrinting().getProperty("num");
QModelIndex idx = deckListModel->findCard(card.getName(), targetZone, providerId, collectorNumber);
// Tokens are usually added to the token zone, but it is possible for imported/hand-edited
// decks to contain them in the main or sideboards. This is why we only try to remove the
// token from the token zone if it does not exist in the given zone, allowing us to still
// remove it from there.
if (!idx.isValid() && card.getInfo().getIsToken() && targetZone != DECK_ZONE_TOKENS) {
targetZone = DECK_ZONE_TOKENS;
idx = deckListModel->findCard(card.getName(), targetZone, providerId, collectorNumber);
}
QModelIndex idx = deckListModel->findCard(card.getName(), zoneName, providerId, collectorNumber);
if (!idx.isValid()) {
return {};
}
@ -261,7 +249,7 @@ QModelIndex DeckStateManager::decrementCard(const ExactCard &card, const QString
}
// old index is no longer safe since rows could have been removed
QModelIndex newIdx = deckListModel->findCard(card.getName(), targetZone, providerId, collectorNumber);
QModelIndex newIdx = deckListModel->findCard(card.getName(), zoneName, providerId, collectorNumber);
if (newIdx.isValid()) {
emit focusIndexChanged(newIdx, true);
}

View file

@ -188,18 +188,17 @@ public:
///@}
/**
* @brief Adds the given card to the given zone. Tokens always go to DECK_ZONE_TOKENS, ignoring the given zone.
* @brief Adds the given card to the given zone.
* Saves the operation to history if successful.
*
* @param card The card to add
* @param zoneName The zone to add the card to if the card is not a token
* @param zoneName The zone to add the card to
* @return The index of the added card
*/
QModelIndex addCard(const ExactCard &card, const QString &zoneName);
/**
* @brief Removes 1 copy of the given card from the given zone.
* If the card is a token and is not in the given zone, then it is removed from DECK_ZONE_TOKENS instead.
* Saves the operation to history if successful.
*
* @param card The card to remove

View file

@ -22,7 +22,6 @@
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QString>
#include <QStringList>
#include <QTextStream>
#include <QUrl>
#include <QVBoxLayout>
@ -34,7 +33,6 @@
class QWidget;
static const QStringList SUPPORTED_PROVIDERS = {"Archidekt", "Deckstats", "ManaBox", "Moxfield", "TappedOut"};
DlgLoadDeckFromWebsite::DlgLoadDeckFromWebsite(QWidget *parent) : QDialog(parent)
{
nam = NetworkManagerFactory::create(this);
@ -43,7 +41,6 @@ DlgLoadDeckFromWebsite::DlgLoadDeckFromWebsite(QWidget *parent) : QDialog(parent
setLayout(layout);
instructionLabel = new QLabel(this);
instructionLabel->setWordWrap(true);
layout->addWidget(instructionLabel);
urlEdit = new QLineEdit(this);
@ -67,8 +64,8 @@ DlgLoadDeckFromWebsite::DlgLoadDeckFromWebsite(QWidget *parent) : QDialog(parent
void DlgLoadDeckFromWebsite::retranslateUi()
{
instructionLabel->setText(tr("Paste a link to a decklist site here to import it.") + "\n" +
tr("Supported services: %1").arg(SUPPORTED_PROVIDERS.join(", ")));
instructionLabel->setText(tr("Paste a link to a decklist site here to import it.\n(Archidekt, Deckstats, Moxfield, "
"and TappedOut are supported.)"));
}
bool DlgLoadDeckFromWebsite::testValidUrl()
@ -87,8 +84,8 @@ void DlgLoadDeckFromWebsite::accept()
if (!jsonParser && info.provider != DeckProvider::Deckstats && info.provider != DeckProvider::TappedOut) {
qCWarning(DlgLoadDeckFromWebsiteLog) << "No parser found for provider";
QMessageBox::warning(this, tr("Load Deck from Website"),
tr("No parser available for this deck provider.") + "\n" +
tr("Supported services: %1").arg(SUPPORTED_PROVIDERS.join(", ")));
tr("No parser available for this deck provider.\n (Archidekt, Deckstats, Moxfield, "
"and TappedOut are supported.)"));
QDialog::reject();
return;
}
@ -155,7 +152,6 @@ void DlgLoadDeckFromWebsite::accept()
"https://archidekt.com/decks/9999999\n"
"https://deckstats.net/decks/99999/9999999-your-deck-name/en\n"
"https://moxfield.com/decks/XYZxx-XYZ99Yyy-xyzXzzz\n"
"https://manabox.app/decks/XYZxxa-YZ99Yyyx_yzXzzz\n"
"https://tappedout.net/mtg-decks/your-deck-name/"));
QDialog::reject();
}
@ -168,9 +164,7 @@ QSharedPointer<IJsonDeckParser> DlgLoadDeckFromWebsite::createParserForProvider(
return QSharedPointer<IJsonDeckParser>(new ArchidektJsonParser());
case DeckProvider::Moxfield:
return QSharedPointer<IJsonDeckParser>(new MoxfieldJsonParser());
case DeckProvider::Manabox:
return QSharedPointer<IJsonDeckParser>(new ManaboxJsonParser());
default:
return QSharedPointer<IJsonDeckParser>(nullptr);
}
}
}

View file

@ -1,149 +0,0 @@
#include "user_games_model.h"
#include <QVariant>
#include <libcockatrice/network/client/abstract/abstract_client.h>
#include <libcockatrice/protocol/pb/response.pb.h>
#include <libcockatrice/protocol/pb/response_get_games_of_user.pb.h>
#include <libcockatrice/protocol/pb/session_commands.pb.h>
#include <libcockatrice/protocol/pending_command.h>
#include <utility>
UserGamesModel::UserGamesModel(AbstractClient *_client, int requestTimeoutMs, QObject *parent)
: QAbstractListModel(parent), client(_client)
{
timeout.setSingleShot(true);
timeout.setInterval(requestTimeoutMs);
connect(&timeout, &QTimer::timeout, this, [this] {
invalidateRequest();
setState(State::Error);
});
connected = client->getStatus() == StatusLoggedIn;
connect(client, &AbstractClient::statusChanged, this, [this](ClientStatus status) {
// AbstractClient::setStatus emits this signal while holding the (non-recursive)
// status mutex, which getStatus() would try to lock again. Track the emitted
// value here, and read this cache from canRefresh() for the same reason.
connected = status == StatusLoggedIn;
if (!connected) {
invalidateRequest();
replaceGames({});
setState(online ? State::Disconnected : State::Offline);
} else if (online) {
refresh();
}
});
connect(client, &QObject::destroyed, this, [this] {
client = nullptr;
connected = false;
invalidateRequest();
replaceGames({});
setState(online ? State::Disconnected : State::Offline);
});
}
int UserGamesModel::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : games.size();
}
QVariant UserGamesModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.model() != this || index.column() != 0 || index.row() < 0 ||
index.row() >= games.size() || role != GameRole) {
return {};
}
return QVariant::fromValue(games.at(index.row()));
}
void UserGamesModel::setUser(const QString &name, bool isOnline)
{
userName = name;
online = isOnline;
refresh();
}
UserGamesModel::State UserGamesModel::getState() const
{
return state;
}
bool UserGamesModel::canRefresh() const
{
return online && !userName.isEmpty() && client && connected && state != State::Loading;
}
void UserGamesModel::invalidateRequest()
{
++requestGeneration;
// The client owns pending commands. Detach our interest without deleting
// an object that may already have moved to the client's thread.
disconnect(responseConnection);
responseConnection = {};
timeout.stop();
}
void UserGamesModel::replaceGames(QList<ServerInfo_Game> replacement)
{
beginResetModel();
games = std::move(replacement);
endResetModel();
}
void UserGamesModel::setState(State newState)
{
state = newState;
emit stateChanged();
}
void UserGamesModel::refresh()
{
invalidateRequest();
const quint64 request = requestGeneration;
replaceGames({});
if (!online || userName.isEmpty()) {
setState(State::Offline);
return;
}
if (!client || !connected) {
setState(State::Disconnected);
return;
}
setState(State::Loading);
// State listeners may select another user or disconnect the client.
if (request != requestGeneration) {
return;
}
Command_GetGamesOfUser command;
command.set_user_name(userName.toStdString());
PendingCommand *pending = client->prepareSessionCommand(command);
responseConnection = connect(pending, &PendingCommand::finished, this,
[this, request](const Response &response) { finishRequest(response, request); });
timeout.start();
client->sendCommand(pending);
}
void UserGamesModel::finishRequest(const Response &response, quint64 request)
{
if (request != requestGeneration) {
return;
}
invalidateRequest();
const quint64 completion = requestGeneration;
if (response.response_code() != Response::RespOk || !response.HasExtension(Response_GetGamesOfUser::ext)) {
setState(State::Error);
return;
}
const auto &result = response.GetExtension(Response_GetGamesOfUser::ext);
QList<ServerInfo_Game> replacement;
replacement.reserve(result.game_list_size());
for (const auto &game : result.game_list()) {
replacement.append(game);
}
replaceGames(std::move(replacement));
if (completion != requestGeneration) {
return;
}
setState(games.isEmpty() ? State::Empty : State::Ready);
}

View file

@ -1,63 +0,0 @@
#ifndef COCKATRICE_USER_GAMES_MODEL_H
#define COCKATRICE_USER_GAMES_MODEL_H
#include <QAbstractListModel>
#include <QList>
#include <QPointer>
#include <QString>
#include <QTimer>
#include <libcockatrice/protocol/pb/serverinfo_game.pb.h>
class AbstractClient;
class Response;
/** Current user's games and the lifetime of the request that supplies them. */
class UserGamesModel : public QAbstractListModel
{
Q_OBJECT
public:
enum class State
{
Offline,
Disconnected,
Loading,
Ready,
Empty,
Error
};
static constexpr int DefaultRequestTimeoutMs = 15000;
static constexpr int GameRole = Qt::UserRole + 10;
explicit UserGamesModel(AbstractClient *client,
int requestTimeoutMs = DefaultRequestTimeoutMs,
QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = {}) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
void setUser(const QString &name, bool isOnline);
void refresh();
State getState() const;
bool canRefresh() const;
signals:
void stateChanged();
private:
void invalidateRequest();
void replaceGames(QList<ServerInfo_Game> replacement);
void finishRequest(const Response &response, quint64 request);
void setState(State newState);
QPointer<AbstractClient> client;
QString userName;
bool online = false;
bool connected = false;
State state = State::Offline;
QList<ServerInfo_Game> games;
quint64 requestGeneration = 0;
QMetaObject::Connection responseConnection;
QTimer timeout;
};
#endif // COCKATRICE_USER_GAMES_MODEL_H

View file

@ -6,9 +6,10 @@
#include "../../interface/widgets/tabs/tab_supervisor.h"
#include "libcockatrice/card/database/card_database_querier.h"
#include "libcockatrice/card/printing/exact_card.h"
#include "libcockatrice/protocol/pb/response.pb.h"
#include "libcockatrice/protocol/pb/serverinfo_game.pb.h"
#include "libcockatrice/protocol/pb/serverinfo_user.pb.h"
#include "user_games_model.h"
#include "libcockatrice/protocol/pb/session_commands.pb.h"
#include "user_level.h"
#include "user_list_painter.h"
@ -33,7 +34,6 @@
#include <QPainter>
#include <QPainterPath>
#include <QPen>
#include <QPersistentModelIndex>
#include <QPoint>
#include <QPushButton>
#include <QRect>
@ -41,6 +41,8 @@
#include <QSharedPointer>
#include <QSize>
#include <QSizePolicy>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QStringLiteral>
#include <QStyle>
#include <QStyleOptionViewItem>
@ -50,6 +52,8 @@
#include <QtGlobal>
#include <libcockatrice/card/database/card_database_manager.h>
#include <libcockatrice/network/client/abstract/abstract_client.h>
#include <libcockatrice/protocol/pb/response_get_games_of_user.pb.h>
#include <libcockatrice/protocol/pending_command.h>
#include <libcockatrice/utility/card_ref.h>
#include <libcockatrice/utility/qt_utils.h>
#include <qnumeric.h>
@ -423,7 +427,6 @@ void UserInfoPopup::buildUi()
refreshBtn = new QPushButton(QStringLiteral("↻"), this);
refreshBtn->setFixedSize(20, 20);
refreshBtn->setFlat(true);
refreshBtn->setToolTip(tr("Refresh games"));
connect(refreshBtn, &QPushButton::clicked, this, &UserInfoPopup::refreshGames);
gh->addWidget(refreshBtn);
root->addLayout(gh);
@ -434,8 +437,7 @@ void UserInfoPopup::buildUi()
root->addWidget(gamesStatus);
// Games list
gamesModel = new UserGamesModel(client, UserGamesModel::DefaultRequestTimeoutMs, this);
connect(gamesModel, &UserGamesModel::stateChanged, this, &UserInfoPopup::updateGamesDisplay);
gamesModel = new QStandardItemModel(this);
gamesView = new QListView(this);
gamesView->setModel(gamesModel);
gamesView->setItemDelegate(new PopupGameDelegate(gamesView));
@ -643,21 +645,13 @@ void UserInfoPopup::rebuildActionButtons(const ServerInfo_User &userInfo, bool o
void UserInfoPopup::updateActionButtons(const ServerInfo_User &userInfo, bool online, bool isBuddy, bool isIgnored)
{
currentUserInfo = userInfo;
currentBuddy = isBuddy;
currentIgnored = isIgnored;
if (currentOnline != online) {
setOnline(online);
} else {
refreshHeader();
rebuildActionButtons(userInfo, online, isBuddy, isIgnored);
adjustSize();
}
rebuildActionButtons(userInfo, online, isBuddy, isIgnored);
adjustSize();
}
void UserInfoPopup::onGamesContextMenu(const QPoint &pos)
{
const QPersistentModelIndex idx = gamesView->indexAt(pos);
const QModelIndex idx = gamesView->indexAt(pos);
if (!idx.isValid()) {
return;
}
@ -685,7 +679,7 @@ void UserInfoPopup::onGamesContextMenu(const QPoint &pos)
}
const QAction *chosen = menu.exec(gamesView->viewport()->mapToGlobal(pos));
if (!chosen || !idx.isValid()) {
if (!chosen) {
return;
}
@ -722,8 +716,6 @@ void UserInfoPopup::showForUser(const QString &userName,
currentUser = userName;
currentUserInfo = userInfo;
currentOnline = online;
currentBuddy = isBuddy;
currentIgnored = isIgnored;
// Header
refreshHeader();
@ -731,71 +723,88 @@ void UserInfoPopup::showForUser(const QString &userName,
// Actions
rebuildActionButtons(userInfo, online, isBuddy, isIgnored);
// Games list reset
gamesModel->clear();
gamesView->hide();
gamesStatus->setText(tr("Loading games…"));
gamesStatus->show();
// Close button, top right corner, above everything
closeBtn->move(PopupWidth - closeBtn->width() - 6, 6);
closeBtn->raise();
gamesModel->setUser(currentUser, currentOnline);
adjustSize();
fetchGames();
}
// ── Games fetch ───────────────────────────────────────────────────────────────
void UserInfoPopup::fetchGames()
{
gamesModel->refresh();
}
void UserInfoPopup::setOnline(bool online)
{
if (currentOnline == online) {
if (!client || currentUser.isEmpty()) {
return;
}
currentOnline = online;
refreshHeader();
rebuildActionButtons(currentUserInfo, online, currentBuddy, currentIgnored);
gamesModel->setUser(currentUser, online);
Command_GetGamesOfUser cmd;
cmd.set_user_name(currentUser.toStdString());
const QString snapshot = currentUser;
PendingCommand *pend = client->prepareSessionCommand(cmd);
connect(pend, &PendingCommand::finished, this,
[this, snapshot](const Response &r) { onGamesReceived(r, snapshot); });
client->sendCommand(pend);
}
void UserInfoPopup::updateGamesDisplay()
void UserInfoPopup::onGamesReceived(const Response &r, const QString &forUser)
{
refreshBtn->setEnabled(gamesModel->canRefresh());
const auto state = gamesModel->getState();
const bool ready = state == UserGamesModel::State::Ready;
gamesView->setVisible(ready);
gamesStatus->setVisible(!ready);
switch (state) {
case UserGamesModel::State::Offline:
gamesStatus->setText(tr("User is offline."));
break;
case UserGamesModel::State::Disconnected:
gamesStatus->setText(tr("Not connected to the server."));
break;
case UserGamesModel::State::Loading:
gamesStatus->setText(tr("Loading games…"));
break;
case UserGamesModel::State::Empty:
gamesStatus->setText(tr("No active games."));
break;
case UserGamesModel::State::Error:
gamesStatus->setText(tr("Could not load games."));
break;
case UserGamesModel::State::Ready: {
// Fit exactly to the number of visible rows, scroll when more than 5.
constexpr int rowH = 38; // must match PopupGameDelegate::sizeHint
constexpr int maxRows = 5;
const int count = gamesModel->rowCount();
gamesView->setFixedHeight(qMin(count, maxRows) * rowH + 2);
gamesView->setVerticalScrollBarPolicy(count > maxRows ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAlwaysOff);
break;
}
if (forUser != currentUser) {
return; // stale response, different user showing now
}
gamesModel->clear();
if (r.response_code() != Response::RespOk) {
gamesStatus->setText(tr("Could not load games."));
gamesStatus->show();
gamesView->hide();
return;
}
const auto &resp = r.GetExtension(Response_GetGamesOfUser::ext);
if (resp.game_list_size() == 0) {
gamesStatus->setText(tr("No active games."));
gamesStatus->show();
gamesView->hide();
return;
}
for (int i = 0; i < resp.game_list_size(); ++i) {
auto *item = new QStandardItem;
item->setData(QVariant::fromValue(resp.game_list(i)), PopupRoles::GameData);
item->setEditable(false);
gamesModel->appendRow(item);
}
gamesStatus->hide();
gamesView->show();
// Fit exactly to the number of visible rows, scroll when more than 5
constexpr int rowH = 38; // must match PopupGameDelegate::sizeHint
constexpr int maxRows = 5;
const int count = gamesModel->rowCount();
const int visible = qMin(count, maxRows);
gamesView->setFixedHeight(visible * rowH + 2);
gamesView->setVerticalScrollBarPolicy(count > maxRows ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAlwaysOff);
adjustSize();
}
void UserInfoPopup::refreshGames()
{
gamesModel->clear();
gamesView->hide();
gamesStatus->setText(tr("Loading games…"));
gamesStatus->show();
fetchGames();
}

View file

@ -1,7 +1,6 @@
#ifndef COCKATRICE_USER_INFO_POPUP_H
#define COCKATRICE_USER_INFO_POPUP_H
#include "user_games_model.h"
#include "user_list_painter.h"
#include <QColor>
@ -22,13 +21,15 @@ class QPushButton;
class TabSupervisor;
class QListView;
class QPoint;
class QStandardItemModel;
class Response;
template <class Key, class T> class QMap;
// ── Roles ─────────────────────────────────────────────────────────────────────
namespace PopupRoles
{
constexpr int GameData = UserGamesModel::GameRole;
constexpr int GameData = Qt::UserRole + 10;
}
// Popup theme
@ -142,7 +143,6 @@ public:
void
showForUser(const QString &userName, const ServerInfo_User &userInfo, bool online, bool isBuddy, bool isIgnored);
void fetchGames();
void setOnline(bool online);
[[nodiscard]] QString getCurrentUser() const
{
@ -199,7 +199,7 @@ protected:
private slots:
void refreshGames();
void updateGamesDisplay();
void onGamesReceived(const Response &r, const QString &forUser);
void onGamesContextMenu(const QPoint &pos);
private:
@ -218,8 +218,6 @@ private:
QString currentUser;
ServerInfo_User currentUserInfo;
bool currentOnline = false;
bool currentBuddy = false;
bool currentIgnored = false;
std::function<bool(const QString &userName)> gameInviteAvailable;
UserInfoHeaderWidget *header;
@ -227,7 +225,7 @@ private:
QLabel *gamesLabel;
QFrame *separator;
QListView *gamesView;
UserGamesModel *gamesModel;
QStandardItemModel *gamesModel;
QLabel *gamesStatus;
QPushButton *closeBtn;
QPushButton *refreshBtn;

View file

@ -617,14 +617,7 @@ void UserListWidget::bind(UserListManager *mgr)
connect(manager, &UserListManager::addedToIgnoreList, this, refreshCurrentPopup);
connect(manager, &UserListManager::removedFromIgnoreList, this, refreshIfPopupOpen);
connect(manager, &UserListManager::userJoinedOnline, this, refreshCurrentPopup);
connect(manager, &UserListManager::userLeftOnline, this, [this, refreshIfPopupOpen](const QString &name) {
// The online row may already have been removed; the pinned popup must
// still invalidate its games request and display the offline state.
if (userInfoPopup && userInfoPopup->getCurrentUser() == name) {
userInfoPopup->setOnline(false);
}
refreshIfPopupOpen(name);
});
connect(manager, &UserListManager::userLeftOnline, this, refreshIfPopupOpen);
rebuild();
}

View file

@ -26,11 +26,6 @@ quint64 CommanderBracketService::estimateBracket(const DeckList &deck, QObject *
return CommanderSpellbookApiAccessor::instance().estimateBracket(deck, requester);
}
void CommanderBracketService::cancelEstimate(quint64 requestId)
{
CommanderSpellbookApiAccessor::instance().cancelEstimate(requestId);
}
void CommanderBracketService::onEstimateBracketFinished(CommanderSpellbookApiAccessor::RequestId id,
QObject *requester,
const EstimateBracketResult &result)

View file

@ -30,7 +30,6 @@ public:
static CommanderBracketService &instance();
quint64 estimateBracket(const DeckList &deck, QObject *requester);
void cancelEstimate(quint64 requestId);
signals:
void estimateFinished(quint64 requestId, QObject *requester, const CommanderBracketEstimate &estimate);

View file

@ -28,18 +28,9 @@ template <class T> class QSharedPointer;
CommanderBracketWidget::CommanderBracketWidget(QWidget *parent) : QWidget(parent)
{
autoEstimateTimer = new QTimer(this);
autoEstimateTimer->setSingleShot(true);
connect(autoEstimateTimer, &QTimer::timeout, this, [this]() {
if (SettingsCache::instance().deckEditor().getCommanderSpellbookIntegrationEnabled() ==
commanderSpellbookIntegrationEnabledIndexAutomatic) {
requestBracketEstimate();
}
});
bracketLabel = new QLabel(tr("Bracket:"), this);
bracketValueLabel = new QLabel(this);
bracketValueLabel->setTextFormat(Qt::PlainText);
bracketValueLabel->setText("-");
bracketValueLabel->setObjectName("bracketValueLabel");
@ -74,38 +65,18 @@ CommanderBracketWidget::CommanderBracketWidget(QWidget *parent) : QWidget(parent
this, &CommanderBracketWidget::maybeAutoEstimateBracket);
connect(&SettingsCache::instance().deckEditor(),
&DeckEditorSettings::commanderSpellbookIntegrationUseOfficialBracketNamesChanged, this,
&CommanderBracketWidget::displayEstimate);
&CommanderBracketWidget::maybeAutoEstimateBracket);
setVisible(false);
}
CommanderBracketWidget::~CommanderBracketWidget()
{
cancelEstimate();
}
void CommanderBracketWidget::cancelEstimate()
{
autoEstimateTimer->stop();
const quint64 canceledRequest = requestId;
requestId = 0;
CommanderBracketService::instance().cancelEstimate(canceledRequest);
bracketRefreshButton->setEnabled(true);
if (canceledRequest) {
bracketValueLabel->setText("-");
bracketValueLabel->setToolTip({});
}
}
void CommanderBracketWidget::setDeck(const QSharedPointer<DeckList> &_deck)
{
cancelEstimate();
deck = _deck;
hasEstimate = false;
requestId = 0; // invalidate any in-flight estimate for the previous deck
// Reset the displayed bracket
bracketValueLabel->setText("-");
bracketValueLabel->setToolTip({});
bracketInfoButton->setToolTip({});
bracketInfoButton->setEnabled(false);
bracketRefreshButton->setEnabled(true);
@ -173,7 +144,7 @@ bool CommanderBracketWidget::promptCommanderSpellbookIntegration()
dialog.exec();
// Persist naming choice (if not disabled)
if (clickedButton == enableBtn || clickedButton == automaticBtn) {
if (clickedButton != disableBtn) {
bool useOfficial = namingCombo->currentIndex() == 1;
SettingsCache::instance().deckEditor().setCommanderSpellbookIntegrationUseOfficialBracketNames(useOfficial);
}
@ -205,20 +176,9 @@ void CommanderBracketWidget::updateBracketVisibility(bool visible)
void CommanderBracketWidget::requestBracketEstimate()
{
const int mode = SettingsCache::instance().deckEditor().getCommanderSpellbookIntegrationEnabled();
if (!deck || deck->getGameFormat().compare("commander", Qt::CaseInsensitive) != 0 || requestId ||
(mode != commanderSpellbookIntegrationEnabledIndexEnabled &&
mode != commanderSpellbookIntegrationEnabledIndexAutomatic)) {
return;
}
autoEstimateTimer->stop();
hasEstimate = false;
bracketRefreshButton->setEnabled(false);
bracketInfoButton->setEnabled(false);
bracketInfoButton->setToolTip({});
bracketValueLabel->setText(tr("Calculating…"));
bracketValueLabel->setToolTip({});
requestId = CommanderBracketService::instance().estimateBracket(*deck, this);
}
@ -231,35 +191,22 @@ void CommanderBracketWidget::onEstimateBracketFinished(quint64 id,
return;
}
requestId = 0;
hasEstimate = true;
lastEstimate = result;
displayEstimate();
bracketRefreshButton->setEnabled(true);
}
void CommanderBracketWidget::displayEstimate()
{
if (!hasEstimate) {
bracketInfoButton->setToolTip(tr("Why this bracket?"));
return;
}
BracketExplainer explainer;
lastBracketExplanation = explainer.explain(lastEstimate.rawResult);
lastBracketExplanation = explainer.explain(result.rawResult);
// Display bracket
bracketValueLabel->setText(
SettingsCache::instance().deckEditor().getCommanderSpellbookIntegrationUseOfficialBracketNames()
? lastEstimate.officialName
: lastEstimate.displayName);
? result.officialName
: result.displayName);
bracketRefreshButton->setEnabled(true);
// Build tooltip
QString tooltip;
for (const auto &section : lastBracketExplanation.sections) {
tooltip += "<b>" + section.title.toHtmlEscaped() + "</b><br>";
tooltip += "<b>" + section.title + "</b><br>";
for (const auto &line : section.bulletPoints) {
tooltip += "• " + line.toHtmlEscaped() + "<br>";
tooltip += "• " + line + "<br>";
}
tooltip += "<br>";
}
@ -268,17 +215,13 @@ void CommanderBracketWidget::displayEstimate()
bracketInfoButton->setEnabled(!tooltip.isEmpty());
}
void CommanderBracketWidget::onEstimateBracketError(quint64 id, QObject *requester, const QString &error)
void CommanderBracketWidget::onEstimateBracketError(quint64 id, QObject *requester, const QString & /*error*/)
{
if (requester != this || id != requestId) {
return;
}
requestId = 0;
hasEstimate = false;
bracketValueLabel->setText("-");
bracketValueLabel->setToolTip(
QStringLiteral("<qt>%1</qt>").arg(tr("Unable to estimate bracket: %1").arg(error).toHtmlEscaped()));
bracketRefreshButton->setEnabled(true);
bracketInfoButton->setToolTip({});
bracketInfoButton->setEnabled(false);
@ -286,15 +229,6 @@ void CommanderBracketWidget::onEstimateBracketError(quint64 id, QObject *request
void CommanderBracketWidget::maybeAutoEstimateBracket()
{
if (prompting) {
return;
}
autoEstimateTimer->stop();
if (!deck) {
cancelEstimate();
updateBracketVisibility(false);
return;
}
const QString formatKey = deck->getGameFormat();
const bool isCommander = (formatKey.compare("commander", Qt::CaseInsensitive) == 0);
@ -302,20 +236,17 @@ void CommanderBracketWidget::maybeAutoEstimateBracket()
int mode = SettingsCache::instance().deckEditor().getCommanderSpellbookIntegrationEnabled();
if (!isCommander || mode == commanderSpellbookIntegrationEnabledIndexDisabled) {
cancelEstimate();
updateBracketVisibility(false);
return;
}
if (mode == commanderSpellbookIntegrationEnabledIndexUnprompted) {
const auto promptedDeck = deck;
if (prompting) {
return;
}
prompting = true;
const bool accepted = promptCommanderSpellbookIntegration();
prompting = false;
if (deck != promptedDeck || !deck || deck->getGameFormat().compare("commander", Qt::CaseInsensitive) != 0) {
maybeAutoEstimateBracket();
return;
}
if (!accepted) {
updateBracketVisibility(false);
return;
@ -330,17 +261,17 @@ void CommanderBracketWidget::maybeAutoEstimateBracket()
}
// Avoid firing if we already have a result or a request in flight
if (requestId || hasEstimate) {
if (!bracketRefreshButton->isEnabled()) {
return;
}
// Defer to avoid races during init / model rebuild
autoEstimateTimer->start(0);
QTimer::singleShot(0, this, &CommanderBracketWidget::requestBracketEstimate);
}
void CommanderBracketWidget::retranslateUi()
{
bracketLabel->setText(tr("Bracket:"));
displayEstimate();
bracketInfoButton->setToolTip(tr("Why this bracket?"));
bracketRefreshButton->setToolTip(tr("Recalculate bracket"));
}

View file

@ -1,7 +1,6 @@
#ifndef COCKATRICE_COMMANDER_BRACKET_WIDGET_H
#define COCKATRICE_COMMANDER_BRACKET_WIDGET_H
#include "commander_bracket_service.h"
#include "commander_spellbook_bracket_explainer.h"
#include <QSharedPointer>
@ -12,7 +11,6 @@
class QLabel;
class QToolButton;
class QTimer;
struct CommanderBracketEstimate;
class DeckList;
class QObject;
@ -24,7 +22,6 @@ class CommanderBracketWidget : public QWidget
public:
explicit CommanderBracketWidget(QWidget *parent = nullptr);
~CommanderBracketWidget() override;
void setDeck(const QSharedPointer<DeckList> &_deck);
void retranslateUi();
@ -38,15 +35,10 @@ private slots:
private:
bool promptCommanderSpellbookIntegration();
void updateBracketVisibility(bool visible);
void cancelEstimate();
void displayEstimate();
QSharedPointer<DeckList> deck;
bool prompting = false;
quint64 requestId = 0;
QTimer *autoEstimateTimer;
bool hasEstimate = false;
CommanderBracketEstimate lastEstimate;
QLabel *bracketLabel;
QLabel *bracketValueLabel;

View file

@ -9,10 +9,9 @@
#include <QJsonParseError>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPointer>
#include <QStringLiteral>
#include <QUrl>
#include <libcockatrice/network/network_manager.h>
#include <QVariant>
#include <version_string.h>
class DeckList;
@ -25,18 +24,13 @@ CommanderSpellbookApiAccessor &CommanderSpellbookApiAccessor::instance()
return instance;
}
CommanderSpellbookApiAccessor::CommanderSpellbookApiAccessor(QObject *parent)
: QObject(parent), network(NetworkManagerFactory::create(this))
CommanderSpellbookApiAccessor::CommanderSpellbookApiAccessor(QObject *parent) : QObject(parent)
{
}
CommanderSpellbookApiAccessor::RequestId CommanderSpellbookApiAccessor::estimateBracket(const DeckList &deck,
QObject *requester)
{
if (!requester) {
return 0;
}
CommanderSpellbookDeckRequest deckRequest = CommanderSpellbookDeckRequest::fromDeckList(deck);
QJsonDocument doc(deckRequest.toJson());
@ -46,39 +40,30 @@ CommanderSpellbookApiAccessor::RequestId CommanderSpellbookApiAccessor::estimate
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
req.setHeader(QNetworkRequest::UserAgentHeader, QString("Cockatrice %1").arg(VERSION_STRING));
QNetworkReply *reply = network->post(req, body);
QNetworkReply *reply = network.post(req, body);
const RequestId id = nextRequestId++;
pendingRequests.insert(id, reply);
const QPointer<QObject> guardedRequester(requester);
connect(requester, &QObject::destroyed, reply, [this, id]() { cancelEstimate(id); });
connect(reply, &QNetworkReply::finished, this, [this, reply, id, guardedRequester]() {
if (pendingRequests.take(id) != reply) {
return;
}
reply->deleteLater();
if (guardedRequester) {
onEstimateReplyFinished(reply, id, guardedRequester);
}
});
reply->setProperty("requestId", QVariant::fromValue(id));
reply->setProperty("requester", QVariant::fromValue(requester));
connect(reply, &QNetworkReply::finished, this, [this, reply]() { onEstimateReplyFinished(reply); });
return id;
}
void CommanderSpellbookApiAccessor::cancelEstimate(RequestId id)
void CommanderSpellbookApiAccessor::onEstimateReplyFinished(QNetworkReply *reply)
{
const QPointer<QNetworkReply> reply = pendingRequests.take(id);
if (!reply) {
reply->deleteLater();
const RequestId id = reply->property("requestId").toULongLong();
QObject *requester = reply->property("requester").value<QObject *>();
if (!requester) {
// Requester died — silently drop
return;
}
disconnect(reply, nullptr, this, nullptr);
reply->abort();
reply->deleteLater();
}
void CommanderSpellbookApiAccessor::onEstimateReplyFinished(QNetworkReply *reply, RequestId id, QObject *requester)
{
if (reply->error() != QNetworkReply::NoError) {
emit estimateBracketError(id, requester, reply->errorString());
return;
@ -93,10 +78,6 @@ void CommanderSpellbookApiAccessor::onEstimateReplyFinished(QNetworkReply *reply
}
EstimateBracketResult result = EstimateBracketResult::fromJson(doc.object());
if (result.bracketTag.trimmed().isEmpty()) {
emit estimateBracketError(id, requester, QStringLiteral("Missing bracket in response"));
return;
}
emit estimateBracketFinished(id, requester, result);
}

View file

@ -1,16 +1,14 @@
#ifndef COCKATRICE_COMMANDER_SPELLBOOK_API_ACCESSOR_H
#define COCKATRICE_COMMANDER_SPELLBOOK_API_ACCESSOR_H
#include <QHash>
#include <QNetworkAccessManager>
#include <QObject>
#include <QPointer>
#include <QString>
#include <QtGlobal>
#include <qtmetamacros.h>
class DeckList;
class QNetworkReply;
class QNetworkAccessManager;
struct EstimateBracketResult;
class CommanderSpellbookApiAccessor final : public QObject
@ -23,7 +21,6 @@ public:
using RequestId = quint64;
RequestId estimateBracket(const DeckList &deck, QObject *requester);
void cancelEstimate(RequestId id);
signals:
void estimateBracketFinished(RequestId id, QObject *requester, const EstimateBracketResult &result);
@ -34,10 +31,9 @@ private:
explicit CommanderSpellbookApiAccessor(QObject *parent = nullptr);
Q_DISABLE_COPY_MOVE(CommanderSpellbookApiAccessor)
void onEstimateReplyFinished(QNetworkReply *reply, RequestId id, QObject *requester);
void onEstimateReplyFinished(QNetworkReply *reply);
QNetworkAccessManager *network;
QHash<RequestId, QPointer<QNetworkReply>> pendingRequests;
QNetworkAccessManager network;
RequestId nextRequestId = 1;
};

View file

@ -3,14 +3,11 @@
#include "../../../../../client/settings/cache_settings.h"
#include <QByteArray>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QMap>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QSet>
#include <QString>
#include <QStringLiteral>
#include <QUrl>
@ -25,14 +22,6 @@ HandleCommanderBrackets::HandleCommanderBrackets(QObject *parent)
{
}
HandleCommanderBrackets::~HandleCommanderBrackets()
{
if (reply) {
disconnect(reply, nullptr, this, nullptr);
reply->abort();
}
}
void HandleCommanderBrackets::downloadBracketDefinitions()
{
if (reply) {
@ -46,49 +35,31 @@ void HandleCommanderBrackets::downloadBracketDefinitions()
void HandleCommanderBrackets::actFinishParsingDownloadedData()
{
auto *finishedReply = qobject_cast<QNetworkReply *>(sender());
if (!finishedReply || finishedReply != reply) {
return;
}
reply = qobject_cast<QNetworkReply *>(sender());
// Clear the active request before notifying listeners, which may immediately retry.
reply = nullptr;
finishedReply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
emit sigBracketDefinitionsDownloadFailed(reply->error());
if (finishedReply->error() != QNetworkReply::NoError) {
emit sigBracketDefinitionsDownloadFailed(finishedReply->error());
reply->deleteLater();
return;
}
QJsonParseError parseError;
auto document = QJsonDocument::fromJson(finishedReply->readAll(), &parseError);
auto document = QJsonDocument::fromJson(reply->readAll(), &parseError);
if (parseError.error != QJsonParseError::NoError || !document.isObject() ||
!document.object().value("brackets").isArray() || document.object().value("brackets").toArray().isEmpty()) {
if (parseError.error != QJsonParseError::NoError) {
emit sigBracketDefinitionsDownloadFailed(QNetworkReply::UnknownContentError);
return;
}
// Validate the complete replacement before touching the last usable definitions.
// Tags are QSettings group names, so path separators must not create nested groups.
QSet<QString> tags;
for (const auto &value : document.object().value("brackets").toArray()) {
const auto definition = value.toObject();
const auto tag = definition.value("tag").toString();
if (!value.isObject() || tag.trimmed().isEmpty() || tag.contains('/') || tag.contains('\\') ||
tags.contains(tag) || definition.value("officialName").toString().trimmed().isEmpty() ||
definition.value("displayName").toString().trimmed().isEmpty() ||
!definition.value("explanation").isString()) {
emit sigBracketDefinitionsDownloadFailed(QNetworkReply::UnknownContentError);
return;
}
tags.insert(tag);
reply->deleteLater();
return;
}
updateBracketDefinitions(document.toVariant().toMap());
emit sigBracketDefinitionsDownloaded();
reply->deleteLater();
}
void HandleCommanderBrackets::updateBracketDefinitions(const QVariantMap &jsonMap)

View file

@ -3,7 +3,6 @@
#include <QNetworkReply>
#include <QObject>
#include <QPointer>
#include <QVariantMap>
#include <qtmetamacros.h>
@ -15,7 +14,6 @@ class HandleCommanderBrackets : public QObject
public:
explicit HandleCommanderBrackets(QObject *parent = nullptr);
~HandleCommanderBrackets() override;
void downloadBracketDefinitions();
@ -30,7 +28,7 @@ private:
void updateBracketDefinitions(const QVariantMap &jsonMap);
QNetworkAccessManager *nam;
QPointer<QNetworkReply> reply;
QNetworkReply *reply;
};
#endif // COCKATRICE_HANDLE_COMMANDER_BRACKETS_H

View file

@ -131,16 +131,10 @@ void TabDeckEditor::loadLayout()
LayoutsSettings &layouts = SettingsCache::instance().layouts();
auto layoutState = layouts.getDeckEditorLayoutState();
// Start with every current dock placed. Saved layouts from older versions
// cannot describe docks introduced later; restoreState leaves those docks
// in their existing positions while restoring the saved docks, including
// their visibility and floating state.
restartLayout();
if (!layoutState.isEmpty()) {
if (!restoreState(layoutState)) {
// A corrupt or incompatible state must not leave a partial layout.
restartLayout();
}
if (layoutState.isNull()) {
restartLayout();
} else {
restoreState(layoutState);
restoreGeometry(layouts.getDeckEditorGeometry());
}
}

View file

@ -20,6 +20,7 @@
#include "tab_deck_editor_visual_tab_widget.h"
#include <QAction>
#include <QApplication>
#include <QByteArray>
#include <QDebug>
#include <QDockWidget>
@ -260,25 +261,17 @@ void TabDeckEditorVisual::processMainboardCardClick(const QMouseEvent *event,
}
}
/** @brief Get a zone name corresponding to keyboard modifiers. */
static QString zoneForClickModifiers(const Qt::KeyboardModifiers &modifiers)
{
if (modifiers.testFlag(Qt::ControlModifier)) {
return DECK_ZONE_SIDE;
} else if (modifiers.testFlag(Qt::ShiftModifier)) {
return DECK_ZONE_MAYBEBOARD;
} else {
return DECK_ZONE_MAIN;
}
}
/** @brief Handles clicks on cards in the database display. */
void TabDeckEditorVisual::processDatabaseCardClick(const QMouseEvent *event, const ExactCard &card)
{
if (event->button() == Qt::LeftButton) {
addCard(card, zoneForClickModifiers(event->modifiers()));
if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
addCard(card, DECK_ZONE_SIDE);
} else {
addCard(card, DECK_ZONE_MAIN);
}
} else if (event->button() == Qt::RightButton) {
decrementCard(card, zoneForClickModifiers(event->modifiers()));
decrementCard(card, DECK_ZONE_MAIN);
} else if (event->button() == Qt::MiddleButton) {
deckDockWidget->actRemoveCard();
}

View file

@ -130,11 +130,8 @@ void CardDatabaseVisualView::wheelEvent(QWheelEvent *event)
return;
}
// macOS uses transient (overlay) scroll bars that hide themselves
// once they fade out, so we need to use the range to determine if we ignore the wheel when there is nothing to
// scroll. This lets an enclosing scroll area take over.
QScrollBar *bar = verticalScrollBar();
if (bar->maximum() <= bar->minimum()) {
if (!bar->isVisible()) {
event->ignore();
return;
}

View file

@ -1,7 +1,6 @@
@page editing_decks Editing Decks
- @subpage editing_decks_classic
- @subpage editing_decks_visual
- @subpage editing_decks_classic
- @subpage editing_decks_visual
- @subpage visual_database_display
- @subpage editing_decks_printings
- @subpage editing_decks_printings

View file

@ -70,4 +70,4 @@ confirm.
The action will automatically import the deck from the online service without any other required user action.
Currently supported services are Archidekt, Deckstats, ManaBox, Moxfield, and TappedOut.
Currently supported services are Archidekt, Deckstats, Moxfield, and TappedOut.

View file

@ -1,25 +0,0 @@
@page visual_database_display Visual Database Display
# Purpose
The VisualDatabaseDisplay presents all the cards from the enabled sets in the CardDatabase, providing a visual way to find and add cards to your DeckList.
# Using the Visual Database Display
The VisualDatabaseDisplay can be opened by itself using the Tabs section in the menu bar at the top of the screen, or by selecting the "Visual Database Display" tab in the visual deck editor. When opened as a part of the visual deck editor, the VisualDatabaseDisplay can be used to add and remove cards from your deck. See @ref editing_decks_visual for more information about modifying your deck.
By default the cards are displayed as a grid of pictures. However, a table view using card names can be toggled by pressing the Visual/Table button at the top right of the widget.
# Filtering cards
The top section of the VisualDatabaseDisplay can be used to filter cards based on various card properties, as well as specifying in which way they should be sorted. Filters can be saved and reused at a later time by using the Save/Load button at the right of this panel.
# Modifying the Deck list
When the VisualDatabaseDisplay is opened as part of the visual deck editor, clicking on cards adds or removes them to and from your deck.
In the picture view, left-clicking on a card will add that card to the main board of your deck, while right-clicking will remove that printing of the card from the main board, if it exists. When clicking cards, modifier keys can be used to add (or remove) the card to zones other than the main board. Holding a Ctrl key on Windows and Linux or a Command key on MacOS adds/removes cards to the sideboard, while the Shift keys add/remove cards to the maybeboard.
In the table view, double-clicking on a card adds that card to the main board of your deck, while right-click opens the card menu. Holding the Ctrl key on Windows and Linux or the Command key on MacOS when double-clicking adds the card to the sideboard instead.
Tokens are always added to the token zone, regardless of which view is open or which modifier key is pressed.

View file

@ -83,7 +83,7 @@ LoadStatus CardDatabaseLoader::loadCardDatabase(const QString &path, CardDatabas
auto startTime = QTime::currentTime();
LoadStatus tempLoadStatus = NotLoaded;
if (!path.isEmpty()) {
QMutexLocker locker(&loadFromFileMutex);
QMutexLocker locker(loadFromFileMutex);
tempLoadStatus = loadFromFile(path, data);
}
@ -102,7 +102,7 @@ LoadStatus CardDatabaseLoader::loadCardDatabases(bool ignoreCache)
LoadStatus CardDatabaseLoader::doLoadCardDatabases(bool ignoreCache)
{
QMutexLocker locker(&reloadDatabaseMutex);
QMutexLocker locker(reloadDatabaseMutex);
if (!database) {
qCWarning(CardDatabaseLoadingLog) << "Loader has no database pointer";

View file

@ -177,8 +177,8 @@ private:
ICardSetPriorityController *priorityController; /**< Controller for reconstructing set state. */
QList<ICardDatabaseParser *> availableParsers; /**< List of available parsers for different formats. */
QBasicMutex loadFromFileMutex; /**< Mutex for single-file loading. */
QBasicMutex reloadDatabaseMutex; /**< Mutex for reloading entire database. */
QBasicMutex *loadFromFileMutex = new QBasicMutex(); /**< Mutex for single-file loading. */
QBasicMutex *reloadDatabaseMutex = new QBasicMutex(); /**< Mutex for reloading entire database. */
};
#endif // COCKATRICE_CARD_DATABASE_LOADER_H

View file

@ -423,23 +423,8 @@ DecklistCardNode *DeckList::addCard(const QString &cardName,
const QString &cardProviderId,
bool formatLegal)
{
return addCards(cardName, 1, zoneName, position, cardSetName, cardSetCollectorNumber, cardProviderId, formatLegal);
}
DecklistCardNode *DeckList::addCards(const QString &cardName,
int amount,
const QString &zoneName,
int position,
const QString &cardSetName,
const QString &cardSetCollectorNumber,
const QString &cardProviderId,
bool formatLegal)
{
if (amount <= 0) {
return nullptr;
}
auto node = tree.addCard(cardName, amount, zoneName, position, cardSetName, cardSetCollectorNumber, cardProviderId,
formatLegal);
auto node =
tree.addCard(cardName, 1, zoneName, position, cardSetName, cardSetCollectorNumber, cardProviderId, formatLegal);
refreshDeckHash();
return node;
}

View file

@ -284,14 +284,6 @@ public:
const QString &cardSetCollectorNumber = QString(),
const QString &cardProviderId = QString(),
const bool formatLegal = true);
DecklistCardNode *addCards(const QString &cardName,
int amount,
const QString &zoneName,
int position = -1,
const QString &cardSetName = QString(),
const QString &cardSetCollectorNumber = QString(),
const QString &cardProviderId = QString(),
const bool formatLegal = true);
///@}
/** @name Deck identity */

View file

@ -137,7 +137,6 @@ RemoteClient::~RemoteClient()
void RemoteClient::slotSocketError(QAbstractSocket::SocketError /*error*/)
{
QString errorString = socket->errorString();
qCWarning(RemoteClientLog) << "Server connection error:" << errorString;
doDisconnectFromServer();
emit socketError(errorString);
}
@ -147,7 +146,6 @@ void RemoteClient::slotWebSocketError(QAbstractSocket::SocketError /*error*/)
QString errorString = websocket->errorString();
if (getStatus() != ClientStatus::StatusDisconnected) {
qCWarning(RemoteClientLog) << "Server connection error:" << errorString;
doDisconnectFromServer();
emit socketError(errorString);
}
@ -155,7 +153,6 @@ void RemoteClient::slotWebSocketError(QAbstractSocket::SocketError /*error*/)
void RemoteClient::slotConnected()
{
qCInfo(RemoteClientLog) << "Server transport connected";
timeRunning = lastDataReceived = 0;
timer->start();
@ -169,12 +166,6 @@ void RemoteClient::slotConnected()
void RemoteClient::processServerIdentificationEvent(const Event_ServerIdentification &event)
{
// Identification arrives before login, including when protocol versions differ.
// Quote the server-supplied strings in the log and limit their size.
const QString serverName = QString::fromStdString(event.server_name()).left(256);
const QString serverVersion = QString::fromStdString(event.server_version()).left(256);
qCInfo(RemoteClientLog) << "Server identification:" << serverName << "version" << serverVersion
<< "protocol version" << event.protocol_version();
if (event.protocol_version() != protocolVersion) {
emit protocolVersionMismatch(protocolVersion, event.protocol_version());
setStatus(StatusDisconnecting);
@ -707,8 +698,6 @@ void RemoteClient::sendCommandContainer(const CommandContainer &cont)
void RemoteClient::connectToHost(const QString &hostname, unsigned int port)
{
usingWebSocket = port == 443 || port == 80 || port == 4748 || port == 8080;
qCInfo(RemoteClientLog) << "Connecting to server" << hostname << "port" << port
<< (usingWebSocket ? "using WebSocket" : "using TCP");
if (usingWebSocket) {
QUrl url(QString("%1://%2:%3/servatrice").arg(port == 443 ? "wss" : "ws").arg(hostname).arg(port));
websocket->open(url);

View file

@ -137,22 +137,22 @@
<message>
<location filename="src/pages.cpp" line="379"/>
<source>Downloading (0 MB)</source>
<translation>Herunterladen (0 MB)</translation>
<translation type="unfinished"/>
</message>
<message>
<location filename="src/pages.cpp" line="460"/>
<source>Downloading (%1 MB)</source>
<translation>Herunterladen (%1 MB)</translation>
<translation type="unfinished"/>
</message>
<message>
<location filename="src/pages.cpp" line="509"/>
<source>Parsing file (%1%)</source>
<translation>Datei wird verarbeitet (%1%)</translation>
<translation type="unfinished"/>
</message>
<message>
<location filename="src/pages.cpp" line="524"/>
<source>Extracting file...</source>
<translation>Extrahiere Datei...</translation>
<translation type="unfinished"/>
</message>
<message>
<location filename="src/pages.cpp" line="604"/>
@ -168,7 +168,7 @@
<message>
<location filename="src/pages.cpp" line="666"/>
<source>Parsing file (100%)</source>
<translation>Datei wird verarbeitet (100%)</translation>
<translation type="unfinished"/>
</message>
</context>
<context>
@ -348,7 +348,7 @@
<message>
<location filename="src/pages.cpp" line="797"/>
<source>A Cockatrice card database file of %1 MB has been downloaded.</source>
<translation>Eine Cockatrice-Kartendatenbankdatei der Größe %1 MB wurde heruntergeladen.</translation>
<translation type="unfinished"/>
</message>
<message>
<location filename="src/pages.cpp" line="800"/>
@ -434,7 +434,7 @@
<location filename="src/pagetemplates.cpp" line="115"/>
<source>Downloading (0 MB)</source>
<oldsource>Downloading (0MB)</oldsource>
<translation>Herunterladen (0 MB)</translation>
<translation type="unfinished"/>
</message>
<message>
<location filename="src/pagetemplates.cpp" line="129"/>

View file

@ -178,18 +178,6 @@ cockatrice_add_test(NAME user_data_backup_test SOURCES user_data_backup_test.cpp
cockatrice_add_test(NAME password_hash_test SOURCES password_hash_test.cpp LIBS libcockatrice_utility)
cockatrice_add_test(NAME report_categories_test SOURCES report_categories_test.cpp LIBS libcockatrice_utility)
cockatrice_add_test(NAME warning_categories_test SOURCES warning_categories_test.cpp LIBS libcockatrice_utility)
cockatrice_add_test(
NAME
user_games_model_test
SOURCES
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/widgets/server/user/user_games_model.cpp
user_games_model_test.cpp
LIBS
libcockatrice_network_client_abstract
INCLUDE_DIRS
${CMAKE_SOURCE_DIR}/cockatrice/src
${CMAKE_SOURCE_DIR}/libcockatrice_network
)
# The installer's holder probe is Windows-only, but the wording it produces and the
# question which programs are the payload's own are plain C++ and are what a stuck user
# has to act on, so they are tested everywhere.
@ -424,6 +412,23 @@ cockatrice_add_test(
INCLUDE_DIRS
${CMAKE_SOURCE_DIR}/cockatrice/src
)
cockatrice_add_test(
NAME
loader_local_matching_test
SOURCES
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/card_picture_loader/card_picture_loader_local.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/client/settings/cache_settings.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/client/settings/card_counter_settings.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/client/settings/shortcuts_settings.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/client/network/update/client/release_channel.cpp
${VERSION_STRING_CPP}
loader_local_matching_test.cpp
LIBS
libcockatrice_network
libcockatrice_settings
INCLUDE_DIRS
${CMAKE_SOURCE_DIR}/cockatrice/src
)
cockatrice_add_test(
NAME
deck_hash_performance_test
@ -475,19 +480,6 @@ endif()
# Guard must match the condition for src/single_instance_manager.cpp in cockatrice/CMakeLists.txt.
if(WITH_CLIENT)
cockatrice_add_test(
NAME
moxfield_signature_spells_test
SOURCES
${VERSION_STRING_CPP}
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/deck_loader/card_node_function.cpp
moxfield_signature_spells_test.cpp
LIBS
libcockatrice_card
libcockatrice_deck_list
INCLUDE_DIRS
${CMAKE_SOURCE_DIR}/cockatrice/src
)
cockatrice_add_test(
NAME
single_instance_manager_test
@ -556,46 +548,3 @@ endif()
if(WITH_ORACLE OR WITH_CLIENT)
add_subdirectory(picture_loader_benchmark)
endif()
# loader_local_matching_test and deck_state_manager_test links libcockatrice_settings,
# which only exists when a client/UI-capable target is being built.
if(WITH_ORACLE OR WITH_CLIENT)
set(SETTINGS_SOURCES
${CMAKE_SOURCE_DIR}/cockatrice/src/client/network/update/client/release_channel.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/client/settings/cache_settings.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/client/settings/card_counter_settings.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/client/settings/shortcuts_settings.cpp
${VERSION_STRING_CPP}
)
set(SETTINGS_LIBS libcockatrice_network libcockatrice_settings)
set(SETTINGS_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/cockatrice/src)
cockatrice_add_test(
NAME
loader_local_matching_test
SOURCES
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/card_picture_loader/card_picture_loader_local.cpp
${SETTINGS_SOURCES}
loader_local_matching_test.cpp
LIBS
${SETTINGS_LIBS}
INCLUDE_DIRS
${SETTINGS_INCLUDE_DIRS}
)
cockatrice_add_test(
NAME
deck_state_manager_test
SOURCES
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp
${SETTINGS_SOURCES}
deck_state_manager_test.cpp
LIBS
libcockatrice_card
libcockatrice_deck_list
libcockatrice_models
libcockatrice_utility
${SETTINGS_LIBS}
INCLUDE_DIRS
${SETTINGS_INCLUDE_DIRS}
)
endif()

View file

@ -1,190 +0,0 @@
/** @file deck_state_manager_test.cpp
* @brief Tests for DeckStateManager operations.
* @ingroup Tests
*/
#include "libcockatrice/card/database/card_database.h"
#include <QCoreApplication>
#include <QDir>
#include <QStandardPaths>
#include <client/settings/cache_settings.h>
#include <deck_list_model.h>
#include <gtest/gtest.h>
#include <interface/widgets/deck_editor/deck_state_manager.h>
#include <libcockatrice/card/database/card_database_manager.h>
#include <libcockatrice/card/printing/exact_card.h>
#include <libcockatrice/deck_list/tree/inner_deck_list_node.h>
namespace
{
/**
* @brief Assert that the DeckStateManager's deck list contains only the given zone,
* and that that zone only contains the given number of cards, all with the given card name.
*
* @param manager the DeckStateManager
* @param restrictToZones In which zones to look for the zone and cards. Empty means use the entire deck
* @param zone The only zone that should exist in the deck
* @param cardName The name of the only card that should exist in the deck
* @param cardNumber The number of cards that should be in the deck
*/
static void containsExactly(const DeckStateManager &manager,
const QSet<QString> &restrictToZones,
QString zone,
QString cardName,
int cardNumber)
{
QList<const InnerDecklistNode *> zones = manager.getDeckList().getZoneNodes(restrictToZones);
ASSERT_EQ(zones.size(), 1);
ASSERT_EQ(zones[0]->getName(), zone);
ASSERT_EQ(zones[0]->size(), 1);
const DecklistCardNode *card = dynamic_cast<const DecklistCardNode *>((*zones[0])[0]);
ASSERT_NE(card, nullptr);
ASSERT_EQ(card->getName(), cardName);
ASSERT_EQ(card->getNumber(), cardNumber);
}
/** @brief Return CardInfo of a token with the given name. */
static CardInfoPtr makeToken(QString name)
{
return CardInfo::newInstance(name, "", true, {}, {}, {}, {}, {});
}
// =====================================================================================================================
// addCard
// =====================================================================================================================
TEST(DeckStateManager, AddCards)
{
DeckStateManager manager;
manager.addCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_MAIN);
containsExactly(manager, {}, DECK_ZONE_MAIN, "Lightning Bolt", 1);
manager.addCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_MAIN);
containsExactly(manager, {}, DECK_ZONE_MAIN, "Lightning Bolt", 2);
}
TEST(DeckStateManager, AddCardZones)
{
DeckStateManager manager;
manager.addCard(ExactCard(CardInfo::newInstance("Grizzly Bears")), DECK_ZONE_MAIN);
manager.addCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_SIDE);
manager.addCard(ExactCard(CardInfo::newInstance("Swords to Plowshares")), DECK_ZONE_MAYBEBOARD);
// Check if the cards got put into the correct zones.
ASSERT_EQ(manager.getDeckList().getZoneNodes().size(), 3);
containsExactly(manager, {DECK_ZONE_MAIN}, DECK_ZONE_MAIN, "Grizzly Bears", 1);
containsExactly(manager, {DECK_ZONE_SIDE}, DECK_ZONE_SIDE, "Lightning Bolt", 1);
containsExactly(manager, {DECK_ZONE_MAYBEBOARD}, DECK_ZONE_MAYBEBOARD, "Swords to Plowshares", 1);
}
TEST(DeckStateManager, AddTokens)
{
DeckStateManager manager;
manager.addCard(ExactCard(makeToken("Beast")), DECK_ZONE_MAIN);
manager.addCard(ExactCard(makeToken("Beast")), DECK_ZONE_SIDE);
manager.addCard(ExactCard(makeToken("Beast")), DECK_ZONE_MAYBEBOARD);
manager.addCard(ExactCard(makeToken("Beast")), DECK_ZONE_TOKENS);
// A token should always be put into the tokens zone.
containsExactly(manager, {}, DECK_ZONE_TOKENS, "Beast", 4);
}
// =====================================================================================================================
// decrementCard
// =====================================================================================================================
TEST(DeckStateManager, DecrementCards)
{
DeckStateManager manager;
manager.addCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_MAIN);
manager.addCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_MAIN);
containsExactly(manager, {}, DECK_ZONE_MAIN, "Lightning Bolt", 2);
// Removing from the sideboard should do nothing, as there is nothing in the side board.
manager.decrementCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_SIDE);
containsExactly(manager, {}, DECK_ZONE_MAIN, "Lightning Bolt", 2);
// Remove the first card.
manager.decrementCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_MAIN);
containsExactly(manager, {}, DECK_ZONE_MAIN, "Lightning Bolt", 1);
// Removing the second card should also remove the zone.
manager.decrementCard(ExactCard(CardInfo::newInstance("Lightning Bolt")), DECK_ZONE_MAIN);
ASSERT_EQ(manager.getDeckList().getZoneNodes().size(), 0);
}
TEST(DeckStateManager, DecrementTokens)
{
DeckStateManager manager;
manager.addCard(ExactCard(makeToken("Beast")), DECK_ZONE_MAIN);
manager.addCard(ExactCard(makeToken("Beast")), DECK_ZONE_SIDE);
manager.addCard(ExactCard(makeToken("Beast")), DECK_ZONE_TOKENS);
containsExactly(manager, {}, DECK_ZONE_TOKENS, "Beast", 3);
manager.decrementCard(ExactCard(makeToken("Beast")), DECK_ZONE_TOKENS);
containsExactly(manager, {}, DECK_ZONE_TOKENS, "Beast", 2);
// Removing tokens from a given zone should remove them from the
// token zone if the given zone does not contain the token.
manager.decrementCard(ExactCard(makeToken("Beast")), DECK_ZONE_SIDE);
containsExactly(manager, {}, DECK_ZONE_TOKENS, "Beast", 1);
manager.decrementCard(ExactCard(makeToken("Beast")), DECK_ZONE_MAIN);
ASSERT_EQ(manager.getDeckList().getZoneNodes().size(), 0);
}
TEST(DeckStateManager, DecrementTokenMainboard)
{
DeckStateManager manager;
// Add cards to the deck list directly so tokens are not
// automatically added to the token zone.
manager.getDeckListShared()->addCard("Beast", DECK_ZONE_MAIN);
manager.getDeckListShared()->addCard("Beast", DECK_ZONE_TOKENS);
ASSERT_EQ(manager.getDeckList().getZoneNodes().size(), 2);
containsExactly(manager, {DECK_ZONE_MAIN}, DECK_ZONE_MAIN, "Beast", 1);
containsExactly(manager, {DECK_ZONE_TOKENS}, DECK_ZONE_TOKENS, "Beast", 1);
// decrementCard uses the model to find the card, so we need to rebuild it.
manager.getModel()->rebuildTree();
// Tokens should be removed from the main zone first.
manager.decrementCard(ExactCard(makeToken("Beast")), DECK_ZONE_MAIN);
ASSERT_EQ(manager.getDeckList().getZoneNodes({DECK_ZONE_MAIN}).size(), 0);
containsExactly(manager, {DECK_ZONE_TOKENS}, DECK_ZONE_TOKENS, "Beast", 1);
// If the main zone is empty they can be removed from the token zone.
manager.decrementCard(ExactCard(makeToken("Beast")), DECK_ZONE_MAIN);
ASSERT_EQ(manager.getDeckList().getZoneNodes().size(), 0);
}
} // namespace
int main(int argc, char **argv)
{
// Redirect SettingsCache reads/writes (app-data location) away from the real user profile.
QStandardPaths::setTestModeEnabled(true);
QCoreApplication app(argc, argv);
QCoreApplication::setOrganizationName(QStringLiteral("CockatriceTest"));
QCoreApplication::setApplicationName(
QStringLiteral("deck-state-manager-test-%1").arg(QCoreApplication::applicationPid()));
::testing::InitGoogleTest(&argc, argv);
// Add cards to the card database
auto *db = CardDatabaseManager::getInstance();
db->addCard(CardInfo::newInstance("Lightning Bolt"));
db->addCard(CardInfo::newInstance("Grizzly Bears"));
db->addCard(CardInfo::newInstance("Swords to Plowshares"));
db->addCard(makeToken("Beast"));
int result = RUN_ALL_TESTS();
// Clean up the settings directory in ~/.qttest if the tests ran.
if (!::testing::GTEST_FLAG(list_tests)) {
QDir(SettingsCache::instance().getDataPath()).removeRecursively();
QDir(SettingsCache::instance().getCachePath()).removeRecursively();
}
return result;
}

View file

@ -1,84 +0,0 @@
#include "client/network/parsers/interface_json_deck_parser.h"
#include <QJsonDocument>
#include <gtest/gtest.h>
#include <libcockatrice/deck_list/tree/deck_list_card_node.h>
#include <libcockatrice/deck_list/tree/inner_deck_list_node.h>
TEST(MoxfieldImport, SignatureSpellIsAddedToMainWithoutReplacingCommanderBanner)
{
// Moxfield v2 board objects map IDs to entries with quantity and card.
const auto input = QJsonDocument::fromJson(R"json({
"name": "Oathbreaker example", "description": "Notes retained",
"mainboard": {"land": {"quantity": 1, "card": {"name": "Island", "set": "abc", "cn": "1"}}},
"sideboard": {"side": {"quantity": 1, "card": {"name": "Mountain", "set": "abc", "cn": "2"}}},
"commanders": {"walker": {"quantity": 1, "card": {"name": "Jace", "set": "abc", "cn": "3", "scryfall_id": "walker-id"}}},
"signatureSpells": {"spell": {"quantity": 1, "card": {"name": "Lightning Bolt", "set": "xyz", "cn": "4", "scryfall_id": "spell-id"}}}
})json")
.object();
MoxfieldJsonParser parser;
DeckList deck = parser.parse(input);
int mainSpellCount = 0;
int sideSpellCount = 0;
int mainLands = 0;
int sideLands = 0;
deck.forEachCard([&](InnerDecklistNode *zone, DecklistCardNode *card) {
if (card->getName() == "Island" && zone->getName() == DECK_ZONE_MAIN) {
mainLands += card->getNumber();
}
if (card->getName() == "Mountain" && zone->getName() == DECK_ZONE_SIDE) {
sideLands += card->getNumber();
}
if (card->getName() != "Lightning Bolt") {
return;
}
if (zone->getName() == DECK_ZONE_MAIN) {
mainSpellCount += card->getNumber();
EXPECT_EQ(card->getCardSetShortName(), "XYZ");
EXPECT_EQ(card->getCardCollectorNumber(), "4");
EXPECT_EQ(card->getCardProviderId(), "spell-id");
} else if (zone->getName() == DECK_ZONE_SIDE) {
sideSpellCount += card->getNumber();
}
});
EXPECT_EQ(mainSpellCount, 1);
EXPECT_EQ(sideSpellCount, 0);
EXPECT_EQ(mainLands, 1);
EXPECT_EQ(sideLands, 1);
EXPECT_EQ(deck.getName(), "Oathbreaker example");
EXPECT_EQ(deck.getComments(), "Notes retained");
EXPECT_EQ(deck.getBannerCard().name, "Jace");
EXPECT_EQ(deck.getBannerCard().providerId, "walker-id");
}
TEST(MoxfieldImport, QuantityAwareDeckInsertionRetainsCountAndPrinting)
{
DeckList deck;
auto *card = deck.addCards("Island", 2, DECK_ZONE_MAIN, -1, "ABC", "4", "id");
ASSERT_NE(card, nullptr);
EXPECT_EQ(card->getNumber(), 2);
EXPECT_EQ(card->getCardProviderId(), "id");
EXPECT_EQ(deck.addCards("Island", 0, DECK_ZONE_MAIN), nullptr);
}
TEST(OnlineImport, ArchidektPreservesNameDescriptionAndCards)
{
const auto input = QJsonDocument::fromJson(R"json({
"name": "Online deck", "description": "Deck notes",
"cards": [{"quantity": 2, "card": {
"oracleCard": {"name": "Island"}, "edition": {"editioncode": "abc"}, "collectorNumber": "1"
}}]
})json")
.object();
ArchidektJsonParser parser;
const DeckList deck = parser.parse(input);
int count = 0;
deck.forEachCard([&](InnerDecklistNode *zone, DecklistCardNode *card) {
if (zone->getName() == DECK_ZONE_MAIN && card->getName() == "Island") {
count += card->getNumber();
}
});
EXPECT_EQ(count, 2);
EXPECT_EQ(deck.getName(), "Online deck");
EXPECT_EQ(deck.getComments(), "Deck notes");
}

View file

@ -1,248 +0,0 @@
#include "interface/widgets/server/user/user_games_model.h"
#include <QAbstractItemModelTester>
#include <QCoreApplication>
#include <QPersistentModelIndex>
#include <QSignalSpy>
#include <gtest/gtest.h>
#include <libcockatrice/network/client/abstract/abstract_client.h>
#include <libcockatrice/protocol/pb/commands.pb.h>
#include <libcockatrice/protocol/pb/response.pb.h>
#include <libcockatrice/protocol/pb/response_get_games_of_user.pb.h>
#include <libcockatrice/protocol/pb/server_message.pb.h>
#include <libcockatrice/protocol/pending_command.h>
#include <libcockatrice/rng/rng_abstract.h>
#include <memory>
RNG_Abstract *rng = nullptr; // required by the transitive server library; this suite sends no game commands
namespace
{
class GamesClient : public AbstractClient
{
public:
QList<CommandContainer> sent;
GamesClient()
{
setStatus(StatusLoggedIn);
}
~GamesClient() override
{
qDeleteAll(pendingCommands);
pendingCommands.clear();
}
void changeStatus(ClientStatus status)
{
setStatus(status);
}
void answer(int request, Response response)
{
response.set_cmd_id(sent.at(request).cmd_id());
ServerMessage message;
message.set_message_type(ServerMessage::RESPONSE);
*message.mutable_response() = response;
processProtocolItem(message);
}
protected:
void sendCommandContainer(const CommandContainer &command) override
{
sent.append(command);
}
};
Response gamesResponse(std::initializer_list<int> ids)
{
Response response;
response.set_response_code(Response::RespOk);
auto *games = response.MutableExtension(Response_GetGamesOfUser::ext);
for (int id : ids) {
auto *game = games->add_game_list();
game->set_game_id(id);
game->set_room_id(7);
}
return response;
}
using State = UserGamesModel::State;
TEST(UserGamesModel, OfflineUserDoesNotSendARequest)
{
GamesClient client;
UserGamesModel model(&client);
model.setUser("Alice", false);
model.refresh();
EXPECT_TRUE(client.sent.isEmpty());
EXPECT_EQ(State::Offline, model.getState());
EXPECT_FALSE(model.canRefresh());
EXPECT_EQ(0, model.rowCount());
}
TEST(UserGamesModel, PresenceLossInvalidatesTheOutstandingResponse)
{
GamesClient client;
UserGamesModel model(&client);
model.setUser("Alice", true);
EXPECT_EQ(State::Loading, model.getState());
EXPECT_FALSE(model.canRefresh());
model.setUser("Alice", false);
client.answer(0, gamesResponse({1}));
EXPECT_EQ(State::Offline, model.getState());
EXPECT_EQ(0, model.rowCount());
model.setUser("Alice", true);
client.answer(1, gamesResponse({2}));
EXPECT_EQ(State::Ready, model.getState());
EXPECT_TRUE(model.canRefresh());
EXPECT_EQ(2, model.data(model.index(0), UserGamesModel::GameRole).value<ServerInfo_Game>().game_id());
}
TEST(UserGamesModel, SwitchingBackToTheSameUserDoesNotAcceptTheirOldRequest)
{
GamesClient client;
UserGamesModel model(&client);
model.setUser("Alice", true);
model.setUser("Bob", true);
model.setUser("Alice", true);
client.answer(2, gamesResponse({3}));
client.answer(0, gamesResponse({1}));
client.answer(1, gamesResponse({2}));
EXPECT_EQ(1, model.rowCount());
EXPECT_EQ(3, model.data(model.index(0), UserGamesModel::GameRole).value<ServerInfo_Game>().game_id());
}
TEST(UserGamesModel, RefreshSupersedesThePreviousRequest)
{
GamesClient client;
UserGamesModel model(&client);
model.setUser("Alice", true);
model.refresh();
client.answer(0, gamesResponse({1}));
EXPECT_EQ(State::Loading, model.getState());
EXPECT_EQ(0, model.rowCount());
client.answer(1, gamesResponse({2}));
EXPECT_EQ(State::Ready, model.getState());
EXPECT_EQ(2, model.data(model.index(0), UserGamesModel::GameRole).value<ServerInfo_Game>().game_id());
}
TEST(UserGamesModel, EmptySuccessAndMissingPayloadAreDifferentStates)
{
GamesClient client;
UserGamesModel model(&client);
model.setUser("Alice", true);
client.answer(0, gamesResponse({}));
EXPECT_EQ(State::Empty, model.getState());
EXPECT_TRUE(model.canRefresh());
model.refresh();
Response missingPayload;
missingPayload.set_response_code(Response::RespOk);
client.answer(1, missingPayload);
EXPECT_EQ(State::Error, model.getState());
EXPECT_TRUE(model.canRefresh());
}
TEST(UserGamesModel, FailedRequestsCanBeRetried)
{
GamesClient client;
UserGamesModel model(&client);
model.setUser("Alice", true);
Response error;
error.set_response_code(Response::RespNameNotFound);
client.answer(0, error);
EXPECT_EQ(State::Error, model.getState());
model.refresh();
client.answer(1, gamesResponse({4}));
EXPECT_EQ(State::Ready, model.getState());
}
TEST(UserGamesModel, DisconnectRejectsLateRepliesAndReconnectFetchesAgain)
{
GamesClient client;
UserGamesModel model(&client);
model.setUser("Alice", true);
client.changeStatus(StatusDisconnecting);
client.answer(0, gamesResponse({1}));
EXPECT_EQ(State::Disconnected, model.getState());
EXPECT_FALSE(model.canRefresh());
model.refresh();
EXPECT_EQ(1, client.sent.size());
client.changeStatus(StatusLoggedIn);
client.answer(1, gamesResponse({2}));
EXPECT_EQ(State::Ready, model.getState());
}
TEST(UserGamesModel, ClientDestructionClearsGamesAndDisablesRefresh)
{
auto client = std::make_unique<GamesClient>();
UserGamesModel model(client.get());
model.setUser("Alice", true);
client->answer(0, gamesResponse({1}));
client.reset();
EXPECT_EQ(State::Disconnected, model.getState());
EXPECT_EQ(0, model.rowCount());
EXPECT_FALSE(model.canRefresh());
model.refresh();
EXPECT_EQ(State::Disconnected, model.getState());
}
TEST(UserGamesModel, ResetInvalidatesAnOpenGameActionAndPreservesTheModelContract)
{
GamesClient client;
UserGamesModel model(&client);
QAbstractItemModelTester tester(&model, QAbstractItemModelTester::FailureReportingMode::Fatal);
model.setUser("Alice", true);
client.answer(0, gamesResponse({1, 2, 3}));
QPersistentModelIndex selected(model.index(1));
EXPECT_TRUE(selected.isValid());
model.refresh();
EXPECT_FALSE(selected.isValid());
EXPECT_EQ(0, model.rowCount());
client.answer(1, gamesResponse({4}));
EXPECT_EQ(1, model.rowCount());
}
TEST(UserGamesModel, StateListenerCanSelectAnotherUserBeforeTheRequestIsSent)
{
GamesClient client;
UserGamesModel model(&client);
bool switched = false;
QObject::connect(&model, &UserGamesModel::stateChanged, &model, [&] {
if (!switched && model.getState() == State::Loading) {
switched = true;
model.setUser("Bob", false);
}
});
model.setUser("Alice", true);
EXPECT_TRUE(client.sent.isEmpty());
EXPECT_EQ(State::Offline, model.getState());
}
TEST(UserGamesModel, TimedOutResponseCannotReplaceARetry)
{
GamesClient client;
UserGamesModel model(&client, 50);
model.setUser("Alice", true);
QSignalSpy changes(&model, &UserGamesModel::stateChanged);
ASSERT_TRUE(changes.wait(1000));
ASSERT_EQ(State::Error, model.getState());
EXPECT_TRUE(model.canRefresh());
model.refresh();
client.answer(0, gamesResponse({1}));
EXPECT_EQ(State::Loading, model.getState());
client.answer(1, gamesResponse({2}));
EXPECT_EQ(State::Ready, model.getState());
EXPECT_EQ(2, model.data(model.index(0), UserGamesModel::GameRole).value<ServerInfo_Game>().game_id());
}
} // namespace
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}