Cockatrice/oracle/src/oracleimporter.h
BruebachL 7d867b9745
Some checks failed
CodeQL / Analyze (cpp) (push) Has been cancelled
CodeQL / Analyze (actions) (push) Has been cancelled
Build Desktop / Configure (push) Has been cancelled
Build Docker / Servatrice (arm) (push) Has been cancelled
Build Docker / Servatrice (x86) (push) Has been cancelled
Build Desktop / Debian 13 (push) Has been cancelled
Build Desktop / Debian 12 (push) Has been cancelled
Build Desktop / Fedora 44 (push) Has been cancelled
Build Desktop / Fedora 43 (push) Has been cancelled
Build Desktop / Servatrice_Debian 12 (push) Has been cancelled
Build Desktop / Ubuntu 26.04 (push) Has been cancelled
Build Desktop / Ubuntu 24.04 (push) Has been cancelled
Build Desktop / Arch (push) Has been cancelled
Build Desktop / macOS 13 Intel (push) Has been cancelled
Build Desktop / macOS 14 (push) Has been cancelled
Build Desktop / macOS 15 (push) Has been cancelled
Build Desktop / macOS 26 Debug (push) Has been cancelled
Build Desktop / Windows 10 (push) Has been cancelled
Build Docker / Publish multi-platform Servatrice image (push) Has been cancelled
[Oracle/Client] Report card database download progress (#7253)
* [Oracle/Client] Report card database download progress

Card database updates ran invisibly: MTGJSON parsing spun an indeterminate
bar on the UI thread and the set import blocked the window, while the
onboarding wizard spawned `oracle -b` with no progress to show at all.

- Add byte-level scan progress to `RawJson::scanSetRanges` via an optional
  callback, throttled to ~100 reports per scan.
- Emit `OracleImporter::dataReadProgress` during the scan and import sets on a
  worker thread, driving the wizard's progress bar per set.
- With `-b`, write machine-readable `PROGRESS <stage> <done> <total>` lines to
  stdout for the download/scan/import stages; stderr keeps the log output.
- Parse the oracle stdout in `MainWindow` and forward it to the onboarding
  wizard, giving the card database step a determinate bar with stage-specific
  status text.
- Guard the async workers against the wizard being closed mid-run.
- Add Google Test coverage for scan progress reporting.

* [Oracle/Client] Harden oracle progress workers and quit prompt

Address review feedback on the download-progress change: decompress and read
sets files off the UI thread, cancel the load/import workers before the
wizard can tear down the importer, and show an 'Extracting file...' status
plus a clean 100% tail so the poll never looks stuck. Quitting Cockatrice
while a card database update runs now asks for confirmation.

* Show 100% for 500ms on complete.

* Disable buttons on set import until done.

* Clean up progress bar.

* Drop wrapper around lambda

---------

Co-authored-by: Lukas Brübach <Bruebach.Lukas@bdosecurity.de>
2026-09-09 22:27:16 +02:00

237 lines
7.1 KiB
C++

#ifndef ORACLEIMPORTER_H
#define ORACLEIMPORTER_H
#include "raw_json_scanner.h"
#include <QAtomicInt>
#include <QByteArray>
#include <QJsonArray>
#include <QJsonObject>
#include <QMap>
#include <QRegularExpression>
#include <QVariant>
#include <libcockatrice/card/card_info.h>
#include <utility>
// many users prefer not to see these sets with non english arts
// they will given priority PriorityLowest
const QStringList nonEnglishSets = {"4BB", "FBB", "PS11", "PSAL", "REN", "RIN"};
const QMap<QString, CardSet::Priority> setTypePriorities{
{"core", CardSet::PriorityPrimary},
{"expansion", CardSet::PriorityPrimary},
{"commander", CardSet::PrioritySecondary},
{"starter", CardSet::PrioritySecondary},
{"draft_innovation", CardSet::PrioritySecondary},
{"duel_deck", CardSet::PrioritySecondary},
{"archenemy", CardSet::PriorityReprint},
{"arsenal", CardSet::PriorityReprint},
{"box", CardSet::PriorityReprint},
{"eternal", CardSet::PriorityReprint},
{"from_the_vault", CardSet::PriorityReprint},
{"masterpiece", CardSet::PriorityReprint},
{"masters", CardSet::PriorityReprint},
{"memorabilia", CardSet::PriorityReprint},
{"planechase", CardSet::PriorityReprint},
{"premium_deck", CardSet::PriorityReprint},
{"promo", CardSet::PriorityReprint},
{"spellbook", CardSet::PriorityReprint},
{"token", CardSet::PriorityReprint},
{"treasure_chest", CardSet::PriorityReprint},
{"alchemy", CardSet::PriorityOther},
{"funny", CardSet::PriorityOther},
{"minigame", CardSet::PriorityOther},
{"vanguard", CardSet::PriorityOther},
};
class SetToDownload
{
private:
QString shortName, longName;
QDate releaseDate;
QString setType;
CardSet::Priority priority;
// Byte range of this set's object within the importer's raw JSON text. Parsing
// one set at a time keeps peak memory low instead of holding the whole document.
RawJson::SetDataRange rawRange;
public:
const QString &getShortName() const
{
return shortName;
}
const QString &getLongName() const
{
return longName;
}
const QString &getSetType() const
{
return setType;
}
const QDate &getReleaseDate() const
{
return releaseDate;
}
CardSet::Priority getPriority() const
{
return priority;
}
const RawJson::SetDataRange &getRawRange() const
{
return rawRange;
}
SetToDownload(QString _shortName,
QString _longName,
CardSet::Priority _priority,
QString _setType = QString(),
const QDate &_releaseDate = QDate())
: shortName(std::move(_shortName)), longName(std::move(_longName)), releaseDate(_releaseDate),
setType(std::move(_setType)), priority(_priority)
{
}
void setRawRange(const RawJson::SetDataRange &_rawRange)
{
rawRange = _rawRange;
}
bool operator<(const SetToDownload &set) const
{
return longName.compare(set.longName, Qt::CaseInsensitive) < 0;
}
};
class SplitCardPart
{
public:
SplitCardPart(const QString &_name,
const QString &_text,
const QHash<QString, QString> &_properties,
const PrintingInfo &_printingInfo);
inline const QString &getName() const
{
return name;
}
inline const QString &getText() const
{
return text;
}
inline const QHash<QString, QString> &getProperties() const
{
return properties;
}
inline const PrintingInfo &getPrintingInfo() const
{
return printingInfo;
}
private:
QString name;
QString text;
QHash<QString, QString> properties;
PrintingInfo printingInfo;
};
class OracleImporter : public QObject
{
Q_OBJECT
private:
static const QRegularExpression formatRegex;
/**
* The cards, indexed by name.
*/
CardNameMap cards;
/**
* The sets, indexed by short name.
*/
SetNameMap sets;
QList<SetToDownload> allSets;
/**
* The raw JSON text of the source document, retained for lazy per-set
* parsing during startImport(). Frees the card data as each set is imported.
*/
QByteArray rawSetsData;
/**
* Whether readSetsFromByteArray() should report scan progress via
* dataReadProgress. A background run routes that signal to stdout (for the
* hosting Cockatrice client to parse); the flag exists to skip the scanner
* instrumentation entirely when no consumer needs it.
*/
bool progressReporting = true;
/**
* Atomic "please stop importing" flag. startImport() checks it between sets
* so a wizard being closed mid-import can be torn down without waiting for
* the whole import (or racing it).
*/
QAtomicInt importCancelled;
CardInfoPtr addCard(QString name,
const QString &text,
bool isToken,
QHash<QString, QString> properties,
const QList<CardRelation *> &relatedCards,
const PrintingInfo &printingInfo);
signals:
void setIndexChanged(int cardsImported, int setIndex, const QString &setName);
void dataReadProgress(int bytesRead, int totalBytes);
public:
explicit OracleImporter(QObject *parent = nullptr);
/**
* @brief Controls whether readSetsFromByteArray() instruments the raw scan.
*
* When enabled (the default) the raw scanner reports progress via
* dataReadProgress(), which an interactive wizard shows on its progress bar
* and a background run routes to stdout for the hosting client. Switch it
* off only when nothing will consume scan progress.
*/
void setProgressReporting(bool enabled)
{
progressReporting = enabled;
}
/**
* Scans the given JSON document for set metadata. Takes the data by value so
* the wizard can hand over its decompressed buffer without copying it.
*/
bool readSetsFromByteArray(QByteArray data);
int startImport();
/**
* @brief Requests an in-flight startImport() to stop at the next set boundary.
*
* Works by setting an atomic flag that startImport() polls between sets, so
* cancelImport() followed by a short waitForFinished() on the running future is
* safe the moment the wizard is about to be destroyed.
*/
void cancelImport()
{
importCancelled.storeRelease(1);
}
bool saveToFile(const QString &fileName, const QString &sourceUrl, const QString &sourceVersion);
int importCardsFromSet(const CardSetPtr &currentSet, const QJsonArray &cardsList);
/**
* @brief Returns the default format rules. The result is memoized on first use and must be treated as immutable.
*/
const FormatRulesNameMap &createDefaultMagicFormats();
const CardNameMap &getCardList() const
{
return cards;
}
QList<SetToDownload> &getSets()
{
return allSets;
}
const QByteArray &getRawSetsData() const
{
return rawSetsData;
}
void releaseSetData();
void clear();
};
#endif