Commit 1e3fb6c6 authored by Fabio Bas's avatar Fabio Bas
Browse files

Rework "paths" settings loading and card database loading

 * main.cpp: removed path checking and db loading
 * card database: merge card loading methods into a single one
 * settings cache: take care of returning safe paths for decks,
replays, etc..
 * main window: if db loading fails (eg. first run), propose to run
oracle

NSIS: propose to run cockatrice instead of oracle

Rework card database loading

 * Move carddatabase-related method out of deckeditor tab
 * Load cards in another thread and render them progressively
 * Optimize database reload after enabled sets change

Fix deck editor column width

 * removed the noCard hack.
 * getCard() no more creates cards instead of just returning existing
ones
 * Fix the “edit tokens” dialog.
 * PictureLoader: avoid trying to download twice the same card
 * PictureLoader: correct return of card background
 * AbstractCardItem: avoid recalculating card color at every paint

Use a different file to save custom tokens

Misc required improvements

 * Use nullptr;
 * Refactor CardInfoWidget to use CardInfoPicture and CardInfoText
instead of duplicating code;
 * Added CardInfo::getColorChar()
 * Fixed some potential crashes
 * removed dead code related to CardInfoWidget
 * Don't require a restart after adding a new custom sets file
 * Bump CMake requirements to 3.1
