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 "carddatabase.h"
#include "carddatabasemodel.h"
#include "main.h"
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
......@@ -15,8 +17,8 @@
#include <QInputDialog>
#include <QMessageBox>
DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent)
: QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel)
DlgEditTokens::DlgEditTokens(QWidget *parent)
: QDialog(parent), currentCard(0)
{
nameLabel = new QLabel(tr("&Name:"));
nameEdit = new QLineEdit;
......@@ -25,13 +27,13 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par
colorLabel = new QLabel(tr("C&olor:"));
colorEdit = new QComboBox;
colorEdit->addItem(tr("white"), "w");
colorEdit->addItem(tr("blue"), "u");
colorEdit->addItem(tr("black"), "b");
colorEdit->addItem(tr("red"), "r");
colorEdit->addItem(tr("green"), "g");
colorEdit->addItem(tr("multicolor"), "m");
colorEdit->addItem(tr("colorless"), QString());
colorEdit->addItem(tr("white"), QChar('w'));
colorEdit->addItem(tr("blue"), QChar('u'));
colorEdit->addItem(tr("black"), QChar('b'));
colorEdit->addItem(tr("red"), QChar('r'));
colorEdit->addItem(tr("green"), QChar('g'));
colorEdit->addItem(tr("multicolor"), QChar('m'));
colorEdit->addItem(tr("colorless"), QChar());
colorLabel->setBuddy(colorEdit);
connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int)));
......@@ -57,9 +59,11 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par
QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data"));
tokenDataGroupBox->setLayout(grid);
cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this);
cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel);
databaseModel = new CardDatabaseModel(db, this);
databaseModel->setObjectName("databaseModel");
cardDatabaseDisplayModel = new TokenDisplayModel(this);
cardDatabaseDisplayModel->setSourceModel(databaseModel);
cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue);
chooseTokenView = new QTreeView;
......@@ -116,39 +120,43 @@ DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *par
void DlgEditTokens::tokenSelectionChanged(const QModelIndex &current, const QModelIndex & /* previous */)
{
const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard();
if (!cardInfo->getName().isEmpty())
currentCard = cardInfo;
else
currentCard = 0;
nameEdit->setText(cardInfo->getName());
const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first());
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
ptEdit->setText(cardInfo->getPowTough());
annotationEdit->setText(cardInfo->getText());
currentCard = current.row() >= 0 ? databaseModel->getCard(realIndex.row()) : 0;
if(currentCard)
{
nameEdit->setText(currentCard->getName());
const QChar cardColor = currentCard->getColorChar();
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
ptEdit->setText(currentCard->getPowTough());
annotationEdit->setText(currentCard->getText());
} else {
nameEdit->setText("");
colorEdit->setCurrentIndex(colorEdit->findData(QChar(), Qt::UserRole, Qt::MatchFixedString));
ptEdit->setText("");
annotationEdit->setText("");
}
}
void DlgEditTokens::actAddToken()
{
QString name;
bool askAgain;
bool askAgain = true;
do {
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."));
askAgain = true;
} else
} else {
askAgain = false;
}
} while (askAgain);
if (name.isEmpty())
return;
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");
cardDatabaseModel->getDatabase()->addCard(card);
databaseModel->getDatabase()->addCard(card);
}
void DlgEditTokens::actRemoveToken()
......@@ -156,7 +164,7 @@ void DlgEditTokens::actRemoveToken()
if (currentCard) {
CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard()
currentCard = 0;
cardDatabaseModel->getDatabase()->removeCard(cardToRemove);
databaseModel->getDatabase()->removeCard(cardToRemove);
delete cardToRemove;
}
}
......@@ -164,7 +172,7 @@ void DlgEditTokens::actRemoveToken()
void DlgEditTokens::colorChanged(int colorIndex)
{
if (currentCard)
currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString());
currentCard->setColors(QStringList() << QString(colorEdit->itemData(colorIndex).toChar()));
}
void DlgEditTokens::ptChanged(const QString &_pt)
......
......@@ -5,7 +5,7 @@
class QModelIndex;
class CardDatabaseModel;
class CardDatabaseDisplayModel;
class TokenDisplayModel;
class QLabel;
class QComboBox;
class QLineEdit;
......@@ -24,15 +24,15 @@ private slots:
void actRemoveToken();
private:
CardInfo *currentCard;
CardDatabaseModel *cardDatabaseModel;
CardDatabaseDisplayModel *cardDatabaseDisplayModel;
CardDatabaseModel *databaseModel;
TokenDisplayModel *cardDatabaseDisplayModel;
QStringList predefinedTokens;
QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel;
QComboBox *colorEdit;
QLineEdit *nameEdit, *ptEdit, *annotationEdit;
QTreeView *chooseTokenView;
public:
DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0);
DlgEditTokens(QWidget *parent = 0);
};
#endif
......@@ -27,7 +27,6 @@
#include <QLibraryInfo>
#include <QDateTime>
#include <QDir>
#include <QDesktopServices>
#include <QDebug>
#include <QSystemTrayIcon>
#include "QtNetwork/QNetworkInterface"
......@@ -86,14 +85,6 @@ void installNewTranslator()
qApp->installTranslator(translator);
}
bool settingsValid()
{
return QDir(settingsCache->getDeckPath()).exists() &&
!settingsCache->getDeckPath().isEmpty() &&
QDir(settingsCache->getPicsPath()).exists() &&
!settingsCache->getPicsPath().isEmpty();
}
QString const generateClientID()
{
QString macList;
......@@ -156,73 +147,21 @@ int main(int argc, char *argv[])
qsrand(QDateTime::currentDateTime().toTime_t());
#ifdef PORTABLE_BUILD
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();
qDebug("main(): starting main program");
if (settingsValid()) {
qDebug("main(): starting main program");
MainWindow ui;
qDebug("main(): MainWindow constructor finished");
MainWindow ui;
qDebug("main(): MainWindow constructor finished");
ui.setWindowIcon(QPixmap("theme:cockatrice"));
settingsCache->setClientID(generateClientID());
ui.setWindowIcon(QPixmap("theme:cockatrice"));
settingsCache->setClientID(generateClientID());
ui.show();
qDebug("main(): ui.show() finished");
ui.show();
qDebug("main(): ui.show() finished");
#if QT_VERSION > 0x050000
app.setAttribute(Qt::AA_UseHighDpiPixmaps);
app.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
app.exec();
}
app.exec();
qDebug("Event loop finished, terminating...");
delete db;
......
......@@ -16,6 +16,4 @@ void installNewTranslator();
QString const generateClientID();
bool settingsValid();
#endif
......@@ -7,7 +7,6 @@
class Player;
class CardZone;
class CardInfoWidget;
class GameEventContext;
class CardItem;
......
......@@ -96,6 +96,7 @@ PictureLoaderWorker::PictureLoaderWorker()
downloadRunning(false), loadQueueRunning(false)
{
picsPath = settingsCache->getPicsPath();
customPicsPath = settingsCache->getCustomPicsPath();
picDownload = settingsCache->getPicDownload();
connect(this, SIGNAL(startLoadQueue()), this, SLOT(processLoadQueue()), Qt::QueuedConnection);
......@@ -167,7 +168,7 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor
imgReader.setDecideFormatFromContent(true);
//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())
{
......@@ -196,7 +197,7 @@ bool PictureLoaderWorker::cardImageExistsOnDisk(QString & setName, QString & cor
QString PictureLoaderWorker::getPicUrl()
{
if (!picDownload) return QString("");
if (!picDownload) return QString();
CardInfo *card = cardBeingDownloaded.getCard();
CardSet *set=cardBeingDownloaded.getCurrentSet();
......@@ -236,7 +237,7 @@ QString PictureLoaderWorker::getPicUrl()
)
{
qDebug() << "Insufficient card data to download" << card->getName() << "Url:" << picUrl;
return QString("");
return QString();
}
return picUrl;
......@@ -275,12 +276,12 @@ void PictureLoaderWorker::picDownloadFailed()
mutex.lock();
loadQueue.prepend(cardBeingDownloaded);
mutex.unlock();
emit startLoadQueue();
} else {
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());
cardBeingDownloaded = 0;
}
emit startLoadQueue();
}
bool PictureLoaderWorker::imageIsBlackListed(const QByteArray &picData)
......@@ -354,7 +355,7 @@ void PictureLoaderWorker::enqueueImageLoad(CardInfo *card)
QMutexLocker locker(&mutex);
// 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;
foreach(PictureToLoad pic, loadQueue)
......@@ -363,6 +364,12 @@ void PictureLoaderWorker::enqueueImageLoad(CardInfo *card)
return;
}
foreach(PictureToLoad pic, cardsToDownload)
{
if(pic.getCard() == card)
return;
}
loadQueue.append(PictureToLoad(card));
emit startLoadQueue();
}
......@@ -377,6 +384,7 @@ void PictureLoaderWorker::picsPathChanged()
{
QMutexLocker locker(&mutex);
picsPath = settingsCache->getPicsPath();
customPicsPath = settingsCache->getCustomPicsPath();
}
PictureLoader::PictureLoader()
......@@ -409,11 +417,6 @@ void PictureLoader::getPixmap(QPixmap &pixmap, CardInfo *card, QSize size)
{
if(card)
{
if (card->getName().isEmpty()) {
internalGetCardBackPixmap(pixmap, size);
return;
}
// search for an exact size copy of the picure in cache
QString key = card->getPixmapCacheKey();
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)
QPixmapCache::insert(sizekey, pixmap);
return;
}
}
// load a temporary back picture
internalGetCardBackPixmap(pixmap, size);
if(card)
{
// add the card to the load queue
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)
{
if(image.isNull())
return;
if(card->getUpsideDownArt())
{
QImage mirrorImage = image.mirrored(true, true);
QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap::fromImage(mirrorImage));
QPixmapCache::insert(card->getPixmapCacheKey(), QPixmap());
} 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();
......
......@@ -39,7 +39,7 @@ private:
static QStringList md5Blacklist;
QThread *pictureLoaderThread;
QString picsPath;
QString picsPath, customPicsPath;
QList<PictureToLoad> loadQueue;
QMutex mutex;
QNetworkAccessManager *networkManager;
......
......@@ -1081,7 +1081,8 @@ void Player::actCreateToken()
lastTokenName = dlg.getName();
lastTokenPT = dlg.getPT();
if (CardInfo *correctedCard = db->getCardBySimpleName(lastTokenName, false)) {
CardInfo *correctedCard = db->getCardBySimpleName(lastTokenName);
if (correctedCard) {
lastTokenName = correctedCard->getName();
lastTokenTableRow = table->clampValidTableRow(2 - correctedCard->getTableRow());
if (lastTokenPT.isEmpty())
......@@ -1114,7 +1115,9 @@ void Player::actCreatePredefinedToken()
{
QAction *action = static_cast<QAction *>(sender());
CardInfo *cardInfo = db->getCard(action->text());
if(!cardInfo)
return;
lastTokenName = cardInfo->getName();
lastTokenColor = cardInfo->getColors().isEmpty() ? QString() : cardInfo->getColors().first().toLower();
lastTokenPT = cardInfo->getPowTough();
......@@ -1141,6 +1144,8 @@ void Player::actCreateRelatedCard()
if (spaces.at(0).indexOf("/") != -1) // Strip space from creatures
spaces.removeFirst();
CardInfo *cardInfo = db->getCard(spaces.join(" "));
if(!cardInfo)
return;
// get the target token's location
// TODO: Define this QPoint into its own function along with the one below
......@@ -1256,9 +1261,13 @@ void Player::eventCreateToken(const Event_CreateToken &event)
CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id());
// use db PT if not provided in event
if (!QString::fromStdString(event.pt()).isEmpty())
{
card->setPT(QString::fromStdString(event.pt()));
else
card->setPT(db->getCard(QString::fromStdString(event.card_name()))->getPowTough());
} else {
CardInfo * dbCard = db->getCard(QString::fromStdString(event.card_name()));
if(dbCard)
card->setPT(dbCard->getPowTough());
}
card->setColor(QString::fromStdString(event.color()));
card->setAnnotation(QString::fromStdString(event.annotation()));
card->setDestroyOnZoneChange(event.destroy_on_zone_change());
......@@ -1713,6 +1722,8 @@ void Player::playCard(CardItem *c, bool faceDown, bool tapped)
cardToMove->set_card_id(c->getId());
CardInfo *ci = c->getInfo();
if(!ci)
return;
if (!faceDown && ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) ||
((settingsCache->getPlayToStack() && ci->getTableRow() != 0) &&
c->getZone()->getName().toStdString() != "stack"))) {
......@@ -2293,7 +2304,8 @@ void Player::actPlay()
if(!game->getActiveCard())
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()
......@@ -2374,20 +2386,23 @@ void Player::updateCardMenu(CardItem *card)
if (card->getFaceDown())
cardMenu->addAction(aPeek);
QStringList relatedCards = card->getInfo()->getRelatedCards();
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
if(relatedCards.size() || reverserelatedCards2Me.size())
if(card->getInfo())
{
QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card"));
for (int i = 0; i < relatedCards.size(); ++i) {
QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i));
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()));
QStringList relatedCards = card->getInfo()->getRelatedCards();
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
if(relatedCards.size() || reverserelatedCards2Me.size())
{
QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card"));
for (int i = 0; i < relatedCards.size(); ++i) {
QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i));
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();
......@@ -2413,20 +2428,23 @@ void Player::updateCardMenu(CardItem *card)
cardMenu->addAction(aDrawArrow);
cardMenu->addMenu(moveMenu);
QStringList relatedCards = card->getInfo()->getRelatedCards();
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
if(relatedCards.size() || reverserelatedCards2Me.size())
if(card->getInfo())
{
QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card"));
for (int i = 0; i < relatedCards.size(); ++i) {
QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i));
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()));
QStringList relatedCards = card->getInfo()->getRelatedCards();
QStringList reverserelatedCards2Me = card->getInfo()->getReverseRelatedCards2Me();
if(relatedCards.size() || reverserelatedCards2Me.size())
{
QMenu * createRelatedCardMenu = cardMenu->addMenu(tr("Cr&eate related card"));
for (int i = 0; i < relatedCards.size(); ++i) {
QAction *a = createRelatedCardMenu->addAction(relatedCards.at(i));
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 {
......
......@@ -60,7 +60,9 @@ void DBPriceUpdater::updatePrices()
bool bNotFirst=false;
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();
for(int j = 0; j < sets.size(); ++j)
{
......
......@@ -194,7 +194,7 @@ void SetsModel::save(CardDatabase *db)
sets.sortByKey();
db->emitCardListChanged();
db->notifyEnabledSetsChanged();
}
void SetsModel::restore(CardDatabase *db)
......
#include "settingscache.h"
#include <QSettings>
#include <QFile>
#include <QDir>
#include <QDebug>
#include <QApplication>
#if QT_VERSION >= 0x050000
......@@ -9,20 +11,21 @@
#include <QDesktopServices>
#endif
QString SettingsCache::getSettingsPath()
QString SettingsCache::getDataPath()
{
QString file = qApp->applicationDirPath() + "/settings/";
#ifndef PORTABLE_BUILD
#if QT_VERSION >= 0x050000
file = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#else
file = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#endif
file.append("/settings/");
#endif
return
#ifdef PORTABLE_BUILD
qApp->applicationDirPath() + "/data/";
#elif QT_VERSION >= 0x050000
QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#else
QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#endif
}
return file;
QString SettingsCache::getSettingsPath()
{
return getDataPath() + "/settings/";
}
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()
{
QString dataPath = getDataPath();
QString settingsPath = getSettingsPath();
settings = new QSettings(settingsPath+"global.ini", QSettings::IniFormat, this);
shortcutsSettings = new ShortcutsSettings(settingsPath,this);
......@@ -133,20 +159,20 @@ SettingsCache::SettingsCache()
if(!QFile(settingsPath+"global.ini").exists())
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();
lang = settings->value("personal/lang").toString();
keepalive = settings->value("personal/keepalive", 5).toInt();
deckPath = settings->value("paths/decks").toString();
replaysPath = settings->value("paths/replays").toString();
picsPath = settings->value("paths/pics").toString();
cardDatabasePath = settings->value("paths/carddatabase").toString();
tokenDatabasePath = settings->value("paths/tokendatabase").toString();
deckPath = getSafeConfigPath("paths/decks", dataPath + "/decks/");
replaysPath = getSafeConfigPath("paths/replays", dataPath + "/replays/");
picsPath = getSafeConfigPath("paths/pics", dataPath + "/pics/");
// 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();
......@@ -175,7 +201,6 @@ SettingsCache::SettingsCache()
doubleClickToPlay = settings->value("interface/doubleclicktoplay", true).toBool();
playToStack = settings->value("interface/playtostack", true).toBool();
annotateTokens = settings->value("interface/annotatetokens", false).toBool();
cardInfoMinimized = settings->value("interface/cardinfominimized", 0).toInt();
tabGameSplitterSizes = settings->value("interface/tabgame_splittersizes").toByteArray();
displayCardNames = settings->value("cards/displaycardnames", true).toBool();
horizontalHand = settings->value("hand/horizontal", true).toBool();
......@@ -291,6 +316,8 @@ void SettingsCache::setPicsPath(const QString &_picsPath)
{
picsPath = _picsPath;
settings->setValue("paths/pics", picsPath);
// get a new value for customPicsPath, currently derived from picsPath
customPicsPath = getSafeConfigPath("paths/custompics", picsPath + "CUSTOM/");
emit picsPathChanged();
}
......@@ -305,7 +332,7 @@ void SettingsCache::setTokenDatabasePath(const QString &_tokenDatabasePath)
{
tokenDatabasePath = _tokenDatabasePath;
settings->setValue("paths/tokendatabase", tokenDatabasePath);
emit tokenDatabasePathChanged();
emit cardDatabasePathChanged();
}
void SettingsCache::setThemeName(const QString &_themeName)
......@@ -363,12 +390,6 @@ void SettingsCache::setAnnotateTokens(int _annotateTokens)
settings->setValue("interface/annotatetokens", annotateTokens);
}
void SettingsCache::setCardInfoMinimized(int _cardInfoMinimized)
{
cardInfoMinimized = _cardInfoMinimized;
settings->setValue("interface/cardinfominimized", cardInfoMinimized);
}
void SettingsCache::setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes)
{
tabGameSplitterSizes = _tabGameSplitterSizes;
......
......@@ -27,7 +27,6 @@ signals:
void langChanged();
void picsPathChanged();
void cardDatabasePathChanged();
void tokenDatabasePathChanged();
void themeChanged();
void picDownloadChanged();
void displayCardNamesChanged();
......@@ -54,7 +53,7 @@ private:
QByteArray mainWindowGeometry;
QString lang;
QString deckPath, replaysPath, picsPath, cardDatabasePath, tokenDatabasePath, themeName;
QString deckPath, replaysPath, picsPath, customPicsPath, cardDatabasePath, customCardDatabasePath, tokenDatabasePath, themeName;
bool notifyAboutUpdates;
bool picDownload;
bool notificationsEnabled;
......@@ -62,7 +61,6 @@ private:
bool doubleClickToPlay;
bool playToStack;
bool annotateTokens;
int cardInfoMinimized;
QByteArray tabGameSplitterSizes;
bool displayCardNames;
bool horizontalHand;
......@@ -105,16 +103,21 @@ private:
bool spectatorsCanSeeEverything;
int keepalive;
void translateLegacySettings();
QString getSafeConfigPath(QString configEntry, QString defaultPath) const;
QString getSafeConfigFilePath(QString configEntry, QString defaultPath) const;
bool rememberGameSettings;
public:
SettingsCache();
QString getDataPath();
QString getSettingsPath();
const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; }
QString getLang() const { return lang; }
QString getDeckPath() const { return deckPath; }
QString getReplaysPath() const { return replaysPath; }
QString getPicsPath() const { return picsPath; }
QString getCustomPicsPath() const { return customPicsPath; }
QString getCustomCardDatabasePath() const { return customCardDatabasePath; }
QString getCardDatabasePath() const { return cardDatabasePath; }
QString getTokenDatabasePath() const { return tokenDatabasePath; }
QString getThemeName() const { return themeName; }
......@@ -128,7 +131,6 @@ public:
bool getDoubleClickToPlay() const { return doubleClickToPlay; }
bool getPlayToStack() const { return playToStack; }
bool getAnnotateTokens() const { return annotateTokens; }
int getCardInfoMinimized() const { return cardInfoMinimized; }
QByteArray getTabGameSplitterSizes() const { return tabGameSplitterSizes; }
bool getDisplayCardNames() const { return displayCardNames; }
bool getHorizontalHand() const { return horizontalHand; }
......@@ -200,7 +202,6 @@ public slots:
void setDoubleClickToPlay(int _doubleClickToPlay);
void setPlayToStack(int _playToStack);
void setAnnotateTokens(int _annotateTokens);
void setCardInfoMinimized(int _cardInfoMinimized);
void setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes);
void setDisplayCardNames(int _displayCardNames);
void setHorizontalHand(int _horizontalHand);
......
......@@ -15,7 +15,7 @@ void Tab::showCardInfoPopup(const QPoint &pos, const QString &cardName)
infoPopup->deleteLater();
}
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);
QRect screenRect = qApp->desktop()->screenGeometry(this);
infoPopup->move(
......
......@@ -24,15 +24,11 @@
#include <QDir>
#include <QDesktopServices>
#include "tab_deck_editor.h"
#include "window_sets.h"
#include "carddatabase.h"
#include "pictureloader.h"
#include "carddatabasemodel.h"
#include "decklistmodel.h"
#include "cardinfowidget.h"
#include "dlg_load_deck_from_clipboard.h"
#include "dlg_edit_tokens.h"
#include "dlg_add_set_result.h"
#include "main.h"
#include "settingscache.h"
#include "priceupdater.h"
......@@ -46,10 +42,6 @@
#include "cardframe.h"
#include "filterbuilder.h"
const QStringList TabDeckEditor::fileNameFilters = QStringList()
<< QObject::tr("Cockatrice card database (*.xml)")
<< QObject::tr("All files (*.*)");
void SearchLineEdit::keyPressEvent(QKeyEvent *event)
{
if (treeView && ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down)))
......@@ -251,9 +243,6 @@ void TabDeckEditor::createMenus()
aSaveDeckAs = new QAction(QString(), this);
connect(aSaveDeckAs, SIGNAL(triggered()), this, SLOT(actSaveDeckAs()));
aOpenCustomsetsFolder = new QAction(QString(), this);
connect(aOpenCustomsetsFolder, SIGNAL(triggered()), this, SLOT(actOpenCustomsetsFolder()));
aLoadDeckFromClipboard = new QAction(QString(), this);
connect(aLoadDeckFromClipboard, SIGNAL(triggered()), this, SLOT(actLoadDeckFromClipboard()));
......@@ -269,17 +258,13 @@ void TabDeckEditor::createMenus()
aClose = new QAction(QString(), this);
connect(aClose, SIGNAL(triggered()), this, SLOT(closeRequest()));
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()));
aClearFilterAll = new QAction(QString(), this);
aClearFilterAll->setIcon(QPixmap("theme:icons/clearsearch"));
connect(aClearFilterAll, SIGNAL(triggered()), this, SLOT(actClearFilterAll()));
aEditTokens = new QAction(QString(), this);
connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens()));
aClearFilterOne = new QAction(QString(), this);
aClearFilterOne->setIcon(QPixmap("theme:icons/decrement"));
connect(aClearFilterOne, SIGNAL(triggered()), this, SLOT(actClearFilterOne()));
deckMenu = new QMenu(this);
deckMenu->addAction(aNewDeck);
......@@ -291,34 +276,14 @@ void TabDeckEditor::createMenus()
deckMenu->addAction(aSaveDeckToClipboard);
deckMenu->addSeparator();
deckMenu->addAction(aPrintDeck);
deckMenu->addSeparator();
deckMenu->addAction(aAnalyzeDeck);
deckMenu->addSeparator();
deckMenu->addAction(aClearFilterOne);
deckMenu->addAction(aClearFilterAll);
deckMenu->addSeparator();
deckMenu->addAction(aClose);
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);
cardInfoDockMenu = viewMenu->addMenu(QString());
......@@ -392,7 +357,12 @@ void TabDeckEditor::createCentralFrame()
databaseView->setSortingEnabled(true);
databaseView->sortByColumn(0, Qt::AscendingOrder);
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, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard()));
searchEdit->setTreeView(databaseView);
......@@ -497,9 +467,6 @@ void TabDeckEditor::refreshShortcuts()
aPrintDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aPrintDeck"));
aAnalyzeDeck->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aAnalyzeDeck"));
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"));
aClearFilterAll->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterAll"));
aClearFilterOne->setShortcuts(settingsCache->shortcuts().getShortcut("TabDeckEditor/aClearFilterOne"));
......@@ -561,7 +528,6 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent)
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(refreshShortcuts()));
refreshShortcuts();
QTimer::singleShot(0, this, SLOT(checkFirstRunDetected()));
QTimer::singleShot(0, this, SLOT(loadLayout()));
}
......@@ -592,9 +558,6 @@ void TabDeckEditor::retranslateUi()
aSaveDeckToClipboard->setText(tr("Save deck to clip&board"));
aPrintDeck->setText(tr("&Print deck..."));
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"));
aAddCard->setText(tr("Add card to &maindeck"));
......@@ -607,10 +570,6 @@ void TabDeckEditor::retranslateUi()
aDecrement->setText(tr("&Decrement number"));
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"));
deckDock->setWindowTitle(tr("Deck"));
......@@ -822,117 +781,6 @@ void TabDeckEditor::actAnalyzeDeck()
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()
{
databaseDisplayModel->clearFilterAll();
......@@ -1158,15 +1006,6 @@ void TabDeckEditor::filterRemove(QAction *action) {
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
bool TabDeckEditor::eventFilter(QObject * o, QEvent * e)
{
......
......@@ -53,12 +53,6 @@ class TabDeckEditor : public Tab {
void actSaveDeckToClipboard();
void actPrintDeck();
void actAnalyzeDeck();
void actOpenCustomFolder();
void actOpenCustomsetsFolder();
void actAddCustomSet();
void actEditSets();
void actEditTokens();
void actClearFilterAll();
void actClearFilterOne();
......@@ -90,13 +84,11 @@ class TabDeckEditor : public Tab {
void dockFloatingTriggered();
void dockTopLevelChanged(bool topLevel);
private:
static const QStringList fileNameFilters;
CardInfo *currentCardInfo() const;
void addCardHelper(QString zoneName);
void offsetCountAtIndex(const QModelIndex &idx, int offset);
void decrementCardHelper(QString zoneName);
void recursiveExpand(const QModelIndex &index);
int getNextCustomSetPrefix(QDir dataDir);
CardDatabaseModel *databaseModel;
CardDatabaseDisplayModel *databaseDisplayModel;
......@@ -119,9 +111,9 @@ private:
QTreeView *filterView;
QWidget *filterBox;
QMenu *deckMenu, *dbMenu, *viewMenu, *cardInfoDockMenu, *deckDockMenu, *filterDockMenu;
QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose, *aOpenCustomFolder, *aOpenCustomsetsFolder, *aAddCustomSet;
QAction *aEditSets, *aEditTokens, *aClearFilterAll, *aClearFilterOne;
QMenu *deckMenu, *viewMenu, *cardInfoDockMenu, *deckDockMenu, *filterDockMenu;
QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose;
QAction *aClearFilterAll, *aClearFilterOne;
QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement;// *aUpdatePrices;
QAction *aResetLayout;
QAction *aCardInfoDockVisible, *aCardInfoDockFloating, *aDeckDockVisible, *aDeckDockFloating, *aFilterDockVisible, *aFilterDockFloating;
......@@ -149,7 +141,6 @@ public:
public slots:
void closeRequest();
void checkFirstRunDetected();
signals:
void deckEditorClosing(TabDeckEditor *tab);
};
......
......@@ -34,6 +34,8 @@
#if QT_VERSION < 0x050000
#include <QtGui/qtextdocument.h> // for Qt::escape()
#else
#include <QtConcurrent>
#endif
#include "main.h"
......@@ -51,6 +53,9 @@
#include "tab_game.h"
#include "version_string.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/room_commands.pb.h"
......@@ -69,6 +74,9 @@
#define DOWNLOAD_URL "https://dl.bintray.com/cockatrice/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)
{
......@@ -507,6 +515,13 @@ void MainWindow::retranslateUi()
cockatriceMenu->setTitle(tr("&Cockatrice"));
#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"));
aUpdate->setText(tr("&Update Cockatrice"));
helpMenu->setTitle(tr("&Help"));
......@@ -545,6 +560,21 @@ void MainWindow::createActions()
aCheckCardUpdates = new QAction(this);
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 */
aSettings->setMenuRole(QAction::PreferencesRole);
aExit->setMenuRole(QAction::QuitRole);
......@@ -580,6 +610,16 @@ void MainWindow::createMenus()
cockatriceMenu->addSeparator();
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->addAction(aAbout);
helpMenu->addAction(aUpdate);
......@@ -635,6 +675,11 @@ MainWindow::MainWindow(QWidget *parent)
connect(&settingsCache->shortcuts(), SIGNAL(shortCutchanged()),this,SLOT(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()
......@@ -727,6 +772,59 @@ void MainWindow::showWindowIfHidden() {
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 */
void MainWindow::actCheckCardUpdates()
......@@ -811,11 +909,9 @@ void MainWindow::cardUpdateFinished(int, QProcess::ExitStatus)
cardUpdateProcess->deleteLater();
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
settingsCache->setCardDatabasePath(settingsCache->getCardDatabasePath());
settingsCache->setTokenDatabasePath(settingsCache->getTokenDatabasePath());
QtConcurrent::run(db, &CardDatabase::loadCardDatabases);
}
void MainWindow::refreshShortcuts()
......@@ -830,9 +926,107 @@ void MainWindow::refreshShortcuts()
aSettings->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aSettings"));
aExit->setShortcuts(settingsCache->shortcuts().getShortcut("MainWindow/aExit"));
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()
{
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:
void cardUpdateError(QProcess::ProcessError err);
void cardUpdateFinished(int exitCode, QProcess::ExitStatus exitStatus);
void refreshShortcuts();
void cardDatabaseLoadingFailed();
void cardDatabaseNewSetsFound(int numUnknownSets);
void cardDatabaseAllNewSetsEnabled();
void actOpenCustomFolder();
void actOpenCustomsetsFolder();
void actAddCustomSet();
void actEditSets();
void actEditTokens();
private:
static const QString appName;
static const QStringList fileNameFilters;
void setClientStatusTitle();
void retranslateUi();
void createActions();
......@@ -88,13 +99,15 @@ private:
void createTrayIcon();
void createTrayActions();
int getNextCustomSetPrefix(QDir dataDir);
// TODO: add a preference item to choose updater name for other games
inline QString getCardUpdaterBinaryName() { return "oracle"; };
QList<QMenu *> tabMenus;
QMenu *cockatriceMenu, *helpMenu;
QMenu *cockatriceMenu, *dbMenu, *helpMenu;
QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit,
*aAbout, *aCheckCardUpdates, *aRegister, *aUpdate;
QAction *aEditSets, *aEditTokens, *aOpenCustomFolder, *aOpenCustomsetsFolder, *aAddCustomSet;
TabSupervisor *tabSupervisor;
QMenu *trayIconMenu;
......
......@@ -2,7 +2,6 @@
#
# provides the common library
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
add_subdirectory(pb)
SET(common_SOURCES
......
......@@ -2,8 +2,6 @@
#
# provides the protobuf interfaces
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
SET(PROTO_FILES
admin_commands.proto
card_attributes.proto
......
......@@ -48,19 +48,7 @@ OracleWizard::OracleWizard(QWidget *parent)
settings = new QSettings(settingsCache->getSettingsPath()+"global.ini",QSettings::IniFormat, this);
connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage()));
QString dataDir;
#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);
importer = new OracleImporter(settingsCache->getDataPath(), this);
addPage(new IntroPage);
addPage(new LoadSetsPage);
......@@ -521,47 +509,19 @@ void SaveSetsPage::updateTotalProgress(int cardsImported, int /* setIndex */, co
bool SaveSetsPage::validatePage()
{
bool ok = false;
QString dataDir;
#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 defaultPath = settingsCache->getCardDatabasePath();
QString windowName = tr("Save card database");
QString fileType = tr("XML; card database (*.xml)");
do {
QString fileName;
if (defaultPath.isEmpty()) {
if (defaultPathCheckBox->isChecked())
fileName = dataDir + "/cards.xml";
else
fileName = QFileDialog::getSaveFileName(this, windowName, dataDir + "/cards.xml", fileType);
if (defaultPathCheckBox->isChecked())
fileName = defaultPath;
else
fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
settings->setValue("paths/carddatabase", fileName);
}
else {
if (defaultPathCheckBox->isChecked())
fileName = defaultPath;
else
fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
}
if (fileName.isEmpty()) {
if (fileName.isEmpty())
return false;
}
QFileInfo fi(fileName);
QDir fileDir(fi.path());
......@@ -741,55 +701,24 @@ void SaveTokensPage::retranslateUi()
"Press \"Save\" to save the imported tokens to the Cockatrice tokens database."));
defaultPathCheckBox->setText(tr("Save to the default path (recommended)"));
#ifdef PORTABLE_BUILD
defaultPathCheckBox->setEnabled(false);
#endif
}
bool SaveTokensPage::validatePage()
{
bool ok = false;
QString dataDir;
#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 defaultPath = settingsCache->getTokenDatabasePath();
QString windowName = tr("Save token database");
QString fileType = tr("XML; token database (*.xml)");
do {
QString fileName;
if (defaultPath.isEmpty()) {
if (defaultPathCheckBox->isChecked())
fileName = dataDir + "/tokens.xml";
else
fileName = QFileDialog::getSaveFileName(this, windowName, dataDir + "/tokens.xml", fileType);
settings->setValue("paths/tokendatabase", fileName);
}
else {
if (defaultPathCheckBox->isChecked())
fileName = defaultPath;
else
fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
}
if (fileName.isEmpty()) {
if (defaultPathCheckBox->isChecked())
fileName = defaultPath;
else
fileName = QFileDialog::getSaveFileName(this, windowName, defaultPath, fileType);
if (fileName.isEmpty())
return false;
}
QFileInfo fi(fileName);
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