parent 0b8f52e0
#include "dlg_edit_tokens.h" #include "dlg_edit_tokens.h"
#include "carddatabase.h"
#include "carddatabasemodel.h" #include "carddatabasemodel.h"
#include "main.h"
#include <QDialogButtonBox> #include <QDialogButtonBox>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout> #include <QHBoxLayout>
...@@ -15,8 +17,8 @@ ...@@ -15,8 +17,8 @@
#include <QInputDialog> #include <QInputDialog>
#include <QMessageBox> #include <QMessageBox>
DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent) DlgEditTokens::DlgEditTokens(QWidget *parent)
: QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel) : QDialog(parent), currentCard(0)
{ {
nameLabel = new QLabel(tr("&Name:")); nameLabel = new QLabel(tr("&Name:"));
nameEdit = new QLineEdit; nameEdit = new QLineEdit;
...@@ -25,13 +27,13 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par ...@@ -25,13 +27,13 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par
colorLabel = new QLabel(tr("C&olor:")); colorLabel = new QLabel(tr("C&olor:"));
colorEdit = new QComboBox; colorEdit = new QComboBox;
colorEdit->addItem(tr("white"), "w"); colorEdit->addItem(tr("white"), QChar('w'));
colorEdit->addItem(tr("blue"), "u"); colorEdit->addItem(tr("blue"), QChar('u'));
colorEdit->addItem(tr("black"), "b"); colorEdit->addItem(tr("black"), QChar('b'));
colorEdit->addItem(tr("red"), "r"); colorEdit->addItem(tr("red"), QChar('r'));
colorEdit->addItem(tr("green"), "g"); colorEdit->addItem(tr("green"), QChar('g'));
colorEdit->addItem(tr("multicolor"), "m"); colorEdit->addItem(tr("multicolor"), QChar('m'));
colorEdit->addItem(tr("colorless"), QString()); colorEdit->addItem(tr("colorless"), QChar());
colorLabel->setBuddy(colorEdit); colorLabel->setBuddy(colorEdit);
connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int))); connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int)));
...@@ -57,9 +59,11 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par ...@@ -57,9 +59,11 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par
QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data"));
tokenDataGroupBox->setLayout(grid); tokenDataGroupBox->setLayout(grid);
cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); databaseModel = new CardDatabaseModel(db, this);
cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); databaseModel->setObjectName("databaseModel");
cardDatabaseDisplayModel = new TokenDisplayModel(this);
cardDatabaseDisplayModel->setSourceModel(databaseModel);
cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue);
chooseTokenView = new QTreeView; chooseTokenView = new QTreeView;
...@@ -116,39 +120,43 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par ...@@ -116,39 +120,43 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par
void DlgEditTokens::tokenSelectionChanged(const QModelIndex &current, const QModelIndex & /* previous */) void DlgEditTokens::tokenSelectionChanged(const QModelIndex &current, const QModelIndex & /* previous */)
{ {
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard(); currentCard = current.row() >= 0 ? databaseModel->getCard(realIndex.row()) : 0;
if (!cardInfo->getName().isEmpty())
currentCard = cardInfo; if(currentCard)
else {
currentCard = 0; nameEdit->setText(currentCard->getName());
const QChar cardColor = currentCard->getColorChar();
nameEdit->setText(cardInfo->getName()); colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); ptEdit->setText(currentCard->getPowTough());
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); annotationEdit->setText(currentCard->getText());
ptEdit->setText(cardInfo->getPowTough()); } else {
annotationEdit->setText(cardInfo->getText()); nameEdit->setText("");
colorEdit->setCurrentIndex(colorEdit->findData(QChar(), Qt::UserRole, Qt::MatchFixedString));
ptEdit->setText("");
annotationEdit->setText("");
}
} }
void DlgEditTokens::actAddToken() void DlgEditTokens::actAddToken()
{ {
QString name; QString name;
bool askAgain; bool askAgain = true;
do { do {
name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:")); name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:"));
if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) { if(name.isEmpty())
return;
if (databaseModel->getDatabase()->getCard(name)) {
QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.\nMake sure to enable the 'token set' in the 'Edit sets...' dialog to display them correctly.")); QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.\nMake sure to enable the 'token set' in the 'Edit sets...' dialog to display them correctly."));
askAgain = true; } else {
} else
askAgain = false; askAgain = false;
}
} while (askAgain); } while (askAgain);
if (name.isEmpty())
return;
CardInfo *card = new CardInfo(name, true); CardInfo *card = new CardInfo(name, true);
card->addToSet(cardDatabaseModel->getDatabase()->getSet(CardDatabase::TOKENS_SETNAME)); card->addToSet(databaseModel->getDatabase()->getSet(CardDatabase::TOKENS_SETNAME));
card->setCardType("Token"); card->setCardType("Token");
cardDatabaseModel->getDatabase()->addCard(card); databaseModel->getDatabase()->addCard(card);
} }
void DlgEditTokens::actRemoveToken() void DlgEditTokens::actRemoveToken()
...@@ -156,7 +164,7 @@ void DlgEditTokens::actRemoveToken() ...@@ -156,7 +164,7 @@ void DlgEditTokens::actRemoveToken()
if (currentCard) { if (currentCard) {
CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard()
currentCard = 0; currentCard = 0;
cardDatabaseModel->getDatabase()->removeCard(cardToRemove); databaseModel->getDatabase()->removeCard(cardToRemove);
delete cardToRemove; delete cardToRemove;
} }
} }
...@@ -164,7 +172,7 @@ void DlgEditTokens::actRemoveToken() ...@@ -164,7 +172,7 @@ void DlgEditTokens::actRemoveToken()
void DlgEditTokens::colorChanged(int colorIndex) void DlgEditTokens::colorChanged(int colorIndex)
{ {
if (currentCard) if (currentCard)
currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString()); currentCard->setColors(QStringList() << QString(colorEdit->itemData(colorIndex).toChar()));
} }
void DlgEditTokens::ptChanged(const QString &_pt) void DlgEditTokens::ptChanged(const QString &_pt)
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
class QModelIndex; class QModelIndex;
class CardDatabaseModel; class CardDatabaseModel;
class CardDatabaseDisplayModel; class TokenDisplayModel;
class QLabel; class QLabel;
class QComboBox; class QComboBox;
class QLineEdit; class QLineEdit;
...@@ -24,15 +24,15 @@ private slots: ...@@ -24,15 +24,15 @@ private slots:
void actRemoveToken(); void actRemoveToken();
private: private:
CardInfo *currentCard; CardInfo *currentCard;
CardDatabaseModel *cardDatabaseModel; CardDatabaseModel *databaseModel;
CardDatabaseDisplayModel *cardDatabaseDisplayModel; TokenDisplayModel *cardDatabaseDisplayModel;
QStringList predefinedTokens; QStringList predefinedTokens;
QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel;
QComboBox *colorEdit; QComboBox *colorEdit;
QLineEdit *nameEdit, *ptEdit, *annotationEdit; QLineEdit *nameEdit, *ptEdit, *annotationEdit;
QTreeView *chooseTokenView; QTreeView *chooseTokenView;
public: public:
DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0); DlgEditTokens(QWidget *parent = 0);
}; };
#endif #endif
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
#include <QLibraryInfo> #include <QLibraryInfo>
#include <QDateTime> #include <QDateTime>
#include <QDir> #include <QDir>
#include <QDesktopServices>
#include <QDebug> #include <QDebug>
#include <QSystemTrayIcon> #include <QSystemTrayIcon>
#include "QtNetwork/QNetworkInterface" #include "QtNetwork/QNetworkInterface"
...@@ -86,14 +85,6 @@ void installNewTranslator() ...@@ -86,14 +85,6 @@ void installNewTranslator()
qApp->installTranslator(translator); qApp->installTranslator(translator);
} }
bool settingsValid()
{
return QDir(settingsCache->getDeckPath()).exists() &&
!settingsCache->getDeckPath().isEmpty() &&
QDir(settingsCache->getPicsPath()).exists() &&
!settingsCache->getPicsPath().isEmpty();
}
QString const generateClientID() QString const generateClientID()
{ {
QString macList; QString macList;
...@@ -156,73 +147,21 @@ int main(int argc, char *argv[]) ...@@ -156,73 +147,21 @@ int main(int argc, char *argv[])
qsrand(QDateTime::currentDateTime().toTime_t()); qsrand(QDateTime::currentDateTime().toTime_t());
#ifdef PORTABLE_BUILD qDebug("main(): starting main program");
const QString dataDir = "data/";
#elif QT_VERSION < 0x050000
const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
const QString dataDir = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
if (settingsCache->getCardDatabasePath().isEmpty() ||
db->loadCardDatabase() != Ok)
settingsCache->setCardDatabasePath(dataDir + "/cards.xml");
if (settingsCache->getTokenDatabasePath().isEmpty() ||
db->loadTokenDatabase() != Ok)
settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml");
if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) {
QDir().mkpath(dataDir + "/decks");
settingsCache->setDeckPath(dataDir + "/decks");
}
if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) {
QDir().mkpath(dataDir + "/replays");
settingsCache->setReplaysPath(dataDir + "/replays");
}
if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) {
QDir().mkpath(dataDir + "/pics");
settingsCache->setPicsPath(dataDir + "/pics");
}
if (!QDir().mkpath(settingsCache->getPicsPath() + "/CUSTOM"))
qDebug() << "Could not create " + settingsCache->getPicsPath().toUtf8() + "/CUSTOM. Will fall back on default card images.";
if (!settingsValid() || db->getLoadStatus() != Ok) {
qDebug("main(): invalid settings or load status");
DlgSettings dlgSettings;
dlgSettings.show();
app.exec();
}
// load custom databased after LoadStatus check, so that they don't bring up the settings dialog
if (QDir().mkpath(dataDir + "/customsets"))
{
// if the dir exists (or has just been created)
db->loadCustomCardDatabases(dataDir + "/customsets");
} else {
qDebug() << "Could not create " + dataDir + "/customsets folder.";
}
// when all the cards have been loaded, resolve the reverse-related tags
db->refreshCachedReverseRelatedCards();
if (settingsValid()) { MainWindow ui;
qDebug("main(): starting main program"); qDebug("main(): MainWindow constructor finished");
MainWindow ui; ui.setWindowIcon(QPixmap("theme:cockatrice"));
qDebug("main(): MainWindow constructor finished");
settingsCache->setClientID(generateClientID());
ui.setWindowIcon(QPixmap("theme:cockatrice")); ui.show();
qDebug("main(): ui.show() finished");
settingsCache->setClientID(generateClientID());
ui.show();
qDebug("main(): ui.show() finished");
#if QT_VERSION > 0x050000 #if QT_VERSION > 0x050000
app.setAttribute(Qt::AA_UseHighDpiPixmaps); app.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif #endif
app.exec(); app.exec();
}
qDebug("Event loop finished, terminating..."); qDebug("Event loop finished, terminating...");
delete db; delete db;
......
...@@ -16,6 +16,4 @@ void installNewTranslator(); ...@@ -16,6 +16,4 @@ void installNewTranslator();
QString const generateClientID(); QString const generateClientID();
bool settingsValid();
#endif #endif
...@@ -7,7 +7,6 @@ ...@@ -7,7 +7,6 @@
class Player; class Player;
class CardZone; class CardZone;
class CardInfoWidget;
class GameEventContext; class GameEventContext;
class CardItem; class CardItem;
......
...@@ -96,6 +96,7 @@ PictureLoaderWorker::PictureLoaderWorker() ...@@ -96,6 +96,7 @@ PictureLoaderWorker::PictureLoaderWorker()
downloadRunning(false), loadQueueRunning(false) downloadRunning(false), loadQueueRunning(false)
{ {
picsPath = settingsCache->getPicsPath(); picsPath = settingsCache->getPicsPath();
customPicsPath = settingsCache->getCustomPicsPath();
picDownload = settingsCache->getPicDownload(); picDownload = settingsCache->getPicDownload();
connect(this, SIGNAL(startLoadQueue()), this, SLOT(processLoadQueue()), Qt::QueuedConnection); connect(this, SIGNAL(startLoadQueue()), this, SLOT(processLoadQueue()), Qt::QueuedConnection);
...@@ -167,7 +168,7 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor ...@@ -167,7 +168,7 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor
imgReader.setDecideFormatFromContent(true); imgReader.setDecideFormatFromContent(true);
//The list of paths to the folders in which to search for images //The list of paths to the folders in which to search for images
QList<QString> picsPaths = QList<QString>() << picsPath + "/CUSTOM/" + correctedCardname; QList<QString> picsPaths = QList<QString>() << customPicsPath + correctedCardname;
if(!setName.isEmpty()) if(!setName.isEmpty())
{ {
...@@ -196,7 +197,7 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor ...@@ -196,7 +197,7 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor
QString PictureLoaderWorker::getPicUrl() QString PictureLoaderWorker::getPicUrl()
{ {
if (!picDownload) return QString(""); if (!picDownload) return QString();
CardInfo *card = cardBeingDownloaded.getCard(); CardInfo *card = cardBeingDownloaded.getCard();
CardSet *set=cardBeingDownloaded.getCurrentSet(); CardSet *set=cardBeingDownloaded.getCurrentSet();
...@@ -236,7 +237,7 @@ QString PictureLoaderWorker::getPicUrl() ...@@ -236,7 +237,7 @@ QString PictureLoaderWorker::getPicUrl()
) )
{ {
qDebug() << "Insufficient card data to download" << card->getName() << "Url:" << picUrl; qDebug() << "Insufficient card data to download" << card->getName() << "Url:" << picUrl;
return QString(""); return QString();
} }
return picUrl; return picUrl;
...@@ -275,12 +276,12 @@ void PictureLoaderWorker::picDownloadFailed() ...@@ -275,12 +276,12 @@ void PictureLoaderWorker::picDownloadFailed()
mutex.lock(); mutex.lock();
loadQueue.prepend(cardBeingDownloaded); loadQueue.prepend(cardBeingDownloaded);
mutex.unlock(); mutex.unlock();
emit startLoadQueue();
} else { } else {
qDebug() << "Picture NOT found, download failed, no more sets to try: BAILING OUT (oldset: " << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getCorrectedName() << ")"; qDebug() << "Picture NOT found, download failed, no more sets to try: BAILING OUT (oldset: " << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getCorrectedName() << ")";
cardBeingDownloaded = 0;
imageLoaded(cardBeingDownloaded.getCard(), QImage()); imageLoaded(cardBeingDownloaded.getCard(), QImage());
cardBeingDownloaded = 0;
} }
emit startLoadQueue();
} }
bool PictureLoaderWorker::imageIsBlackListed(const QByteArray &picData) bool PictureLoaderWorker::imageIsBlackListed(const QByteArray &picData)
...@@ -354,7 +355,7 @@ void PictureLoaderWorker::enqueueImageLoad(CardInfo *card) ...@@ -354,7 +355,7 @@ void PictureLoaderWorker::enqueueImageLoad(CardInfo *card)
QMutexLocker locker(&mutex); QMutexLocker locker(&mutex);
// avoid queueing the same card more than once // avoid queueing the same card more than once
if(card == 0 || card == cardBeingLoaded.getCard() || card == cardBeingDownloaded.getCard()) if(!card || card == cardBeingLoaded.getCard() || card == cardBeingDownloaded.getCard())
return; return;
foreach(PictureToLoad pic, loadQueue) foreach(PictureToLoad pic, loadQueue)
...@@ -363,6 +364,12 @@ void PictureLoaderWorker::enqueueImageLoad(CardInfo *card) ...@@ -363,6 +364,12 @@ void PictureLoaderWorker::enqueueImageLoad(CardInfo *card)
return; return;
} }
foreach(PictureToLoad pic, cardsToDownload)
{
if(pic.getCard() == card)
return;
}
loadQueue.append(PictureToLoad(card)); loadQueue.append(PictureToLoad(card));
emit startLoadQueue(); emit startLoadQueue();
} }
...@@ -377,6 +384,7 @@ void PictureLoaderWorker::picsPathChanged() ...@@ -377,6 +384,7 @@ void PictureLoaderWorker::picsPathChanged()
{ {
QMutexLocker locker(&mutex); QMutexLocker locker(&mutex);
picsPath = settingsCache->getPicsPath(); picsPath = settingsCache->getPicsPath();
customPicsPath = settingsCache->getCustomPicsPath();
} }
PictureLoader::PictureLoader() PictureLoader::PictureLoader()
...@@ -409,11 +417,6 @@ void PictureLoader::getPixmap(QPixmap &pixmap, CardInfo *card, QSize size) ...@@ -409,11 +417,6 @@ void PictureLoader::getPixmap(QPixmap &pixmap, CardInfo *card, QSize size)
{ {
if(card) if(card)
{ {
if (card->getName().isEmpty()) {
internalGetCardBackPixmap(pixmap, size);
return;
}
// search for an exact size copy of the picure in cache // search for an exact size copy of the picure in cache
QString key = card->getPixmapCacheKey(); QString key = card->getPixmapCacheKey();
QString sizekey = key + QLatin1Char('_') + QString::number(size.width()) + QString::number(size.height()); QString sizekey = key + QLatin1Char('_') + QString::number(size.width()) + QString::number(size.height());
...@@ -428,30 +431,28 @@ void PictureLoader::getPixmap(QPixmap &pixmap, CardInfo *card, QSize size) ...@@ -428,30 +431,28 @@ void PictureLoader::getPixmap(QPixmap &pixmap, CardInfo *card, QSize size)
QPixmapCache::insert(sizekey, pixmap); QPixmapCache::insert(sizekey, pixmap);
return; return;
} }
}
// load a temporary back picture
internalGetCardBackPixmap(pixmap, size);
if(card)
{
// add the card to the load queue // add the card to the load queue
getInstance().worker->enqueueImageLoad(card); getInstance().worker->enqueueImageLoad(card);
} else {
// requesting the image for a null card is a shortcut to get the card background image
internalGetCardBackPixmap(pixmap, size);
} }
} }
void PictureLoader::imageLoaded(CardInfo *card, const QImage &image) void PictureLoader::imageLoaded(CardInfo *card, const QImage &image)
{ {
if(image.isNull()) if(image.isNull())
return;
if(card->getUpsideDownArt())
{ {
QImage mirrorImage = image.mirrored(true, true); QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap());
QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap::fromImage(mirrorImage));
} else { } else {
QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap::fromImage(image)); if(card->getUpsideDownArt())
{
QImage mirrorImage = image.mirrored(true, true);
QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap::fromImage(mirrorImage));
} else {
QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap::fromImage(image));
}
} }
card->emitPixmapUpdated(); card->emitPixmapUpdated();
......
...@@ -39,7 +39,7 @@ private: ...@@ -39,7 +39,7 @@ private:
static QStringList md5Blacklist; static QStringList md5Blacklist;
QThread *pictureLoaderThread; QThread *pictureLoaderThread;
QString picsPath; QString picsPath, customPicsPath;
QList<PictureToLoad> loadQueue; QList<PictureToLoad> loadQueue;
QMutex mutex; QMutex mutex;
QNetworkAccessManager *networkManager; QNetworkAccessManager *networkManager;
......
...@@ -1081,7 +1081,8 @@ void Player::actCreateToken() ...@@ -1081,7 +1081,8 @@ void Player::actCreateToken()
lastTokenName = dlg.getName(); lastTokenName = dlg.getName();
lastTokenPT = dlg.getPT(); lastTokenPT = dlg.getPT();
if (CardInfo *correctedCard = db->getCardBySimpleName(lastTokenName, false)) { CardInfo *correctedCard = db->getCardBySimpleName(lastTokenName);
if (correctedCard) {
lastTokenName = correctedCard->getName(); lastTokenName = correctedCard->getName();
lastTokenTableRow = table->clampValidTableRow(2 - correctedCard->getTableRow()); lastTokenTableRow = table->clampValidTableRow(2 - correctedCard->getTableRow());
if (lastTokenPT.isEmpty()) if (lastTokenPT.isEmpty())
...@@ -1114,7 +1115,9 @@ void Player::actCreatePredefinedToken() ...@@ -1114,7 +1115,9 @@ void Player::actCreatePredefinedToken()
{ {
QAction *action = static_cast<QAction *>(sender()); QAction *action = static_cast<QAction *>(sender());
CardInfo *cardInfo = db->getCard(action->text()); CardInfo *cardInfo = db->getCard(action->text());
if(!cardInfo)
return;
lastTokenName = cardInfo->getName(); lastTokenName = cardInfo->getName();
lastTokenColor = cardInfo->getColors().isEmpty() ? QString() : cardInfo->getColors().first().toLower(); lastTokenColor = cardInfo->getColors().isEmpty() ? QString() : cardInfo->getColors().first().toLower();
lastTokenPT = cardInfo->getPowTough(); lastTokenPT = cardInfo->getPowTough();
...@@ -1141,6 +1144,8 @@ void Player::actCreateRelatedCard() ...@@ -1141,6 +1144,8 @@ void Player::actCreateRelatedCard()
if (spaces.at(0).indexOf("/") != -1) // Strip space from creatures if (spaces.at(0).indexOf("/") != -1) // Strip space from creatures
spaces.removeFirst(); spaces.removeFirst();
CardInfo *cardInfo = db->getCard(spaces.join(" ")); CardInfo *cardInfo = db->getCard(spaces.join(" "));
if(!cardInfo)
return;
// get the target token's location // get the target token's location
// TODO: Define this QPoint into its own function along with the one below // TODO: Define this QPoint into its own function along with the one below
...@@ -1256,9 +1261,13 @@ void Player::eventCreateToken(const Event_CreateToken &event) ...@@ -1256,9 +1261,13 @@ void Player::eventCreateToken(const Event_CreateToken &event)
CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id()); CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id());
// use db PT if not provided in event // use db PT if not provided in event
if (!QString::fromStdString(event.pt()).isEmpty()) if (!QString::fromStdString(event.pt()).isEmpty())
{
card->setPT(QString::fromStdString(event.pt())); card->setPT(QString::fromStdString(event.pt()));
else } else {
card->setPT(db->getCard(QString::fromStdString(event.card_name()))->getPowTough()); CardInfo * dbCard = db->getCard(QString::fromStdString(event.card_name()));
if(dbCard)
card->setPT(dbCard->getPowTough());
}
card->setColor(QString::fromStdString(event.color())); card->setColor(QString::fromStdString(event.color()));
card->setAnnotation(QString::fromStdString(event.annotation())); card->setAnnotation(QString::fromStdString(event.annotation()));
card->setDestroyOnZoneChange(event.destroy_on_zone_change()); card->setDestroyOnZoneChange(event.destroy_on_zone_change());
...@@ -1713,6 +1722,8 @@ void Player::playCard(CardItem *c, bool faceDown, bool tapped) ...@@ -1713,6 +1722,8 @@ void Player::playCard(CardItem *c, bool faceDown, bool tapped)
cardToMove->set_card_id(c->getId()); cardToMove->set_card_id(c->getId());
CardInfo *ci = c->getInfo(); CardInfo *ci = c->getInfo();
if(!ci)
return;
if (!faceDown && ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || if (!faceDown && ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) ||
((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) &&
c->getZone()->getName().toStdString() != "stack"))) { c->getZone()->getName().toStdString() != "stack"))) {
...@@ -2293,7 +2304,8 @@ void Player::actPlay() ...@@ -2293,7 +2304,8 @@ void Player::actPlay()
if(!game->getActiveCard()) if(!game->getActiveCard())
return; return;
playCard(game->getActiveCard(), false, game->getActiveCard()->getInfo()->getCipt()); bool cipt = game->getActiveCard()->getInfo() ? game->getActiveCard()->getInfo()->getCipt(): false;
playCard(game->getActiveCard(), false, cipt);
} }
void Player::actHide() void Player::actHide()
...@@ -2374,20 +2386,23 @@ void Player::updateCardMenu(CardItem *card) ...@@ -2374,20 +2386,23 @@ void Player::updateCardMenu(CardItem *card)
if (card->getFaceDown()) if (card->getFaceDown())
cardMenu->addAction(aPeek); cardMenu->addAction(aPeek);
QStringList relatedCards = card->getInfo()->getRelatedCards(); if(card->getInfo())
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
if(relatedCards.size() || reverserelatedCards2Me.size())
{ {
QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card")); QStringList relatedCards = card->getInfo()->getRelatedCards();
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
for (int i = 0; i < relatedCards.size(); ++i) { if(relatedCards.size() || reverserelatedCards2Me.size())
QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i)); {
connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard())); QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card"));
}
for (int i = 0; i < relatedCards.size(); ++i) {
for (int i = 0; i < reverserelatedCards2Me.size(); ++i) { QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i));
QAction *a = createRelatedCardMenu->addAction(reverserelatedCards2Me.at(i)); connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard()));
connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard())); }
for (int i = 0; i < reverserelatedCards2Me.size(); ++i) {
QAction *a = createRelatedCardMenu->addAction(reverserelatedCards2Me.at(i));
connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard()));
}
} }
} }
cardMenu->addSeparator(); cardMenu->addSeparator();
...@@ -2413,20 +2428,23 @@ void Player::updateCardMenu(CardItem *card) ...@@ -2413,20 +2428,23 @@ void Player::updateCardMenu(CardItem *card)
cardMenu->addAction(aDrawArrow); cardMenu->addAction(aDrawArrow);
cardMenu->addMenu(moveMenu); cardMenu->addMenu(moveMenu);
QStringList relatedCards = card->getInfo()->getRelatedCards(); if(card->getInfo())
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
if(relatedCards.size() || reverserelatedCards2Me.size())
{ {
QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card")); QStringList relatedCards = card->getInfo()->getRelatedCards();
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
for (int i = 0; i < relatedCards.size(); ++i) { if(relatedCards.size() || reverserelatedCards2Me.size())
QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i)); {
connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard())); QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card"));
}
for (int i = 0; i < relatedCards.size(); ++i) {
for (int i = 0; i < reverserelatedCards2Me.size(); ++i) { QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i));
QAction *a = createRelatedCardMenu->addAction(reverserelatedCards2Me.at(i)); connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard()));
connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard())); }
for (int i = 0; i < reverserelatedCards2Me.size(); ++i) {
QAction *a = createRelatedCardMenu->addAction(reverserelatedCards2Me.at(i));
connect(a, SIGNAL(triggered()), this, SLOT(actCreateRelatedCard()));
}
} }
} }
} else { } else {
......
...@@ -60,7 +60,9 @@ void DBPriceUpdater::updatePrices() ...@@ -60,7 +60,9 @@ void DBPriceUpdater::updatePrices()
bool bNotFirst=false; bool bNotFirst=false;
for (int i = 0; i < cards.size(); ++i) { for (int i = 0; i < cards.size(); ++i) {
card = db->getCard(cards[i], false); card = db->getCard(cards[i]);
if(!card)
continue;
sets = card->getSets(); sets = card->getSets();
for(int j = 0; j < sets.size(); ++j) for(int j = 0; j < sets.size(); ++j)
{ {
......
...@@ -194,7 +194,7 @@ void SetsModel::save(CardDatabase *db) ...@@ -194,7 +194,7 @@ void SetsModel::save(CardDatabase *db)
sets.sortByKey(); sets.sortByKey();
db->emitCardListChanged(); db->notifyEnabledSetsChanged();
} }
void SetsModel::restore(CardDatabase *db) void SetsModel::restore(CardDatabase *db)
......
#include "settingscache.h" #include "settingscache.h"
#include <QSettings> #include <QSettings>
#include <QFile> #include <QFile>
#include <QDir>
#include <QDebug>
#include <QApplication> #include <QApplication>
#if QT_VERSION >= 0x050000 #if QT_VERSION >= 0x050000
...@@ -9,20 +11,21 @@ ...@@ -9,20 +11,21 @@
#include <QDesktopServices> #include <QDesktopServices>
#endif #endif
QString SettingsCache::getSettingsPath() QString SettingsCache::getDataPath()
{ {
QString file = qApp->applicationDirPath() + "/settings/"; return
#ifdef PORTABLE_BUILD
#ifndef PORTABLE_BUILD qApp->applicationDirPath() + "/data/";
#if QT_VERSION >= 0x050000 #elif QT_VERSION >= 0x050000
file = QStandardPaths::writableLocation(QStandardPaths::DataLocation); QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#else #else
file = QDesktopServices::storageLocation(QDesktopServices::DataLocation); QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#endif #endif
file.append("/settings/"); }
#endif
return file; QString SettingsCache::getSettingsPath()
{
return getDataPath() + "/settings/";
} }
void SettingsCache::translateLegacySettings() void SettingsCache::translateLegacySettings()
...@@ -119,8 +122,31 @@ void SettingsCache::translateLegacySettings() ...@@ -119,8 +122,31 @@ void SettingsCache::translateLegacySettings()
} }
} }
QString SettingsCache::getSafeConfigPath(QString configEntry, QString defaultPath) const
{
QString tmp = settings->value(configEntry).toString();
// if the config settings is empty or refers to a not-existing folder,
// ensure that the defaut path exists and return it
if (!QDir(tmp).exists() || tmp.isEmpty()) {
if(!QDir().mkpath(defaultPath))
qDebug() << "[SettingsCache] Could not create folder:" << defaultPath;
tmp = defaultPath;
}
return tmp;
}
QString SettingsCache::getSafeConfigFilePath(QString configEntry, QString defaultPath) const
{
QString tmp = settings->value(configEntry).toString();
// if the config settings is empty or refers to a not-existing file,
// return the default Path
if (!QFile::exists(tmp) || tmp.isEmpty())
tmp = defaultPath;
return tmp;
}
SettingsCache::SettingsCache() SettingsCache::SettingsCache()
{ {
QString dataPath = getDataPath();
QString settingsPath = getSettingsPath(); QString settingsPath = getSettingsPath();
settings = new QSettings(settingsPath+"global.ini", QSettings::IniFormat, this); settings = new QSettings(settingsPath+"global.ini", QSettings::IniFormat, this);
shortcutsSettings = new ShortcutsSettings(settingsPath,this); shortcutsSettings = new ShortcutsSettings(settingsPath,this);
...@@ -133,20 +159,20 @@ SettingsCache::SettingsCache() ...@@ -133,20 +159,20 @@ SettingsCache::SettingsCache()
if(!QFile(settingsPath+"global.ini").exists()) if(!QFile(settingsPath+"global.ini").exists())
translateLegacySettings(); translateLegacySettings();
#ifdef PORTABLE_BUILD
setDeckPath(qApp->applicationDirPath() + "data/decks");
setReplaysPath(qApp->applicationDirPath() +"data/replays");
setPicsPath(qApp->applicationDirPath() + "data/pics");
#endif
notifyAboutUpdates = settings->value("personal/updatenotification", true).toBool(); notifyAboutUpdates = settings->value("personal/updatenotification", true).toBool();
lang = settings->value("personal/lang").toString(); lang = settings->value("personal/lang").toString();
keepalive = settings->value("personal/keepalive", 5).toInt(); keepalive = settings->value("personal/keepalive", 5).toInt();
deckPath = settings->value("paths/decks").toString();
replaysPath = settings->value("paths/replays").toString(); deckPath = getSafeConfigPath("paths/decks", dataPath + "/decks/");
picsPath = settings->value("paths/pics").toString(); replaysPath = getSafeConfigPath("paths/replays", dataPath + "/replays/");
cardDatabasePath = settings->value("paths/carddatabase").toString(); picsPath = getSafeConfigPath("paths/pics", dataPath + "/pics/");
tokenDatabasePath = settings->value("paths/tokendatabase").toString(); // this has never been exposed as an user-configurable setting
customPicsPath = getSafeConfigPath("paths/custompics", picsPath + "/CUSTOM/");
// this has never been exposed as an user-configurable setting
customCardDatabasePath = getSafeConfigPath("paths/customsets", dataPath + "/customsets/");
cardDatabasePath = getSafeConfigFilePath("paths/carddatabase", dataPath + "/cards.xml");
tokenDatabasePath = getSafeConfigFilePath("paths/tokendatabase", dataPath + "/tokens.xml");
themeName = settings->value("theme/name").toString(); themeName = settings->value("theme/name").toString();
...@@ -175,7 +201,6 @@ SettingsCache::SettingsCache() ...@@ -175,7 +201,6 @@ SettingsCache::SettingsCache()
doubleClickToPlay = settings->value("interface/doubleclicktoplay", true).toBool(); doubleClickToPlay = settings->value("interface/doubleclicktoplay", true).toBool();
playToStack = settings->value("interface/playtostack", true).toBool(); playToStack = settings->value("interface/playtostack", true).toBool();
annotateTokens = settings->value("interface/annotatetokens", false).toBool(); annotateTokens = settings->value("interface/annotatetokens", false).toBool();
cardInfoMinimized = settings->value("interface/cardinfominimized", 0).toInt();
tabGameSplitterSizes = settings->value("interface/tabgame_splittersizes").toByteArray(); tabGameSplitterSizes = settings->value("interface/tabgame_splittersizes").toByteArray();
displayCardNames = settings->value("cards/displaycardnames", true).toBool(); displayCardNames = settings->value("cards/displaycardnames", true).toBool();
horizontalHand = settings->value("hand/horizontal", true).toBool(); horizontalHand = settings->value("hand/horizontal", true).toBool();
...@@ -291,6 +316,8 @@ void SettingsCache::setPicsPath(const QString &_picsPath) ...@@ -291,6 +316,8 @@ void SettingsCache::setPicsPath(const QString &_picsPath)
{ {
picsPath = _picsPath; picsPath = _picsPath;
settings->setValue("paths/pics", picsPath); settings->setValue("paths/pics", picsPath);
// get a new value for customPicsPath, currently derived from picsPath
customPicsPath = getSafeConfigPath("paths/custompics", picsPath + "CUSTOM/");
emit picsPathChanged(); emit picsPathChanged();
} }
...@@ -305,7 +332,7 @@ void SettingsCache::setTokenDatabasePath(const QString &_tokenDatabasePath) ...@@ -305,7 +332,7 @@ void SettingsCache::setTokenDatabasePath(const QString &_tokenDatabasePath)
{ {
tokenDatabasePath = _tokenDatabasePath; tokenDatabasePath = _tokenDatabasePath;
settings->setValue("paths/tokendatabase", tokenDatabasePath); settings->setValue("paths/tokendatabase", tokenDatabasePath);
emit tokenDatabasePathChanged(); emit cardDatabasePathChanged();
} }
void SettingsCache::setThemeName(const QString &_themeName) void SettingsCache::setThemeName(const QString &_themeName)
...@@ -363,12 +390,6 @@ void SettingsCache::setAnnotateTokens(int _annotateTokens) ...@@ -363,12 +390,6 @@ void SettingsCache::setAnnotateTokens(int _annotateTokens)
settings->setValue("interface/annotatetokens", annotateTokens); settings->setValue("interface/annotatetokens", annotateTokens);
} }
void SettingsCache::setCardInfoMinimized(int _cardInfoMinimized)
{
cardInfoMinimized = _cardInfoMinimized;
settings->setValue("interface/cardinfominimized", cardInfoMinimized);
}
void SettingsCache::setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes) void SettingsCache::setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes)
{ {
tabGameSplitterSizes = _tabGameSplitterSizes; tabGameSplitterSizes = _tabGameSplitterSizes;
......
...@@ -27,7 +27,6 @@ signals: ...@@ -27,7 +27,6 @@ signals:
void langChanged(); void langChanged();
void picsPathChanged(); void picsPathChanged();
void cardDatabasePathChanged(); void cardDatabasePathChanged();
void tokenDatabasePathChanged();
void themeChanged(); void themeChanged();
void picDownloadChanged(); void picDownloadChanged();
void displayCardNamesChanged(); void displayCardNamesChanged();
...@@ -54,7 +53,7 @@ private: ...@@ -54,7 +53,7 @@ private:
QByteArray mainWindowGeometry; QByteArray mainWindowGeometry;
QString lang; QString lang;
QString deckPath, replaysPath, picsPath, cardDatabasePath, tokenDatabasePath, themeName; QString deckPath, replaysPath, picsPath, customPicsPath, cardDatabasePath, customCardDatabasePath, tokenDatabasePath, themeName;
bool notifyAboutUpdates; bool notifyAboutUpdates;
bool picDownload; bool picDownload;
bool notificationsEnabled; bool notificationsEnabled;
...@@ -62,7 +61,6 @@ private: ...@@ -62,7 +61,6 @@ private:
bool doubleClickToPlay; bool doubleClickToPlay;
bool playToStack; bool playToStack;
bool annotateTokens; bool annotateTokens;
int cardInfoMinimized;
QByteArray tabGameSplitterSizes; QByteArray tabGameSplitterSizes;
bool displayCardNames; bool displayCardNames;
bool horizontalHand; bool horizontalHand;
...@@ -105,16 +103,21 @@ private: ...@@ -105,16 +103,21 @@ private:
bool spectatorsCanSeeEverything; bool spectatorsCanSeeEverything;
int keepalive; int keepalive;
void translateLegacySettings(); void translateLegacySettings();
QString getSafeConfigPath(QString configEntry, QString defaultPath) const;
QString getSafeConfigFilePath(QString configEntry, QString defaultPath) const;
bool rememberGameSettings; bool rememberGameSettings;
public: public:
SettingsCache(); SettingsCache();
QString getDataPath();
QString getSettingsPath(); QString getSettingsPath();
const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; } const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; }
QString getLang() const { return lang; } QString getLang() const { return lang; }
QString getDeckPath() const { return deckPath; } QString getDeckPath() const { return deckPath; }
QString getReplaysPath() const { return replaysPath; } QString getReplaysPath() const { return replaysPath; }
QString getPicsPath() const { return picsPath; } QString getPicsPath() const { return picsPath; }
QString getCustomPicsPath() const { return customPicsPath; }
QString getCustomCardDatabasePath() const { return customCardDatabasePath; }
QString getCardDatabasePath() const { return cardDatabasePath; } QString getCardDatabasePath() const { return cardDatabasePath; }
QString getTokenDatabasePath() const { return tokenDatabasePath; } QString getTokenDatabasePath() const { return tokenDatabasePath; }
QString getThemeName() const { return themeName; } QString getThemeName() const { return themeName; }
...@@ -128,7 +131,6 @@ public: ...@@ -128,7 +131,6 @@ public:
bool getDoubleClickToPlay() const { return doubleClickToPlay; } bool getDoubleClickToPlay() const { return doubleClickToPlay; }
bool getPlayToStack() const { return playToStack; } bool getPlayToStack() const { return playToStack; }
bool getAnnotateTokens() const { return annotateTokens; } bool getAnnotateTokens() const { return annotateTokens; }
int getCardInfoMinimized() const { return cardInfoMinimized; }
QByteArray getTabGameSplitterSizes() const { return tabGameSplitterSizes; } QByteArray getTabGameSplitterSizes() const { return tabGameSplitterSizes; }
bool getDisplayCardNames() const { return displayCardNames; } bool getDisplayCardNames() const { return displayCardNames; }
bool getHorizontalHand() const { return horizontalHand; } bool getHorizontalHand() const { return horizontalHand; }
...@@ -200,7 +202,6 @@ public slots: ...@@ -200,7 +202,6 @@ public slots:
void setDoubleClickToPlay(int _doubleClickToPlay); void setDoubleClickToPlay(int _doubleClickToPlay);
void setPlayToStack(int _playToStack); void setPlayToStack(int _playToStack);
void setAnnotateTokens(int _annotateTokens); void setAnnotateTokens(int _annotateTokens);
void setCardInfoMinimized(int _cardInfoMinimized);
void setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes); void setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes);
void setDisplayCardNames(int _displayCardNames); void setDisplayCardNames(int _displayCardNames);
void setHorizontalHand(int _horizontalHand); void setHorizontalHand(int _horizontalHand);
......
...@@ -15,7 +15,7 @@ void Tab::showCardInfoPopup(const QPoint &pos, const QString &cardName) ...@@ -15,7 +15,7 @@ void Tab::showCardInfoPopup(const QPoint &pos, const QString &cardName)
infoPopup->deleteLater(); infoPopup->deleteLater();
} }
currentCardName = cardName; currentCardName = cardName;
infoPopup = new CardInfoWidget(CardInfoWidget::ModePopUp, cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint); infoPopup = new CardInfoWidget(cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint);
infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents); infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents);
QRect screenRect = qApp->desktop()->screenGeometry(this); QRect screenRect = qApp->desktop()->screenGeometry(this);
infoPopup->move( infoPopup->move(
......
...@@ -24,15 +24,11 @@ ...@@ -24,15 +24,11 @@
#include <QDir> #include <QDir>
#include <QDesktopServices> #include <QDesktopServices>
#include "tab_deck_editor.h" #include "tab_deck_editor.h"
#include "window_sets.h"
#include "carddatabase.h" #include "carddatabase.h"
#include "pictureloader.h" #include "pictureloader.h"
#include "carddatabasemodel.h" #include "carddatabasemodel.h"
#include "decklistmodel.h" #include "decklistmodel.h"
#include "cardinfowidget.h"
#include "dlg_load_deck_from_clipboard.h" #include "dlg_load_deck_from_clipboard.h"
#include "dlg_edit_tokens.h"
#include "dlg_add_set_result.h"
#include "main.h" #include "main.h"
#include "settingscache.h" #include "settingscache.h"
#include "priceupdater.h" #include "priceupdater.h"
...@@ -46,10 +42,6 @@ ...@@ -46,10 +42,6 @@
#include "cardframe.h" #include "cardframe.h"
#include "filterbuilder.h" #include "filterbuilder.h"
const QStringList TabDeckEditor::fileNameFilters = QStringList()
<< QObject::tr("Cockatrice card database (*.xml)")
<< QObject::tr("All files (*.*)");
void SearchLineEdit::keyPressEvent(QKeyEvent *event) void SearchLineEdit::keyPressEvent(QKeyEvent *event)
{ {
if (treeView && ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down))) if (treeView && ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down)))
...@@ -251,9 +243,6 @@ void TabDeckEditor::createMenus() ...@@ -251,9 +243,6 @@ void TabDeckEditor::createMenus()
aSaveDeckAs = new QAction(QString(), this); aSaveDeckAs = new QAction(QString(), this);
connect(aSaveDeckAs, SIGNAL(triggered()), this, SLOT(actSaveDeckAs())); connect(aSaveDeckAs, SIGNAL(triggered()), this, SLOT(actSaveDeckAs()));
aOpenCustomsetsFolder = new QAction(QString(), this);
connect(aOpenCustomsetsFolder, SIGNAL(triggered()), this, SLOT(actOpenCustomsetsFolder()));
aLoadDeckFromClipboard = new QAction(QString(), this); aLoadDeckFromClipboard = new QAction(QString(), this);
connect(aLoadDeckFromClipboard, SIGNAL(triggered()), this, SLOT(actLoadDeckFromClipboard())); connect(aLoadDeckFromClipboard, SIGNAL(triggered()), this, SLOT(actLoadDeckFromClipboard()));
...@@ -269,17 +258,13 @@ void TabDeckEditor::createMenus() ...@@ -269,17 +258,13 @@ void TabDeckEditor::createMenus()
aClose = new QAction(QString(), this); aClose = new QAction(QString(), this);
connect(aClose, SIGNAL(triggered()), this, SLOT(closeRequest())); connect(aClose, SIGNAL(triggered()), this, SLOT(closeRequest()));
aOpenCustomFolder = new QAction(QString(), this); aClearFilterAll = new QAction(QString(), this);
connect(aOpenCustomFolder, SIGNAL(triggered()), this, SLOT(actOpenCustomFolder())); aClearFilterAll->setIcon(QPixmap("theme:icons/clearsearch"));
connect(aClearFilterAll, SIGNAL(triggered()), this, SLOT(actClearFilterAll()));
aAddCustomSet = new QAction(QString(), this);
connect(aAddCustomSet, SIGNAL(triggered()), this, SLOT(actAddCustomSet()));
aEditSets = new QAction(QString(), this);
connect(aEditSets, SIGNAL(triggered()), this, SLOT(actEditSets()));
aEditTokens = new QAction(QString(), this); aClearFilterOne = new QAction(QString(), this);
connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens())); aClearFilterOne->setIcon(QPixmap("theme:icons/decrement"));
connect(aClearFilterOne, SIGNAL(triggered()), this, SLOT(actClearFilterOne()));
deckMenu = new QMenu(this); deckMenu = new QMenu(this);
deckMenu->addAction(aNewDeck); deckMenu->addAction(aNewDeck);
...@@ -291,34 +276,14 @@ void TabDeckEditor::createMenus() ...@@ -291,34 +276,14 @@ void TabDeckEditor::createMenus()
deckMenu->addAction(aSaveDeckToClipboard); deckMenu->addAction(aSaveDeckToClipboard);
deckMenu->addSeparator(); deckMenu->addSeparator();
deckMenu->addAction(aPrintDeck); deckMenu->addAction(aPrintDeck);
deckMenu->addSeparator();
deckMenu->addAction(aAnalyzeDeck); deckMenu->addAction(aAnalyzeDeck);
deckMenu->addSeparator(); deckMenu->addSeparator();
deckMenu->addAction(aClearFilterOne);
deckMenu->addAction(aClearFilterAll);
deckMenu->addSeparator();
deckMenu->addAction(aClose); deckMenu->addAction(aClose);
addTabMenu(deckMenu); addTabMenu(deckMenu);
aClearFilterAll = new QAction(QString(), this);
aClearFilterAll->setIcon(QPixmap("theme:icons/clearsearch"));
connect(aClearFilterAll, SIGNAL(triggered()), this, SLOT(actClearFilterAll()));
aClearFilterOne = new QAction(QString(), this);
aClearFilterOne->setIcon(QPixmap("theme:icons/decrement"));
connect(aClearFilterOne, SIGNAL(triggered()), this, SLOT(actClearFilterOne()));
dbMenu = new QMenu(this);
dbMenu->addAction(aEditSets);
dbMenu->addAction(aEditTokens);
dbMenu->addSeparator();
dbMenu->addAction(aClearFilterOne);
dbMenu->addAction(aClearFilterAll);
dbMenu->addSeparator();
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
dbMenu->addAction(aOpenCustomFolder);
dbMenu->addAction(aOpenCustomsetsFolder);
#endif
dbMenu->addAction(aAddCustomSet);
addTabMenu(dbMenu);
viewMenu = new QMenu(this); viewMenu = new QMenu(this);
cardInfoDockMenu = viewMenu->addMenu(QString()); cardInfoDockMenu = viewMenu->addMenu(QString());
...@@ -392,7 +357,12 @@ void TabDeckEditor::createCentralFrame() ...@@ -392,7 +357,12 @@ void TabDeckEditor::createCentralFrame()
databaseView->setSortingEnabled(true); databaseView->setSortingEnabled(true);
databaseView->sortByColumn(0, Qt::AscendingOrder); databaseView->sortByColumn(0, Qt::AscendingOrder);
databaseView->setModel(databaseDisplayModel); databaseView->setModel(databaseDisplayModel);
databaseView->resizeColumnToContents(0); databaseView->header()->setStretchLastSection(false);
#if QT_VERSION >= 0x050000
databaseView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
#else
databaseView->header()->setResizeMode(0, QHeaderView::Stretch);
#endif
connect(databaseView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoLeft(const QModelIndex &, const QModelIndex &))); connect(databaseView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoLeft(const QModelIndex &, const QModelIndex &)));
connect(databaseView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard())); connect(databaseView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard()));
searchEdit->setTreeView(databaseView); searchEdit->setTreeView(databaseView);
...@@ -497,9 +467,6 @@ void TabDeckEditor::refreshShortcuts() ...@@ -497,9 +467,6 @@ void TabDeckEditor::refreshShortcuts()
aPrintDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aPrintDeck")); aPrintDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aPrintDeck"));
aAnalyzeDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aAnalyzeDeck")); aAnalyzeDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aAnalyzeDeck"));
aClose->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClose")); aClose->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClose"));
aOpenCustomFolder->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aOpenCustomFolder"));
aEditSets->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aEditSets"));
aEditTokens->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aEditTokens"));
aResetLayout->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aResetLayout")); aResetLayout->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aResetLayout"));
aClearFilterAll->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterAll")); aClearFilterAll->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterAll"));
aClearFilterOne->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterOne")); aClearFilterOne->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterOne"));
...@@ -561,7 +528,6 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) ...@@ -561,7 +528,6 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent)
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts()));
refreshShortcuts(); refreshShortcuts();
QTimer::singleShot(0, this, SLOT(checkFirstRunDetected()));
QTimer::singleShot(0, this, SLOT(loadLayout())); QTimer::singleShot(0, this, SLOT(loadLayout()));
} }
...@@ -592,9 +558,6 @@ void TabDeckEditor::retranslateUi() ...@@ -592,9 +558,6 @@ void TabDeckEditor::retranslateUi()
aSaveDeckToClipboard->setText(tr("Save deck to clip&board")); aSaveDeckToClipboard->setText(tr("Save deck to clip&board"));
aPrintDeck->setText(tr("&Print deck...")); aPrintDeck->setText(tr("&Print deck..."));
aAnalyzeDeck->setText(tr("&Analyze deck on deckstats.net")); aAnalyzeDeck->setText(tr("&Analyze deck on deckstats.net"));
aOpenCustomFolder->setText(tr("Open custom image folder"));
aOpenCustomsetsFolder->setText(tr("Open custom sets folder"));
aAddCustomSet->setText(tr("Add custom sets/cards"));
aClose->setText(tr("&Close")); aClose->setText(tr("&Close"));
aAddCard->setText(tr("Add card to &maindeck")); aAddCard->setText(tr("Add card to &maindeck"));
...@@ -607,10 +570,6 @@ void TabDeckEditor::retranslateUi() ...@@ -607,10 +570,6 @@ void TabDeckEditor::retranslateUi()
aDecrement->setText(tr("&Decrement number")); aDecrement->setText(tr("&Decrement number"));
deckMenu->setTitle(tr("&Deck Editor")); deckMenu->setTitle(tr("&Deck Editor"));
dbMenu->setTitle(tr("C&ard Database"));
aEditSets->setText(tr("&Edit sets..."));
aEditTokens->setText(tr("Edit &tokens..."));
cardInfoDock->setWindowTitle(tr("Card Info")); cardInfoDock->setWindowTitle(tr("Card Info"));
deckDock->setWindowTitle(tr("Deck")); deckDock->setWindowTitle(tr("Deck"));
...@@ -822,117 +781,6 @@ void TabDeckEditor::actAnalyzeDeck() ...@@ -822,117 +781,6 @@ void TabDeckEditor::actAnalyzeDeck()
interface->analyzeDeck(deckModel->getDeckList()); interface->analyzeDeck(deckModel->getDeckList());
} }
void TabDeckEditor::actOpenCustomFolder() {
#if defined(Q_OS_MAC)
QStringList scriptArgs;
scriptArgs << QLatin1String("-e");
scriptArgs << QString::fromLatin1("tell application \"Finder\" to open POSIX file \"%1\"").arg(settingsCache->getPicsPath() + "/custom/");
scriptArgs << QLatin1String("-e");
scriptArgs << QLatin1String("tell application \"Finder\" to activate");
QProcess::execute("/usr/bin/osascript", scriptArgs);
#endif
#if defined(Q_OS_WIN)
QStringList args;
QString pathToFolder = settingsCache->getPicsPath().append("/custom");
args << QDir::toNativeSeparators(pathToFolder);
QProcess::startDetached("explorer", args);
#endif
}
void TabDeckEditor::actOpenCustomsetsFolder() {
#if QT_VERSION < 0x050000
QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
QString dataDir = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
#if defined(Q_OS_MAC)
QStringList scriptArgs;
scriptArgs << QLatin1String("-e");
scriptArgs << QString::fromLatin1("tell application \"Finder\" to open POSIX file \"%1\"").arg(dataDir + "/customsets/");
scriptArgs << QLatin1String("-e");
scriptArgs << QLatin1String("tell application \"Finder\" to activate");
QProcess::execute("/usr/bin/osascript", scriptArgs);
#endif
#if defined(Q_OS_WIN)
QStringList args;
dataDir.append("/customsets");
args << QDir::toNativeSeparators(dataDir);
QProcess::startDetached("explorer", args);
#endif
}
void TabDeckEditor::actAddCustomSet()
{
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
QString dataDir = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
QFileDialog dialog(this, tr("Load sets/cards"));
dialog.setDirectory(dataDir);
dialog.setNameFilters(TabDeckEditor::fileNameFilters);
if (!dialog.exec())
return;
QString fileName = dialog.selectedFiles().at(0);
if (!QFile::exists(fileName)) {
DlgAddSetResult dlg(this, false, QString("Selected file cannot be found."));
dlg.exec();
return;
}
QDir dir(dataDir + "/customsets");
int nextPrefix = getNextCustomSetPrefix(dir);
bool res = QFile::copy(
fileName, dir.absolutePath() + "/" + (nextPrefix > 9 ? "" : "0") +
QString::number(nextPrefix) + "." + QFileInfo(fileName).fileName()
);
DlgAddSetResult dlg(this, res, QString());
dlg.exec();
}
int TabDeckEditor::getNextCustomSetPrefix(QDir dataDir) {
QStringList files = dataDir.entryList();
int maxIndex = 0;
QStringList::const_iterator filesIterator;
for (filesIterator = files.constBegin(); filesIterator != files.constEnd(); ++filesIterator) {
int fileIndex = (*filesIterator).split(".").at(0).toInt();
if (fileIndex > maxIndex)
maxIndex = fileIndex;
}
return maxIndex + 1;
}
void TabDeckEditor::actEditSets()
{
WndSets *w = new WndSets;
w->setWindowModality(Qt::WindowModal);
w->show();
}
void TabDeckEditor::actEditTokens()
{
DlgEditTokens dlg(databaseModel);
dlg.exec();
db->saveToFile(settingsCache->getTokenDatabasePath(), true);
}
void TabDeckEditor::actClearFilterAll() void TabDeckEditor::actClearFilterAll()
{ {
databaseDisplayModel->clearFilterAll(); databaseDisplayModel->clearFilterAll();
...@@ -1158,15 +1006,6 @@ void TabDeckEditor::filterRemove(QAction *action) { ...@@ -1158,15 +1006,6 @@ void TabDeckEditor::filterRemove(QAction *action) {
filterModel->removeRow(idx.row(), idx.parent()); filterModel->removeRow(idx.row(), idx.parent());
} }
void TabDeckEditor::checkFirstRunDetected()
{
if(db->hasDetectedFirstRun())
{
QMessageBox::information(this, tr("Welcome"), tr("Hi! It seems like you're running this version of Cockatrice for the first time.\nAll the sets in the card database have been enabled.\nRead more about changing the set order or disabling specific sets and consequent effects in the \"Edit Sets\" window."));
actEditSets();
}
}
// Method uses to sync docks state with menu items state // Method uses to sync docks state with menu items state
bool TabDeckEditor::eventFilter(QObject * o, QEvent * e) bool TabDeckEditor::eventFilter(QObject * o, QEvent * e)
{ {
......
...@@ -53,12 +53,6 @@ class TabDeckEditor : public Tab { ...@@ -53,12 +53,6 @@ class TabDeckEditor : public Tab {
void actSaveDeckToClipboard(); void actSaveDeckToClipboard();
void actPrintDeck(); void actPrintDeck();
void actAnalyzeDeck(); void actAnalyzeDeck();
void actOpenCustomFolder();
void actOpenCustomsetsFolder();
void actAddCustomSet();
void actEditSets();
void actEditTokens();
void actClearFilterAll(); void actClearFilterAll();
void actClearFilterOne(); void actClearFilterOne();
...@@ -90,13 +84,11 @@ class TabDeckEditor : public Tab { ...@@ -90,13 +84,11 @@ class TabDeckEditor : public Tab {
void dockFloatingTriggered(); void dockFloatingTriggered();
void dockTopLevelChanged(bool topLevel); void dockTopLevelChanged(bool topLevel);
private: private:
static const QStringList fileNameFilters;
CardInfo *currentCardInfo() const; CardInfo *currentCardInfo() const;
void addCardHelper(QString zoneName); void addCardHelper(QString zoneName);
void offsetCountAtIndex(const QModelIndex &idx, int offset); void offsetCountAtIndex(const QModelIndex &idx, int offset);
void decrementCardHelper(QString zoneName); void decrementCardHelper(QString zoneName);
void recursiveExpand(const QModelIndex &index); void recursiveExpand(const QModelIndex &index);
int getNextCustomSetPrefix(QDir dataDir);
CardDatabaseModel *databaseModel; CardDatabaseModel *databaseModel;
CardDatabaseDisplayModel *databaseDisplayModel; CardDatabaseDisplayModel *databaseDisplayModel;
...@@ -119,9 +111,9 @@ private: ...@@ -119,9 +111,9 @@ private:
QTreeView *filterView; QTreeView *filterView;
QWidget *filterBox; QWidget *filterBox;
QMenu *deckMenu, *dbMenu, *viewMenu, *cardInfoDockMenu, *deckDockMenu, *filterDockMenu; QMenu *deckMenu, *viewMenu, *cardInfoDockMenu, *deckDockMenu, *filterDockMenu;
QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose, *aOpenCustomFolder, *aOpenCustomsetsFolder, *aAddCustomSet; QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose;
QAction *aEditSets, *aEditTokens, *aClearFilterAll, *aClearFilterOne; QAction *aClearFilterAll, *aClearFilterOne;
QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement;// *aUpdatePrices; QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement;// *aUpdatePrices;
QAction *aResetLayout; QAction *aResetLayout;
QAction *aCardInfoDockVisible, *aCardInfoDockFloating, *aDeckDockVisible, *aDeckDockFloating, *aFilterDockVisible, *aFilterDockFloating; QAction *aCardInfoDockVisible, *aCardInfoDockFloating, *aDeckDockVisible, *aDeckDockFloating, *aFilterDockVisible, *aFilterDockFloating;
...@@ -149,7 +141,6 @@ public: ...@@ -149,7 +141,6 @@ public:
public slots: public slots:
void closeRequest(); void closeRequest();
void checkFirstRunDetected();
signals: signals:
void deckEditorClosing(TabDeckEditor *tab); void deckEditorClosing(TabDeckEditor *tab);
}; };
......
...@@ -34,6 +34,8 @@ ...@@ -34,6 +34,8 @@
#if QT_VERSION < 0x050000 #if QT_VERSION < 0x050000
#include <QtGui/qtextdocument.h> // for Qt::escape() #include <QtGui/qtextdocument.h> // for Qt::escape()
#else
#include <QtConcurrent>
#endif #endif
#include "main.h" #include "main.h"
...@@ -51,6 +53,9 @@ ...@@ -51,6 +53,9 @@
#include "tab_game.h" #include "tab_game.h"
#include "version_string.h" #include "version_string.h"
#include "update_checker.h" #include "update_checker.h"
#include "carddatabase.h"
#include "window_sets.h"
#include "dlg_edit_tokens.h"
#include "pb/game_replay.pb.h" #include "pb/game_replay.pb.h"
#include "pb/room_commands.pb.h" #include "pb/room_commands.pb.h"
...@@ -69,6 +74,9 @@ ...@@ -69,6 +74,9 @@
#define DOWNLOAD_URL "https://dl.bintray.com/cockatrice/Cockatrice/" #define DOWNLOAD_URL "https://dl.bintray.com/cockatrice/Cockatrice/"
const QString MainWindow::appName = "Cockatrice"; const QString MainWindow::appName = "Cockatrice";
const QStringList MainWindow::fileNameFilters = QStringList()
<< QObject::tr("Cockatrice card database (*.xml)")
<< QObject::tr("All files (*.*)");
void MainWindow::updateTabMenu(const QList<QMenu *> &newMenuList) void MainWindow::updateTabMenu(const QList<QMenu *> &newMenuList)
{ {
...@@ -507,6 +515,13 @@ void MainWindow::retranslateUi() ...@@ -507,6 +515,13 @@ void MainWindow::retranslateUi()
cockatriceMenu->setTitle(tr("&Cockatrice")); cockatriceMenu->setTitle(tr("&Cockatrice"));
#endif #endif
dbMenu->setTitle(tr("C&ard Database"));
aOpenCustomFolder->setText(tr("Open custom image folder"));
aOpenCustomsetsFolder->setText(tr("Open custom sets folder"));
aAddCustomSet->setText(tr("Add custom sets/cards"));
aEditSets->setText(tr("&Edit sets..."));
aEditTokens->setText(tr("Edit &tokens..."));
aAbout->setText(tr("&About Cockatrice")); aAbout->setText(tr("&About Cockatrice"));
aUpdate->setText(tr("&Update Cockatrice")); aUpdate->setText(tr("&Update Cockatrice"));
helpMenu->setTitle(tr("&Help")); helpMenu->setTitle(tr("&Help"));
...@@ -545,6 +560,21 @@ void MainWindow::createActions() ...@@ -545,6 +560,21 @@ void MainWindow::createActions()
aCheckCardUpdates = new QAction(this); aCheckCardUpdates = new QAction(this);
connect(aCheckCardUpdates, SIGNAL(triggered()), this, SLOT(actCheckCardUpdates())); connect(aCheckCardUpdates, SIGNAL(triggered()), this, SLOT(actCheckCardUpdates()));
aOpenCustomsetsFolder = new QAction(QString(), this);
connect(aOpenCustomsetsFolder, SIGNAL(triggered()), this, SLOT(actOpenCustomsetsFolder()));
aOpenCustomFolder = new QAction(QString(), this);
connect(aOpenCustomFolder, SIGNAL(triggered()), this, SLOT(actOpenCustomFolder()));
aAddCustomSet = new QAction(QString(), this);
connect(aAddCustomSet, SIGNAL(triggered()), this, SLOT(actAddCustomSet()));
aEditSets = new QAction(QString(), this);
connect(aEditSets, SIGNAL(triggered()), this, SLOT(actEditSets()));
aEditTokens = new QAction(QString(), this);
connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens()));
#if defined(__APPLE__) /* For OSX */ #if defined(__APPLE__) /* For OSX */
aSettings->setMenuRole(QAction::PreferencesRole); aSettings->setMenuRole(QAction::PreferencesRole);
aExit->setMenuRole(QAction::QuitRole); aExit->setMenuRole(QAction::QuitRole);
...@@ -580,6 +610,16 @@ void MainWindow::createMenus() ...@@ -580,6 +610,16 @@ void MainWindow::createMenus()
cockatriceMenu->addSeparator(); cockatriceMenu->addSeparator();
cockatriceMenu->addAction(aExit); cockatriceMenu->addAction(aExit);
dbMenu = menuBar()->addMenu(QString());
dbMenu->addAction(aEditSets);
dbMenu->addAction(aEditTokens);
dbMenu->addSeparator();
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
dbMenu->addAction(aOpenCustomFolder);
dbMenu->addAction(aOpenCustomsetsFolder);
#endif
dbMenu->addAction(aAddCustomSet);
helpMenu = menuBar()->addMenu(QString()); helpMenu = menuBar()->addMenu(QString());
helpMenu->addAction(aAbout); helpMenu->addAction(aAbout);
helpMenu->addAction(aUpdate); helpMenu->addAction(aUpdate);
...@@ -635,6 +675,11 @@ MainWindow::MainWindow(QWidget *parent) ...@@ -635,6 +675,11 @@ MainWindow::MainWindow(QWidget *parent)
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts())); connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts()));
refreshShortcuts(); refreshShortcuts();
connect(db, SIGNAL(cardDatabaseLoadingFailed()), this, SLOT(cardDatabaseLoadingFailed()));
connect(db, SIGNAL(cardDatabaseNewSetsFound(int)), this, SLOT(cardDatabaseNewSetsFound(int)));
connect(db, SIGNAL(cardDatabaseAllNewSetsEnabled()), this, SLOT(cardDatabaseAllNewSetsEnabled()));
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
} }
MainWindow::~MainWindow() MainWindow::~MainWindow()
...@@ -727,6 +772,59 @@ void MainWindow::showWindowIfHidden() { ...@@ -727,6 +772,59 @@ void MainWindow::showWindowIfHidden() {
show(); show();
} }
void MainWindow::cardDatabaseLoadingFailed()
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Card database"));
msgBox.setIcon(QMessageBox::Question);
msgBox.setText(tr("Cockatrice is unable to load the card database.\n"
"Do you want to update your card database now?\n"
"If unsure or first time user, choose \"Yes\""));
QPushButton *yesButton = msgBox.addButton(tr("Yes"), QMessageBox::YesRole);
msgBox.addButton(tr("No"), QMessageBox::NoRole);
QPushButton *settingsButton = msgBox.addButton(tr("Open settings"), QMessageBox::ActionRole);
msgBox.setDefaultButton(yesButton);
msgBox.exec();
if (msgBox.clickedButton() == yesButton) {
actCheckCardUpdates();
} else if (msgBox.clickedButton() == settingsButton) {
actSettings();
}
}
void MainWindow::cardDatabaseNewSetsFound(int numUnknownSets)
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("New sets found"));
msgBox.setIcon(QMessageBox::Question);
msgBox.setText(tr("%1 new set(s) have been found in the card database.\n"
"Do you want to enable them?").arg(numUnknownSets));
QPushButton *yesButton = msgBox.addButton(tr("Yes"), QMessageBox::YesRole);
QPushButton *noButton = msgBox.addButton(tr("No"), QMessageBox::NoRole);
QPushButton *settingsButton = msgBox.addButton(tr("View sets"), QMessageBox::ActionRole);
msgBox.setDefaultButton(yesButton);
msgBox.exec();
if (msgBox.clickedButton() == yesButton) {
db->enableAllUnknownSets();
} else if (msgBox.clickedButton() == noButton) {
db->markAllSetsAsKnown();
} else if (msgBox.clickedButton() == settingsButton) {
actEditSets();
}
}
void MainWindow::cardDatabaseAllNewSetsEnabled()
{
QMessageBox::information(this, tr("Welcome"), tr("Hi! It seems like you're running this version of Cockatrice for the first time.\nAll the sets in the card database have been enabled.\nRead more about changing the set order or disabling specific sets and consequent effects in the \"Edit Sets\" window."));
actEditSets();
}
/* CARD UPDATER */ /* CARD UPDATER */
void MainWindow::actCheckCardUpdates() void MainWindow::actCheckCardUpdates()
...@@ -811,11 +909,9 @@ void MainWindow::cardUpdateFinished(int, QProcess::ExitStatus) ...@@ -811,11 +909,9 @@ void MainWindow::cardUpdateFinished(int, QProcess::ExitStatus)
cardUpdateProcess->deleteLater(); cardUpdateProcess->deleteLater();
cardUpdateProcess = 0; cardUpdateProcess = 0;
QMessageBox::information(this, tr("Information"), tr("Update completed successfully. Cockatrice will now reload the card database.")); QMessageBox::information(this, tr("Information"), tr("Update completed successfully.\nCockatrice will now reload the card database."));
// this will force a database reload QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
settingsCache->setCardDatabasePath(settingsCache->getCardDatabasePath());
settingsCache->setTokenDatabasePath(settingsCache->getTokenDatabasePath());
} }
void MainWindow::refreshShortcuts() void MainWindow::refreshShortcuts()
...@@ -830,9 +926,107 @@ void MainWindow::refreshShortcuts() ...@@ -830,9 +926,107 @@ void MainWindow::refreshShortcuts()
aSettings->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aSettings")); aSettings->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aSettings"));
aExit->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aExit")); aExit->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aExit"));
aCheckCardUpdates->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aCheckCardUpdates")); aCheckCardUpdates->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aCheckCardUpdates"));
aOpenCustomFolder->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aOpenCustomFolder"));
aEditSets->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aEditSets"));
aEditTokens->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aEditTokens"));
} }
void MainWindow::notifyUserAboutUpdate() void MainWindow::notifyUserAboutUpdate()
{ {
QMessageBox::information(this, tr("Information"), tr("Your client appears to be missing features that the server supports.\nThis usually means that your client version is out of date, please check to see if there is a new client available for download.")); QMessageBox::information(this, tr("Information"), tr("Your client appears to be missing features that the server supports.\nThis usually means that your client version is out of date, please check to see if there is a new client available for download."));
} }
void MainWindow::actOpenCustomFolder()
{
QString dir = settingsCache->getCustomPicsPath();
#if defined(Q_OS_MAC)
QStringList scriptArgs;
scriptArgs << QLatin1String("-e");
scriptArgs << QString::fromLatin1("tell application \"Finder\" to open POSIX file \"%1\"").arg(dir);
scriptArgs << QLatin1String("-e");
scriptArgs << QLatin1String("tell application \"Finder\" to activate");
QProcess::execute("/usr/bin/osascript", scriptArgs);
#elif defined(Q_OS_WIN)
QStringList args;
args << QDir::toNativeSeparators(dir);
QProcess::startDetached("explorer", args);
#endif
}
void MainWindow::actOpenCustomsetsFolder()
{
QString dir = settingsCache->getCustomCardDatabasePath();
#if defined(Q_OS_MAC)
QStringList scriptArgs;
scriptArgs << QLatin1String("-e");
scriptArgs << QString::fromLatin1("tell application \"Finder\" to open POSIX file \"%1\"").arg(dir);
scriptArgs << QLatin1String("-e");
scriptArgs << QLatin1String("tell application \"Finder\" to activate");
QProcess::execute("/usr/bin/osascript", scriptArgs);
#elif defined(Q_OS_WIN)
QStringList args;
args << QDir::toNativeSeparators(dir);
QProcess::startDetached("explorer", args);
#endif
}
void MainWindow::actAddCustomSet()
{
QFileDialog dialog(this, tr("Load sets/cards"), QDir::homePath());
dialog.setNameFilters(MainWindow::fileNameFilters);
if (!dialog.exec())
return;
QString fileName = dialog.selectedFiles().at(0);
if (!QFile::exists(fileName)) {
QMessageBox::warning(this, tr("Load sets/cards"), tr("Selected file cannot be found."));
return;
}
QDir dir = settingsCache->getCustomCardDatabasePath();
int nextPrefix = getNextCustomSetPrefix(dir);
bool res = QFile::copy(
fileName, dir.absolutePath() + "/" + (nextPrefix > 9 ? "" : "0") +
QString::number(nextPrefix) + "." + QFileInfo(fileName).fileName()
);
if (res) {
QMessageBox::information(this, tr("Load sets/cards"), tr("The new sets/cards have been added successfully.\nCockatrice will now reload the card database."));
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
} else {
QMessageBox::warning(this, tr("Load sets/cards"), tr("Sets/cards failed to import."));
}
}
int MainWindow::getNextCustomSetPrefix(QDir dataDir) {
QStringList files = dataDir.entryList();
int maxIndex = 0;
QStringList::const_iterator filesIterator;
for (filesIterator = files.constBegin(); filesIterator != files.constEnd(); ++filesIterator) {
int fileIndex = (*filesIterator).split(".").at(0).toInt();
if (fileIndex > maxIndex)
maxIndex = fileIndex;
}
return maxIndex + 1;
}
void MainWindow::actEditSets()
{
WndSets *w = new WndSets;
w->setWindowModality(Qt::WindowModal);
w->show();
}
void MainWindow::actEditTokens()
{
DlgEditTokens dlg;
dlg.exec();
db->saveCustomTokensToFile();
}
...@@ -79,8 +79,19 @@ private slots: ...@@ -79,8 +79,19 @@ private slots:
void cardUpdateError(QProcess::ProcessError err); void cardUpdateError(QProcess::ProcessError err);
void cardUpdateFinished(int exitCode, QProcess::ExitStatus exitStatus); void cardUpdateFinished(int exitCode, QProcess::ExitStatus exitStatus);
void refreshShortcuts(); void refreshShortcuts();
void cardDatabaseLoadingFailed();
void cardDatabaseNewSetsFound(int numUnknownSets);
void cardDatabaseAllNewSetsEnabled();
void actOpenCustomFolder();
void actOpenCustomsetsFolder();
void actAddCustomSet();
void actEditSets();
void actEditTokens();
private: private:
static const QString appName; static const QString appName;
static const QStringList fileNameFilters;
void setClientStatusTitle(); void setClientStatusTitle();
void retranslateUi(); void retranslateUi();
void createActions(); void createActions();
...@@ -88,13 +99,15 @@ private: ...@@ -88,13 +99,15 @@ private:
void createTrayIcon(); void createTrayIcon();
void createTrayActions(); void createTrayActions();
int getNextCustomSetPrefix(QDir dataDir);
// TODO: add a preference item to choose updater name for other games // TODO: add a preference item to choose updater name for other games
inline QString getCardUpdaterBinaryName() { return "oracle"; }; inline QString getCardUpdaterBinaryName() { return "oracle"; };
QList<QMenu *> tabMenus; QList<QMenu *> tabMenus;
QMenu *cockatriceMenu, *helpMenu; QMenu *cockatriceMenu, *dbMenu, *helpMenu;
QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit, QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit,
*aAbout, *aCheckCardUpdates, *aRegister, *aUpdate; *aAbout, *aCheckCardUpdates, *aRegister, *aUpdate;
QAction *aEditSets, *aEditTokens, *aOpenCustomFolder, *aOpenCustomsetsFolder, *aAddCustomSet;
TabSupervisor *tabSupervisor; TabSupervisor *tabSupervisor;
QMenu *trayIconMenu; QMenu *trayIconMenu;
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
# #
# provides the common library # provides the common library
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
add_subdirectory(pb) add_subdirectory(pb)
SET(common_SOURCES SET(common_SOURCES
......
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
# #
# provides the protobuf interfaces # provides the protobuf interfaces
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
SET(PROTO_FILES SET(PROTO_FILES
admin_commands.proto admin_commands.proto
card_attributes.proto card_attributes.proto
......
...@@ -48,19 +48,7 @@ OracleWizard::OracleWizard(QWidget *parent) ...@@ -48,19 +48,7 @@ OracleWizard::OracleWizard(QWidget *parent)
settings = new QSettings(settingsCache->getSettingsPath()+"global.ini",QSettings::IniFormat, this); settings = new QSettings(settingsCache->getSettingsPath()+"global.ini",QSettings::IniFormat, this);
connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage())); connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage()));
QString dataDir; importer = new OracleImporter(settingsCache->getDataPath(), this);
#ifndef PORTABLE_BUILD
#if QT_VERSION < 0x050000
QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
#else
dataDir.append("data");
#endif
importer = new OracleImporter(dataDir, this);
addPage(new IntroPage); addPage(new IntroPage);
addPage(new LoadSetsPage); addPage(new LoadSetsPage);
...@@ -521,47 +509,19 @@ void SaveSetsPage::updateTotalProgress(int cardsImported, int /* setIndex */, co ...@@ -521,47 +509,19 @@ void SaveSetsPage::updateTotalProgress(int cardsImported, int /* setIndex */, co
bool SaveSetsPage::validatePage() bool SaveSetsPage::validatePage()
{ {
bool ok = false; bool ok = false;
QString dataDir; QString defaultPath = settingsCache->getCardDatabasePath();
#ifndef PORTABLE_BUILD
#if QT_VERSION < 0x050000
dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
dataDir = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
#else
dataDir = qApp->applicationDirPath() + "/data";
#endif
#ifdef PORTABLE_BUILD
QSettings* settings = new QSettings("settings/global.ini",QSettings::IniFormat,this);
QString defaultPath = "data/cards.xml";
settings->setValue("paths/carddatabase", defaultPath);
#else
QSettings* settings = new QSettings(settingsCache->getSettingsPath()+"global.ini",QSettings::IniFormat,this);
QString defaultPath = settings->value("paths/carddatabase").toString();
#endif
QString windowName = tr("Save card database"); QString windowName = tr("Save card database");
QString fileType = tr("XML; card database (*.xml)"); QString fileType = tr("XML; card database (*.xml)");
do { do {
QString fileName; QString fileName;
if (defaultPath.isEmpty()) { if (defaultPathCheckBox->isChecked())
if (defaultPathCheckBox->isChecked()) fileName = defaultPath;
fileName = dataDir + "/cards.xml"; else
else fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
fileName = QFileDialog::getSaveFileName(this, windowName, dataDir + "/cards.xml", fileType);
settings->setValue("paths/carddatabase", fileName); if (fileName.isEmpty())
}
else {
if (defaultPathCheckBox->isChecked())
fileName = defaultPath;
else
fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
}
if (fileName.isEmpty()) {
return false; return false;
}
QFileInfo fi(fileName); QFileInfo fi(fileName);
QDir fileDir(fi.path()); QDir fileDir(fi.path());
...@@ -741,55 +701,24 @@ void SaveTokensPage::retranslateUi() ...@@ -741,55 +701,24 @@ void SaveTokensPage::retranslateUi()
"Press \"Save\" to save the imported tokens to the Cockatrice tokens database.")); "Press \"Save\" to save the imported tokens to the Cockatrice tokens database."));
defaultPathCheckBox->setText(tr("Save to the default path (recommended)")); defaultPathCheckBox->setText(tr("Save to the default path (recommended)"));
#ifdef PORTABLE_BUILD
defaultPathCheckBox->setEnabled(false);
#endif
} }
bool SaveTokensPage::validatePage() bool SaveTokensPage::validatePage()
{ {
bool ok = false; bool ok = false;
QString dataDir; QString defaultPath = settingsCache->getTokenDatabasePath();
#ifndef PORTABLE_BUILD
#if QT_VERSION < 0x050000
dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
dataDir = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
#else
dataDir = qApp->applicationDirPath() + "/data";
#endif
#ifdef PORTABLE_BUILD
QSettings* settings = new QSettings("settings/global.ini",QSettings::IniFormat,this);
QString defaultPath = "data/tokens.xml";
settings->setValue("paths/tokendatabase", defaultPath);
#else
QSettings* settings = new QSettings(settingsCache->getSettingsPath()+"global.ini",QSettings::IniFormat,this);
QString defaultPath = settings->value("paths/tokendatabase").toString();
#endif
QString windowName = tr("Save token database"); QString windowName = tr("Save token database");
QString fileType = tr("XML; token database (*.xml)"); QString fileType = tr("XML; token database (*.xml)");
do { do {
QString fileName; QString fileName;
if (defaultPath.isEmpty()) { if (defaultPathCheckBox->isChecked())
if (defaultPathCheckBox->isChecked()) fileName = defaultPath;
fileName = dataDir + "/tokens.xml"; else
else fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
fileName = QFileDialog::getSaveFileName(this, windowName, dataDir + "/tokens.xml", fileType);
settings->setValue("paths/tokendatabase", fileName); if (fileName.isEmpty())
}
else {
if (defaultPathCheckBox->isChecked())
fileName = defaultPath;
else
fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
}
if (fileName.isEmpty()) {
return false; return false;
}
QFileInfo fi(fileName); QFileInfo fi(fileName);
QDir fileDir(fi.path()); QDir fileDir(fi.path());
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment