From 0b2231639f9513b9760b6675cbc0c49610520000 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Sun, 5 Jan 2014 09:47:50 +0000 Subject: [PATCH 01/55] initial experiment with editor layout --- cockatrice/CMakeLists.txt | 2 + cockatrice/src/cardframe.cpp | 64 ++++++++++++++++++++++++++++++ cockatrice/src/cardframe.h | 32 +++++++++++++++ cockatrice/src/cardinfowidget.cpp | 38 ++++++++++-------- cockatrice/src/tab_deck_editor.cpp | 60 +++++++++++++++++----------- cockatrice/src/tab_deck_editor.h | 4 +- 6 files changed, 158 insertions(+), 42 deletions(-) create mode 100644 cockatrice/src/cardframe.cpp create mode 100644 cockatrice/src/cardframe.h diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 70de75a5..50e7eba8 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -33,6 +33,7 @@ SET(cockatrice_SOURCES src/dlg_load_deck_from_clipboard.cpp src/dlg_load_remote_deck.cpp src/cardinfowidget.cpp + src/cardframe.cpp src/messagelogwidget.cpp src/zoneviewzone.cpp src/zoneviewwidget.cpp @@ -110,6 +111,7 @@ SET(cockatrice_HEADERS src/dlg_load_deck_from_clipboard.h src/dlg_load_remote_deck.h src/cardinfowidget.h + src/cardframe.h src/messagelogwidget.h src/zoneviewzone.h src/zoneviewwidget.h diff --git a/cockatrice/src/cardframe.cpp b/cockatrice/src/cardframe.cpp new file mode 100644 index 00000000..bdfca5cf --- /dev/null +++ b/cockatrice/src/cardframe.cpp @@ -0,0 +1,64 @@ +#include "cardframe.h" + +#include +#include "carditem.h" +#include "carddatabase.h" +#include "main.h" + +CardFrame::CardFrame(const QString &cardName, QWidget *parent, Qt::WindowFlags flags) + : QLabel(parent, flags) + , info(0) +{ + this->setAlignment(Qt::AlignCenter); + + setFrameStyle(QFrame::Panel | QFrame::Raised); + setFixedWidth(250); + + setCard(db->getCard(cardName)); +} + +void CardFrame::setCard(CardInfo *card) +{ + if (info) + disconnect(info, 0, this, 0); + info = card; + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); + connect(info, SIGNAL(destroyed()), this, SLOT(clear())); + + updatePixmap(); +} + +void CardFrame::setCard(const QString &cardName) +{ + setCard(db->getCard(cardName)); +} + +void CardFrame::setCard(AbstractCardItem *card) +{ + setCard(card->getInfo()); +} + +void CardFrame::clear() +{ + setCard(db->getCard()); +} + +void CardFrame::updatePixmap() +{ + qreal aspectRatio = (qreal) CARD_HEIGHT / (qreal) CARD_WIDTH; + qreal pixmapWidth = this->width(); + + if (pixmapWidth == 0) + return; + + QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); + if (resizedPixmap) + this->setPixmap(*resizedPixmap); + else + this->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); +} + +QString CardFrame::getCardName() const +{ + return info->getName(); +} diff --git a/cockatrice/src/cardframe.h b/cockatrice/src/cardframe.h new file mode 100644 index 00000000..465dff24 --- /dev/null +++ b/cockatrice/src/cardframe.h @@ -0,0 +1,32 @@ +#ifndef CARDFRAME_H +#define CARDFRAME_H + +#include +#include + +class AbstractCardItem; +class CardInfo; +class QResizeEvent; + +class CardFrame : public QLabel { + Q_OBJECT + +private: + CardInfo *info; + +public: + CardFrame(const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0); + QString getCardName() const; + +public slots: + void setCard(CardInfo *card); + void setCard(const QString &cardName); + void setCard(AbstractCardItem *card); + +private slots: + void clear(); + void updatePixmap(); + +}; + +#endif diff --git a/cockatrice/src/cardinfowidget.cpp b/cockatrice/src/cardinfowidget.cpp index e0ad1b7e..61b35453 100644 --- a/cockatrice/src/cardinfowidget.cpp +++ b/cockatrice/src/cardinfowidget.cpp @@ -51,23 +51,29 @@ CardInfoWidget::CardInfoWidget(ResizeMode _mode, const QString &cardName, QWidge textLabel->setReadOnly(true); QGridLayout *grid = new QGridLayout(this); - int row = 0; - if (mode == ModeGameTab) + if (mode == ModeGameTab) { + int row = 0; + grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight); - grid->addWidget(cardPicture, row++, 0, 1, 2); - grid->addWidget(nameLabel1, row, 0); - grid->addWidget(nameLabel2, row++, 1); - grid->addWidget(manacostLabel1, row, 0); - grid->addWidget(manacostLabel2, row++, 1); - grid->addWidget(cardtypeLabel1, row, 0); - grid->addWidget(cardtypeLabel2, row++, 1); - grid->addWidget(powtoughLabel1, row, 0); - grid->addWidget(powtoughLabel2, row++, 1); - grid->addWidget(loyaltyLabel1, row, 0); - grid->addWidget(loyaltyLabel2, row++, 1); - grid->addWidget(textLabel, row, 0, -1, 2); - grid->setRowStretch(row, 1); - grid->setColumnStretch(1, 1); + grid->addWidget(cardPicture, row++, 0, 1, 2); + grid->addWidget(nameLabel1, row, 0); + grid->addWidget(nameLabel2, row++, 1); + grid->addWidget(manacostLabel1, row, 0); + grid->addWidget(manacostLabel2, row++, 1); + grid->addWidget(cardtypeLabel1, row, 0); + grid->addWidget(cardtypeLabel2, row++, 1); + grid->addWidget(powtoughLabel1, row, 0); + grid->addWidget(powtoughLabel2, row++, 1); + grid->addWidget(loyaltyLabel1, row, 0); + grid->addWidget(loyaltyLabel2, row++, 1); + grid->addWidget(textLabel, row, 0, -1, 2); + grid->setRowStretch(row, 1); + grid->setColumnStretch(1, 1); + } else { + /*grid->addWidget(cardPicture, 0, 0); + grid->setRowStretch(0, 1); + grid->setColumnStretch(0, 1);*/ + } retranslateUi(); setFrameStyle(QFrame::Panel | QFrame::Raised); diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 216958ac..9ec0cac2 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -21,7 +21,6 @@ #include "carddatabase.h" #include "carddatabasemodel.h" #include "decklistmodel.h" -#include "cardinfowidget.h" #include "dlg_cardsearch.h" #include "dlg_load_deck_from_clipboard.h" #include "dlg_edit_tokens.h" @@ -34,6 +33,18 @@ #include "pending_command.h" #include "pb/response.pb.h" #include "pb/command_deck_upload.pb.h" +#include +#include +#include +#include +#include +#include +#include +#include "cardframe.h" +#include "carditem.h" +#include "carddatabase.h" +#include "main.h" +#include "settingscache.h" void SearchLineEdit::keyPressEvent(QKeyEvent *event) { @@ -85,25 +96,16 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) connect(databaseView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard())); searchEdit->setTreeView(databaseView); - QVBoxLayout *leftFrame = new QVBoxLayout; - leftFrame->addLayout(searchLayout); - leftFrame->addWidget(databaseView); - - cardInfo = new CardInfoWidget(CardInfoWidget::ModeDeckEditor); + cardInfo = new CardFrame(); cardInfo->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); QToolBar *verticalToolBar = new QToolBar; - verticalToolBar->setOrientation(Qt::Vertical); - verticalToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + verticalToolBar->setOrientation(Qt::Horizontal); verticalToolBar->setIconSize(QSize(24, 24)); QHBoxLayout *verticalToolBarLayout = new QHBoxLayout; - verticalToolBarLayout->addStretch(); + //verticalToolBarLayout->addStretch(); verticalToolBarLayout->addWidget(verticalToolBar); - verticalToolBarLayout->addStretch(); - - QVBoxLayout *middleFrame = new QVBoxLayout; - middleFrame->addWidget(cardInfo, 10); - middleFrame->addLayout(verticalToolBarLayout); + //verticalToolBarLayout->addStretch(); deckModel = new DeckListModel(this); connect(deckModel, SIGNAL(deckHashChanged()), this, SLOT(updateHash())); @@ -129,8 +131,8 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) grid->addWidget(nameLabel, 0, 0); grid->addWidget(nameEdit, 0, 1); - grid->addWidget(commentsLabel, 1, 0); - grid->addWidget(commentsEdit, 1, 1); + /*grid->addWidget(commentsLabel, 1, 0); + grid->addWidget(commentsEdit, 1, 1);*/ grid->addWidget(hashLabel1, 2, 0); grid->addWidget(hashLabel, 2, 1); @@ -152,15 +154,25 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) deckToolbarLayout->addWidget(deckToolBar); deckToolbarLayout->addStretch(); - QVBoxLayout *rightFrame = new QVBoxLayout; - rightFrame->addLayout(grid); - rightFrame->addWidget(deckView, 10); - rightFrame->addLayout(deckToolbarLayout); + QVBoxLayout *deckFrame = new QVBoxLayout; + deckFrame->addLayout(grid); + deckFrame->addWidget(deckView, 10); + deckFrame->addLayout(deckToolbarLayout); - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addLayout(leftFrame, 10); - mainLayout->addLayout(middleFrame); - mainLayout->addLayout(rightFrame, 10); + QHBoxLayout *topFrame = new QHBoxLayout; + topFrame->addWidget(cardInfo, 10); + topFrame->addLayout(deckFrame); + + QVBoxLayout *botFrame = new QVBoxLayout; + QGridLayout *searchAndButtons = new QGridLayout; + searchAndButtons->addLayout(verticalToolBarLayout, 0, 0); + searchAndButtons->addLayout(searchLayout, 0, 1); + botFrame->addLayout(searchAndButtons); + botFrame->addWidget(databaseView); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(topFrame, 10); + mainLayout->addLayout(botFrame, 10); setLayout(mainLayout); aNewDeck = new QAction(QString(), this); diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 73ee8a14..9580aceb 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -10,7 +10,7 @@ class CardDatabaseDisplayModel; class DeckListModel; class QTreeView; class QTableView; -class CardInfoWidget; +class CardFrame; class QTextEdit; class DlgCardSearch; class QLabel; @@ -71,7 +71,7 @@ private: DeckListModel *deckModel; QTreeView *databaseView; QTreeView *deckView; - CardInfoWidget *cardInfo; + CardFrame *cardInfo; QLabel *searchLabel; SearchLineEdit *searchEdit; QLabel *nameLabel; From 863e437d4c8387c4d98aaf6e4a121aec6c7a776c Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Fri, 17 Jan 2014 10:06:45 +0000 Subject: [PATCH 02/55] added filter builder widget and filter tree filter builder takes filter options from user, then adds completed filters to the filter tree. the filter tree does not currently do anything. in the future it will filter the cards in the database view. --- cockatrice/CMakeLists.txt | 8 + cockatrice/src/cardfilter.cpp | 31 ++++ cockatrice/src/cardfilter.h | 39 +++++ cockatrice/src/cardinfowidget.cpp | 4 - cockatrice/src/filterbuilder.cpp | 83 ++++++++++ cockatrice/src/filterbuilder.h | 37 +++++ cockatrice/src/filterlist.cpp | 160 +++++++++++++++++++ cockatrice/src/filterlist.h | 123 ++++++++++++++ cockatrice/src/filterlistmodel.cpp | 247 +++++++++++++++++++++++++++++ cockatrice/src/filterlistmodel.h | 41 +++++ cockatrice/src/tab_deck_editor.cpp | 95 ++++++++--- cockatrice/src/tab_deck_editor.h | 5 + 12 files changed, 847 insertions(+), 26 deletions(-) create mode 100644 cockatrice/src/cardfilter.cpp create mode 100644 cockatrice/src/cardfilter.h create mode 100644 cockatrice/src/filterbuilder.cpp create mode 100644 cockatrice/src/filterbuilder.h create mode 100644 cockatrice/src/filterlist.cpp create mode 100644 cockatrice/src/filterlist.h create mode 100644 cockatrice/src/filterlistmodel.cpp create mode 100644 cockatrice/src/filterlistmodel.h diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 50e7eba8..97f771a9 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -34,6 +34,10 @@ SET(cockatrice_SOURCES src/dlg_load_remote_deck.cpp src/cardinfowidget.cpp src/cardframe.cpp + src/filterbuilder.cpp + src/cardfilter.cpp + src/filterlistmodel.cpp + src/filterlist.cpp src/messagelogwidget.cpp src/zoneviewzone.cpp src/zoneviewwidget.cpp @@ -112,6 +116,10 @@ SET(cockatrice_HEADERS src/dlg_load_remote_deck.h src/cardinfowidget.h src/cardframe.h + src/filterbuilder.h + src/cardfilter.h + src/filterlistmodel.h + src/filterlist.h src/messagelogwidget.h src/zoneviewzone.h src/zoneviewwidget.h diff --git a/cockatrice/src/cardfilter.cpp b/cockatrice/src/cardfilter.cpp new file mode 100644 index 00000000..d6fe790e --- /dev/null +++ b/cockatrice/src/cardfilter.cpp @@ -0,0 +1,31 @@ +#include "cardfilter.h" + +const char *CardFilter::typeName(Type t) +{ + switch(t) { + case TypeAnd: + return "and"; + case TypeOr: + return "or"; + case TypeAndNot: + return "and not"; + case TypeOrNot: + return "or not"; + default: + return ""; + } +} + +const char *CardFilter::attrName(Attr a) +{ + switch(a) { + case AttrName: + return "name"; + case AttrType: + return "type"; + case AttrColor: + return "color"; + default: + return ""; + } +} diff --git a/cockatrice/src/cardfilter.h b/cockatrice/src/cardfilter.h new file mode 100644 index 00000000..67395c2d --- /dev/null +++ b/cockatrice/src/cardfilter.h @@ -0,0 +1,39 @@ +#ifndef CARDFILTER_H +#define CARDFILTER_H + +#include + +class CardFilter { +public: + enum Type { + TypeAnd = 0, + TypeOr, + TypeAndNot, + TypeOrNot, + TypeEnd + }; + + enum Attr { + AttrName = 0, + AttrType, + AttrColor, + AttrEnd + }; + +private: + enum Type t; + enum Attr a; + QString trm; + +public: + CardFilter(QString term, Type type, Attr attr) : trm(term), t(type), a(attr) {}; + + Type type() const { return t; } + const QString &term() const { return trm; } + Attr attr() const { return a; } + + static const char *typeName(Type t); + static const char *attrName(Attr a); +}; + +#endif diff --git a/cockatrice/src/cardinfowidget.cpp b/cockatrice/src/cardinfowidget.cpp index 61b35453..708da01c 100644 --- a/cockatrice/src/cardinfowidget.cpp +++ b/cockatrice/src/cardinfowidget.cpp @@ -69,10 +69,6 @@ CardInfoWidget::CardInfoWidget(ResizeMode _mode, const QString &cardName, QWidge grid->addWidget(textLabel, row, 0, -1, 2); grid->setRowStretch(row, 1); grid->setColumnStretch(1, 1); - } else { - /*grid->addWidget(cardPicture, 0, 0); - grid->setRowStretch(0, 1); - grid->setColumnStretch(0, 1);*/ } retranslateUi(); diff --git a/cockatrice/src/filterbuilder.cpp b/cockatrice/src/filterbuilder.cpp new file mode 100644 index 00000000..53b93144 --- /dev/null +++ b/cockatrice/src/filterbuilder.cpp @@ -0,0 +1,83 @@ +#include "filterbuilder.h" + +#include +#include +#include +#include + +#include "cardfilter.h" + +FilterBuilder::FilterBuilder(QWidget *parent) + : QFrame(parent) +{ + int i; + + QVBoxLayout *layout = new QVBoxLayout; + QHBoxLayout *addFilter = new QHBoxLayout; + + filterCombo = new QComboBox; + for(i = 0; i < CardFilter::AttrEnd; i++) + filterCombo->addItem( + CardFilter::attrName(static_cast(i)), QVariant(i)); + + typeCombo = new QComboBox; + for(i = 0; i < CardFilter::TypeEnd; i++) + typeCombo->addItem( + CardFilter::typeName(static_cast(i)), QVariant(i)); + + QPushButton *ok = new QPushButton("+"); + ok->setMaximumSize(20, 20); + + addFilter->addWidget(ok); + addFilter->addWidget(typeCombo); + addFilter->addWidget(filterCombo, Qt::AlignLeft); + + edit = new QLineEdit; + edit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + layout->addLayout(addFilter); + layout->addWidget(edit); + + setFrameStyle(QFrame::Plain | QFrame::Box); + layout->setAlignment(Qt::AlignTop); + setLayout(layout); + + connect(ok, SIGNAL(released()), this, SLOT(add_released())); + fltr = NULL; +} + +FilterBuilder::~FilterBuilder() +{ + destroyFilter(); +} + +void FilterBuilder::destroyFilter() +{ + if(fltr) + delete fltr; +} + +static int comboCurrentIntData(const QComboBox *combo) +{ + return combo->itemData(combo->currentIndex()).toInt(); +} + +void FilterBuilder::add_released() +{ + QString txt; + + txt = edit->text(); + if(txt.length() < 1) + return; + + destroyFilter(); + fltr = new CardFilter(txt, + static_cast(comboCurrentIntData(typeCombo)), + static_cast(comboCurrentIntData(filterCombo))); + emit add(fltr); +} + +bool FilterBuilder::filter(const CardFilter *f) const +{ + f = fltr; + return false; +} diff --git a/cockatrice/src/filterbuilder.h b/cockatrice/src/filterbuilder.h new file mode 100644 index 00000000..2762ba28 --- /dev/null +++ b/cockatrice/src/filterbuilder.h @@ -0,0 +1,37 @@ +#ifndef FILTERBUILDER_H +#define FILTERBUILDER_H + +#include + +class QCheckBox; +class QComboBox; +class QLineEdit; +class CardFilter; + +class FilterBuilder : public QFrame { + Q_OBJECT + +private: + QComboBox *typeCombo; + QComboBox *filterCombo; + QLineEdit *edit; + CardFilter *fltr; + + void destroyFilter(); + +public: + FilterBuilder(QWidget *parent = 0); + ~FilterBuilder(); + + bool filter(const CardFilter *f) const; + +signals: + void add(const CardFilter *f); + +public slots: +private slots: + void add_released(); +protected: +}; + +#endif diff --git a/cockatrice/src/filterlist.cpp b/cockatrice/src/filterlist.cpp new file mode 100644 index 00000000..35d7a0fc --- /dev/null +++ b/cockatrice/src/filterlist.cpp @@ -0,0 +1,160 @@ +#include "filterlist.h" +#include "CardFilter.h" + +#include + +LogicMap::~LogicMap() +{ + while(!isEmpty()) + delete takeFirst(); +} + +FilterItemList *LogicMap::typeList(CardFilter::Type type) +{ + LogicMap::iterator i; + int count; + + count = 0; + for(i = begin(); i != end(); i++) { + if ((*i)->type == type) + break; + count++; + } + if (i == end()) { + p->preInsertChild(this, count); + i = insert(i, new FilterItemList(type, this)); + p->postInsertChild(this, count); + } + + return *i; +} + +FilterListNode *LogicMap::parent() const +{ + return p; +} + +FilterListNode *LogicMap::nodeAt(int i) const +{ + return ((size() > i)? at(i) : NULL); +} + +void LogicMap::deleteAt(int i) +{ + delete takeAt(i); +} + +int LogicMap::index() const +{ + return p->indexOf(this); +} + +FilterListNode *FilterItemList::nodeAt(int i) const +{ + return ((size() > i)? at(i) : NULL); +} + +void FilterItemList::deleteAt(int i) { + delete takeAt(i); +} + +FilterItemList::~FilterItemList() +{ + while(!isEmpty()) + delete takeFirst(); +} + +FilterList::~FilterList() +{ + while(!logicAttrs.isEmpty()) { + delete logicAttrs.takeFirst(); + } +} + +LogicMap *FilterList::attrLogicMap(CardFilter::Attr attr) +{ + QList::iterator i; + int count; + + count = 0; + for(i = logicAttrs.begin(); i != logicAttrs.end(); i++) { + if((*i)->attr == attr) + break; + count++; + } + + if(i == logicAttrs.end()) { + preInsertChild(this, count); + i = logicAttrs.insert(i, new LogicMap(attr, this)); + postInsertChild(this, count); + } + + return *i; +} + +FilterItemList *FilterList::attrTypeList(CardFilter::Attr attr, + CardFilter::Type type) +{ + return attrLogicMap(attr)->typeList(type); +} + +int FilterList::findTermIndex(CardFilter::Attr attr, CardFilter::Type type, + const QString &term) +{ + FilterItemList *fis; + int i; + + fis = attrTypeList(attr, type); + for(i = 0; i < fis->count(); i++) + if((fis->at(i))->term == term) + return i; + + return -1; +} + +int FilterList::findTermIndex(const CardFilter *f) +{ + return findTermIndex(f->attr(), f->type(), f->term()); +} + +FilterListNode *FilterList::termNode(CardFilter::Attr attr, CardFilter::Type type, + const QString &term) +{ + FilterItemList *fis; + FilterItem *fi; + int i, count; + + fis = attrTypeList(attr, type); + i = findTermIndex(attr, type, term); + if(i < 0) { + fi = new FilterItem(term, fis); + count = fis->childCount(); + preInsertChild(fis, count); + fis->append(fi); + postInsertChild(fis, count); + return fi; + } + + return fis->at(i); +} + +FilterListNode *FilterList::termNode(const CardFilter *f) +{ + return termNode(f->attr(), f->type(), f->term()); +} + +FilterListNode *FilterList::attrTypeNode(CardFilter::Attr attr, + CardFilter::Type type) +{ + return attrTypeList(attr, type); +} + +int FilterList::count(CardFilter::Attr attr, CardFilter::Type type) +{ + return attrTypeList(attr, type)->count(); +} + +int FilterList::count(const CardFilter *f) +{ + return count(f->attr(), f->type()); +} diff --git a/cockatrice/src/filterlist.h b/cockatrice/src/filterlist.h new file mode 100644 index 00000000..aed58f7d --- /dev/null +++ b/cockatrice/src/filterlist.h @@ -0,0 +1,123 @@ +#ifndef FILTERLIST_H +#define FILTERLIST_H + +#include +#include +#include + +#include "cardfilter.h" + +class FilterListNode { +private: + bool enabled; +public: + FilterListNode() : enabled(true) {} + virtual bool isEnabled() const { return enabled; } + virtual void enable() { enabled = true; } + virtual void disable() { enabled = false; } + virtual FilterListNode *parent() const { return NULL; } + virtual FilterListNode *nodeAt(int i) const { return NULL; } + virtual void deleteAt(int i) {} + virtual int childCount() const { return 0; } + virtual int index() const { return -1; } + virtual QString text() const { return ""; } + virtual bool isLeaf() const { return false; } + virtual const char *textCStr() const { return text().toStdString().c_str(); } +}; + +class FilterItemList; +class FilterList; +class LogicMap + : public QList + , public FilterListNode { +private: + FilterList *const p; +public: + const CardFilter::Attr attr; + + LogicMap(CardFilter::Attr a, FilterList *parent) + : attr(a), p(parent) {} + ~LogicMap(); + FilterItemList *typeList(CardFilter::Type type); + virtual FilterListNode *parent() const; + virtual FilterListNode *nodeAt(int i) const; + virtual void deleteAt(int i); + virtual int childCount() const { return size(); } + virtual int index() const; + virtual QString text() const { return QString(CardFilter::attrName(attr)); } +}; + +class FilterItem; +class FilterItemList + : public QList + , public FilterListNode { +private: + LogicMap *const p; +public: + const CardFilter::Type type; + FilterItemList(CardFilter::Type t, LogicMap *parent) + : type(t), p(parent) {} + ~FilterItemList(); + CardFilter::Attr attr() const { return p->attr; } + virtual FilterListNode *parent() const { return p; } + virtual FilterListNode *nodeAt(int i) const; + virtual void deleteAt(int i); + virtual int childCount() const { return size(); } + virtual int index() const { return p->indexOf((FilterItemList *) this); } + virtual QString text() const { return QString(CardFilter::typeName(type)); } +}; + +class FilterItem : public FilterListNode { +private: + FilterItemList *const p; +public: + const QString term; + + FilterItem(QString trm, FilterItemList *parent) + : p(parent), term(trm) {} + + CardFilter::Attr attr() const { return p->attr(); } + CardFilter::Type type() const { return p->type; } + virtual FilterListNode *parent() const { return p; } + virtual int index() const { return p->indexOf((FilterItem *)this); } + virtual QString text() const { return term; } + virtual bool isLeaf() const { return true; } +}; + +class FilterList : public QObject, public FilterListNode { + Q_OBJECT + +signals: + void preInsertRow(const FilterListNode *parent, int i) const; + void postInsertRow(const FilterListNode *parent, int i) const; + +private: + QList logicAttrs; + + LogicMap *attrLogicMap(CardFilter::Attr attr); + FilterItemList *attrTypeList(CardFilter::Attr attr, + CardFilter::Type type); + +public: + ~FilterList(); + int indexOf(const LogicMap *val) const { return logicAttrs.indexOf((LogicMap *) val); } + int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, + const QString &term); + int findTermIndex(const CardFilter *f); + FilterListNode *termNode(CardFilter::Attr attr, CardFilter::Type type, + const QString &term); + FilterListNode *termNode(const CardFilter *f); + FilterListNode *attrTypeNode(CardFilter::Attr attr, + CardFilter::Type type); + int count(CardFilter::Attr attr, CardFilter::Type type); + int count(const CardFilter *f); + virtual FilterListNode *nodeAt(int i) const { return ((logicAttrs.size() > i)? logicAttrs.at(i) : NULL); } + virtual void deleteAt(int i) { delete logicAttrs.takeAt(i); } + virtual int childCount() const { return logicAttrs.size(); } + virtual QString text() const { return QString("root"); } + virtual int index() const { return 0; } + void preInsertChild(const FilterListNode *p, int i) const { emit preInsertRow(p, i); } + void postInsertChild(const FilterListNode *p, int i) const { emit postInsertRow(p, i); } +}; + +#endif diff --git a/cockatrice/src/filterlistmodel.cpp b/cockatrice/src/filterlistmodel.cpp new file mode 100644 index 00000000..6bd84809 --- /dev/null +++ b/cockatrice/src/filterlistmodel.cpp @@ -0,0 +1,247 @@ +#include +#include "filterlistmodel.h" +#include "filterlist.h" +#include "cardfilter.h" + +FilterListModel::FilterListModel(QObject *parent) + : QAbstractItemModel(parent) +{ + filterList = new FilterList; + connect(filterList, + SIGNAL(preInsertRow(const FilterListNode *, int)), + this, SLOT(proxyBeginInsertRow(const FilterListNode *, int))); + connect(filterList, + SIGNAL(postInsertRow(const FilterListNode *, int)), + this, SLOT(proxyEndInsertRow(const FilterListNode *, int))); +} + +FilterListModel::~FilterListModel() +{ + delete filterList; +} + +void FilterListModel::proxyBeginInsertRow(const FilterListNode *node, int i) +{ + int idx; + + idx = node->index(); + if(idx >= 0) + beginInsertRows(createIndex(idx, 0, (void *) node), i, i); +} + +void FilterListModel::proxyEndInsertRow(const FilterListNode *node, int) +{ + int idx; + + idx = node->index(); + if(idx >= 0) + endInsertRows(); +} + +FilterListNode *FilterListModel::indexToNode(const QModelIndex &idx) const +{ + void *ip; + FilterListNode *node; + + if(!idx.isValid()) + return filterList; + + ip = idx.internalPointer(); + if(ip == NULL) + return filterList; + + node = static_cast(ip); + return node; +} + +void FilterListModel::addFilter(const CardFilter *f) +{ + emit layoutAboutToBeChanged(); + filterList->termNode(f); + emit layoutChanged(); +} + +int FilterListModel::rowCount(const QModelIndex &parent) const +{ + const FilterListNode *node; + int result; + + if(parent.column() > 0) + return 0; + + node = indexToNode(parent); + if(node) + result = node->childCount(); + else + result = 0; + + return result; +} + +int FilterListModel::columnCount(const QModelIndex &/*parent*/) const +{ + return 1; +} + +QVariant FilterListModel::data(const QModelIndex &index, int role) const +{ + const FilterListNode *node; + + if (!index.isValid()) + return QVariant(); + if (index.column() >= columnCount()) + return QVariant(); + + node = indexToNode(index); + if(node == NULL) + return QVariant(); + + switch (role) { + case Qt::FontRole: + if(!node->isLeaf()) { + QFont f; + f.setBold(true); + return f; + } + break; + case Qt::DisplayRole: + case Qt::EditRole: + case Qt::ToolTipRole: + case Qt::StatusTipRole: + case Qt::WhatsThisRole: + return node->text(); + case Qt::CheckStateRole: + if(node->isEnabled()) + return Qt::Checked; + else + return Qt::Unchecked; + default: + return QVariant(); + } + + return QVariant(); +} + +bool FilterListModel::setData(const QModelIndex &index, + const QVariant &value, int role) +{ + FilterListNode *node; + + if (!index.isValid()) + return false; + if (index.column() >= columnCount()) + return false; + if (role != Qt::CheckStateRole ) + return false; + + node = indexToNode(index); + if(node == NULL || node == filterList) + return false; + + Qt::CheckState state = static_cast(value.toInt()); + if(state == Qt::Checked) + node->enable(); + else + node->disable(); + + emit dataChanged(index, index); + return true; +} + +Qt::ItemFlags FilterListModel::flags(const QModelIndex &index) const +{ + const FilterListNode *node; + Qt::ItemFlags result; + + if (!index.isValid()) + return 0; + + node = indexToNode(index); + if(node == NULL) + return 0; + + result = Qt::ItemIsEnabled; + if(node == filterList) + return result; + + result |= Qt::ItemIsSelectable; + result |= Qt::ItemIsUserCheckable; + + return result; +} + +QModelIndex FilterListModel::nodeIndex(const FilterListNode *node, int row, int column) const +{ + FilterListNode *child; + + if (column > 0 || row >= node->childCount()) + return QModelIndex(); + + child = node->nodeAt(row); + return createIndex(row, column, child); +} + +QModelIndex FilterListModel::index(int row, int column, + const QModelIndex &parent) const +{ + const FilterListNode *node; + + if (!hasIndex(row, column, parent)) + return QModelIndex(); + + node = indexToNode(parent); + if(node == NULL) + return QModelIndex(); + + return nodeIndex(node, row, column); +} + +QModelIndex FilterListModel::parent(const QModelIndex &ind) const +{ + const FilterListNode *node; + FilterListNode *parent; + int row; + QModelIndex idx; + + if (!ind.isValid()) + return QModelIndex(); + + node = indexToNode(ind); + if(node == NULL || node == filterList) + return QModelIndex(); + + parent = node->parent(); + if(parent) { + row = parent->index(); + if(row < 0) + return QModelIndex(); + idx = createIndex(row, 0, parent); + return idx; + } + + return QModelIndex(); +} + +bool FilterListModel::removeRows(int row, int count, const QModelIndex & parent) +{ + FilterListNode *node; + int i, last; + + last = row+count-1; + if (!parent.isValid() || count < 1 || row < 0) + return false; + + node = indexToNode(parent); + if(node == NULL || last >= node->childCount()) + return false; + + beginRemoveRows(parent, row, last); + for(i = 0; i < count; i++) + node->deleteAt(row); + endRemoveRows(); + + if(node != filterList && node->childCount() < 1) + return removeRow(parent.row(), parent.parent()); + + return true; +} diff --git a/cockatrice/src/filterlistmodel.h b/cockatrice/src/filterlistmodel.h new file mode 100644 index 00000000..de25f452 --- /dev/null +++ b/cockatrice/src/filterlistmodel.h @@ -0,0 +1,41 @@ +#ifndef FILTERLISTMODEL_H +#define FILTERLISTMODEL_H + +#include + +class FilterList; +class CardFilter; +class FilterListNode; + +class FilterListModel : public QAbstractItemModel { + Q_OBJECT +private: + FilterList *filterList; + +public slots: + void addFilter(const CardFilter *f); + +private slots: + void proxyBeginInsertRow(const FilterListNode *, int); + void proxyEndInsertRow(const FilterListNode *node, int i); + +private: + FilterListNode *indexToNode(const QModelIndex &idx) const; + QModelIndex nodeIndex(const FilterListNode *node, int row, int column) const; + +public: + FilterListModel(QObject *parent = 0); + ~FilterListModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role) const; + bool setData(const QModelIndex &index, const QVariant &value, + int role = Qt::EditRole); + Qt::ItemFlags flags(const QModelIndex &index) const; + QModelIndex parent(const QModelIndex &ind) const; + QModelIndex index(int row, int column, + const QModelIndex &parent) const; + bool removeRows(int row, int count, const QModelIndex & parent); +}; + +#endif diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 9ec0cac2..a7aded4c 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -41,10 +41,13 @@ #include #include #include "cardframe.h" +#include "filterbuilder.h" #include "carditem.h" #include "carddatabase.h" #include "main.h" #include "settingscache.h" +#include "filterlistmodel.h" +#include "filterlist.h" void SearchLineEdit::keyPressEvent(QKeyEvent *event) { @@ -131,28 +134,25 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) grid->addWidget(nameLabel, 0, 0); grid->addWidget(nameEdit, 0, 1); - /*grid->addWidget(commentsLabel, 1, 0); - grid->addWidget(commentsEdit, 1, 1);*/ - grid->addWidget(hashLabel1, 2, 0); grid->addWidget(hashLabel, 2, 1); - // Update price - aUpdatePrices = new QAction(QString(), this); - aUpdatePrices->setIcon(QIcon(":/resources/icon_update.png")); - connect(aUpdatePrices, SIGNAL(triggered()), this, SLOT(actUpdatePrices())); + // Update price + aUpdatePrices = new QAction(QString(), this); + aUpdatePrices->setIcon(QIcon(":/resources/icon_update.png")); + connect(aUpdatePrices, SIGNAL(triggered()), this, SLOT(actUpdatePrices())); if (!settingsCache->getPriceTagFeature()) aUpdatePrices->setVisible(false); - - QToolBar *deckToolBar = new QToolBar; - deckToolBar->setOrientation(Qt::Vertical); - deckToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - deckToolBar->setIconSize(QSize(24, 24)); - deckToolBar->addAction(aUpdatePrices); - QHBoxLayout *deckToolbarLayout = new QHBoxLayout; - deckToolbarLayout->addStretch(); - deckToolbarLayout->addWidget(deckToolBar); - deckToolbarLayout->addStretch(); + + QToolBar *deckToolBar = new QToolBar; + deckToolBar->setOrientation(Qt::Vertical); + deckToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + deckToolBar->setIconSize(QSize(24, 24)); + deckToolBar->addAction(aUpdatePrices); + QHBoxLayout *deckToolbarLayout = new QHBoxLayout; + deckToolbarLayout->addStretch(); + deckToolbarLayout->addWidget(deckToolBar); + deckToolbarLayout->addStretch(); QVBoxLayout *deckFrame = new QVBoxLayout; deckFrame->addLayout(grid); @@ -168,7 +168,30 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) searchAndButtons->addLayout(verticalToolBarLayout, 0, 0); searchAndButtons->addLayout(searchLayout, 0, 1); botFrame->addLayout(searchAndButtons); - botFrame->addWidget(databaseView); + + filterModel = new FilterListModel(); + filterView = new QTreeView; + filterView->setModel(filterModel); + filterView->setMaximumWidth(250); + filterView->setUniformRowHeights(true); + filterView->setHeaderHidden(true); + filterView->setExpandsOnDoubleClick(false); + filterView->setContextMenuPolicy(Qt::CustomContextMenu); + connect(filterModel, SIGNAL(layoutChanged()), filterView, SLOT(expandAll())); + connect(filterView, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(filterViewCustomContextMenu(const QPoint &))); + FilterBuilder *filterBuilder = new FilterBuilder; + filterBuilder->setMaximumWidth(250); + connect(filterBuilder, SIGNAL(add(const CardFilter *)), filterModel, SLOT(addFilter(const CardFilter *))); + + QVBoxLayout *filter = new QVBoxLayout; + filter->addWidget(filterBuilder, 0, Qt::AlignTop); + filter->addWidget(filterView); + + QHBoxLayout *dbFrame = new QHBoxLayout; + dbFrame->addLayout(filter); + dbFrame->addWidget(databaseView); + botFrame->addLayout(dbFrame); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(topFrame, 10); @@ -234,16 +257,16 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) aAddCard->setIcon(QIcon(":/resources/arrow_right_green.svg")); connect(aAddCard, SIGNAL(triggered()), this, SLOT(actAddCard())); aAddCardToSideboard = new QAction(QString(), this); - aAddCardToSideboard->setIcon(QIcon(":/resources/add_to_sideboard.svg")); + aAddCardToSideboard->setIcon(QIcon(":/resources/add_to_sideboard.svg")); connect(aAddCardToSideboard, SIGNAL(triggered()), this, SLOT(actAddCardToSideboard())); aRemoveCard = new QAction(QString(), this); - aRemoveCard->setIcon(QIcon(":/resources/remove_row.svg")); + aRemoveCard->setIcon(QIcon(":/resources/remove_row.svg")); connect(aRemoveCard, SIGNAL(triggered()), this, SLOT(actRemoveCard())); aIncrement = new QAction(QString(), this); - aIncrement->setIcon(QIcon(":/resources/increment.svg")); + aIncrement->setIcon(QIcon(":/resources/increment.svg")); connect(aIncrement, SIGNAL(triggered()), this, SLOT(actIncrement())); aDecrement = new QAction(QString(), this); - aDecrement->setIcon(QIcon(":/resources/decrement.svg")); + aDecrement->setIcon(QIcon(":/resources/decrement.svg")); connect(aDecrement, SIGNAL(triggered()), this, SLOT(actDecrement())); verticalToolBar->addAction(aAddCard); @@ -632,3 +655,31 @@ void TabDeckEditor::setModified(bool _modified) modified = _modified; emit tabTextChanged(this, getTabText()); } + +void TabDeckEditor::filterViewCustomContextMenu(const QPoint &point) { + QMenu menu; + QAction *action; + QModelIndex idx; + + idx = filterView->indexAt(point); + if(!idx.isValid()) + return; + + action = menu.addAction(QString("delete")); + action->setData(point); + connect(&menu, SIGNAL(triggered(QAction *)), + this, SLOT(filterRemove(QAction *))); + menu.exec(filterView->mapToGlobal(point)); +} + +void TabDeckEditor::filterRemove(QAction *action) { + QPoint point; + QModelIndex idx; + + point = action->data().toPoint(); + idx = filterView->indexAt(point); + if(!idx.isValid()) + return; + + filterModel->removeRow(idx.row(), idx.parent()); +} diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 9580aceb..716f6ade 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -16,6 +16,7 @@ class DlgCardSearch; class QLabel; class DeckLoader; class Response; +class FilterListModel; class SearchLineEdit : public QLineEdit { private: @@ -61,6 +62,8 @@ private slots: void finishedUpdatingPrices(); void saveDeckRemoteFinished(const Response &r); + void filterViewCustomContextMenu(const QPoint &point); + void filterRemove(QAction *action); private: void addCardHelper(QString zoneName); void recursiveExpand(const QModelIndex &index); @@ -81,6 +84,8 @@ private: QLabel *hashLabel1; QLabel *hashLabel; DlgCardSearch *dlgCardSearch; + FilterListModel *filterModel; + QTreeView *filterView; QMenu *deckMenu, *dbMenu; QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; From 3202243ed0b30699b9e65be6c07ef928f04eb78f Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Tue, 21 Jan 2014 23:37:22 +0000 Subject: [PATCH 03/55] connect filter list functionality to the CardDatabaseDisplayModel class enable/disable check boxes still not functional --- cockatrice/src/carddatabasemodel.cpp | 22 +++- cockatrice/src/carddatabasemodel.h | 6 + cockatrice/src/cardfilter.cpp | 6 + cockatrice/src/cardfilter.h | 5 + cockatrice/src/filterlist.cpp | 179 ++++++++++++++++++++++++++- cockatrice/src/filterlist.h | 28 ++++- cockatrice/src/filterlistmodel.cpp | 23 ++-- cockatrice/src/filterlistmodel.h | 3 +- cockatrice/src/tab_deck_editor.cpp | 1 + 9 files changed, 258 insertions(+), 15 deletions(-) diff --git a/cockatrice/src/carddatabasemodel.cpp b/cockatrice/src/carddatabasemodel.cpp index d63f6bde..559f8cc4 100644 --- a/cockatrice/src/carddatabasemodel.cpp +++ b/cockatrice/src/carddatabasemodel.cpp @@ -1,4 +1,5 @@ #include "carddatabasemodel.h" +#include "filterlist.h" CardDatabaseModel::CardDatabaseModel(CardDatabase *_db, QObject *parent) : QAbstractListModel(parent), db(_db) @@ -109,6 +110,7 @@ CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) : QSortFilterProxyModel(parent), isToken(ShowAll) { + filterList = NULL; setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } @@ -116,7 +118,7 @@ CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { CardInfo const *info = static_cast(sourceModel())->getCard(sourceRow); - + if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken())) return false; @@ -144,6 +146,9 @@ bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex if (!cardTypes.contains(info->getMainCardType())) return false; + if (filterList != NULL) + return filterList->acceptsCard(info); + return true; } @@ -155,3 +160,18 @@ void CardDatabaseDisplayModel::clearSearch() cardColors.clear(); invalidateFilter(); } + +void CardDatabaseDisplayModel::setFilterList(const FilterList *filterList) +{ + if(this->filterList != NULL) + disconnect(this->filterList, 0, this, 0); + + this->filterList = filterList; + connect(this->filterList, SIGNAL(changed()), this, SLOT(filterListChanged())); + invalidate(); +} + +void CardDatabaseDisplayModel::filterListChanged() +{ + invalidate(); +} diff --git a/cockatrice/src/carddatabasemodel.h b/cockatrice/src/carddatabasemodel.h index b2998bfe..ba245b41 100644 --- a/cockatrice/src/carddatabasemodel.h +++ b/cockatrice/src/carddatabasemodel.h @@ -7,6 +7,8 @@ #include #include "carddatabase.h" +class FilterList; + class CardDatabaseModel : public QAbstractListModel { Q_OBJECT public: @@ -36,8 +38,10 @@ private: FilterBool isToken; QString cardNameBeginning, cardName, cardText; QSet cardNameSet, cardTypes, cardColors; + const FilterList *filterList; public: CardDatabaseDisplayModel(QObject *parent = 0); + void setFilterList(const FilterList *filterList); void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } @@ -48,6 +52,8 @@ public: void clearSearch(); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; +private slots: + void filterListChanged(); }; #endif diff --git a/cockatrice/src/cardfilter.cpp b/cockatrice/src/cardfilter.cpp index d6fe790e..27402921 100644 --- a/cockatrice/src/cardfilter.cpp +++ b/cockatrice/src/cardfilter.cpp @@ -25,6 +25,12 @@ const char *CardFilter::attrName(Attr a) return "type"; case AttrColor: return "color"; + case AttrText: + return "text"; + case AttrSet: + return "set"; + case AttrManaCost: + return "mana cost"; default: return ""; } diff --git a/cockatrice/src/cardfilter.h b/cockatrice/src/cardfilter.h index 67395c2d..f4f38771 100644 --- a/cockatrice/src/cardfilter.h +++ b/cockatrice/src/cardfilter.h @@ -13,10 +13,15 @@ public: TypeEnd }; + /* if you add an atribute here you also need to + * add its string representation in attrName */ enum Attr { AttrName = 0, AttrType, AttrColor, + AttrText, + AttrSet, + AttrManaCost, AttrEnd }; diff --git a/cockatrice/src/filterlist.cpp b/cockatrice/src/filterlist.cpp index 35d7a0fc..eaae7d1c 100644 --- a/cockatrice/src/filterlist.cpp +++ b/cockatrice/src/filterlist.cpp @@ -1,5 +1,6 @@ #include "filterlist.h" -#include "CardFilter.h" +#include "cardfilter.h" +#include "carddatabase.h" #include @@ -9,6 +10,17 @@ LogicMap::~LogicMap() delete takeFirst(); } +const FilterItemList *LogicMap::findTypeList(CardFilter::Type type) const +{ + LogicMap::const_iterator i; + + for(i = constBegin(); i != constEnd(); i++) + if ((*i)->type == type) + return *i; + + return NULL; +} + FilterItemList *LogicMap::typeList(CardFilter::Type type) { LogicMap::iterator i; @@ -158,3 +170,168 @@ int FilterList::count(const CardFilter *f) { return count(f->attr(), f->type()); } + +bool FilterList::acceptName(const CardInfo *info, const QString &term) const +{ + return info->getName().contains(term, Qt::CaseInsensitive); +} + +bool FilterList::acceptType(const CardInfo *info, const QString &term) const +{ + return info->getCardType().contains(term, Qt::CaseInsensitive); +} + +bool FilterList::acceptColor(const CardInfo *info, const QString &term) const +{ + QStringList::const_iterator i; + bool status; + + status = false; + for(i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) + if ((*i).contains(term, Qt::CaseInsensitive)) { + status = true; + break; + } + + return status; +} + +bool FilterList::acceptText(const CardInfo *info, const QString &term) const +{ + return info->getText().contains(term, Qt::CaseInsensitive); +} + +bool FilterList::acceptSet(const CardInfo *info, const QString &term) const +{ + SetList::const_iterator i; + bool status; + + status = false; + for(i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) + if ((*i)->getShortName() == term + || (*i)->getLongName().contains(term, Qt::CaseInsensitive)) { + status = true; + break; + } + + return status; +} + +bool FilterList::acceptManaCost(const CardInfo *info, const QString &term) const +{ + return (info->getManaCost() == term); +} + +bool FilterList::acceptCardAttr(const CardInfo *info, const QString &term, + CardFilter::Attr attr) const +{ + bool status; + + switch(attr) { + case CardFilter::AttrName: + status = acceptName(info, term); + break; + case CardFilter::AttrType: + status = acceptType(info, term); + break; + case CardFilter::AttrColor: + status = acceptColor(info, term); + break; + case CardFilter::AttrText: + status = acceptText(info, term); + break; + case CardFilter::AttrSet: + status = acceptSet(info, term); + break; + case CardFilter::AttrManaCost: + status = acceptManaCost(info, term); + break; + default: + status = true; /* ignore this attribute */ + } + + return status; +} + +bool FilterList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr, + const FilterItemList *fil) const +{ + FilterItemList::const_iterator i; + + for(i = fil->constBegin(); i != fil->constEnd(); i++) + if(!acceptCardAttr(info, (*i)->term, attr)) + return false; + + return true; +} + +bool FilterList::testTypeAndNot(const CardInfo *info, CardFilter::Attr attr, + const FilterItemList *fil) const +{ + FilterItemList::const_iterator i; + + for(i = fil->constBegin(); i != fil->constEnd(); i++) + if(acceptCardAttr(info, (*i)->term, attr)) + return false; + + return true; +} + +bool FilterList::testTypeOr(const CardInfo *info, CardFilter::Attr attr, + const FilterItemList *filOr, + const FilterItemList *filOrNot) const +{ + FilterItemList::const_iterator i; + bool status; + + if(filOr == NULL && filOrNot == NULL) + return true; + + status = false; + if (filOr != NULL) + for(i = filOr->constBegin(); i != filOr->constEnd(); i++) + if(acceptCardAttr(info, (*i)->term, attr)) { + status = true; + break; + } + if (status != true && filOrNot != NULL) + for(i = filOrNot->constBegin(); i != filOrNot->constEnd(); i++) + if(!acceptCardAttr(info, (*i)->term, attr)) { + status = true; + break; + } + + return status; +} + +bool FilterList::testAttr(const CardInfo *info, const LogicMap *lm) const +{ + bool status; + const FilterItemList *fil, *fil2; + + fil = lm->findTypeList(CardFilter::TypeAnd); + if (fil != NULL && !testTypeAnd(info, lm->attr, fil)) + return false; + + fil = lm->findTypeList(CardFilter::TypeAndNot); + if (fil != NULL && !testTypeAndNot(info, lm->attr, fil)) + return false; + + fil = lm->findTypeList(CardFilter::TypeOr); + fil2 = lm->findTypeList(CardFilter::TypeOrNot); + if (!testTypeOr(info, lm->attr, fil, fil2)) + return false; + + return true; +} + +bool FilterList::acceptsCard(const CardInfo *info) const +{ + QList::const_iterator i; + + for(i = logicAttrs.constBegin(); i != logicAttrs.constEnd(); i++) + if(!testAttr(info, *i)) + return false; + + return true; +} diff --git a/cockatrice/src/filterlist.h b/cockatrice/src/filterlist.h index aed58f7d..98b885bc 100644 --- a/cockatrice/src/filterlist.h +++ b/cockatrice/src/filterlist.h @@ -7,6 +7,8 @@ #include "cardfilter.h" +class CardInfo; + class FilterListNode { private: bool enabled; @@ -38,6 +40,7 @@ public: LogicMap(CardFilter::Attr a, FilterList *parent) : attr(a), p(parent) {} ~LogicMap(); + const FilterItemList *findTypeList(CardFilter::Type type) const; FilterItemList *typeList(CardFilter::Type type); virtual FilterListNode *parent() const; virtual FilterListNode *nodeAt(int i) const; @@ -55,6 +58,7 @@ private: LogicMap *const p; public: const CardFilter::Type type; + FilterItemList(CardFilter::Type t, LogicMap *parent) : type(t), p(parent) {} ~FilterItemList(); @@ -90,6 +94,7 @@ class FilterList : public QObject, public FilterListNode { signals: void preInsertRow(const FilterListNode *parent, int i) const; void postInsertRow(const FilterListNode *parent, int i) const; + void changed() const; private: QList logicAttrs; @@ -98,6 +103,24 @@ private: FilterItemList *attrTypeList(CardFilter::Attr attr, CardFilter::Type type); + bool acceptName(const CardInfo *info, const QString &term) const; + bool acceptType(const CardInfo *info, const QString &term) const; + bool acceptColor(const CardInfo *info, const QString &term) const; + bool acceptCardAttr(const CardInfo *info, const QString &term, + CardFilter::Attr attr) const; + bool acceptText(const CardInfo *info, const QString &term) const; + bool acceptSet(const CardInfo *info, const QString &term) const; + bool acceptManaCost(const CardInfo *info, const QString &term) const; + + bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr, + const FilterItemList *fil) const; + bool testTypeAndNot(const CardInfo *info, CardFilter::Attr attr, + const FilterItemList *fil) const; + bool testTypeOr(const CardInfo *info, CardFilter::Attr attr, + const FilterItemList *filOr, + const FilterItemList *filOrNot) const; + + bool testAttr(const CardInfo *info, const LogicMap *lm) const; public: ~FilterList(); int indexOf(const LogicMap *val) const { return logicAttrs.indexOf((LogicMap *) val); } @@ -117,7 +140,10 @@ public: virtual QString text() const { return QString("root"); } virtual int index() const { return 0; } void preInsertChild(const FilterListNode *p, int i) const { emit preInsertRow(p, i); } - void postInsertChild(const FilterListNode *p, int i) const { emit postInsertRow(p, i); } + void postInsertChild(const FilterListNode *p, int i) const { emit postInsertRow(p, i); emit changed(); } + void emitChanged() const { emit changed(); } + + bool acceptsCard(const CardInfo *info) const; }; #endif diff --git a/cockatrice/src/filterlistmodel.cpp b/cockatrice/src/filterlistmodel.cpp index 6bd84809..a6f2404b 100644 --- a/cockatrice/src/filterlistmodel.cpp +++ b/cockatrice/src/filterlistmodel.cpp @@ -6,18 +6,18 @@ FilterListModel::FilterListModel(QObject *parent) : QAbstractItemModel(parent) { - filterList = new FilterList; - connect(filterList, + fList = new FilterList; + connect(fList, SIGNAL(preInsertRow(const FilterListNode *, int)), this, SLOT(proxyBeginInsertRow(const FilterListNode *, int))); - connect(filterList, + connect(fList, SIGNAL(postInsertRow(const FilterListNode *, int)), this, SLOT(proxyEndInsertRow(const FilterListNode *, int))); } FilterListModel::~FilterListModel() { - delete filterList; + delete fList; } void FilterListModel::proxyBeginInsertRow(const FilterListNode *node, int i) @@ -44,11 +44,11 @@ FilterListNode *FilterListModel::indexToNode(const QModelIndex &idx) const FilterListNode *node; if(!idx.isValid()) - return filterList; + return fList; ip = idx.internalPointer(); if(ip == NULL) - return filterList; + return fList; node = static_cast(ip); return node; @@ -57,7 +57,7 @@ FilterListNode *FilterListModel::indexToNode(const QModelIndex &idx) const void FilterListModel::addFilter(const CardFilter *f) { emit layoutAboutToBeChanged(); - filterList->termNode(f); + fList->termNode(f); emit layoutChanged(); } @@ -135,7 +135,7 @@ bool FilterListModel::setData(const QModelIndex &index, return false; node = indexToNode(index); - if(node == NULL || node == filterList) + if(node == NULL || node == fList) return false; Qt::CheckState state = static_cast(value.toInt()); @@ -161,7 +161,7 @@ Qt::ItemFlags FilterListModel::flags(const QModelIndex &index) const return 0; result = Qt::ItemIsEnabled; - if(node == filterList) + if(node == fList) return result; result |= Qt::ItemIsSelectable; @@ -207,7 +207,7 @@ QModelIndex FilterListModel::parent(const QModelIndex &ind) const return QModelIndex(); node = indexToNode(ind); - if(node == NULL || node == filterList) + if(node == NULL || node == fList) return QModelIndex(); parent = node->parent(); @@ -239,8 +239,9 @@ bool FilterListModel::removeRows(int row, int count, const QModelIndex & parent) for(i = 0; i < count; i++) node->deleteAt(row); endRemoveRows(); + fList->emitChanged(); - if(node != filterList && node->childCount() < 1) + if(node != fList && node->childCount() < 1) return removeRow(parent.row(), parent.parent()); return true; diff --git a/cockatrice/src/filterlistmodel.h b/cockatrice/src/filterlistmodel.h index de25f452..944bb5b7 100644 --- a/cockatrice/src/filterlistmodel.h +++ b/cockatrice/src/filterlistmodel.h @@ -10,7 +10,7 @@ class FilterListNode; class FilterListModel : public QAbstractItemModel { Q_OBJECT private: - FilterList *filterList; + FilterList *fList; public slots: void addFilter(const CardFilter *f); @@ -26,6 +26,7 @@ private: public: FilterListModel(QObject *parent = 0); ~FilterListModel(); + const FilterList *filterList() const { return fList; } int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index a7aded4c..a1fc1022 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -170,6 +170,7 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) botFrame->addLayout(searchAndButtons); filterModel = new FilterListModel(); + databaseDisplayModel->setFilterList(filterModel->filterList()); filterView = new QTreeView; filterView->setModel(filterModel); filterView->setMaximumWidth(250); From 083005b8a9ff535608604061a71193d356f2c9c0 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Wed, 22 Jan 2014 08:32:00 +0000 Subject: [PATCH 04/55] implemented filter list enable/disable functionality also refactored much of the filter list code to be much cleaner and modular. --- cockatrice/src/filterlist.cpp | 327 ++++++++++++++--------------- cockatrice/src/filterlist.h | 130 +++++++----- cockatrice/src/filterlistmodel.cpp | 34 ++- cockatrice/src/filterlistmodel.h | 4 +- 4 files changed, 266 insertions(+), 229 deletions(-) diff --git a/cockatrice/src/filterlist.cpp b/cockatrice/src/filterlist.cpp index eaae7d1c..9a4b3a71 100644 --- a/cockatrice/src/filterlist.cpp +++ b/cockatrice/src/filterlist.cpp @@ -4,17 +4,48 @@ #include -LogicMap::~LogicMap() +template +FilterListNode *FilterListInnerNode::nodeAt(int i) const { - while(!isEmpty()) - delete takeFirst(); + return ((childNodes.size() > i)? childNodes.at(i) : NULL); +} + +template +void FilterListInnerNode::deleteAt(int i) +{ + preRemoveChild(this, i); + delete childNodes.takeAt(i); + postRemoveChild(this, i); + nodeChanged(); +} + +template +int FilterListInnerNode::childIndex(const FilterListNode *node) const +{ + FilterListNode *unconst; + T downcasted; + + /* to do the dynamic cast to T we will lose const'ness, but we can + * trust QList::indexOf */ + unconst = (FilterListNode *) node; + downcasted = dynamic_cast(unconst); + if(downcasted == NULL) + return -1; + return childNodes.indexOf(downcasted); +} + +template +FilterListInnerNode::~FilterListInnerNode() +{ + while(!childNodes.isEmpty()) + delete childNodes.takeFirst(); } const FilterItemList *LogicMap::findTypeList(CardFilter::Type type) const { - LogicMap::const_iterator i; + QList::const_iterator i; - for(i = constBegin(); i != constEnd(); i++) + for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) if ((*i)->type == type) return *i; @@ -23,19 +54,20 @@ const FilterItemList *LogicMap::findTypeList(CardFilter::Type type) const FilterItemList *LogicMap::typeList(CardFilter::Type type) { - LogicMap::iterator i; + QList::iterator i; int count; count = 0; - for(i = begin(); i != end(); i++) { + for(i = childNodes.begin(); i != childNodes.end(); i++) { if ((*i)->type == type) break; count++; } - if (i == end()) { - p->preInsertChild(this, count); - i = insert(i, new FilterItemList(type, this)); - p->postInsertChild(this, count); + if (i == childNodes.end()) { + preInsertChild(this, count); + i = childNodes.insert(i, new FilterItemList(type, this)); + postInsertChild(this, count); + nodeChanged(); } return *i; @@ -46,142 +78,81 @@ FilterListNode *LogicMap::parent() const return p; } -FilterListNode *LogicMap::nodeAt(int i) const +int FilterItemList::termIndex(const QString &term) const { - return ((size() > i)? at(i) : NULL); -} - -void LogicMap::deleteAt(int i) -{ - delete takeAt(i); -} - -int LogicMap::index() const -{ - return p->indexOf(this); -} - -FilterListNode *FilterItemList::nodeAt(int i) const -{ - return ((size() > i)? at(i) : NULL); -} - -void FilterItemList::deleteAt(int i) { - delete takeAt(i); -} - -FilterItemList::~FilterItemList() -{ - while(!isEmpty()) - delete takeFirst(); -} - -FilterList::~FilterList() -{ - while(!logicAttrs.isEmpty()) { - delete logicAttrs.takeFirst(); - } -} - -LogicMap *FilterList::attrLogicMap(CardFilter::Attr attr) -{ - QList::iterator i; - int count; - - count = 0; - for(i = logicAttrs.begin(); i != logicAttrs.end(); i++) { - if((*i)->attr == attr) - break; - count++; - } - - if(i == logicAttrs.end()) { - preInsertChild(this, count); - i = logicAttrs.insert(i, new LogicMap(attr, this)); - postInsertChild(this, count); - } - - return *i; -} - -FilterItemList *FilterList::attrTypeList(CardFilter::Attr attr, - CardFilter::Type type) -{ - return attrLogicMap(attr)->typeList(type); -} - -int FilterList::findTermIndex(CardFilter::Attr attr, CardFilter::Type type, - const QString &term) -{ - FilterItemList *fis; int i; - fis = attrTypeList(attr, type); - for(i = 0; i < fis->count(); i++) - if((fis->at(i))->term == term) + for(i = 0; i < childNodes.count(); i++) + if((childNodes.at(i))->term == term) return i; return -1; } -int FilterList::findTermIndex(const CardFilter *f) +FilterListNode *FilterItemList::termNode(const QString &term) { - return findTermIndex(f->attr(), f->type(), f->term()); -} - -FilterListNode *FilterList::termNode(CardFilter::Attr attr, CardFilter::Type type, - const QString &term) -{ - FilterItemList *fis; - FilterItem *fi; int i, count; + FilterItem *fi; - fis = attrTypeList(attr, type); - i = findTermIndex(attr, type, term); + i = termIndex(term); if(i < 0) { - fi = new FilterItem(term, fis); - count = fis->childCount(); - preInsertChild(fis, count); - fis->append(fi); - postInsertChild(fis, count); + fi = new FilterItem(term, this); + count = childNodes.count(); + preInsertChild(this, count); + childNodes.append(fi); + postInsertChild(this, count); + nodeChanged(); return fi; } - return fis->at(i); + return childNodes.at(i); } -FilterListNode *FilterList::termNode(const CardFilter *f) +bool FilterItemList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const { - return termNode(f->attr(), f->type(), f->term()); + QList::const_iterator i; + + for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + if (!(*i)->acceptCardAttr(info, attr)) + return false; + + return true; } -FilterListNode *FilterList::attrTypeNode(CardFilter::Attr attr, - CardFilter::Type type) +bool FilterItemList::testTypeAndNot(const CardInfo *info, CardFilter::Attr attr) const { - return attrTypeList(attr, type); + // if any one in the list is true, return false + return !testTypeOr(info, attr); } -int FilterList::count(CardFilter::Attr attr, CardFilter::Type type) +bool FilterItemList::testTypeOr(const CardInfo *info, CardFilter::Attr attr) const { - return attrTypeList(attr, type)->count(); + QList::const_iterator i; + + for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + if ((*i)->acceptCardAttr(info, attr)) + return true; + + return false; } -int FilterList::count(const CardFilter *f) +bool FilterItemList::testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const { - return count(f->attr(), f->type()); + // if any one in the list is false, return true + return !testTypeAnd(info, attr); } -bool FilterList::acceptName(const CardInfo *info, const QString &term) const +bool FilterItem::acceptName(const CardInfo *info) const { return info->getName().contains(term, Qt::CaseInsensitive); } -bool FilterList::acceptType(const CardInfo *info, const QString &term) const +bool FilterItem::acceptType(const CardInfo *info) const { return info->getCardType().contains(term, Qt::CaseInsensitive); } -bool FilterList::acceptColor(const CardInfo *info, const QString &term) const +bool FilterItem::acceptColor(const CardInfo *info) const { QStringList::const_iterator i; bool status; @@ -196,12 +167,12 @@ bool FilterList::acceptColor(const CardInfo *info, const QString &term) const return status; } -bool FilterList::acceptText(const CardInfo *info, const QString &term) const +bool FilterItem::acceptText(const CardInfo *info) const { return info->getText().contains(term, Qt::CaseInsensitive); } -bool FilterList::acceptSet(const CardInfo *info, const QString &term) const +bool FilterItem::acceptSet(const CardInfo *info) const { SetList::const_iterator i; bool status; @@ -217,34 +188,36 @@ bool FilterList::acceptSet(const CardInfo *info, const QString &term) const return status; } -bool FilterList::acceptManaCost(const CardInfo *info, const QString &term) const +bool FilterItem::acceptManaCost(const CardInfo *info) const { return (info->getManaCost() == term); } -bool FilterList::acceptCardAttr(const CardInfo *info, const QString &term, - CardFilter::Attr attr) const +bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const { bool status; + if(!isEnabled()) + return true; + switch(attr) { case CardFilter::AttrName: - status = acceptName(info, term); + status = acceptName(info); break; case CardFilter::AttrType: - status = acceptType(info, term); + status = acceptType(info); break; case CardFilter::AttrColor: - status = acceptColor(info, term); + status = acceptColor(info); break; case CardFilter::AttrText: - status = acceptText(info, term); + status = acceptText(info); break; case CardFilter::AttrSet: - status = acceptSet(info, term); + status = acceptSet(info); break; case CardFilter::AttrManaCost: - status = acceptManaCost(info, term); + status = acceptManaCost(info); break; default: status = true; /* ignore this attribute */ @@ -253,84 +226,104 @@ bool FilterList::acceptCardAttr(const CardInfo *info, const QString &term, return status; } -bool FilterList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr, - const FilterItemList *fil) const +/* need to define these here to make QT happy, otherwise + * moc doesnt find some of the FilterListInnerNode symbols. + */ +FilterList::FilterList() {} +FilterList::~FilterList() {} + +LogicMap *FilterList::attrLogicMap(CardFilter::Attr attr) { - FilterItemList::const_iterator i; + QList::iterator i; + int count; - for(i = fil->constBegin(); i != fil->constEnd(); i++) - if(!acceptCardAttr(info, (*i)->term, attr)) - return false; + count = 0; + for(i = childNodes.begin(); i != childNodes.end(); i++) { + if((*i)->attr == attr) + break; + count++; + } - return true; + if(i == childNodes.end()) { + preInsertChild(this, count); + i = childNodes.insert(i, new LogicMap(attr, this)); + postInsertChild(this, count); + nodeChanged(); + } + + return *i; } -bool FilterList::testTypeAndNot(const CardInfo *info, CardFilter::Attr attr, - const FilterItemList *fil) const +FilterItemList *FilterList::attrTypeList(CardFilter::Attr attr, + CardFilter::Type type) { - FilterItemList::const_iterator i; - - for(i = fil->constBegin(); i != fil->constEnd(); i++) - if(acceptCardAttr(info, (*i)->term, attr)) - return false; - - return true; + return attrLogicMap(attr)->typeList(type); } -bool FilterList::testTypeOr(const CardInfo *info, CardFilter::Attr attr, - const FilterItemList *filOr, - const FilterItemList *filOrNot) const +int FilterList::findTermIndex(CardFilter::Attr attr, CardFilter::Type type, + const QString &term) { - FilterItemList::const_iterator i; - bool status; + attrTypeList(attr, type)->termIndex(term); +} - if(filOr == NULL && filOrNot == NULL) - return true; +int FilterList::findTermIndex(const CardFilter *f) +{ + return findTermIndex(f->attr(), f->type(), f->term()); +} - status = false; - if (filOr != NULL) - for(i = filOr->constBegin(); i != filOr->constEnd(); i++) - if(acceptCardAttr(info, (*i)->term, attr)) { - status = true; - break; - } - if (status != true && filOrNot != NULL) - for(i = filOrNot->constBegin(); i != filOrNot->constEnd(); i++) - if(!acceptCardAttr(info, (*i)->term, attr)) { - status = true; - break; - } +FilterListNode *FilterList::termNode(CardFilter::Attr attr, CardFilter::Type type, + const QString &term) +{ + return attrTypeList(attr, type)->termNode(term); +} - return status; +FilterListNode *FilterList::termNode(const CardFilter *f) +{ + return termNode(f->attr(), f->type(), f->term()); +} + +FilterListNode *FilterList::attrTypeNode(CardFilter::Attr attr, + CardFilter::Type type) +{ + return attrTypeList(attr, type); } bool FilterList::testAttr(const CardInfo *info, const LogicMap *lm) const { + const FilterItemList *fil; bool status; - const FilterItemList *fil, *fil2; + + status = true; fil = lm->findTypeList(CardFilter::TypeAnd); - if (fil != NULL && !testTypeAnd(info, lm->attr, fil)) + if (fil != NULL && fil->isEnabled() && !fil->testTypeAnd(info, lm->attr)) return false; fil = lm->findTypeList(CardFilter::TypeAndNot); - if (fil != NULL && !testTypeAndNot(info, lm->attr, fil)) + if (fil != NULL && fil->isEnabled() && !fil->testTypeAndNot(info, lm->attr)) return false; fil = lm->findTypeList(CardFilter::TypeOr); - fil2 = lm->findTypeList(CardFilter::TypeOrNot); - if (!testTypeOr(info, lm->attr, fil, fil2)) - return false; + if (fil != NULL && fil->isEnabled()) { + status = false; + // if this is true we can return because it is OR'd with the OrNot list + if (fil->testTypeOr(info, lm->attr)) + return true; + } - return true; + fil = lm->findTypeList(CardFilter::TypeOrNot); + if (fil != NULL && fil->isEnabled() && fil->testTypeOrNot(info, lm->attr)) + return true; + + return status; } bool FilterList::acceptsCard(const CardInfo *info) const { QList::const_iterator i; - for(i = logicAttrs.constBegin(); i != logicAttrs.constEnd(); i++) - if(!testAttr(info, *i)) + for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + if ((*i)->isEnabled() && !testAttr(info, *i)) return false; return true; diff --git a/cockatrice/src/filterlist.h b/cockatrice/src/filterlist.h index 98b885bc..20f78984 100644 --- a/cockatrice/src/filterlist.h +++ b/cockatrice/src/filterlist.h @@ -15,45 +15,71 @@ private: public: FilterListNode() : enabled(true) {} virtual bool isEnabled() const { return enabled; } - virtual void enable() { enabled = true; } - virtual void disable() { enabled = false; } + virtual void enable() { enabled = true; nodeChanged(); } + virtual void disable() { enabled = false; nodeChanged(); } virtual FilterListNode *parent() const { return NULL; } virtual FilterListNode *nodeAt(int i) const { return NULL; } virtual void deleteAt(int i) {} virtual int childCount() const { return 0; } - virtual int index() const { return -1; } + virtual int childIndex(const FilterListNode *node) const { return -1; } + virtual int index() const { return (parent() != NULL)? parent()->childIndex(this) : -1; } virtual QString text() const { return ""; } virtual bool isLeaf() const { return false; } virtual const char *textCStr() const { return text().toStdString().c_str(); } + virtual void nodeChanged() const { + printf("%s -> ", textCStr()); + if (parent() != NULL) parent()->nodeChanged(); + } + virtual void preInsertChild(const FilterListNode *p, int i) const { + //printf("%s -> ", textCStr()); + if (parent() != NULL) parent()->preInsertChild(p, i); + } + virtual void postInsertChild(const FilterListNode *p, int i) const { + //printf("%s -> ", textCStr()); + if (parent() != NULL) parent()->postInsertChild(p, i); + } + virtual void preRemoveChild(const FilterListNode *p, int i) const { + printf("%s -> ", textCStr()); + if (parent() != NULL) parent()->preRemoveChild(p, i); + } + virtual void postRemoveChild(const FilterListNode *p, int i) const { + printf("%s -> ", textCStr()); + if (parent() != NULL) parent()->postRemoveChild(p, i); + } +}; + +template +class FilterListInnerNode : public FilterListNode { +protected: + QList childNodes; +public: + ~FilterListInnerNode(); + FilterListNode *nodeAt(int i) const; + void deleteAt(int i); + int childCount() const { return childNodes.size(); } + int childIndex(const FilterListNode *node) const; }; class FilterItemList; class FilterList; -class LogicMap - : public QList - , public FilterListNode { +class LogicMap : public FilterListInnerNode { + private: FilterList *const p; + public: const CardFilter::Attr attr; LogicMap(CardFilter::Attr a, FilterList *parent) : attr(a), p(parent) {} - ~LogicMap(); const FilterItemList *findTypeList(CardFilter::Type type) const; FilterItemList *typeList(CardFilter::Type type); - virtual FilterListNode *parent() const; - virtual FilterListNode *nodeAt(int i) const; - virtual void deleteAt(int i); - virtual int childCount() const { return size(); } - virtual int index() const; - virtual QString text() const { return QString(CardFilter::attrName(attr)); } + FilterListNode *parent() const; + QString text() const { return QString(CardFilter::attrName(attr)); } }; class FilterItem; -class FilterItemList - : public QList - , public FilterListNode { +class FilterItemList : public FilterListInnerNode { private: LogicMap *const p; public: @@ -61,14 +87,16 @@ public: FilterItemList(CardFilter::Type t, LogicMap *parent) : type(t), p(parent) {} - ~FilterItemList(); CardFilter::Attr attr() const { return p->attr; } - virtual FilterListNode *parent() const { return p; } - virtual FilterListNode *nodeAt(int i) const; - virtual void deleteAt(int i); - virtual int childCount() const { return size(); } - virtual int index() const { return p->indexOf((FilterItemList *) this); } - virtual QString text() const { return QString(CardFilter::typeName(type)); } + FilterListNode *parent() const { return p; } + int termIndex(const QString &term) const; + FilterListNode *termNode(const QString &term); + QString text() const { return QString(CardFilter::typeName(type)); } + + bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const; + bool testTypeAndNot(const CardInfo *info, CardFilter::Attr attr) const; + bool testTypeOr(const CardInfo *info, CardFilter::Attr attr) const; + bool testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const; }; class FilterItem : public FilterListNode { @@ -82,48 +110,38 @@ public: CardFilter::Attr attr() const { return p->attr(); } CardFilter::Type type() const { return p->type; } - virtual FilterListNode *parent() const { return p; } - virtual int index() const { return p->indexOf((FilterItem *)this); } - virtual QString text() const { return term; } - virtual bool isLeaf() const { return true; } + FilterListNode *parent() const { return p; } + QString text() const { return term; } + bool isLeaf() const { return true; } + + bool acceptName(const CardInfo *info) const; + bool acceptType(const CardInfo *info) const; + bool acceptColor(const CardInfo *info) const; + bool acceptText(const CardInfo *info) const; + bool acceptSet(const CardInfo *info) const; + bool acceptManaCost(const CardInfo *info) const; + bool acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const; }; -class FilterList : public QObject, public FilterListNode { +class FilterList : public QObject, public FilterListInnerNode { Q_OBJECT signals: void preInsertRow(const FilterListNode *parent, int i) const; void postInsertRow(const FilterListNode *parent, int i) const; + void preRemoveRow(const FilterListNode *parent, int i) const; + void postRemoveRow(const FilterListNode *parent, int i) const; void changed() const; private: - QList logicAttrs; - LogicMap *attrLogicMap(CardFilter::Attr attr); FilterItemList *attrTypeList(CardFilter::Attr attr, CardFilter::Type type); - bool acceptName(const CardInfo *info, const QString &term) const; - bool acceptType(const CardInfo *info, const QString &term) const; - bool acceptColor(const CardInfo *info, const QString &term) const; - bool acceptCardAttr(const CardInfo *info, const QString &term, - CardFilter::Attr attr) const; - bool acceptText(const CardInfo *info, const QString &term) const; - bool acceptSet(const CardInfo *info, const QString &term) const; - bool acceptManaCost(const CardInfo *info, const QString &term) const; - - bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr, - const FilterItemList *fil) const; - bool testTypeAndNot(const CardInfo *info, CardFilter::Attr attr, - const FilterItemList *fil) const; - bool testTypeOr(const CardInfo *info, CardFilter::Attr attr, - const FilterItemList *filOr, - const FilterItemList *filOrNot) const; - bool testAttr(const CardInfo *info, const LogicMap *lm) const; public: + FilterList(); ~FilterList(); - int indexOf(const LogicMap *val) const { return logicAttrs.indexOf((LogicMap *) val); } int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, const QString &term); int findTermIndex(const CardFilter *f); @@ -132,16 +150,14 @@ public: FilterListNode *termNode(const CardFilter *f); FilterListNode *attrTypeNode(CardFilter::Attr attr, CardFilter::Type type); - int count(CardFilter::Attr attr, CardFilter::Type type); - int count(const CardFilter *f); - virtual FilterListNode *nodeAt(int i) const { return ((logicAttrs.size() > i)? logicAttrs.at(i) : NULL); } - virtual void deleteAt(int i) { delete logicAttrs.takeAt(i); } - virtual int childCount() const { return logicAttrs.size(); } - virtual QString text() const { return QString("root"); } - virtual int index() const { return 0; } + QString text() const { return QString("root"); } + int index() const { return 0; } + + void nodeChanged() const { printf("root\n"); emit changed(); } void preInsertChild(const FilterListNode *p, int i) const { emit preInsertRow(p, i); } - void postInsertChild(const FilterListNode *p, int i) const { emit postInsertRow(p, i); emit changed(); } - void emitChanged() const { emit changed(); } + void postInsertChild(const FilterListNode *p, int i) const { emit postInsertRow(p, i); } + void preRemoveChild(const FilterListNode *p, int i) const { printf("root\n"); emit preRemoveRow(p, i); } + void postRemoveChild(const FilterListNode *p, int i) const { printf("root\n"); emit postRemoveRow(p, i); } bool acceptsCard(const CardInfo *info) const; }; diff --git a/cockatrice/src/filterlistmodel.cpp b/cockatrice/src/filterlistmodel.cpp index a6f2404b..2185ff5c 100644 --- a/cockatrice/src/filterlistmodel.cpp +++ b/cockatrice/src/filterlistmodel.cpp @@ -13,6 +13,12 @@ FilterListModel::FilterListModel(QObject *parent) connect(fList, SIGNAL(postInsertRow(const FilterListNode *, int)), this, SLOT(proxyEndInsertRow(const FilterListNode *, int))); + connect(fList, + SIGNAL(preRemoveRow(const FilterListNode *, int)), + this, SLOT(proxyBeginRemoveRow(const FilterListNode *, int))); + connect(fList, + SIGNAL(postRemoveRow(const FilterListNode *, int)), + this, SLOT(proxyEndRemoveRow(const FilterListNode *, int))); } FilterListModel::~FilterListModel() @@ -38,6 +44,24 @@ void FilterListModel::proxyEndInsertRow(const FilterListNode *node, int) endInsertRows(); } +void FilterListModel::proxyBeginRemoveRow(const FilterListNode *node, int i) +{ + int idx; + + idx = node->index(); + if(idx >= 0) + beginRemoveRows(createIndex(idx, 0, (void *) node), i, i); +} + +void FilterListModel::proxyEndRemoveRow(const FilterListNode *node, int) +{ + int idx; + + idx = node->index(); + if(idx >= 0) + endRemoveRows(); +} + FilterListNode *FilterListModel::indexToNode(const QModelIndex &idx) const { void *ip; @@ -235,11 +259,13 @@ bool FilterListModel::removeRows(int row, int count, const QModelIndex & parent) if(node == NULL || last >= node->childCount()) return false; - beginRemoveRows(parent, row, last); - for(i = 0; i < count; i++) + printf("delete children in %s\n", node->textCStr()); + fflush(stdout); + for(i = 0; i < count; i++) { + printf(" delete %d\n", i); + fflush(stdout); node->deleteAt(row); - endRemoveRows(); - fList->emitChanged(); + } if(node != fList && node->childCount() < 1) return removeRow(parent.row(), parent.parent()); diff --git a/cockatrice/src/filterlistmodel.h b/cockatrice/src/filterlistmodel.h index 944bb5b7..73cdb7e9 100644 --- a/cockatrice/src/filterlistmodel.h +++ b/cockatrice/src/filterlistmodel.h @@ -17,7 +17,9 @@ public slots: private slots: void proxyBeginInsertRow(const FilterListNode *, int); - void proxyEndInsertRow(const FilterListNode *node, int i); + void proxyEndInsertRow(const FilterListNode *, int); + void proxyBeginRemoveRow(const FilterListNode *, int); + void proxyEndRemoveRow(const FilterListNode *, int); private: FilterListNode *indexToNode(const QModelIndex &idx) const; From 16d30fb9e1c9fe8baf566d4a236fe2e706daec67 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Wed, 22 Jan 2014 20:52:52 +0000 Subject: [PATCH 05/55] miscellaneous code cleanup renamed filter list modules to filter tree to more accurately reflect the nature of the data structure. --- cockatrice/CMakeLists.txt | 8 +- cockatrice/src/carddatabasemodel.cpp | 20 +-- cockatrice/src/carddatabasemodel.h | 8 +- cockatrice/src/cardfilter.cpp | 4 +- cockatrice/src/cardfilter.h | 2 +- cockatrice/src/filterbuilder.cpp | 14 +- cockatrice/src/filterbuilder.h | 2 - .../src/{filterlist.cpp => filtertree.cpp} | 76 +++++----- cockatrice/src/{filterlist.h => filtertree.h} | 78 +++++----- ...ilterlistmodel.cpp => filtertreemodel.cpp} | 142 +++++++++--------- .../{filterlistmodel.h => filtertreemodel.h} | 30 ++-- cockatrice/src/tab_deck_editor.cpp | 15 +- cockatrice/src/tab_deck_editor.h | 4 +- 13 files changed, 197 insertions(+), 206 deletions(-) rename cockatrice/src/{filterlist.cpp => filtertree.cpp} (74%) rename cockatrice/src/{filterlist.h => filtertree.h} (65%) rename cockatrice/src/{filterlistmodel.cpp => filtertreemodel.cpp} (53%) rename cockatrice/src/{filterlistmodel.h => filtertreemodel.h} (53%) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 97f771a9..a1e8683a 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -36,8 +36,8 @@ SET(cockatrice_SOURCES src/cardframe.cpp src/filterbuilder.cpp src/cardfilter.cpp - src/filterlistmodel.cpp - src/filterlist.cpp + src/filtertreemodel.cpp + src/filtertree.cpp src/messagelogwidget.cpp src/zoneviewzone.cpp src/zoneviewwidget.cpp @@ -118,8 +118,8 @@ SET(cockatrice_HEADERS src/cardframe.h src/filterbuilder.h src/cardfilter.h - src/filterlistmodel.h - src/filterlist.h + src/filtertreemodel.h + src/filtertree.h src/messagelogwidget.h src/zoneviewzone.h src/zoneviewwidget.h diff --git a/cockatrice/src/carddatabasemodel.cpp b/cockatrice/src/carddatabasemodel.cpp index 559f8cc4..7f314abe 100644 --- a/cockatrice/src/carddatabasemodel.cpp +++ b/cockatrice/src/carddatabasemodel.cpp @@ -1,5 +1,5 @@ #include "carddatabasemodel.h" -#include "filterlist.h" +#include "filtertree.h" CardDatabaseModel::CardDatabaseModel(CardDatabase *_db, QObject *parent) : QAbstractListModel(parent), db(_db) @@ -110,7 +110,7 @@ CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) : QSortFilterProxyModel(parent), isToken(ShowAll) { - filterList = NULL; + filterTree = NULL; setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } @@ -146,8 +146,8 @@ bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex if (!cardTypes.contains(info->getMainCardType())) return false; - if (filterList != NULL) - return filterList->acceptsCard(info); + if (filterTree != NULL) + return filterTree->acceptsCard(info); return true; } @@ -161,17 +161,17 @@ void CardDatabaseDisplayModel::clearSearch() invalidateFilter(); } -void CardDatabaseDisplayModel::setFilterList(const FilterList *filterList) +void CardDatabaseDisplayModel::setFilterTree(const FilterTree *filterTree) { - if(this->filterList != NULL) - disconnect(this->filterList, 0, this, 0); + if (this->filterTree != NULL) + disconnect(this->filterTree, 0, this, 0); - this->filterList = filterList; - connect(this->filterList, SIGNAL(changed()), this, SLOT(filterListChanged())); + this->filterTree = filterTree; + connect(this->filterTree, SIGNAL(changed()), this, SLOT(filterTreeChanged())); invalidate(); } -void CardDatabaseDisplayModel::filterListChanged() +void CardDatabaseDisplayModel::filterTreeChanged() { invalidate(); } diff --git a/cockatrice/src/carddatabasemodel.h b/cockatrice/src/carddatabasemodel.h index ba245b41..dd72e58d 100644 --- a/cockatrice/src/carddatabasemodel.h +++ b/cockatrice/src/carddatabasemodel.h @@ -7,7 +7,7 @@ #include #include "carddatabase.h" -class FilterList; +class FilterTree; class CardDatabaseModel : public QAbstractListModel { Q_OBJECT @@ -38,10 +38,10 @@ private: FilterBool isToken; QString cardNameBeginning, cardName, cardText; QSet cardNameSet, cardTypes, cardColors; - const FilterList *filterList; + const FilterTree *filterTree; public: CardDatabaseDisplayModel(QObject *parent = 0); - void setFilterList(const FilterList *filterList); + void setFilterTree(const FilterTree *filterTree); void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } @@ -53,7 +53,7 @@ public: protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; private slots: - void filterListChanged(); + void filterTreeChanged(); }; #endif diff --git a/cockatrice/src/cardfilter.cpp b/cockatrice/src/cardfilter.cpp index 27402921..38017377 100644 --- a/cockatrice/src/cardfilter.cpp +++ b/cockatrice/src/cardfilter.cpp @@ -2,7 +2,7 @@ const char *CardFilter::typeName(Type t) { - switch(t) { + switch (t) { case TypeAnd: return "and"; case TypeOr: @@ -18,7 +18,7 @@ const char *CardFilter::typeName(Type t) const char *CardFilter::attrName(Attr a) { - switch(a) { + switch (a) { case AttrName: return "name"; case AttrType: diff --git a/cockatrice/src/cardfilter.h b/cockatrice/src/cardfilter.h index f4f38771..539cdb0c 100644 --- a/cockatrice/src/cardfilter.h +++ b/cockatrice/src/cardfilter.h @@ -11,7 +11,7 @@ public: TypeAndNot, TypeOrNot, TypeEnd - }; + }; /* if you add an atribute here you also need to * add its string representation in attrName */ diff --git a/cockatrice/src/filterbuilder.cpp b/cockatrice/src/filterbuilder.cpp index 53b93144..6e659752 100644 --- a/cockatrice/src/filterbuilder.cpp +++ b/cockatrice/src/filterbuilder.cpp @@ -16,12 +16,12 @@ FilterBuilder::FilterBuilder(QWidget *parent) QHBoxLayout *addFilter = new QHBoxLayout; filterCombo = new QComboBox; - for(i = 0; i < CardFilter::AttrEnd; i++) + for (i = 0; i < CardFilter::AttrEnd; i++) filterCombo->addItem( CardFilter::attrName(static_cast(i)), QVariant(i)); typeCombo = new QComboBox; - for(i = 0; i < CardFilter::TypeEnd; i++) + for (i = 0; i < CardFilter::TypeEnd; i++) typeCombo->addItem( CardFilter::typeName(static_cast(i)), QVariant(i)); @@ -52,7 +52,7 @@ FilterBuilder::~FilterBuilder() void FilterBuilder::destroyFilter() { - if(fltr) + if (fltr) delete fltr; } @@ -66,7 +66,7 @@ void FilterBuilder::add_released() QString txt; txt = edit->text(); - if(txt.length() < 1) + if (txt.length() < 1) return; destroyFilter(); @@ -75,9 +75,3 @@ void FilterBuilder::add_released() static_cast(comboCurrentIntData(filterCombo))); emit add(fltr); } - -bool FilterBuilder::filter(const CardFilter *f) const -{ - f = fltr; - return false; -} diff --git a/cockatrice/src/filterbuilder.h b/cockatrice/src/filterbuilder.h index 2762ba28..c126c82b 100644 --- a/cockatrice/src/filterbuilder.h +++ b/cockatrice/src/filterbuilder.h @@ -23,8 +23,6 @@ public: FilterBuilder(QWidget *parent = 0); ~FilterBuilder(); - bool filter(const CardFilter *f) const; - signals: void add(const CardFilter *f); diff --git a/cockatrice/src/filterlist.cpp b/cockatrice/src/filtertree.cpp similarity index 74% rename from cockatrice/src/filterlist.cpp rename to cockatrice/src/filtertree.cpp index 9a4b3a71..852ff5cd 100644 --- a/cockatrice/src/filterlist.cpp +++ b/cockatrice/src/filtertree.cpp @@ -1,17 +1,17 @@ -#include "filterlist.h" +#include "filtertree.h" #include "cardfilter.h" #include "carddatabase.h" #include template -FilterListNode *FilterListInnerNode::nodeAt(int i) const +FilterTreeNode *FilterTreeBranch::nodeAt(int i) const { return ((childNodes.size() > i)? childNodes.at(i) : NULL); } template -void FilterListInnerNode::deleteAt(int i) +void FilterTreeBranch::deleteAt(int i) { preRemoveChild(this, i); delete childNodes.takeAt(i); @@ -20,24 +20,24 @@ void FilterListInnerNode::deleteAt(int i) } template -int FilterListInnerNode::childIndex(const FilterListNode *node) const +int FilterTreeBranch::childIndex(const FilterTreeNode *node) const { - FilterListNode *unconst; + FilterTreeNode *unconst; T downcasted; /* to do the dynamic cast to T we will lose const'ness, but we can * trust QList::indexOf */ - unconst = (FilterListNode *) node; + unconst = (FilterTreeNode *) node; downcasted = dynamic_cast(unconst); - if(downcasted == NULL) + if (downcasted == NULL) return -1; return childNodes.indexOf(downcasted); } template -FilterListInnerNode::~FilterListInnerNode() +FilterTreeBranch::~FilterTreeBranch() { - while(!childNodes.isEmpty()) + while (!childNodes.isEmpty()) delete childNodes.takeFirst(); } @@ -45,7 +45,7 @@ const FilterItemList *LogicMap::findTypeList(CardFilter::Type type) const { QList::const_iterator i; - for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) if ((*i)->type == type) return *i; @@ -58,7 +58,7 @@ FilterItemList *LogicMap::typeList(CardFilter::Type type) int count; count = 0; - for(i = childNodes.begin(); i != childNodes.end(); i++) { + for (i = childNodes.begin(); i != childNodes.end(); i++) { if ((*i)->type == type) break; count++; @@ -73,7 +73,7 @@ FilterItemList *LogicMap::typeList(CardFilter::Type type) return *i; } -FilterListNode *LogicMap::parent() const +FilterTreeNode *LogicMap::parent() const { return p; } @@ -82,20 +82,20 @@ int FilterItemList::termIndex(const QString &term) const { int i; - for(i = 0; i < childNodes.count(); i++) - if((childNodes.at(i))->term == term) + for (i = 0; i < childNodes.count(); i++) + if ((childNodes.at(i))->term == term) return i; return -1; } -FilterListNode *FilterItemList::termNode(const QString &term) +FilterTreeNode *FilterItemList::termNode(const QString &term) { int i, count; FilterItem *fi; i = termIndex(term); - if(i < 0) { + if (i < 0) { fi = new FilterItem(term, this); count = childNodes.count(); preInsertChild(this, count); @@ -112,7 +112,7 @@ bool FilterItemList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr) co { QList::const_iterator i; - for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) if (!(*i)->acceptCardAttr(info, attr)) return false; @@ -129,7 +129,7 @@ bool FilterItemList::testTypeOr(const CardInfo *info, CardFilter::Attr attr) con { QList::const_iterator i; - for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) if ((*i)->acceptCardAttr(info, attr)) return true; @@ -158,7 +158,7 @@ bool FilterItem::acceptColor(const CardInfo *info) const bool status; status = false; - for(i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) + for (i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) if ((*i).contains(term, Qt::CaseInsensitive)) { status = true; break; @@ -178,7 +178,7 @@ bool FilterItem::acceptSet(const CardInfo *info) const bool status; status = false; - for(i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) + for (i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) if ((*i)->getShortName() == term || (*i)->getLongName().contains(term, Qt::CaseInsensitive)) { status = true; @@ -197,10 +197,10 @@ bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) con { bool status; - if(!isEnabled()) + if (!isEnabled()) return true; - switch(attr) { + switch (attr) { case CardFilter::AttrName: status = acceptName(info); break; @@ -227,24 +227,24 @@ bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) con } /* need to define these here to make QT happy, otherwise - * moc doesnt find some of the FilterListInnerNode symbols. + * moc doesnt find some of the FilterTreeBranch symbols. */ -FilterList::FilterList() {} -FilterList::~FilterList() {} +FilterTree::FilterTree() {} +FilterTree::~FilterTree() {} -LogicMap *FilterList::attrLogicMap(CardFilter::Attr attr) +LogicMap *FilterTree::attrLogicMap(CardFilter::Attr attr) { QList::iterator i; int count; count = 0; - for(i = childNodes.begin(); i != childNodes.end(); i++) { - if((*i)->attr == attr) + for (i = childNodes.begin(); i != childNodes.end(); i++) { + if ((*i)->attr == attr) break; count++; } - if(i == childNodes.end()) { + if (i == childNodes.end()) { preInsertChild(this, count); i = childNodes.insert(i, new LogicMap(attr, this)); postInsertChild(this, count); @@ -254,41 +254,41 @@ LogicMap *FilterList::attrLogicMap(CardFilter::Attr attr) return *i; } -FilterItemList *FilterList::attrTypeList(CardFilter::Attr attr, +FilterItemList *FilterTree::attrTypeList(CardFilter::Attr attr, CardFilter::Type type) { return attrLogicMap(attr)->typeList(type); } -int FilterList::findTermIndex(CardFilter::Attr attr, CardFilter::Type type, +int FilterTree::findTermIndex(CardFilter::Attr attr, CardFilter::Type type, const QString &term) { attrTypeList(attr, type)->termIndex(term); } -int FilterList::findTermIndex(const CardFilter *f) +int FilterTree::findTermIndex(const CardFilter *f) { return findTermIndex(f->attr(), f->type(), f->term()); } -FilterListNode *FilterList::termNode(CardFilter::Attr attr, CardFilter::Type type, +FilterTreeNode *FilterTree::termNode(CardFilter::Attr attr, CardFilter::Type type, const QString &term) { return attrTypeList(attr, type)->termNode(term); } -FilterListNode *FilterList::termNode(const CardFilter *f) +FilterTreeNode *FilterTree::termNode(const CardFilter *f) { return termNode(f->attr(), f->type(), f->term()); } -FilterListNode *FilterList::attrTypeNode(CardFilter::Attr attr, +FilterTreeNode *FilterTree::attrTypeNode(CardFilter::Attr attr, CardFilter::Type type) { return attrTypeList(attr, type); } -bool FilterList::testAttr(const CardInfo *info, const LogicMap *lm) const +bool FilterTree::testAttr(const CardInfo *info, const LogicMap *lm) const { const FilterItemList *fil; bool status; @@ -318,11 +318,11 @@ bool FilterList::testAttr(const CardInfo *info, const LogicMap *lm) const return status; } -bool FilterList::acceptsCard(const CardInfo *info) const +bool FilterTree::acceptsCard(const CardInfo *info) const { QList::const_iterator i; - for(i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) if ((*i)->isEnabled() && !testAttr(info, *i)) return false; diff --git a/cockatrice/src/filterlist.h b/cockatrice/src/filtertree.h similarity index 65% rename from cockatrice/src/filterlist.h rename to cockatrice/src/filtertree.h index 20f78984..1ee84ffa 100644 --- a/cockatrice/src/filterlist.h +++ b/cockatrice/src/filtertree.h @@ -1,5 +1,5 @@ -#ifndef FILTERLIST_H -#define FILTERLIST_H +#ifndef FILTERTREE_H +#define FILTERTREE_H #include #include @@ -9,19 +9,19 @@ class CardInfo; -class FilterListNode { +class FilterTreeNode { private: bool enabled; public: - FilterListNode() : enabled(true) {} + FilterTreeNode() : enabled(true) {} virtual bool isEnabled() const { return enabled; } virtual void enable() { enabled = true; nodeChanged(); } virtual void disable() { enabled = false; nodeChanged(); } - virtual FilterListNode *parent() const { return NULL; } - virtual FilterListNode *nodeAt(int i) const { return NULL; } + virtual FilterTreeNode *parent() const { return NULL; } + virtual FilterTreeNode *nodeAt(int i) const { return NULL; } virtual void deleteAt(int i) {} virtual int childCount() const { return 0; } - virtual int childIndex(const FilterListNode *node) const { return -1; } + virtual int childIndex(const FilterTreeNode *node) const { return -1; } virtual int index() const { return (parent() != NULL)? parent()->childIndex(this) : -1; } virtual QString text() const { return ""; } virtual bool isLeaf() const { return false; } @@ -30,56 +30,56 @@ public: printf("%s -> ", textCStr()); if (parent() != NULL) parent()->nodeChanged(); } - virtual void preInsertChild(const FilterListNode *p, int i) const { + virtual void preInsertChild(const FilterTreeNode *p, int i) const { //printf("%s -> ", textCStr()); if (parent() != NULL) parent()->preInsertChild(p, i); } - virtual void postInsertChild(const FilterListNode *p, int i) const { + virtual void postInsertChild(const FilterTreeNode *p, int i) const { //printf("%s -> ", textCStr()); if (parent() != NULL) parent()->postInsertChild(p, i); } - virtual void preRemoveChild(const FilterListNode *p, int i) const { + virtual void preRemoveChild(const FilterTreeNode *p, int i) const { printf("%s -> ", textCStr()); if (parent() != NULL) parent()->preRemoveChild(p, i); } - virtual void postRemoveChild(const FilterListNode *p, int i) const { + virtual void postRemoveChild(const FilterTreeNode *p, int i) const { printf("%s -> ", textCStr()); if (parent() != NULL) parent()->postRemoveChild(p, i); } }; template -class FilterListInnerNode : public FilterListNode { +class FilterTreeBranch : public FilterTreeNode { protected: QList childNodes; public: - ~FilterListInnerNode(); - FilterListNode *nodeAt(int i) const; + ~FilterTreeBranch(); + FilterTreeNode *nodeAt(int i) const; void deleteAt(int i); int childCount() const { return childNodes.size(); } - int childIndex(const FilterListNode *node) const; + int childIndex(const FilterTreeNode *node) const; }; class FilterItemList; -class FilterList; -class LogicMap : public FilterListInnerNode { +class FilterTree; +class LogicMap : public FilterTreeBranch { private: - FilterList *const p; + FilterTree *const p; public: const CardFilter::Attr attr; - LogicMap(CardFilter::Attr a, FilterList *parent) + LogicMap(CardFilter::Attr a, FilterTree *parent) : attr(a), p(parent) {} const FilterItemList *findTypeList(CardFilter::Type type) const; FilterItemList *typeList(CardFilter::Type type); - FilterListNode *parent() const; + FilterTreeNode *parent() const; QString text() const { return QString(CardFilter::attrName(attr)); } }; class FilterItem; -class FilterItemList : public FilterListInnerNode { +class FilterItemList : public FilterTreeBranch { private: LogicMap *const p; public: @@ -88,9 +88,9 @@ public: FilterItemList(CardFilter::Type t, LogicMap *parent) : type(t), p(parent) {} CardFilter::Attr attr() const { return p->attr; } - FilterListNode *parent() const { return p; } + FilterTreeNode *parent() const { return p; } int termIndex(const QString &term) const; - FilterListNode *termNode(const QString &term); + FilterTreeNode *termNode(const QString &term); QString text() const { return QString(CardFilter::typeName(type)); } bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const; @@ -99,7 +99,7 @@ public: bool testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const; }; -class FilterItem : public FilterListNode { +class FilterItem : public FilterTreeNode { private: FilterItemList *const p; public: @@ -110,7 +110,7 @@ public: CardFilter::Attr attr() const { return p->attr(); } CardFilter::Type type() const { return p->type; } - FilterListNode *parent() const { return p; } + FilterTreeNode *parent() const { return p; } QString text() const { return term; } bool isLeaf() const { return true; } @@ -123,14 +123,14 @@ public: bool acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const; }; -class FilterList : public QObject, public FilterListInnerNode { +class FilterTree : public QObject, public FilterTreeBranch { Q_OBJECT signals: - void preInsertRow(const FilterListNode *parent, int i) const; - void postInsertRow(const FilterListNode *parent, int i) const; - void preRemoveRow(const FilterListNode *parent, int i) const; - void postRemoveRow(const FilterListNode *parent, int i) const; + void preInsertRow(const FilterTreeNode *parent, int i) const; + void postInsertRow(const FilterTreeNode *parent, int i) const; + void preRemoveRow(const FilterTreeNode *parent, int i) const; + void postRemoveRow(const FilterTreeNode *parent, int i) const; void changed() const; private: @@ -140,24 +140,24 @@ private: bool testAttr(const CardInfo *info, const LogicMap *lm) const; public: - FilterList(); - ~FilterList(); + FilterTree(); + ~FilterTree(); int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, const QString &term); int findTermIndex(const CardFilter *f); - FilterListNode *termNode(CardFilter::Attr attr, CardFilter::Type type, + FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, const QString &term); - FilterListNode *termNode(const CardFilter *f); - FilterListNode *attrTypeNode(CardFilter::Attr attr, + FilterTreeNode *termNode(const CardFilter *f); + FilterTreeNode *attrTypeNode(CardFilter::Attr attr, CardFilter::Type type); QString text() const { return QString("root"); } int index() const { return 0; } void nodeChanged() const { printf("root\n"); emit changed(); } - void preInsertChild(const FilterListNode *p, int i) const { emit preInsertRow(p, i); } - void postInsertChild(const FilterListNode *p, int i) const { emit postInsertRow(p, i); } - void preRemoveChild(const FilterListNode *p, int i) const { printf("root\n"); emit preRemoveRow(p, i); } - void postRemoveChild(const FilterListNode *p, int i) const { printf("root\n"); emit postRemoveRow(p, i); } + void preInsertChild(const FilterTreeNode *p, int i) const { emit preInsertRow(p, i); } + void postInsertChild(const FilterTreeNode *p, int i) const { emit postInsertRow(p, i); } + void preRemoveChild(const FilterTreeNode *p, int i) const { printf("root\n"); emit preRemoveRow(p, i); } + void postRemoveChild(const FilterTreeNode *p, int i) const { printf("root\n"); emit postRemoveRow(p, i); } bool acceptsCard(const CardInfo *info) const; }; diff --git a/cockatrice/src/filterlistmodel.cpp b/cockatrice/src/filtertreemodel.cpp similarity index 53% rename from cockatrice/src/filterlistmodel.cpp rename to cockatrice/src/filtertreemodel.cpp index 2185ff5c..d23c46ed 100644 --- a/cockatrice/src/filterlistmodel.cpp +++ b/cockatrice/src/filtertreemodel.cpp @@ -1,100 +1,100 @@ #include -#include "filterlistmodel.h" -#include "filterlist.h" +#include "filtertreemodel.h" +#include "filtertree.h" #include "cardfilter.h" -FilterListModel::FilterListModel(QObject *parent) +FilterTreeModel::FilterTreeModel(QObject *parent) : QAbstractItemModel(parent) { - fList = new FilterList; - connect(fList, - SIGNAL(preInsertRow(const FilterListNode *, int)), - this, SLOT(proxyBeginInsertRow(const FilterListNode *, int))); - connect(fList, - SIGNAL(postInsertRow(const FilterListNode *, int)), - this, SLOT(proxyEndInsertRow(const FilterListNode *, int))); - connect(fList, - SIGNAL(preRemoveRow(const FilterListNode *, int)), - this, SLOT(proxyBeginRemoveRow(const FilterListNode *, int))); - connect(fList, - SIGNAL(postRemoveRow(const FilterListNode *, int)), - this, SLOT(proxyEndRemoveRow(const FilterListNode *, int))); + fTree = new FilterTree; + connect(fTree, + SIGNAL(preInsertRow(const FilterTreeNode *, int)), + this, SLOT(proxyBeginInsertRow(const FilterTreeNode *, int))); + connect(fTree, + SIGNAL(postInsertRow(const FilterTreeNode *, int)), + this, SLOT(proxyEndInsertRow(const FilterTreeNode *, int))); + connect(fTree, + SIGNAL(preRemoveRow(const FilterTreeNode *, int)), + this, SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int))); + connect(fTree, + SIGNAL(postRemoveRow(const FilterTreeNode *, int)), + this, SLOT(proxyEndRemoveRow(const FilterTreeNode *, int))); } -FilterListModel::~FilterListModel() +FilterTreeModel::~FilterTreeModel() { - delete fList; + delete fTree; } -void FilterListModel::proxyBeginInsertRow(const FilterListNode *node, int i) +void FilterTreeModel::proxyBeginInsertRow(const FilterTreeNode *node, int i) { int idx; idx = node->index(); - if(idx >= 0) + if (idx >= 0) beginInsertRows(createIndex(idx, 0, (void *) node), i, i); } -void FilterListModel::proxyEndInsertRow(const FilterListNode *node, int) +void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int) { int idx; idx = node->index(); - if(idx >= 0) + if (idx >= 0) endInsertRows(); } -void FilterListModel::proxyBeginRemoveRow(const FilterListNode *node, int i) +void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i) { int idx; idx = node->index(); - if(idx >= 0) + if (idx >= 0) beginRemoveRows(createIndex(idx, 0, (void *) node), i, i); } -void FilterListModel::proxyEndRemoveRow(const FilterListNode *node, int) +void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int) { int idx; idx = node->index(); - if(idx >= 0) + if (idx >= 0) endRemoveRows(); } -FilterListNode *FilterListModel::indexToNode(const QModelIndex &idx) const +FilterTreeNode *FilterTreeModel::indexToNode(const QModelIndex &idx) const { void *ip; - FilterListNode *node; + FilterTreeNode *node; - if(!idx.isValid()) - return fList; + if (!idx.isValid()) + return fTree; ip = idx.internalPointer(); - if(ip == NULL) - return fList; + if (ip == NULL) + return fTree; - node = static_cast(ip); + node = static_cast(ip); return node; } -void FilterListModel::addFilter(const CardFilter *f) +void FilterTreeModel::addFilter(const CardFilter *f) { emit layoutAboutToBeChanged(); - fList->termNode(f); + fTree->termNode(f); emit layoutChanged(); } -int FilterListModel::rowCount(const QModelIndex &parent) const +int FilterTreeModel::rowCount(const QModelIndex &parent) const { - const FilterListNode *node; + const FilterTreeNode *node; int result; - if(parent.column() > 0) + if (parent.column() > 0) return 0; node = indexToNode(parent); - if(node) + if (node) result = node->childCount(); else result = 0; @@ -102,14 +102,14 @@ int FilterListModel::rowCount(const QModelIndex &parent) const return result; } -int FilterListModel::columnCount(const QModelIndex &/*parent*/) const +int FilterTreeModel::columnCount(const QModelIndex &/*parent*/) const { return 1; } -QVariant FilterListModel::data(const QModelIndex &index, int role) const +QVariant FilterTreeModel::data(const QModelIndex &index, int role) const { - const FilterListNode *node; + const FilterTreeNode *node; if (!index.isValid()) return QVariant(); @@ -117,12 +117,12 @@ QVariant FilterListModel::data(const QModelIndex &index, int role) const return QVariant(); node = indexToNode(index); - if(node == NULL) + if (node == NULL) return QVariant(); switch (role) { case Qt::FontRole: - if(!node->isLeaf()) { + if (!node->isLeaf()) { QFont f; f.setBold(true); return f; @@ -135,7 +135,7 @@ QVariant FilterListModel::data(const QModelIndex &index, int role) const case Qt::WhatsThisRole: return node->text(); case Qt::CheckStateRole: - if(node->isEnabled()) + if (node->isEnabled()) return Qt::Checked; else return Qt::Unchecked; @@ -146,10 +146,10 @@ QVariant FilterListModel::data(const QModelIndex &index, int role) const return QVariant(); } -bool FilterListModel::setData(const QModelIndex &index, +bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) { - FilterListNode *node; + FilterTreeNode *node; if (!index.isValid()) return false; @@ -159,33 +159,33 @@ bool FilterListModel::setData(const QModelIndex &index, return false; node = indexToNode(index); - if(node == NULL || node == fList) + if (node == NULL || node == fTree) return false; Qt::CheckState state = static_cast(value.toInt()); - if(state == Qt::Checked) + if (state == Qt::Checked) node->enable(); - else + else node->disable(); emit dataChanged(index, index); - return true; + return true; } -Qt::ItemFlags FilterListModel::flags(const QModelIndex &index) const +Qt::ItemFlags FilterTreeModel::flags(const QModelIndex &index) const { - const FilterListNode *node; + const FilterTreeNode *node; Qt::ItemFlags result; if (!index.isValid()) return 0; node = indexToNode(index); - if(node == NULL) + if (node == NULL) return 0; result = Qt::ItemIsEnabled; - if(node == fList) + if (node == fTree) return result; result |= Qt::ItemIsSelectable; @@ -194,9 +194,9 @@ Qt::ItemFlags FilterListModel::flags(const QModelIndex &index) const return result; } -QModelIndex FilterListModel::nodeIndex(const FilterListNode *node, int row, int column) const +QModelIndex FilterTreeModel::nodeIndex(const FilterTreeNode *node, int row, int column) const { - FilterListNode *child; + FilterTreeNode *child; if (column > 0 || row >= node->childCount()) return QModelIndex(); @@ -205,25 +205,25 @@ QModelIndex FilterListModel::nodeIndex(const FilterListNode *node, int row, int return createIndex(row, column, child); } -QModelIndex FilterListModel::index(int row, int column, +QModelIndex FilterTreeModel::index(int row, int column, const QModelIndex &parent) const { - const FilterListNode *node; + const FilterTreeNode *node; if (!hasIndex(row, column, parent)) return QModelIndex(); node = indexToNode(parent); - if(node == NULL) + if (node == NULL) return QModelIndex(); return nodeIndex(node, row, column); } -QModelIndex FilterListModel::parent(const QModelIndex &ind) const +QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const { - const FilterListNode *node; - FilterListNode *parent; + const FilterTreeNode *node; + FilterTreeNode *parent; int row; QModelIndex idx; @@ -231,13 +231,13 @@ QModelIndex FilterListModel::parent(const QModelIndex &ind) const return QModelIndex(); node = indexToNode(ind); - if(node == NULL || node == fList) + if (node == NULL || node == fTree) return QModelIndex(); parent = node->parent(); - if(parent) { + if (parent) { row = parent->index(); - if(row < 0) + if (row < 0) return QModelIndex(); idx = createIndex(row, 0, parent); return idx; @@ -246,9 +246,9 @@ QModelIndex FilterListModel::parent(const QModelIndex &ind) const return QModelIndex(); } -bool FilterListModel::removeRows(int row, int count, const QModelIndex & parent) +bool FilterTreeModel::removeRows(int row, int count, const QModelIndex & parent) { - FilterListNode *node; + FilterTreeNode *node; int i, last; last = row+count-1; @@ -256,18 +256,18 @@ bool FilterListModel::removeRows(int row, int count, const QModelIndex & parent) return false; node = indexToNode(parent); - if(node == NULL || last >= node->childCount()) + if (node == NULL || last >= node->childCount()) return false; printf("delete children in %s\n", node->textCStr()); fflush(stdout); - for(i = 0; i < count; i++) { + for (i = 0; i < count; i++) { printf(" delete %d\n", i); fflush(stdout); node->deleteAt(row); } - if(node != fList && node->childCount() < 1) + if (node != fTree && node->childCount() < 1) return removeRow(parent.row(), parent.parent()); return true; diff --git a/cockatrice/src/filterlistmodel.h b/cockatrice/src/filtertreemodel.h similarity index 53% rename from cockatrice/src/filterlistmodel.h rename to cockatrice/src/filtertreemodel.h index 73cdb7e9..fd2e7e33 100644 --- a/cockatrice/src/filterlistmodel.h +++ b/cockatrice/src/filtertreemodel.h @@ -1,34 +1,34 @@ -#ifndef FILTERLISTMODEL_H -#define FILTERLISTMODEL_H +#ifndef FILTERTREEMODEL_H +#define FILTERTREEMODEL_H #include -class FilterList; +class FilterTree; class CardFilter; -class FilterListNode; +class FilterTreeNode; -class FilterListModel : public QAbstractItemModel { +class FilterTreeModel : public QAbstractItemModel { Q_OBJECT private: - FilterList *fList; + FilterTree *fTree; public slots: void addFilter(const CardFilter *f); private slots: - void proxyBeginInsertRow(const FilterListNode *, int); - void proxyEndInsertRow(const FilterListNode *, int); - void proxyBeginRemoveRow(const FilterListNode *, int); - void proxyEndRemoveRow(const FilterListNode *, int); + void proxyBeginInsertRow(const FilterTreeNode *, int); + void proxyEndInsertRow(const FilterTreeNode *, int); + void proxyBeginRemoveRow(const FilterTreeNode *, int); + void proxyEndRemoveRow(const FilterTreeNode *, int); private: - FilterListNode *indexToNode(const QModelIndex &idx) const; - QModelIndex nodeIndex(const FilterListNode *node, int row, int column) const; + FilterTreeNode *indexToNode(const QModelIndex &idx) const; + QModelIndex nodeIndex(const FilterTreeNode *node, int row, int column) const; public: - FilterListModel(QObject *parent = 0); - ~FilterListModel(); - const FilterList *filterList() const { return fList; } + FilterTreeModel(QObject *parent = 0); + ~FilterTreeModel(); + const FilterTree *filterTree() const { return fTree; } int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index a1fc1022..57b48135 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -42,12 +42,11 @@ #include #include "cardframe.h" #include "filterbuilder.h" -#include "carditem.h" -#include "carddatabase.h" +//#include "carditem.h" +//#include "carddatabase.h" #include "main.h" #include "settingscache.h" -#include "filterlistmodel.h" -#include "filterlist.h" +#include "filtertreemodel.h" void SearchLineEdit::keyPressEvent(QKeyEvent *event) { @@ -169,8 +168,8 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) searchAndButtons->addLayout(searchLayout, 0, 1); botFrame->addLayout(searchAndButtons); - filterModel = new FilterListModel(); - databaseDisplayModel->setFilterList(filterModel->filterList()); + filterModel = new FilterTreeModel(); + databaseDisplayModel->setFilterTree(filterModel->filterTree()); filterView = new QTreeView; filterView->setModel(filterModel); filterView->setMaximumWidth(250); @@ -663,7 +662,7 @@ void TabDeckEditor::filterViewCustomContextMenu(const QPoint &point) { QModelIndex idx; idx = filterView->indexAt(point); - if(!idx.isValid()) + if (!idx.isValid()) return; action = menu.addAction(QString("delete")); @@ -679,7 +678,7 @@ void TabDeckEditor::filterRemove(QAction *action) { point = action->data().toPoint(); idx = filterView->indexAt(point); - if(!idx.isValid()) + if (!idx.isValid()) return; filterModel->removeRow(idx.row(), idx.parent()); diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 716f6ade..2b955c3f 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -16,7 +16,7 @@ class DlgCardSearch; class QLabel; class DeckLoader; class Response; -class FilterListModel; +class FilterTreeModel; class SearchLineEdit : public QLineEdit { private: @@ -84,7 +84,7 @@ private: QLabel *hashLabel1; QLabel *hashLabel; DlgCardSearch *dlgCardSearch; - FilterListModel *filterModel; + FilterTreeModel *filterModel; QTreeView *filterView; QMenu *deckMenu, *dbMenu; From c786e180c39db86c5e4b1f4104bf65cc45c41801 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Sun, 26 Jan 2014 23:20:35 +0000 Subject: [PATCH 06/55] reverted back to original deck editor layout but including filtertree the original layout is actually more space efficient if using CardFrame instead of CardInfoWidget and reducing the size of the deck editor toolbar. this commit also removes the old search feature by removing the search button and the clear search button. the clear search menu item is left in place, however it now clears the filtertree. finally, the stretch factor for the right frame in the main layout was reduced to zero so that the card database gets priority for extra space. this makes more sense because the deck editor does not actually need very much horizontal space. --- cockatrice/src/carddatabasemodel.cpp | 4 +- cockatrice/src/carddatabasemodel.h | 4 +- cockatrice/src/cardframe.cpp | 9 +- cockatrice/src/cardframe.h | 2 +- cockatrice/src/filtertree.cpp | 6 ++ cockatrice/src/filtertree.h | 19 ++-- cockatrice/src/filtertreemodel.h | 2 +- cockatrice/src/tab_deck_editor.cpp | 154 ++++++++++----------------- cockatrice/src/tab_deck_editor.h | 5 +- 9 files changed, 80 insertions(+), 125 deletions(-) diff --git a/cockatrice/src/carddatabasemodel.cpp b/cockatrice/src/carddatabasemodel.cpp index 7f314abe..ddddddfe 100644 --- a/cockatrice/src/carddatabasemodel.cpp +++ b/cockatrice/src/carddatabasemodel.cpp @@ -158,10 +158,12 @@ void CardDatabaseDisplayModel::clearSearch() cardText.clear(); cardTypes.clear(); cardColors.clear(); + if (filterTree != NULL) + filterTree->clear(); invalidateFilter(); } -void CardDatabaseDisplayModel::setFilterTree(const FilterTree *filterTree) +void CardDatabaseDisplayModel::setFilterTree(FilterTree *filterTree) { if (this->filterTree != NULL) disconnect(this->filterTree, 0, this, 0); diff --git a/cockatrice/src/carddatabasemodel.h b/cockatrice/src/carddatabasemodel.h index dd72e58d..621eff5a 100644 --- a/cockatrice/src/carddatabasemodel.h +++ b/cockatrice/src/carddatabasemodel.h @@ -38,10 +38,10 @@ private: FilterBool isToken; QString cardNameBeginning, cardName, cardText; QSet cardNameSet, cardTypes, cardColors; - const FilterTree *filterTree; + FilterTree *filterTree; public: CardDatabaseDisplayModel(QObject *parent = 0); - void setFilterTree(const FilterTree *filterTree); + void setFilterTree(FilterTree *filterTree); void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } diff --git a/cockatrice/src/cardframe.cpp b/cockatrice/src/cardframe.cpp index bdfca5cf..dd4191ef 100644 --- a/cockatrice/src/cardframe.cpp +++ b/cockatrice/src/cardframe.cpp @@ -5,15 +5,12 @@ #include "carddatabase.h" #include "main.h" -CardFrame::CardFrame(const QString &cardName, QWidget *parent, Qt::WindowFlags flags) - : QLabel(parent, flags) +CardFrame::CardFrame(const QString &cardName, QWidget *parent) + : QLabel(parent) , info(0) { - this->setAlignment(Qt::AlignCenter); - setFrameStyle(QFrame::Panel | QFrame::Raised); - setFixedWidth(250); - + setMaximumWidth(250); setCard(db->getCard(cardName)); } diff --git a/cockatrice/src/cardframe.h b/cockatrice/src/cardframe.h index 465dff24..1dccf821 100644 --- a/cockatrice/src/cardframe.h +++ b/cockatrice/src/cardframe.h @@ -15,7 +15,7 @@ private: CardInfo *info; public: - CardFrame(const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0); + CardFrame(const QString &cardName = QString(), QWidget *parent = 0); QString getCardName() const; public slots: diff --git a/cockatrice/src/filtertree.cpp b/cockatrice/src/filtertree.cpp index 852ff5cd..9e647e82 100644 --- a/cockatrice/src/filtertree.cpp +++ b/cockatrice/src/filtertree.cpp @@ -328,3 +328,9 @@ bool FilterTree::acceptsCard(const CardInfo *info) const return true; } + +void FilterTree::clear() +{ + while(childCount() > 0) + deleteAt(0); +} diff --git a/cockatrice/src/filtertree.h b/cockatrice/src/filtertree.h index 1ee84ffa..816bf97a 100644 --- a/cockatrice/src/filtertree.h +++ b/cockatrice/src/filtertree.h @@ -27,23 +27,18 @@ public: virtual bool isLeaf() const { return false; } virtual const char *textCStr() const { return text().toStdString().c_str(); } virtual void nodeChanged() const { - printf("%s -> ", textCStr()); if (parent() != NULL) parent()->nodeChanged(); } virtual void preInsertChild(const FilterTreeNode *p, int i) const { - //printf("%s -> ", textCStr()); if (parent() != NULL) parent()->preInsertChild(p, i); } virtual void postInsertChild(const FilterTreeNode *p, int i) const { - //printf("%s -> ", textCStr()); if (parent() != NULL) parent()->postInsertChild(p, i); } virtual void preRemoveChild(const FilterTreeNode *p, int i) const { - printf("%s -> ", textCStr()); if (parent() != NULL) parent()->preRemoveChild(p, i); } virtual void postRemoveChild(const FilterTreeNode *p, int i) const { - printf("%s -> ", textCStr()); if (parent() != NULL) parent()->postRemoveChild(p, i); } }; @@ -139,6 +134,13 @@ private: CardFilter::Type type); bool testAttr(const CardInfo *info, const LogicMap *lm) const; + + void nodeChanged() const { emit changed(); } + void preInsertChild(const FilterTreeNode *p, int i) const { emit preInsertRow(p, i); } + void postInsertChild(const FilterTreeNode *p, int i) const { emit postInsertRow(p, i); } + void preRemoveChild(const FilterTreeNode *p, int i) const { emit preRemoveRow(p, i); } + void postRemoveChild(const FilterTreeNode *p, int i) const { emit postRemoveRow(p, i); } + public: FilterTree(); ~FilterTree(); @@ -153,13 +155,8 @@ public: QString text() const { return QString("root"); } int index() const { return 0; } - void nodeChanged() const { printf("root\n"); emit changed(); } - void preInsertChild(const FilterTreeNode *p, int i) const { emit preInsertRow(p, i); } - void postInsertChild(const FilterTreeNode *p, int i) const { emit postInsertRow(p, i); } - void preRemoveChild(const FilterTreeNode *p, int i) const { printf("root\n"); emit preRemoveRow(p, i); } - void postRemoveChild(const FilterTreeNode *p, int i) const { printf("root\n"); emit postRemoveRow(p, i); } - bool acceptsCard(const CardInfo *info) const; + void clear(); }; #endif diff --git a/cockatrice/src/filtertreemodel.h b/cockatrice/src/filtertreemodel.h index fd2e7e33..7e49e9b1 100644 --- a/cockatrice/src/filtertreemodel.h +++ b/cockatrice/src/filtertreemodel.h @@ -28,7 +28,7 @@ private: public: FilterTreeModel(QObject *parent = 0); ~FilterTreeModel(); - const FilterTree *filterTree() const { return fTree; } + FilterTree *filterTree() const { return fTree; } int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 57b48135..2de449f4 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -21,7 +21,7 @@ #include "carddatabase.h" #include "carddatabasemodel.h" #include "decklistmodel.h" -#include "dlg_cardsearch.h" +#include "cardinfowidget.h" #include "dlg_load_deck_from_clipboard.h" #include "dlg_edit_tokens.h" #include "main.h" @@ -33,20 +33,9 @@ #include "pending_command.h" #include "pb/response.pb.h" #include "pb/command_deck_upload.pb.h" -#include -#include -#include -#include -#include -#include -#include +#include "filtertreemodel.h" #include "cardframe.h" #include "filterbuilder.h" -//#include "carditem.h" -//#include "carddatabase.h" -#include "main.h" -#include "settingscache.h" -#include "filtertreemodel.h" void SearchLineEdit::keyPressEvent(QKeyEvent *event) { @@ -58,9 +47,6 @@ void SearchLineEdit::keyPressEvent(QKeyEvent *event) TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) : Tab(_tabSupervisor, parent), modified(false) { - aSearch = new QAction(QString(), this); - aSearch->setIcon(QIcon(":/resources/icon_search.svg")); - connect(aSearch, SIGNAL(triggered()), this, SLOT(actSearch())); aClearSearch = new QAction(QString(), this); aClearSearch->setIcon(QIcon(":/resources/icon_clearsearch.svg")); connect(aClearSearch, SIGNAL(triggered()), this, SLOT(actClearSearch())); @@ -70,16 +56,15 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) searchLabel->setBuddy(searchEdit); connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); connect(searchEdit, SIGNAL(returnPressed()), this, SLOT(actAddCard())); - QToolButton *searchButton = new QToolButton; - searchButton->setDefaultAction(aSearch); - QToolButton *clearSearchButton = new QToolButton; - clearSearchButton->setDefaultAction(aClearSearch); + + QToolBar *deckEditToolBar = new QToolBar; + deckEditToolBar->setOrientation(Qt::Horizontal); + deckEditToolBar->setIconSize(QSize(24, 24)); QHBoxLayout *searchLayout = new QHBoxLayout; + searchLayout->addWidget(deckEditToolBar); searchLayout->addWidget(searchLabel); searchLayout->addWidget(searchEdit); - searchLayout->addWidget(searchButton); - searchLayout->addWidget(clearSearchButton); databaseModel = new CardDatabaseModel(db, this); databaseDisplayModel = new CardDatabaseDisplayModel(this); @@ -98,16 +83,33 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) connect(databaseView, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(actAddCard())); searchEdit->setTreeView(databaseView); - cardInfo = new CardFrame(); - cardInfo->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); + QVBoxLayout *leftFrame = new QVBoxLayout; + leftFrame->addLayout(searchLayout); + leftFrame->addWidget(databaseView); - QToolBar *verticalToolBar = new QToolBar; - verticalToolBar->setOrientation(Qt::Horizontal); - verticalToolBar->setIconSize(QSize(24, 24)); - QHBoxLayout *verticalToolBarLayout = new QHBoxLayout; - //verticalToolBarLayout->addStretch(); - verticalToolBarLayout->addWidget(verticalToolBar); - //verticalToolBarLayout->addStretch(); + cardInfo = new CardFrame(); + filterModel = new FilterTreeModel(); + databaseDisplayModel->setFilterTree(filterModel->filterTree()); + filterView = new QTreeView; + filterView->setModel(filterModel); + filterView->setMaximumWidth(250); + filterView->setUniformRowHeights(true); + filterView->setHeaderHidden(true); + filterView->setContextMenuPolicy(Qt::CustomContextMenu); + connect(filterModel, SIGNAL(layoutChanged()), filterView, SLOT(expandAll())); + connect(filterView, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(filterViewCustomContextMenu(const QPoint &))); + FilterBuilder *filterBuilder = new FilterBuilder; + filterBuilder->setMaximumWidth(250); + connect(filterBuilder, SIGNAL(add(const CardFilter *)), filterModel, SLOT(addFilter(const CardFilter *))); + + QVBoxLayout *filter = new QVBoxLayout; + filter->addWidget(filterBuilder, 0, Qt::AlignTop); + filter->addWidget(filterView, 10); + + QVBoxLayout *middleFrame = new QVBoxLayout; + middleFrame->addWidget(cardInfo, 0, Qt::AlignTop); + middleFrame->addLayout(filter, 10); deckModel = new DeckListModel(this); connect(deckModel, SIGNAL(deckHashChanged()), this, SLOT(updateHash())); @@ -133,6 +135,9 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) grid->addWidget(nameLabel, 0, 0); grid->addWidget(nameEdit, 0, 1); + grid->addWidget(commentsLabel, 1, 0); + grid->addWidget(commentsEdit, 1, 1); + grid->addWidget(hashLabel1, 2, 0); grid->addWidget(hashLabel, 2, 1); @@ -153,49 +158,15 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) deckToolbarLayout->addWidget(deckToolBar); deckToolbarLayout->addStretch(); - QVBoxLayout *deckFrame = new QVBoxLayout; - deckFrame->addLayout(grid); - deckFrame->addWidget(deckView, 10); - deckFrame->addLayout(deckToolbarLayout); + QVBoxLayout *rightFrame = new QVBoxLayout; + rightFrame->addLayout(grid); + rightFrame->addWidget(deckView, 10); + rightFrame->addLayout(deckToolbarLayout); - QHBoxLayout *topFrame = new QHBoxLayout; - topFrame->addWidget(cardInfo, 10); - topFrame->addLayout(deckFrame); - - QVBoxLayout *botFrame = new QVBoxLayout; - QGridLayout *searchAndButtons = new QGridLayout; - searchAndButtons->addLayout(verticalToolBarLayout, 0, 0); - searchAndButtons->addLayout(searchLayout, 0, 1); - botFrame->addLayout(searchAndButtons); - - filterModel = new FilterTreeModel(); - databaseDisplayModel->setFilterTree(filterModel->filterTree()); - filterView = new QTreeView; - filterView->setModel(filterModel); - filterView->setMaximumWidth(250); - filterView->setUniformRowHeights(true); - filterView->setHeaderHidden(true); - filterView->setExpandsOnDoubleClick(false); - filterView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(filterModel, SIGNAL(layoutChanged()), filterView, SLOT(expandAll())); - connect(filterView, SIGNAL(customContextMenuRequested(const QPoint &)), - this, SLOT(filterViewCustomContextMenu(const QPoint &))); - FilterBuilder *filterBuilder = new FilterBuilder; - filterBuilder->setMaximumWidth(250); - connect(filterBuilder, SIGNAL(add(const CardFilter *)), filterModel, SLOT(addFilter(const CardFilter *))); - - QVBoxLayout *filter = new QVBoxLayout; - filter->addWidget(filterBuilder, 0, Qt::AlignTop); - filter->addWidget(filterView); - - QHBoxLayout *dbFrame = new QHBoxLayout; - dbFrame->addLayout(filter); - dbFrame->addWidget(databaseView); - botFrame->addLayout(dbFrame); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(topFrame, 10); - mainLayout->addLayout(botFrame, 10); + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addLayout(leftFrame, 10); + mainLayout->addLayout(middleFrame); + mainLayout->addLayout(rightFrame); setLayout(mainLayout); aNewDeck = new QAction(QString(), this); @@ -249,7 +220,6 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) dbMenu->addAction(aEditSets); dbMenu->addAction(aEditTokens); dbMenu->addSeparator(); - dbMenu->addAction(aSearch); dbMenu->addAction(aClearSearch); addTabMenu(dbMenu); @@ -269,14 +239,12 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) aDecrement->setIcon(QIcon(":/resources/decrement.svg")); connect(aDecrement, SIGNAL(triggered()), this, SLOT(actDecrement())); - verticalToolBar->addAction(aAddCard); - verticalToolBar->addAction(aAddCardToSideboard); - verticalToolBar->addAction(aRemoveCard); - verticalToolBar->addAction(aIncrement); - verticalToolBar->addAction(aDecrement); - verticalToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - - dlgCardSearch = new DlgCardSearch(this); + deckEditToolBar->addAction(aAddCard); + deckEditToolBar->addAction(aAddCardToSideboard); + deckEditToolBar->addAction(aRemoveCard); + deckEditToolBar->addAction(aIncrement); + deckEditToolBar->addAction(aDecrement); + deckEditToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); retranslateUi(); @@ -290,7 +258,6 @@ TabDeckEditor::~TabDeckEditor() void TabDeckEditor::retranslateUi() { - aSearch->setText(tr("&Search...")); aClearSearch->setText(tr("&Clear search")); searchLabel->setText(tr("&Search for:")); @@ -299,11 +266,11 @@ void TabDeckEditor::retranslateUi() hashLabel1->setText(tr("Hash:")); aUpdatePrices->setText(tr("&Update prices")); - aUpdatePrices->setShortcut(tr("Ctrl+U")); - - aNewDeck->setText(tr("&New deck")); - aLoadDeck->setText(tr("&Load deck...")); - aSaveDeck->setText(tr("&Save deck")); + aUpdatePrices->setShortcut(tr("Ctrl+U")); + + aNewDeck->setText(tr("&New deck")); + aLoadDeck->setText(tr("&Load deck...")); + aSaveDeck->setText(tr("&Save deck")); aSaveDeckAs->setText(tr("Save deck &as...")); aLoadDeckFromClipboard->setText(tr("Load deck from cl&ipboard...")); aSaveDeckToClipboard->setText(tr("Save deck to clip&board")); @@ -532,17 +499,6 @@ void TabDeckEditor::actEditTokens() db->saveToFile(settingsCache->getTokenDatabasePath(), true); } -void TabDeckEditor::actSearch() -{ - if (dlgCardSearch->exec()) { - searchEdit->clear(); - databaseDisplayModel->setCardName(dlgCardSearch->getCardName()); - databaseDisplayModel->setCardText(dlgCardSearch->getCardText()); - databaseDisplayModel->setCardTypes(dlgCardSearch->getCardTypes()); - databaseDisplayModel->setCardColors(dlgCardSearch->getCardColors()); - } -} - void TabDeckEditor::actClearSearch() { databaseDisplayModel->clearSearch(); diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 2b955c3f..3554df82 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -12,7 +12,6 @@ class QTreeView; class QTableView; class CardFrame; class QTextEdit; -class DlgCardSearch; class QLabel; class DeckLoader; class Response; @@ -50,7 +49,6 @@ private slots: void actEditSets(); void actEditTokens(); - void actSearch(); void actClearSearch(); void actAddCard(); @@ -83,13 +81,12 @@ private: QTextEdit *commentsEdit; QLabel *hashLabel1; QLabel *hashLabel; - DlgCardSearch *dlgCardSearch; FilterTreeModel *filterModel; QTreeView *filterView; QMenu *deckMenu, *dbMenu; QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; - QAction *aEditSets, *aEditTokens, *aSearch, *aClearSearch; + QAction *aEditSets, *aEditTokens, *aClearSearch; QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement, *aUpdatePrices; bool modified; From 5d223b5917e73b68e3e1510a20976832097ded41 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Tue, 28 Jan 2014 23:51:18 +0000 Subject: [PATCH 07/55] clear the filter term text edit box appropriately clear the text box when the '+' button is pressed or when the filter attribute is changed. also changed the frame style to match the card frame style. --- cockatrice/src/filterbuilder.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cockatrice/src/filterbuilder.cpp b/cockatrice/src/filterbuilder.cpp index 6e659752..3b520663 100644 --- a/cockatrice/src/filterbuilder.cpp +++ b/cockatrice/src/filterbuilder.cpp @@ -37,11 +37,12 @@ FilterBuilder::FilterBuilder(QWidget *parent) layout->addLayout(addFilter); layout->addWidget(edit); - setFrameStyle(QFrame::Plain | QFrame::Box); + setFrameStyle(QFrame::Panel | QFrame::Raised); layout->setAlignment(Qt::AlignTop); setLayout(layout); connect(ok, SIGNAL(released()), this, SLOT(add_released())); + connect(filterCombo, SIGNAL(currentIndexChanged(int)), edit, SLOT(clear())); fltr = NULL; } @@ -74,4 +75,5 @@ void FilterBuilder::add_released() static_cast(comboCurrentIntData(typeCombo)), static_cast(comboCurrentIntData(filterCombo))); emit add(fltr); + edit->clear(); } From f77054f20d9cf963fea09f8f7458656a24e97edb Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Wed, 29 Jan 2014 00:19:34 +0000 Subject: [PATCH 08/55] refactor cardframe as a parent of a text card frame and a picture card frame cardframe is now a stacked widget that prefers to show the card picture only so that the screen can be more space efficient and the card pixel map can be displayed as a larger size. however if the card pixel map can not be loaded for some reason, the cardframe class will automatically switch to the text version of the card. a menu item was added under the database menu to allow for users to prefer card text only. --- cockatrice/CMakeLists.txt | 4 ++ cockatrice/src/cardframe.cpp | 44 ++++++++++---------- cockatrice/src/cardframe.h | 22 ++++++---- cockatrice/src/cardinfopicture.cpp | 53 +++++++++++++++++++++++ cockatrice/src/cardinfopicture.h | 34 +++++++++++++++ cockatrice/src/cardinfotext.cpp | 67 ++++++++++++++++++++++++++++++ cockatrice/src/cardinfotext.h | 31 ++++++++++++++ cockatrice/src/tab_deck_editor.cpp | 8 +++- cockatrice/src/tab_deck_editor.h | 2 +- 9 files changed, 231 insertions(+), 34 deletions(-) create mode 100644 cockatrice/src/cardinfopicture.cpp create mode 100644 cockatrice/src/cardinfopicture.h create mode 100644 cockatrice/src/cardinfotext.cpp create mode 100644 cockatrice/src/cardinfotext.h diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index a1e8683a..4012795f 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -34,6 +34,8 @@ SET(cockatrice_SOURCES src/dlg_load_remote_deck.cpp src/cardinfowidget.cpp src/cardframe.cpp + src/cardinfopicture.cpp + src/cardinfotext.cpp src/filterbuilder.cpp src/cardfilter.cpp src/filtertreemodel.cpp @@ -116,6 +118,8 @@ SET(cockatrice_HEADERS src/dlg_load_remote_deck.h src/cardinfowidget.h src/cardframe.h + src/cardinfopicture.h + src/cardinfotext.h src/filterbuilder.h src/cardfilter.h src/filtertreemodel.h diff --git a/cockatrice/src/cardframe.cpp b/cockatrice/src/cardframe.cpp index dd4191ef..89b3cb6b 100644 --- a/cockatrice/src/cardframe.cpp +++ b/cockatrice/src/cardframe.cpp @@ -1,16 +1,27 @@ #include "cardframe.h" -#include #include "carditem.h" #include "carddatabase.h" #include "main.h" +#include "cardinfopicture.h" +#include "cardinfotext.h" -CardFrame::CardFrame(const QString &cardName, QWidget *parent) - : QLabel(parent) +CardFrame::CardFrame(int width, int height, + const QString &cardName, QWidget *parent) + : QStackedWidget(parent) , info(0) + , cardTextOnly(false) { setFrameStyle(QFrame::Panel | QFrame::Raised); - setMaximumWidth(250); + setMaximumWidth(width); + setMinimumWidth(width); + setMaximumHeight(height); + setMinimumHeight(height); + pic = new CardInfoPicture(width); + addWidget(pic); + text = new CardInfoText(); + addWidget(text); + connect(pic, SIGNAL(hasPictureChanged()), this, SLOT(hasPictureChanged())); setCard(db->getCard(cardName)); } @@ -19,10 +30,9 @@ void CardFrame::setCard(CardInfo *card) if (info) disconnect(info, 0, this, 0); info = card; - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); connect(info, SIGNAL(destroyed()), this, SLOT(clear())); - - updatePixmap(); + text->setCard(info); + pic->setCard(info); } void CardFrame::setCard(const QString &cardName) @@ -40,22 +50,10 @@ void CardFrame::clear() setCard(db->getCard()); } -void CardFrame::updatePixmap() +void CardFrame::hasPictureChanged() { - qreal aspectRatio = (qreal) CARD_HEIGHT / (qreal) CARD_WIDTH; - qreal pixmapWidth = this->width(); - - if (pixmapWidth == 0) - return; - - QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); - if (resizedPixmap) - this->setPixmap(*resizedPixmap); + if (pic->hasPicture() && !cardTextOnly) + setCurrentWidget(pic); else - this->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); -} - -QString CardFrame::getCardName() const -{ - return info->getName(); + setCurrentWidget(text); } diff --git a/cockatrice/src/cardframe.h b/cockatrice/src/cardframe.h index 1dccf821..c241c51a 100644 --- a/cockatrice/src/cardframe.h +++ b/cockatrice/src/cardframe.h @@ -1,32 +1,36 @@ #ifndef CARDFRAME_H #define CARDFRAME_H -#include -#include +#include class AbstractCardItem; class CardInfo; -class QResizeEvent; +class CardInfoPicture; +class CardInfoText; -class CardFrame : public QLabel { +class CardFrame : public QStackedWidget { Q_OBJECT private: CardInfo *info; + CardInfoPicture *pic; + CardInfoText *text; + bool cardTextOnly; public: - CardFrame(const QString &cardName = QString(), QWidget *parent = 0); - QString getCardName() const; + CardFrame(int width, int height, const QString &cardName = QString(), + QWidget *parent = 0); + void setCardTextOnly(bool status) { cardTextOnly = status; hasPictureChanged(); } public slots: void setCard(CardInfo *card); void setCard(const QString &cardName); void setCard(AbstractCardItem *card); + void clear(); private slots: - void clear(); - void updatePixmap(); - + void hasPictureChanged(); + void toggleCardTextOnly() { setCardTextOnly(!cardTextOnly); } }; #endif diff --git a/cockatrice/src/cardinfopicture.cpp b/cockatrice/src/cardinfopicture.cpp new file mode 100644 index 00000000..7a7d6195 --- /dev/null +++ b/cockatrice/src/cardinfopicture.cpp @@ -0,0 +1,53 @@ +#include "cardinfopicture.h" + +#include +#include "carditem.h" +#include "carddatabase.h" +#include "main.h" + +CardInfoPicture::CardInfoPicture(int maximumWidth, QWidget *parent) + : QLabel(parent) + , info(0) + , noPicture(true) +{ + setMaximumWidth(maximumWidth); +} + +void CardInfoPicture::setNoPicture(bool status) +{ + if (noPicture != status) { + noPicture = status; + emit hasPictureChanged(); + } +} + +void CardInfoPicture::setCard(CardInfo *card) +{ + if (info) + disconnect(info, 0, this, 0); + info = card; + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); + + updatePixmap(); +} + +void CardInfoPicture::updatePixmap() +{ + qreal aspectRatio = (qreal) CARD_HEIGHT / (qreal) CARD_WIDTH; + qreal pixmapWidth = this->width(); + + if (pixmapWidth == 0) { + setNoPicture(true); + return; + } + + QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); + if (resizedPixmap) { + setNoPicture(false); + this->setPixmap(*resizedPixmap); + } + else { + setNoPicture(true); + this->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); + } +} diff --git a/cockatrice/src/cardinfopicture.h b/cockatrice/src/cardinfopicture.h new file mode 100644 index 00000000..9f34da94 --- /dev/null +++ b/cockatrice/src/cardinfopicture.h @@ -0,0 +1,34 @@ +#ifndef CARDINFOPICTURE_H +#define CARDINFOPICTURE_H + +#include + +class AbstractCardItem; +class CardInfo; + +class CardInfoPicture : public QLabel { + Q_OBJECT + +signals: + void hasPictureChanged(); + +private: + CardInfo *info; + bool noPicture; + +public: + CardInfoPicture(int maximumWidth, QWidget *parent = 0); + bool hasPicture() const { return !noPicture; } + +private: + void setNoPicture(bool status); + +public slots: + void setCard(CardInfo *card); + +private slots: + void updatePixmap(); + +}; + +#endif diff --git a/cockatrice/src/cardinfotext.cpp b/cockatrice/src/cardinfotext.cpp new file mode 100644 index 00000000..9e59f33b --- /dev/null +++ b/cockatrice/src/cardinfotext.cpp @@ -0,0 +1,67 @@ +#include "cardinfotext.h" + +#include +#include +#include +#include "carditem.h" +#include "carddatabase.h" +#include "main.h" + +CardInfoText::CardInfoText(QWidget *parent) + : QFrame(parent) + , info(0) +{ + nameLabel1 = new QLabel; + nameLabel2 = new QLabel; + nameLabel2->setWordWrap(true); + manacostLabel1 = new QLabel; + manacostLabel2 = new QLabel; + manacostLabel2->setWordWrap(true); + cardtypeLabel1 = new QLabel; + cardtypeLabel2 = new QLabel; + cardtypeLabel2->setWordWrap(true); + powtoughLabel1 = new QLabel; + powtoughLabel2 = new QLabel; + loyaltyLabel1 = new QLabel; + loyaltyLabel2 = new QLabel; + + textLabel = new QTextEdit(); + textLabel->setReadOnly(true); + + QGridLayout *grid = new QGridLayout(this); + int row = 0; + grid->addWidget(nameLabel1, row, 0); + grid->addWidget(nameLabel2, row++, 1); + grid->addWidget(manacostLabel1, row, 0); + grid->addWidget(manacostLabel2, row++, 1); + grid->addWidget(cardtypeLabel1, row, 0); + grid->addWidget(cardtypeLabel2, row++, 1); + grid->addWidget(powtoughLabel1, row, 0); + grid->addWidget(powtoughLabel2, row++, 1); + grid->addWidget(loyaltyLabel1, row, 0); + grid->addWidget(loyaltyLabel2, row++, 1); + grid->addWidget(textLabel, row, 0, -1, 2); + grid->setRowStretch(row, 1); + grid->setColumnStretch(1, 1); + + retranslateUi(); +} + +void CardInfoText::setCard(CardInfo *card) +{ + nameLabel2->setText(card->getName()); + manacostLabel2->setText(card->getManaCost()); + cardtypeLabel2->setText(card->getCardType()); + powtoughLabel2->setText(card->getPowTough()); + loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); + textLabel->setText(card->getText()); +} + +void CardInfoText::retranslateUi() +{ + nameLabel1->setText(tr("Name:")); + manacostLabel1->setText(tr("Mana cost:")); + cardtypeLabel1->setText(tr("Card type:")); + powtoughLabel1->setText(tr("P / T:")); + loyaltyLabel1->setText(tr("Loyalty:")); +} diff --git a/cockatrice/src/cardinfotext.h b/cockatrice/src/cardinfotext.h new file mode 100644 index 00000000..0b555230 --- /dev/null +++ b/cockatrice/src/cardinfotext.h @@ -0,0 +1,31 @@ +#ifndef CARDINFOTEXT_H +#define CARDINFOTEXT_H + +#include + +class QLabel; +class QTextEdit; +class CardInfo; + +class CardInfoText : public QFrame { + Q_OBJECT + +private: + QLabel *nameLabel1, *nameLabel2; + QLabel *manacostLabel1, *manacostLabel2; + QLabel *cardtypeLabel1, *cardtypeLabel2; + QLabel *powtoughLabel1, *powtoughLabel2; + QLabel *loyaltyLabel1, *loyaltyLabel2; + QTextEdit *textLabel; + + CardInfo *info; + +public: + CardInfoText(QWidget *parent = 0); + void retranslateUi(); + +public slots: + void setCard(CardInfo *card); +}; + +#endif diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 2de449f4..38179197 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -87,7 +87,11 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) leftFrame->addLayout(searchLayout); leftFrame->addWidget(databaseView); - cardInfo = new CardFrame(); + cardInfo = new CardFrame(250, 356); + aCardTextOnly = new QAction(QString(), this); + aCardTextOnly->setCheckable(true); + connect(aCardTextOnly, SIGNAL(triggered()), cardInfo, SLOT(toggleCardTextOnly())); + filterModel = new FilterTreeModel(); databaseDisplayModel->setFilterTree(filterModel->filterTree()); filterView = new QTreeView; @@ -221,6 +225,7 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) dbMenu->addAction(aEditTokens); dbMenu->addSeparator(); dbMenu->addAction(aClearSearch); + dbMenu->addAction(aCardTextOnly); addTabMenu(dbMenu); aAddCard = new QAction(QString(), this); @@ -258,6 +263,7 @@ TabDeckEditor::~TabDeckEditor() void TabDeckEditor::retranslateUi() { + aCardTextOnly->setText(tr("&Show card text only")); aClearSearch->setText(tr("&Clear search")); searchLabel->setText(tr("&Search for:")); diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 3554df82..0821e605 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -86,7 +86,7 @@ private: QMenu *deckMenu, *dbMenu; QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; - QAction *aEditSets, *aEditTokens, *aClearSearch; + QAction *aEditSets, *aEditTokens, *aClearSearch, *aCardTextOnly; QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement, *aUpdatePrices; bool modified; From f6e9676c75816214b02af50d1a544ee7dc552294 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Wed, 29 Jan 2014 07:15:44 +0000 Subject: [PATCH 09/55] revert cardinfowidget to its original content reverted cardinfowidget to its original form at commit 95c6058dc3027df51f114b5b4350306d6bff8217 before i messed with it. i didnt intend to make changes to it. --- cockatrice/src/cardinfowidget.cpp | 34 +++++++++++++++---------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/cockatrice/src/cardinfowidget.cpp b/cockatrice/src/cardinfowidget.cpp index 708da01c..e0ad1b7e 100644 --- a/cockatrice/src/cardinfowidget.cpp +++ b/cockatrice/src/cardinfowidget.cpp @@ -51,25 +51,23 @@ CardInfoWidget::CardInfoWidget(ResizeMode _mode, const QString &cardName, QWidge textLabel->setReadOnly(true); QGridLayout *grid = new QGridLayout(this); - if (mode == ModeGameTab) { - int row = 0; - + int row = 0; + if (mode == ModeGameTab) grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight); - grid->addWidget(cardPicture, row++, 0, 1, 2); - grid->addWidget(nameLabel1, row, 0); - grid->addWidget(nameLabel2, row++, 1); - grid->addWidget(manacostLabel1, row, 0); - grid->addWidget(manacostLabel2, row++, 1); - grid->addWidget(cardtypeLabel1, row, 0); - grid->addWidget(cardtypeLabel2, row++, 1); - grid->addWidget(powtoughLabel1, row, 0); - grid->addWidget(powtoughLabel2, row++, 1); - grid->addWidget(loyaltyLabel1, row, 0); - grid->addWidget(loyaltyLabel2, row++, 1); - grid->addWidget(textLabel, row, 0, -1, 2); - grid->setRowStretch(row, 1); - grid->setColumnStretch(1, 1); - } + grid->addWidget(cardPicture, row++, 0, 1, 2); + grid->addWidget(nameLabel1, row, 0); + grid->addWidget(nameLabel2, row++, 1); + grid->addWidget(manacostLabel1, row, 0); + grid->addWidget(manacostLabel2, row++, 1); + grid->addWidget(cardtypeLabel1, row, 0); + grid->addWidget(cardtypeLabel2, row++, 1); + grid->addWidget(powtoughLabel1, row, 0); + grid->addWidget(powtoughLabel2, row++, 1); + grid->addWidget(loyaltyLabel1, row, 0); + grid->addWidget(loyaltyLabel2, row++, 1); + grid->addWidget(textLabel, row, 0, -1, 2); + grid->setRowStretch(row, 1); + grid->setColumnStretch(1, 1); retranslateUi(); setFrameStyle(QFrame::Panel | QFrame::Raised); From e003114ce3de91f55fccdf90e8dfdff474cf157c Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Thu, 13 Feb 2014 11:56:36 -0500 Subject: [PATCH 10/55] Fix Linux and BSD section formatting --- doc/usermanual/Usermanual.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/doc/usermanual/Usermanual.md b/doc/usermanual/Usermanual.md index 20839a2f..b319c42e 100644 --- a/doc/usermanual/Usermanual.md +++ b/doc/usermanual/Usermanual.md @@ -213,12 +213,22 @@ FreeBSD 9.1 until the systems were updated. FreeBSD : `pkg_add -r qt4 qt4-linguist qt4-moc qt4-qmake qt4-rcc qt4-uic git cmake protobuf` -2. Download the sources from github via\ +2. Download the sources from github via `cd git clone https://github.com/Daenyth/Cockatrice.git` 3. To compile the sources, change into the newly created directory, - create a build directory and invoke cmake:\ - `cd Cockatrice mkdir build cd build cmake .. make`\ + create a build directory and invoke cmake: + + i. `cd Cockatrice` + + ii. `mkdir build` + + iii. `cd build` + + iv. `cmake ..` + + v. `make` + If you have some issues with pthread\_ add ’pthread’ to the “target\_link\_libraries” entry in the `CMakeFiles.txt` in `Cockatrice/common`. From 5e2d3a2f3e9e0cb41b6354e5d467042524cc4569 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Thu, 13 Feb 2014 12:59:04 -0500 Subject: [PATCH 11/55] Additional typo and formatting fixes For example, fixed the card type table which wasn't showing as a table. --- doc/usermanual/Usermanual.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/doc/usermanual/Usermanual.md b/doc/usermanual/Usermanual.md index b319c42e..8f76eacd 100644 --- a/doc/usermanual/Usermanual.md +++ b/doc/usermanual/Usermanual.md @@ -214,7 +214,7 @@ FreeBSD 9.1 until the systems were updated. : `pkg_add -r qt4 qt4-linguist qt4-moc qt4-qmake qt4-rcc qt4-uic git cmake protobuf` 2. Download the sources from github via - `cd git clone https://github.com/Daenyth/Cockatrice.git` + `git clone https://github.com/Daenyth/Cockatrice.git` 3. To compile the sources, change into the newly created directory, create a build directory and invoke cmake: @@ -239,7 +239,7 @@ FreeBSD 9.1 until the systems were updated. 5. Before you start Cockatrice for the first time, run `oracle -dlsets` and download available cards, denn run `cockatrice`. The default - paths for decks, pics, cards and tokens are located in\ + paths for decks, pics, cards and tokens are located in `/home//.local/share/data/Cockatrice/Cockatrice`. #### MacOS X @@ -254,10 +254,10 @@ Cockatrice is open source you are free to run your own. The compilation works like already written above, but instead of invoking `cmake ..`, you have to do it like this: -- If you want to build the server, use:\ +- If you want to build the server, use: `cmake -DWITH_SERVER=1 ..` -- If you want to build the server, but not the client, use:\ +- If you want to build the server, but not the client, use: `cmake -DWITH_SERVER=1 -DWITHOUT_CLIENT=1 ..` There is more information on compiling and running Servatrice on CentOS @@ -378,13 +378,14 @@ has come out, you must re-run the Oracle and download set information. except for “Instant” along with “Artifact” and “U”, the Deck editor will only show you all Blue Instant and Artifact cards. - ll Letter & Card Type\ - U & Blue\ - W & White\ - X & Colorless\ - G & Green\ - R & Red\ - B & Black\ + |Letter | Card Type | + |-------|-----------| + | U | Blue | + | W | White | + | X | Colorless | + | G | Green | + | R | Red | + | B | Black | 3. Card Data : This section shows the Oracle text for the card that you currently From cc08893c12f16982fd11f8225b206549de2dc9f8 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Fri, 14 Feb 2014 13:38:06 -0500 Subject: [PATCH 12/55] Fix another typo in Usermanual --- doc/usermanual/Usermanual.md | 2 +- doc/usermanual/Usermanual.tex | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/usermanual/Usermanual.md b/doc/usermanual/Usermanual.md index 20839a2f..1371671c 100644 --- a/doc/usermanual/Usermanual.md +++ b/doc/usermanual/Usermanual.md @@ -736,7 +736,7 @@ players can not add or remove counters to or from your cards. #### Pointing at Cards / Arrows -Pointing at cars is needed for resolving spells, or declaring attackers +Pointing at cards is needed for resolving spells, or declaring attackers and blockers. All you need to do is right-click over a card and drag an arrow over to what you are pointing at. Permanents, spells in the stack, and even a players life total can be pointed at. You can point at your diff --git a/doc/usermanual/Usermanual.tex b/doc/usermanual/Usermanual.tex index 61643701..f506f7c8 100644 --- a/doc/usermanual/Usermanual.tex +++ b/doc/usermanual/Usermanual.tex @@ -487,7 +487,7 @@ Sometimes Counters are needed to be placed on cards that the counters on the sid (One of each counter) \subsubsection{Pointing at Cards / Arrows} -Pointing at cars is needed for resolving spells, or declaring attackers and blockers. All you need to do is right-click over a card and drag an arrow over to what you are pointing at. Permanents, spells in the stack, and even a players life total can be pointed at. You can point at your opponents cards and life total, and they can point at yours. When your arrows are no loner needed, press Ctrl-R to remove them from the screen. +Pointing at cards is needed for resolving spells, or declaring attackers and blockers. All you need to do is right-click over a card and drag an arrow over to what you are pointing at. Permanents, spells in the stack, and even a players life total can be pointed at. You can point at your opponents cards and life total, and they can point at yours. When your arrows are no loner needed, press Ctrl-R to remove them from the screen. \begin{center} \includegraphics[scale=0.5]{pics/fetch98fd} \\ From a15eb6f29fcfba8657ee2d782afb1e72343a4610 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Sat, 8 Mar 2014 17:08:40 +0100 Subject: [PATCH 13/55] Updated SFMT RNG code, removed Qt RNG --- common/CMakeLists.txt | 2 - common/rng_qt.cpp | 16 - common/rng_qt.h | 13 - common/rng_sfmt.cpp | 15 +- common/rng_sfmt.h | 14 + common/sfmt/LICENSE.txt | 13 +- common/sfmt/SFMT-common.h | 164 ++++++++++ common/sfmt/SFMT-params.h | 81 ++--- common/sfmt/SFMT-params19937.h | 66 ++-- common/sfmt/SFMT.c | 533 +++++++++++---------------------- common/sfmt/SFMT.h | 293 +++++++++++++----- 11 files changed, 653 insertions(+), 557 deletions(-) delete mode 100644 common/rng_qt.cpp delete mode 100644 common/rng_qt.h create mode 100644 common/sfmt/SFMT-common.h diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 3a8031b1..17d3fa46 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -5,7 +5,6 @@ SET(common_SOURCES decklist.cpp get_pb_extension.cpp rng_abstract.cpp - rng_qt.cpp rng_sfmt.cpp server.cpp server_abstractuserinterface.cpp @@ -25,7 +24,6 @@ SET(common_SOURCES SET(common_HEADERS decklist.h rng_abstract.h - rng_qt.h rng_sfmt.h server.h server_arrowtarget.h diff --git a/common/rng_qt.cpp b/common/rng_qt.cpp deleted file mode 100644 index 6704cdb8..00000000 --- a/common/rng_qt.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "rng_qt.h" -#include -#include - -RNG_Qt::RNG_Qt(QObject *parent) - : RNG_Abstract(parent) -{ - int seed = QDateTime::currentDateTime().toTime_t(); - qsrand(seed); -} - -unsigned int RNG_Qt::getNumber(unsigned int min, unsigned int max) -{ - int r = qrand(); - return min + (unsigned int) (((double) (max + 1 - min)) * r / (RAND_MAX + 1.0)); -} diff --git a/common/rng_qt.h b/common/rng_qt.h deleted file mode 100644 index e30719ef..00000000 --- a/common/rng_qt.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef RNG_QT_H -#define RNG_QT_H - -#include "rng_abstract.h" - -class RNG_Qt : public RNG_Abstract { - Q_OBJECT -public: - RNG_Qt(QObject *parent = 0); - unsigned int getNumber(unsigned int min, unsigned int max); -}; - -#endif diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index 9dff7448..438d8f59 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -1,5 +1,4 @@ #include "rng_sfmt.h" -#include "sfmt/SFMT.h" #include #include #include @@ -7,19 +6,17 @@ RNG_SFMT::RNG_SFMT(QObject *parent) : RNG_Abstract(parent) { - std::cerr << "Using SFMT random number generator." << std::endl; - - int seed = QDateTime::currentDateTime().toTime_t(); - init_gen_rand(seed); - for (int i = 0; i < 100000; ++i) - gen_rand64(); + // initialize the random number generator with a 32bit integer seed (timestamp) + sfmt_init_gen_rand(&sfmt, QDateTime::currentDateTime().toTime_t()); } unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) { + // To make the random number generation thread safe, a mutex is created around the generation. mutex.lock(); - uint64_t r = gen_rand64(); + uint64_t r = sfmt_genrand_uint64(&sfmt); mutex.unlock(); - return min + (unsigned int) (((double) (max + 1 - min)) * r / (18446744073709551616.0 + 1.0)); + // return a random number from the interval [min, max] + return (unsigned int) (r % (max - min + 1)); } diff --git a/common/rng_sfmt.h b/common/rng_sfmt.h index 4d131b38..80ff9f2f 100644 --- a/common/rng_sfmt.h +++ b/common/rng_sfmt.h @@ -1,13 +1,27 @@ #ifndef RNG_SFMT_H #define RNG_SFMT_H +#include "sfmt/SFMT.h" #include "rng_abstract.h" #include +/** + * This class represents the random number generator. + * It uses the SIMD-oriented Fast Mersenne Twister code v1.4.1 from + * http://www.math.sci.hiroshima-u.ac.jp/~%20m-mat/MT/SFMT/index.html + * To use this RNG, the class needs a sfmt_t structure for the RNG's internal state. + * It has to be initialized by sfmt_init_gen_rand() which is done in the constructor. + * The function sfmt_genrand_uint64() can then be used to create a 64 bit unsigned int + * pseudorandom number. This is done in getNumber(). + * For more information see the author's website and look at the documentation and + * examples that are part of the official downloads. + */ + class RNG_SFMT : public RNG_Abstract { Q_OBJECT private: QMutex mutex; + sfmt_t sfmt; public: RNG_SFMT(QObject *parent = 0); unsigned int getNumber(unsigned int min, unsigned int max); diff --git a/common/sfmt/LICENSE.txt b/common/sfmt/LICENSE.txt index decb2991..6f9c4a6d 100644 --- a/common/sfmt/LICENSE.txt +++ b/common/sfmt/LICENSE.txt @@ -1,5 +1,8 @@ Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima -University. All rights reserved. +University. +Copyright (c) 2012 Mutsuo Saito, Makoto Matsumoto, Hiroshima University +and The University of Tokyo. +All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -11,10 +14,10 @@ met: copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the Hiroshima University nor the names of - its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. + * Neither the names of Hiroshima University, The University of + Tokyo nor the names of its contributors may be used to endorse + or promote products derived from this software without specific + prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT diff --git a/common/sfmt/SFMT-common.h b/common/sfmt/SFMT-common.h new file mode 100644 index 00000000..c7d8aa9f --- /dev/null +++ b/common/sfmt/SFMT-common.h @@ -0,0 +1,164 @@ +#pragma once +/** + * @file SFMT-common.h + * + * @brief SIMD oriented Fast Mersenne Twister(SFMT) pseudorandom + * number generator with jump function. This file includes common functions + * used in random number generation and jump. + * + * @author Mutsuo Saito (Hiroshima University) + * @author Makoto Matsumoto (The University of Tokyo) + * + * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. + * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto, Hiroshima + * University and The University of Tokyo. + * All rights reserved. + * + * The 3-clause BSD License is applied to this software, see + * LICENSE.txt + */ +#ifndef SFMT_COMMON_H +#define SFMT_COMMON_H + +#if defined(__cplusplus) +extern "C" { +#endif + +#include "SFMT.h" + +inline static void do_recursion(w128_t * r, w128_t * a, w128_t * b, + w128_t * c, w128_t * d); + +inline static void rshift128(w128_t *out, w128_t const *in, int shift); +inline static void lshift128(w128_t *out, w128_t const *in, int shift); + +/** + * This function simulates SIMD 128-bit right shift by the standard C. + * The 128-bit integer given in in is shifted by (shift * 8) bits. + * This function simulates the LITTLE ENDIAN SIMD. + * @param out the output of this function + * @param in the 128-bit data to be shifted + * @param shift the shift value + */ +#ifdef ONLY64 +inline static void rshift128(w128_t *out, w128_t const *in, int shift) { + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); + tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); + + oh = th >> (shift * 8); + ol = tl >> (shift * 8); + ol |= th << (64 - shift * 8); + out->u[0] = (uint32_t)(ol >> 32); + out->u[1] = (uint32_t)ol; + out->u[2] = (uint32_t)(oh >> 32); + out->u[3] = (uint32_t)oh; +} +#else +inline static void rshift128(w128_t *out, w128_t const *in, int shift) +{ + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); + tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); + + oh = th >> (shift * 8); + ol = tl >> (shift * 8); + ol |= th << (64 - shift * 8); + out->u[1] = (uint32_t)(ol >> 32); + out->u[0] = (uint32_t)ol; + out->u[3] = (uint32_t)(oh >> 32); + out->u[2] = (uint32_t)oh; +} +#endif +/** + * This function simulates SIMD 128-bit left shift by the standard C. + * The 128-bit integer given in in is shifted by (shift * 8) bits. + * This function simulates the LITTLE ENDIAN SIMD. + * @param out the output of this function + * @param in the 128-bit data to be shifted + * @param shift the shift value + */ +#ifdef ONLY64 +inline static void lshift128(w128_t *out, w128_t const *in, int shift) { + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); + tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); + + oh = th << (shift * 8); + ol = tl << (shift * 8); + oh |= tl >> (64 - shift * 8); + out->u[0] = (uint32_t)(ol >> 32); + out->u[1] = (uint32_t)ol; + out->u[2] = (uint32_t)(oh >> 32); + out->u[3] = (uint32_t)oh; +} +#else +inline static void lshift128(w128_t *out, w128_t const *in, int shift) +{ + uint64_t th, tl, oh, ol; + + th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); + tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); + + oh = th << (shift * 8); + ol = tl << (shift * 8); + oh |= tl >> (64 - shift * 8); + out->u[1] = (uint32_t)(ol >> 32); + out->u[0] = (uint32_t)ol; + out->u[3] = (uint32_t)(oh >> 32); + out->u[2] = (uint32_t)oh; +} +#endif +/** + * This function represents the recursion formula. + * @param r output + * @param a a 128-bit part of the internal state array + * @param b a 128-bit part of the internal state array + * @param c a 128-bit part of the internal state array + * @param d a 128-bit part of the internal state array + */ +#ifdef ONLY64 +inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c, + w128_t *d) { + w128_t x; + w128_t y; + + lshift128(&x, a, SFMT_SL2); + rshift128(&y, c, SFMT_SR2); + r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SFMT_SR1) & SFMT_MSK2) ^ y.u[0] + ^ (d->u[0] << SFMT_SL1); + r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SFMT_SR1) & SFMT_MSK1) ^ y.u[1] + ^ (d->u[1] << SFMT_SL1); + r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SFMT_SR1) & SFMT_MSK4) ^ y.u[2] + ^ (d->u[2] << SFMT_SL1); + r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SFMT_SR1) & SFMT_MSK3) ^ y.u[3] + ^ (d->u[3] << SFMT_SL1); +} +#else +inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, + w128_t *c, w128_t *d) +{ + w128_t x; + w128_t y; + + lshift128(&x, a, SFMT_SL2); + rshift128(&y, c, SFMT_SR2); + r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SFMT_SR1) & SFMT_MSK1) + ^ y.u[0] ^ (d->u[0] << SFMT_SL1); + r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SFMT_SR1) & SFMT_MSK2) + ^ y.u[1] ^ (d->u[1] << SFMT_SL1); + r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SFMT_SR1) & SFMT_MSK3) + ^ y.u[2] ^ (d->u[2] << SFMT_SL1); + r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SFMT_SR1) & SFMT_MSK4) + ^ y.u[3] ^ (d->u[3] << SFMT_SL1); +} +#endif +#endif + +#if defined(__cplusplus) +} +#endif diff --git a/common/sfmt/SFMT-params.h b/common/sfmt/SFMT-params.h index 661bbf26..372e6f11 100644 --- a/common/sfmt/SFMT-params.h +++ b/common/sfmt/SFMT-params.h @@ -1,95 +1,96 @@ +#pragma once #ifndef SFMT_PARAMS_H #define SFMT_PARAMS_H -#if !defined(MEXP) -#ifdef __GNUC__ - #warning "MEXP is not defined. I assume MEXP is 19937." +#if !defined(SFMT_MEXP) +#if defined(__GNUC__) && !defined(__ICC) + #warning "SFMT_MEXP is not defined. I assume MEXP is 19937." #endif - #define MEXP 19937 + #define SFMT_MEXP 19937 #endif /*----------------- BASIC DEFINITIONS -----------------*/ -/** Mersenne Exponent. The period of the sequence +/** Mersenne Exponent. The period of the sequence * is a multiple of 2^MEXP-1. - * #define MEXP 19937 */ + * #define SFMT_MEXP 19937 */ /** SFMT generator has an internal state array of 128-bit integers, * and N is its size. */ -#define N (MEXP / 128 + 1) +#define SFMT_N (SFMT_MEXP / 128 + 1) /** N32 is the size of internal state array when regarded as an array * of 32-bit integers.*/ -#define N32 (N * 4) +#define SFMT_N32 (SFMT_N * 4) /** N64 is the size of internal state array when regarded as an array * of 64-bit integers.*/ -#define N64 (N * 2) +#define SFMT_N64 (SFMT_N * 2) /*---------------------- the parameters of SFMT following definitions are in paramsXXXX.h file. ----------------------*/ /** the pick up position of the array. -#define POS1 122 +#define SFMT_POS1 122 */ /** the parameter of shift left as four 32-bit registers. -#define SL1 18 +#define SFMT_SL1 18 */ -/** the parameter of shift left as one 128-bit register. - * The 128-bit integer is shifted by (SL2 * 8) bits. -#define SL2 1 +/** the parameter of shift left as one 128-bit register. + * The 128-bit integer is shifted by (SFMT_SL2 * 8) bits. +#define SFMT_SL2 1 */ /** the parameter of shift right as four 32-bit registers. -#define SR1 11 +#define SFMT_SR1 11 */ -/** the parameter of shift right as one 128-bit register. - * The 128-bit integer is shifted by (SL2 * 8) bits. -#define SR2 1 +/** the parameter of shift right as one 128-bit register. + * The 128-bit integer is shifted by (SFMT_SL2 * 8) bits. +#define SFMT_SR21 1 */ /** A bitmask, used in the recursion. These parameters are introduced * to break symmetry of SIMD. -#define MSK1 0xdfffffefU -#define MSK2 0xddfecb7fU -#define MSK3 0xbffaffffU -#define MSK4 0xbffffff6U +#define SFMT_MSK1 0xdfffffefU +#define SFMT_MSK2 0xddfecb7fU +#define SFMT_MSK3 0xbffaffffU +#define SFMT_MSK4 0xbffffff6U */ /** These definitions are part of a 128-bit period certification vector. -#define PARITY1 0x00000001U -#define PARITY2 0x00000000U -#define PARITY3 0x00000000U -#define PARITY4 0xc98e126aU +#define SFMT_PARITY1 0x00000001U +#define SFMT_PARITY2 0x00000000U +#define SFMT_PARITY3 0x00000000U +#define SFMT_PARITY4 0xc98e126aU */ -#if MEXP == 607 +#if SFMT_MEXP == 607 #include "SFMT-params607.h" -#elif MEXP == 1279 +#elif SFMT_MEXP == 1279 #include "SFMT-params1279.h" -#elif MEXP == 2281 +#elif SFMT_MEXP == 2281 #include "SFMT-params2281.h" -#elif MEXP == 4253 +#elif SFMT_MEXP == 4253 #include "SFMT-params4253.h" -#elif MEXP == 11213 +#elif SFMT_MEXP == 11213 #include "SFMT-params11213.h" -#elif MEXP == 19937 +#elif SFMT_MEXP == 19937 #include "SFMT-params19937.h" -#elif MEXP == 44497 +#elif SFMT_MEXP == 44497 #include "SFMT-params44497.h" -#elif MEXP == 86243 +#elif SFMT_MEXP == 86243 #include "SFMT-params86243.h" -#elif MEXP == 132049 +#elif SFMT_MEXP == 132049 #include "SFMT-params132049.h" -#elif MEXP == 216091 +#elif SFMT_MEXP == 216091 #include "SFMT-params216091.h" #else -#ifdef __GNUC__ - #error "MEXP is not valid." - #undef MEXP +#if defined(__GNUC__) && !defined(__ICC) + #error "SFMT_MEXP is not valid." + #undef SFMT_MEXP #else - #undef MEXP + #undef SFMT_MEXP #endif #endif diff --git a/common/sfmt/SFMT-params19937.h b/common/sfmt/SFMT-params19937.h index 04708cdf..fc49fa14 100644 --- a/common/sfmt/SFMT-params19937.h +++ b/common/sfmt/SFMT-params19937.h @@ -1,46 +1,50 @@ +#pragma once #ifndef SFMT_PARAMS19937_H #define SFMT_PARAMS19937_H -#define POS1 122 -#define SL1 18 -#define SL2 1 -#define SR1 11 -#define SR2 1 -#define MSK1 0xdfffffefU -#define MSK2 0xddfecb7fU -#define MSK3 0xbffaffffU -#define MSK4 0xbffffff6U -#define PARITY1 0x00000001U -#define PARITY2 0x00000000U -#define PARITY3 0x00000000U -#define PARITY4 0x13c9e684U +#define SFMT_POS1 122 +#define SFMT_SL1 18 +#define SFMT_SL2 1 +#define SFMT_SR1 11 +#define SFMT_SR2 1 +#define SFMT_MSK1 0xdfffffefU +#define SFMT_MSK2 0xddfecb7fU +#define SFMT_MSK3 0xbffaffffU +#define SFMT_MSK4 0xbffffff6U +#define SFMT_PARITY1 0x00000001U +#define SFMT_PARITY2 0x00000000U +#define SFMT_PARITY3 0x00000000U +#define SFMT_PARITY4 0x13c9e684U /* PARAMETERS FOR ALTIVEC */ #if defined(__APPLE__) /* For OSX */ - #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1) - #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1) - #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4) - #define ALTI_MSK64 \ - (vector unsigned int)(MSK2, MSK1, MSK4, MSK3) - #define ALTI_SL2_PERM \ + #define SFMT_ALTI_SL1 \ + (vector unsigned int)(SFMT_SL1, SFMT_SL1, SFMT_SL1, SFMT_SL1) + #define SFMT_ALTI_SR1 \ + (vector unsigned int)(SFMT_SR1, SFMT_SR1, SFMT_SR1, SFMT_SR1) + #define SFMT_ALTI_MSK \ + (vector unsigned int)(SFMT_MSK1, SFMT_MSK2, SFMT_MSK3, SFMT_MSK4) + #define SFMT_ALTI_MSK64 \ + (vector unsigned int)(SFMT_MSK2, SFMT_MSK1, SFMT_MSK4, SFMT_MSK3) + #define SFMT_ALTI_SL2_PERM \ (vector unsigned char)(1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8) - #define ALTI_SL2_PERM64 \ + #define SFMT_ALTI_SL2_PERM64 \ (vector unsigned char)(1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0) - #define ALTI_SR2_PERM \ + #define SFMT_ALTI_SR2_PERM \ (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14) - #define ALTI_SR2_PERM64 \ + #define SFMT_ALTI_SR2_PERM64 \ (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14) #else /* For OTHER OSs(Linux?) */ - #define ALTI_SL1 {SL1, SL1, SL1, SL1} - #define ALTI_SR1 {SR1, SR1, SR1, SR1} - #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4} - #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3} - #define ALTI_SL2_PERM {1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8} - #define ALTI_SL2_PERM64 {1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0} - #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14} - #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14} + #define SFMT_ALTI_SL1 {SFMT_SL1, SFMT_SL1, SFMT_SL1, SFMT_SL1} + #define SFMT_ALTI_SR1 {SFMT_SR1, SFMT_SR1, SFMT_SR1, SFMT_SR1} + #define SFMT_ALTI_MSK {SFMT_MSK1, SFMT_MSK2, SFMT_MSK3, SFMT_MSK4} + #define SFMT_ALTI_MSK64 {SFMT_MSK2, SFMT_MSK1, SFMT_MSK4, SFMT_MSK3} + #define SFMT_ALTI_SL2_PERM {1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8} + #define SFMT_ALTI_SL2_PERM64 {1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0} + #define SFMT_ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14} + #define SFMT_ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14} #endif /* For OSX */ -#define IDSTR "SFMT-19937:122-18-1-11-1:dfffffef-ddfecb7f-bffaffff-bffffff6" +#define SFMT_IDSTR "SFMT-19937:122-18-1-11-1:dfffffef-ddfecb7f-bffaffff-bffffff6" #endif /* SFMT_PARAMS19937_H */ diff --git a/common/sfmt/SFMT.c b/common/sfmt/SFMT.c index d36465d9..2652df7d 100644 --- a/common/sfmt/SFMT.c +++ b/common/sfmt/SFMT.c @@ -1,19 +1,31 @@ -/** +/** * @file SFMT.c * @brief SIMD oriented Fast Mersenne Twister(SFMT) * * @author Mutsuo Saito (Hiroshima University) * @author Makoto Matsumoto (Hiroshima University) * - * Copyright (C) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima - * University. All rights reserved. + * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. + * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto, Hiroshima + * University and The University of Tokyo. + * Copyright (C) 2013 Mutsuo Saito, Makoto Matsumoto and Hiroshima + * University. + * All rights reserved. * - * The new BSD License is applied to this software, see LICENSE.txt + * The 3-clause BSD License is applied to this software, see + * LICENSE.txt */ + +#if defined(__cplusplus) +extern "C" { +#endif + #include #include #include "SFMT.h" #include "SFMT-params.h" +#include "SFMT-common.h" #if defined(__BIG_ENDIAN__) && !defined(__amd64) && !defined(BIG_ENDIAN64) #define BIG_ENDIAN64 1 @@ -27,74 +39,20 @@ #endif #undef ONLY64 #endif -/*------------------------------------------------------ - 128-bit SIMD data type for Altivec, SSE2 or standard C - ------------------------------------------------------*/ -#if defined(HAVE_ALTIVEC) - #if !defined(__APPLE__) - #include - #endif -/** 128-bit data structure */ -union W128_T { - vector unsigned int s; - uint32_t u[4]; -}; -/** 128-bit data type */ -typedef union W128_T w128_t; - -#elif defined(HAVE_SSE2) - #include - -/** 128-bit data structure */ -union W128_T { - __m128i si; - uint32_t u[4]; -}; -/** 128-bit data type */ -typedef union W128_T w128_t; - -#else - -/** 128-bit data structure */ -struct W128_T { - uint32_t u[4]; -}; -/** 128-bit data type */ -typedef struct W128_T w128_t; - -#endif - -/*-------------------------------------- - FILE GLOBAL VARIABLES - internal state, index counter and flag - --------------------------------------*/ -/** the 128-bit internal state array */ -static w128_t sfmt[N]; -/** the 32bit integer pointer to the 128-bit internal state array */ -static uint32_t *psfmt32 = &sfmt[0].u[0]; -#if !defined(BIG_ENDIAN64) || defined(ONLY64) -/** the 64bit integer pointer to the 128-bit internal state array */ -static uint64_t *psfmt64 = (uint64_t *)&sfmt[0].u[0]; -#endif -/** index counter to the 32-bit internal state array */ -static int idx; -/** a flag: it is 0 if and only if the internal state is not yet - * initialized. */ -static int initialized = 0; -/** a parity check vector which certificate the period of 2^{MEXP} */ -static uint32_t parity[4] = {PARITY1, PARITY2, PARITY3, PARITY4}; +/** + * parameters used by sse2. + */ +static const w128_t sse2_param_mask = {{SFMT_MSK1, SFMT_MSK2, + SFMT_MSK3, SFMT_MSK4}}; /*---------------- STATIC FUNCTIONS ----------------*/ inline static int idxof(int i); -inline static void rshift128(w128_t *out, w128_t const *in, int shift); -inline static void lshift128(w128_t *out, w128_t const *in, int shift); -inline static void gen_rand_all(void); -inline static void gen_rand_array(w128_t *array, int size); +inline static void gen_rand_array(sfmt_t * sfmt, w128_t *array, int size); inline static uint32_t func1(uint32_t x); inline static uint32_t func2(uint32_t x); -static void period_certification(void); +static void period_certification(sfmt_t * sfmt); #if defined(BIG_ENDIAN64) && !defined(ONLY64) inline static void swap(w128_t *array, int size); #endif @@ -102,11 +60,15 @@ inline static void swap(w128_t *array, int size); #if defined(HAVE_ALTIVEC) #include "SFMT-alti.h" #elif defined(HAVE_SSE2) - #include "SFMT-sse2.h" + #if defined(_MSC_VER) + #include "SFMT-sse2-msc.h" + #else + #include "SFMT-sse2.h" + #endif #endif /** - * This function simulate a 64-bit index of LITTLE ENDIAN + * This function simulate a 64-bit index of LITTLE ENDIAN * in BIG ENDIAN machine. */ #ifdef ONLY64 @@ -118,190 +80,48 @@ inline static int idxof(int i) { return i; } #endif -/** - * This function simulates SIMD 128-bit right shift by the standard C. - * The 128-bit integer given in in is shifted by (shift * 8) bits. - * This function simulates the LITTLE ENDIAN SIMD. - * @param out the output of this function - * @param in the 128-bit data to be shifted - * @param shift the shift value - */ -#ifdef ONLY64 -inline static void rshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); - tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); - - oh = th >> (shift * 8); - ol = tl >> (shift * 8); - ol |= th << (64 - shift * 8); - out->u[0] = (uint32_t)(ol >> 32); - out->u[1] = (uint32_t)ol; - out->u[2] = (uint32_t)(oh >> 32); - out->u[3] = (uint32_t)oh; -} -#else -inline static void rshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); - tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); - - oh = th >> (shift * 8); - ol = tl >> (shift * 8); - ol |= th << (64 - shift * 8); - out->u[1] = (uint32_t)(ol >> 32); - out->u[0] = (uint32_t)ol; - out->u[3] = (uint32_t)(oh >> 32); - out->u[2] = (uint32_t)oh; -} -#endif -/** - * This function simulates SIMD 128-bit left shift by the standard C. - * The 128-bit integer given in in is shifted by (shift * 8) bits. - * This function simulates the LITTLE ENDIAN SIMD. - * @param out the output of this function - * @param in the 128-bit data to be shifted - * @param shift the shift value - */ -#ifdef ONLY64 -inline static void lshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]); - tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]); - - oh = th << (shift * 8); - ol = tl << (shift * 8); - oh |= tl >> (64 - shift * 8); - out->u[0] = (uint32_t)(ol >> 32); - out->u[1] = (uint32_t)ol; - out->u[2] = (uint32_t)(oh >> 32); - out->u[3] = (uint32_t)oh; -} -#else -inline static void lshift128(w128_t *out, w128_t const *in, int shift) { - uint64_t th, tl, oh, ol; - - th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]); - tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]); - - oh = th << (shift * 8); - ol = tl << (shift * 8); - oh |= tl >> (64 - shift * 8); - out->u[1] = (uint32_t)(ol >> 32); - out->u[0] = (uint32_t)ol; - out->u[3] = (uint32_t)(oh >> 32); - out->u[2] = (uint32_t)oh; -} -#endif - -/** - * This function represents the recursion formula. - * @param r output - * @param a a 128-bit part of the internal state array - * @param b a 128-bit part of the internal state array - * @param c a 128-bit part of the internal state array - * @param d a 128-bit part of the internal state array - */ -#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2)) -#ifdef ONLY64 -inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c, - w128_t *d) { - w128_t x; - w128_t y; - - lshift128(&x, a, SL2); - rshift128(&y, c, SR2); - r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK2) ^ y.u[0] - ^ (d->u[0] << SL1); - r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK1) ^ y.u[1] - ^ (d->u[1] << SL1); - r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK4) ^ y.u[2] - ^ (d->u[2] << SL1); - r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK3) ^ y.u[3] - ^ (d->u[3] << SL1); -} -#else -inline static void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c, - w128_t *d) { - w128_t x; - w128_t y; - - lshift128(&x, a, SL2); - rshift128(&y, c, SR2); - r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK1) ^ y.u[0] - ^ (d->u[0] << SL1); - r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK2) ^ y.u[1] - ^ (d->u[1] << SL1); - r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK3) ^ y.u[2] - ^ (d->u[2] << SL1); - r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK4) ^ y.u[3] - ^ (d->u[3] << SL1); -} -#endif -#endif #if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2)) -/** - * This function fills the internal state array with pseudorandom - * integers. - */ -inline static void gen_rand_all(void) { - int i; - w128_t *r1, *r2; - - r1 = &sfmt[N - 2]; - r2 = &sfmt[N - 1]; - for (i = 0; i < N - POS1; i++) { - do_recursion(&sfmt[i], &sfmt[i], &sfmt[i + POS1], r1, r2); - r1 = r2; - r2 = &sfmt[i]; - } - for (; i < N; i++) { - do_recursion(&sfmt[i], &sfmt[i], &sfmt[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &sfmt[i]; - } -} - /** * This function fills the user-specified array with pseudorandom * integers. * - * @param array an 128-bit array to be filled by pseudorandom numbers. + * @param sfmt SFMT internal state + * @param array an 128-bit array to be filled by pseudorandom numbers. * @param size number of 128-bit pseudorandom numbers to be generated. */ -inline static void gen_rand_array(w128_t *array, int size) { +inline static void gen_rand_array(sfmt_t * sfmt, w128_t *array, int size) { int i, j; w128_t *r1, *r2; - r1 = &sfmt[N - 2]; - r2 = &sfmt[N - 1]; - for (i = 0; i < N - POS1; i++) { - do_recursion(&array[i], &sfmt[i], &sfmt[i + POS1], r1, r2); - r1 = r2; - r2 = &array[i]; + r1 = &sfmt->state[SFMT_N - 2]; + r2 = &sfmt->state[SFMT_N - 1]; + for (i = 0; i < SFMT_N - SFMT_POS1; i++) { + do_recursion(&array[i], &sfmt->state[i], &sfmt->state[i + SFMT_POS1], r1, r2); + r1 = r2; + r2 = &array[i]; } - for (; i < N; i++) { - do_recursion(&array[i], &sfmt[i], &array[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &array[i]; + for (; i < SFMT_N; i++) { + do_recursion(&array[i], &sfmt->state[i], + &array[i + SFMT_POS1 - SFMT_N], r1, r2); + r1 = r2; + r2 = &array[i]; } - for (; i < size - N; i++) { - do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &array[i]; + for (; i < size - SFMT_N; i++) { + do_recursion(&array[i], &array[i - SFMT_N], + &array[i + SFMT_POS1 - SFMT_N], r1, r2); + r1 = r2; + r2 = &array[i]; } - for (j = 0; j < 2 * N - size; j++) { - sfmt[j] = array[j + size - N]; + for (j = 0; j < 2 * SFMT_N - size; j++) { + sfmt->state[j] = array[j + size - SFMT_N]; } for (; i < size; i++, j++) { - do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2); - r1 = r2; - r2 = &array[i]; - sfmt[j] = array[i]; + do_recursion(&array[i], &array[i - SFMT_N], + &array[i + SFMT_POS1 - SFMT_N], r1, r2); + r1 = r2; + r2 = &array[i]; + sfmt->state[j] = array[i]; } } #endif @@ -312,12 +132,12 @@ inline static void swap(w128_t *array, int size) { uint32_t x, y; for (i = 0; i < size; i++) { - x = array[i].u[0]; - y = array[i].u[2]; - array[i].u[0] = array[i].u[1]; - array[i].u[2] = array[i].u[3]; - array[i].u[1] = x; - array[i].u[3] = y; + x = array[i].u[0]; + y = array[i].u[2]; + array[i].u[0] = array[i].u[1]; + array[i].u[2] = array[i].u[3]; + array[i].u[1] = x; + array[i].u[3] = y; } } #endif @@ -343,114 +163,101 @@ static uint32_t func2(uint32_t x) { /** * This function certificate the period of 2^{MEXP} + * @param sfmt SFMT internal state */ -static void period_certification(void) { +static void period_certification(sfmt_t * sfmt) { int inner = 0; int i, j; uint32_t work; + uint32_t *psfmt32 = &sfmt->state[0].u[0]; + const uint32_t parity[4] = {SFMT_PARITY1, SFMT_PARITY2, + SFMT_PARITY3, SFMT_PARITY4}; for (i = 0; i < 4; i++) - inner ^= psfmt32[idxof(i)] & parity[i]; + inner ^= psfmt32[idxof(i)] & parity[i]; for (i = 16; i > 0; i >>= 1) - inner ^= inner >> i; + inner ^= inner >> i; inner &= 1; /* check OK */ if (inner == 1) { - return; + return; } /* check NG, and modification */ for (i = 0; i < 4; i++) { - work = 1; - for (j = 0; j < 32; j++) { - if ((work & parity[i]) != 0) { - psfmt32[idxof(i)] ^= work; - return; - } - work = work << 1; - } + work = 1; + for (j = 0; j < 32; j++) { + if ((work & parity[i]) != 0) { + psfmt32[idxof(i)] ^= work; + return; + } + work = work << 1; + } } } /*---------------- PUBLIC FUNCTIONS ----------------*/ +#define UNUSED_VARIABLE(x) (void)(x) /** * This function returns the identification string. * The string shows the word size, the Mersenne exponent, * and all parameters of this generator. + * @param sfmt SFMT internal state */ -const char *get_idstring(void) { - return IDSTR; +const char *sfmt_get_idstring(sfmt_t * sfmt) { + UNUSED_VARIABLE(sfmt); + return SFMT_IDSTR; } /** * This function returns the minimum size of array used for \b * fill_array32() function. + * @param sfmt SFMT internal state * @return minimum size of array used for fill_array32() function. */ -int get_min_array_size32(void) { - return N32; +int sfmt_get_min_array_size32(sfmt_t * sfmt) { + UNUSED_VARIABLE(sfmt); + return SFMT_N32; } /** * This function returns the minimum size of array used for \b * fill_array64() function. + * @param sfmt SFMT internal state * @return minimum size of array used for fill_array64() function. */ -int get_min_array_size64(void) { - return N64; +int sfmt_get_min_array_size64(sfmt_t * sfmt) { + UNUSED_VARIABLE(sfmt); + return SFMT_N64; } -#ifndef ONLY64 +#if !defined(HAVE_SSE2) && !defined(HAVE_ALTIVEC) /** - * This function generates and returns 32-bit pseudorandom number. - * init_gen_rand or init_by_array must be called before this function. - * @return 32-bit pseudorandom number + * This function fills the internal state array with pseudorandom + * integers. + * @param sfmt SFMT internal state */ -uint32_t gen_rand32(void) { - uint32_t r; +void sfmt_gen_rand_all(sfmt_t * sfmt) { + int i; + w128_t *r1, *r2; - assert(initialized); - if (idx >= N32) { - gen_rand_all(); - idx = 0; + r1 = &sfmt->state[SFMT_N - 2]; + r2 = &sfmt->state[SFMT_N - 1]; + for (i = 0; i < SFMT_N - SFMT_POS1; i++) { + do_recursion(&sfmt->state[i], &sfmt->state[i], + &sfmt->state[i + SFMT_POS1], r1, r2); + r1 = r2; + r2 = &sfmt->state[i]; + } + for (; i < SFMT_N; i++) { + do_recursion(&sfmt->state[i], &sfmt->state[i], + &sfmt->state[i + SFMT_POS1 - SFMT_N], r1, r2); + r1 = r2; + r2 = &sfmt->state[i]; } - r = psfmt32[idx++]; - return r; } #endif -/** - * This function generates and returns 64-bit pseudorandom number. - * init_gen_rand or init_by_array must be called before this function. - * The function gen_rand64 should not be called after gen_rand32, - * unless an initialization is again executed. - * @return 64-bit pseudorandom number - */ -uint64_t gen_rand64(void) { -#if defined(BIG_ENDIAN64) && !defined(ONLY64) - uint32_t r1, r2; -#else - uint64_t r; -#endif - - assert(initialized); - assert(idx % 2 == 0); - - if (idx >= N32) { - gen_rand_all(); - idx = 0; - } -#if defined(BIG_ENDIAN64) && !defined(ONLY64) - r1 = psfmt32[idx]; - r2 = psfmt32[idx + 1]; - idx += 2; - return ((uint64_t)r2 << 32) | r1; -#else - r = psfmt64[idx / 2]; - idx += 2; - return r; -#endif -} #ifndef ONLY64 /** @@ -464,6 +271,7 @@ uint64_t gen_rand64(void) { * before the first call of this function. This function can not be * used after calling gen_rand function, without initialization. * + * @param sfmt SFMT internal state * @param array an array where pseudorandom 32-bit integers are filled * by this function. The pointer to the array must be \b "aligned" * (namely, must be a multiple of 16) in the SIMD version, since it @@ -478,14 +286,13 @@ uint64_t gen_rand64(void) { * memory. Mac OSX doesn't have these functions, but \b malloc of OSX * returns the pointer to the aligned memory block. */ -void fill_array32(uint32_t *array, int size) { - assert(initialized); - assert(idx == N32); +void sfmt_fill_array32(sfmt_t * sfmt, uint32_t *array, int size) { + assert(sfmt->idx == SFMT_N32); assert(size % 4 == 0); - assert(size >= N32); + assert(size >= SFMT_N32); - gen_rand_array((w128_t *)array, size / 4); - idx = N32; + gen_rand_array(sfmt, (w128_t *)array, size / 4); + sfmt->idx = SFMT_N32; } #endif @@ -496,6 +303,7 @@ void fill_array32(uint32_t *array, int size) { * multiple of two. The generation by this function is much faster * than the following gen_rand function. * + * @param sfmt SFMT internal state * For initialization, init_gen_rand or init_by_array must be called * before the first call of this function. This function can not be * used after calling gen_rand function, without initialization. @@ -514,14 +322,13 @@ void fill_array32(uint32_t *array, int size) { * memory. Mac OSX doesn't have these functions, but \b malloc of OSX * returns the pointer to the aligned memory block. */ -void fill_array64(uint64_t *array, int size) { - assert(initialized); - assert(idx == N32); +void sfmt_fill_array64(sfmt_t * sfmt, uint64_t *array, int size) { + assert(sfmt->idx == SFMT_N32); assert(size % 2 == 0); - assert(size >= N64); + assert(size >= SFMT_N64); - gen_rand_array((w128_t *)array, size / 2); - idx = N32; + gen_rand_array(sfmt, (w128_t *)array, size / 2); + sfmt->idx = SFMT_N32; #if defined(BIG_ENDIAN64) && !defined(ONLY64) swap((w128_t *)array, size /2); @@ -532,54 +339,58 @@ void fill_array64(uint64_t *array, int size) { * This function initializes the internal state array with a 32-bit * integer seed. * + * @param sfmt SFMT internal state * @param seed a 32-bit integer used as the seed. */ -void init_gen_rand(uint32_t seed) { +void sfmt_init_gen_rand(sfmt_t * sfmt, uint32_t seed) { int i; + uint32_t *psfmt32 = &sfmt->state[0].u[0]; + psfmt32[idxof(0)] = seed; - for (i = 1; i < N32; i++) { - psfmt32[idxof(i)] = 1812433253UL * (psfmt32[idxof(i - 1)] - ^ (psfmt32[idxof(i - 1)] >> 30)) - + i; + for (i = 1; i < SFMT_N32; i++) { + psfmt32[idxof(i)] = 1812433253UL * (psfmt32[idxof(i - 1)] + ^ (psfmt32[idxof(i - 1)] >> 30)) + + i; } - idx = N32; - period_certification(); - initialized = 1; + sfmt->idx = SFMT_N32; + period_certification(sfmt); } /** * This function initializes the internal state array, * with an array of 32-bit integers used as the seeds + * @param sfmt SFMT internal state * @param init_key the array of 32-bit integers, used as a seed. * @param key_length the length of init_key. */ -void init_by_array(uint32_t *init_key, int key_length) { +void sfmt_init_by_array(sfmt_t * sfmt, uint32_t *init_key, int key_length) { int i, j, count; uint32_t r; int lag; int mid; - int size = N * 4; + int size = SFMT_N * 4; + uint32_t *psfmt32 = &sfmt->state[0].u[0]; if (size >= 623) { - lag = 11; + lag = 11; } else if (size >= 68) { - lag = 7; + lag = 7; } else if (size >= 39) { - lag = 5; + lag = 5; } else { - lag = 3; + lag = 3; } mid = (size - lag) / 2; - memset(sfmt, 0x8b, sizeof(sfmt)); - if (key_length + 1 > N32) { - count = key_length + 1; + memset(sfmt, 0x8b, sizeof(sfmt_t)); + if (key_length + 1 > SFMT_N32) { + count = key_length + 1; } else { - count = N32; + count = SFMT_N32; } - r = func1(psfmt32[idxof(0)] ^ psfmt32[idxof(mid)] - ^ psfmt32[idxof(N32 - 1)]); + r = func1(psfmt32[idxof(0)] ^ psfmt32[idxof(mid)] + ^ psfmt32[idxof(SFMT_N32 - 1)]); psfmt32[idxof(mid)] += r; r += key_length; psfmt32[idxof(mid + lag)] += r; @@ -587,34 +398,36 @@ void init_by_array(uint32_t *init_key, int key_length) { count--; for (i = 1, j = 0; (j < count) && (j < key_length); j++) { - r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)] - ^ psfmt32[idxof((i + N32 - 1) % N32)]); - psfmt32[idxof((i + mid) % N32)] += r; - r += init_key[j] + i; - psfmt32[idxof((i + mid + lag) % N32)] += r; - psfmt32[idxof(i)] = r; - i = (i + 1) % N32; + r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % SFMT_N32)] + ^ psfmt32[idxof((i + SFMT_N32 - 1) % SFMT_N32)]); + psfmt32[idxof((i + mid) % SFMT_N32)] += r; + r += init_key[j] + i; + psfmt32[idxof((i + mid + lag) % SFMT_N32)] += r; + psfmt32[idxof(i)] = r; + i = (i + 1) % SFMT_N32; } for (; j < count; j++) { - r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)] - ^ psfmt32[idxof((i + N32 - 1) % N32)]); - psfmt32[idxof((i + mid) % N32)] += r; - r += i; - psfmt32[idxof((i + mid + lag) % N32)] += r; - psfmt32[idxof(i)] = r; - i = (i + 1) % N32; + r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % SFMT_N32)] + ^ psfmt32[idxof((i + SFMT_N32 - 1) % SFMT_N32)]); + psfmt32[idxof((i + mid) % SFMT_N32)] += r; + r += i; + psfmt32[idxof((i + mid + lag) % SFMT_N32)] += r; + psfmt32[idxof(i)] = r; + i = (i + 1) % SFMT_N32; } - for (j = 0; j < N32; j++) { - r = func2(psfmt32[idxof(i)] + psfmt32[idxof((i + mid) % N32)] - + psfmt32[idxof((i + N32 - 1) % N32)]); - psfmt32[idxof((i + mid) % N32)] ^= r; - r -= i; - psfmt32[idxof((i + mid + lag) % N32)] ^= r; - psfmt32[idxof(i)] = r; - i = (i + 1) % N32; + for (j = 0; j < SFMT_N32; j++) { + r = func2(psfmt32[idxof(i)] + psfmt32[idxof((i + mid) % SFMT_N32)] + + psfmt32[idxof((i + SFMT_N32 - 1) % SFMT_N32)]); + psfmt32[idxof((i + mid) % SFMT_N32)] ^= r; + r -= i; + psfmt32[idxof((i + mid + lag) % SFMT_N32)] ^= r; + psfmt32[idxof(i)] = r; + i = (i + 1) % SFMT_N32; } - idx = N32; - period_certification(); - initialized = 1; + sfmt->idx = SFMT_N32; + period_certification(sfmt); } +#if defined(__cplusplus) +} +#endif diff --git a/common/sfmt/SFMT.h b/common/sfmt/SFMT.h index f0aba198..dca308a0 100644 --- a/common/sfmt/SFMT.h +++ b/common/sfmt/SFMT.h @@ -1,24 +1,28 @@ -/** - * @file SFMT.h +#pragma once +/** + * @file SFMT.h * * @brief SIMD oriented Fast Mersenne Twister(SFMT) pseudorandom - * number generator + * number generator using C structure. * * @author Mutsuo Saito (Hiroshima University) - * @author Makoto Matsumoto (Hiroshima University) + * @author Makoto Matsumoto (The University of Tokyo) * * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima - * University. All rights reserved. + * University. + * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto, Hiroshima + * University and The University of Tokyo. + * All rights reserved. * - * The new BSD License is applied to this software. - * see LICENSE.txt + * The 3-clause BSD License is applied to this software, see + * LICENSE.txt * * @note We assume that your system has inttypes.h. If your system * doesn't have inttypes.h, you have to typedef uint32_t and uint64_t, * and you have to define PRIu64 and PRIx64 in this file as follows: * @verbatim typedef unsigned int uint32_t - typedef unsigned long long uint64_t + typedef unsigned long long uint64_t #define PRIu64 "llu" #define PRIx64 "llx" @endverbatim @@ -28,14 +32,14 @@ * unsigned int and 64-bit unsigned int in hexadecimal format. */ -#ifndef SFMT_H -#define SFMT_H - -#ifdef __cplusplus +#ifndef SFMTST_H +#define SFMTST_H +#if defined(__cplusplus) extern "C" { #endif #include +#include #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) #include @@ -60,105 +64,232 @@ extern "C" { #endif #endif -#if defined(__GNUC__) -#define ALWAYSINLINE __attribute__((always_inline)) -#else -#define ALWAYSINLINE -#endif +#include "SFMT-params.h" -#if defined(_MSC_VER) - #if _MSC_VER >= 1200 - #define PRE_ALWAYS __forceinline - #else - #define PRE_ALWAYS inline +/*------------------------------------------ + 128-bit SIMD like data type for standard C + ------------------------------------------*/ +#if defined(HAVE_ALTIVEC) + #if !defined(__APPLE__) + #include #endif +/** 128-bit data structure */ +union W128_T { + vector unsigned int s; + uint32_t u[4]; + uint64_t u64[2]; +}; +#elif defined(HAVE_SSE2) + #include + +/** 128-bit data structure */ +union W128_T { + uint32_t u[4]; + uint64_t u64[2]; + __m128i si; +}; #else - #define PRE_ALWAYS inline +/** 128-bit data structure */ +union W128_T { + uint32_t u[4]; + uint64_t u64[2]; +}; #endif -uint32_t gen_rand32(void); -uint64_t gen_rand64(void); -void fill_array32(uint32_t *array, int size); -void fill_array64(uint64_t *array, int size); -void init_gen_rand(uint32_t seed); -void init_by_array(uint32_t *init_key, int key_length); -const char *get_idstring(void); -int get_min_array_size32(void); -int get_min_array_size64(void); +/** 128-bit data type */ +typedef union W128_T w128_t; -/* These real versions are due to Isaku Wada */ -/** generates a random number on [0,1]-real-interval */ -inline static double to_real1(uint32_t v) -{ - return v * (1.0/4294967295.0); - /* divided by 2^32-1 */ +/** + * SFMT internal state + */ +struct SFMT_T { + /** the 128-bit internal state array */ + w128_t state[SFMT_N]; + /** index counter to the 32-bit internal state array */ + int idx; +}; + +typedef struct SFMT_T sfmt_t; + +void sfmt_fill_array32(sfmt_t * sfmt, uint32_t * array, int size); +void sfmt_fill_array64(sfmt_t * sfmt, uint64_t * array, int size); +void sfmt_init_gen_rand(sfmt_t * sfmt, uint32_t seed); +void sfmt_init_by_array(sfmt_t * sfmt, uint32_t * init_key, int key_length); +const char * sfmt_get_idstring(sfmt_t * sfmt); +int sfmt_get_min_array_size32(sfmt_t * sfmt); +int sfmt_get_min_array_size64(sfmt_t * sfmt); +void sfmt_gen_rand_all(sfmt_t * sfmt); + +#ifndef ONLY64 +/** + * This function generates and returns 32-bit pseudorandom number. + * init_gen_rand or init_by_array must be called before this function. + * @param sfmt SFMT internal state + * @return 32-bit pseudorandom number + */ +inline static uint32_t sfmt_genrand_uint32(sfmt_t * sfmt) { + uint32_t r; + uint32_t * psfmt32 = &sfmt->state[0].u[0]; + + if (sfmt->idx >= SFMT_N32) { + sfmt_gen_rand_all(sfmt); + sfmt->idx = 0; + } + r = psfmt32[sfmt->idx++]; + return r; +} +#endif +/** + * This function generates and returns 64-bit pseudorandom number. + * init_gen_rand or init_by_array must be called before this function. + * The function gen_rand64 should not be called after gen_rand32, + * unless an initialization is again executed. + * @param sfmt SFMT internal state + * @return 64-bit pseudorandom number + */ +inline static uint64_t sfmt_genrand_uint64(sfmt_t * sfmt) { +#if defined(BIG_ENDIAN64) && !defined(ONLY64) + uint32_t * psfmt32 = &sfmt->state[0].u[0]; + uint32_t r1, r2; +#else + uint64_t r; +#endif + uint64_t * psfmt64 = &sfmt->state[0].u64[0]; + assert(sfmt->idx % 2 == 0); + + if (sfmt->idx >= SFMT_N32) { + sfmt_gen_rand_all(sfmt); + sfmt->idx = 0; + } +#if defined(BIG_ENDIAN64) && !defined(ONLY64) + r1 = psfmt32[sfmt->idx]; + r2 = psfmt32[sfmt->idx + 1]; + sfmt->idx += 2; + return ((uint64_t)r2 << 32) | r1; +#else + r = psfmt64[sfmt->idx / 2]; + sfmt->idx += 2; + return r; +#endif } -/** generates a random number on [0,1]-real-interval */ -inline static double genrand_real1(void) +/* ================================================= + The following real versions are due to Isaku Wada + ================================================= */ +/** + * converts an unsigned 32-bit number to a double on [0,1]-real-interval. + * @param v 32-bit unsigned integer + * @return double on [0,1]-real-interval + */ +inline static double sfmt_to_real1(uint32_t v) { - return to_real1(gen_rand32()); + return v * (1.0/4294967295.0); + /* divided by 2^32-1 */ } -/** generates a random number on [0,1)-real-interval */ -inline static double to_real2(uint32_t v) +/** + * generates a random number on [0,1]-real-interval + * @param sfmt SFMT internal state + * @return double on [0,1]-real-interval + */ +inline static double sfmt_genrand_real1(sfmt_t * sfmt) { - return v * (1.0/4294967296.0); + return sfmt_to_real1(sfmt_genrand_uint32(sfmt)); +} + +/** + * converts an unsigned 32-bit integer to a double on [0,1)-real-interval. + * @param v 32-bit unsigned integer + * @return double on [0,1)-real-interval + */ +inline static double sfmt_to_real2(uint32_t v) +{ + return v * (1.0/4294967296.0); /* divided by 2^32 */ } -/** generates a random number on [0,1)-real-interval */ -inline static double genrand_real2(void) +/** + * generates a random number on [0,1)-real-interval + * @param sfmt SFMT internal state + * @return double on [0,1)-real-interval + */ +inline static double sfmt_genrand_real2(sfmt_t * sfmt) { - return to_real2(gen_rand32()); + return sfmt_to_real2(sfmt_genrand_uint32(sfmt)); } -/** generates a random number on (0,1)-real-interval */ -inline static double to_real3(uint32_t v) +/** + * converts an unsigned 32-bit integer to a double on (0,1)-real-interval. + * @param v 32-bit unsigned integer + * @return double on (0,1)-real-interval + */ +inline static double sfmt_to_real3(uint32_t v) { - return (((double)v) + 0.5)*(1.0/4294967296.0); + return (((double)v) + 0.5)*(1.0/4294967296.0); /* divided by 2^32 */ } -/** generates a random number on (0,1)-real-interval */ -inline static double genrand_real3(void) +/** + * generates a random number on (0,1)-real-interval + * @param sfmt SFMT internal state + * @return double on (0,1)-real-interval + */ +inline static double sfmt_genrand_real3(sfmt_t * sfmt) { - return to_real3(gen_rand32()); -} -/** These real versions are due to Isaku Wada */ - -/** generates a random number on [0,1) with 53-bit resolution*/ -inline static double to_res53(uint64_t v) -{ - return v * (1.0/18446744073709551616.0L); + return sfmt_to_real3(sfmt_genrand_uint32(sfmt)); } -/** generates a random number on [0,1) with 53-bit resolution from two - * 32 bit integers */ -inline static double to_res53_mix(uint32_t x, uint32_t y) -{ - return to_res53(x | ((uint64_t)y << 32)); -} - -/** generates a random number on [0,1) with 53-bit resolution +/** + * converts an unsigned 32-bit integer to double on [0,1) + * with 53-bit resolution. + * @param v 32-bit unsigned integer + * @return double on [0,1)-real-interval with 53-bit resolution. */ -inline static double genrand_res53(void) -{ - return to_res53(gen_rand64()); -} +inline static double sfmt_to_res53(uint64_t v) +{ + return v * (1.0/18446744073709551616.0); +} -/** generates a random number on [0,1) with 53-bit resolution - using 32bit integer. +/** + * generates a random number on [0,1) with 53-bit resolution + * @param sfmt SFMT internal state + * @return double on [0,1) with 53-bit resolution */ -inline static double genrand_res53_mix(void) -{ +inline static double sfmt_genrand_res53(sfmt_t * sfmt) +{ + return sfmt_to_res53(sfmt_genrand_uint64(sfmt)); +} + + +/* ================================================= + The following function are added by Saito. + ================================================= */ +/** + * generates a random number on [0,1) with 53-bit resolution from two + * 32 bit integers + */ +inline static double sfmt_to_res53_mix(uint32_t x, uint32_t y) +{ + return sfmt_to_res53(x | ((uint64_t)y << 32)); +} + +/** + * generates a random number on [0,1) with 53-bit resolution + * using two 32bit integers. + * @param sfmt SFMT internal state + * @return double on [0,1) with 53-bit resolution + */ +inline static double sfmt_genrand_res53_mix(sfmt_t * sfmt) +{ uint32_t x, y; - x = gen_rand32(); - y = gen_rand32(); - return to_res53_mix(x, y); -} -#ifdef __cplusplus + x = sfmt_genrand_uint32(sfmt); + y = sfmt_genrand_uint32(sfmt); + return sfmt_to_res53_mix(x, y); +} + +#if defined(__cplusplus) } #endif + #endif From 424513eb90bd2755aa5885bafa191006ffd3fa27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Sat, 8 Mar 2014 17:45:59 +0100 Subject: [PATCH 14/55] Forgot to add lower bound in RNG generation. --- common/rng_sfmt.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index 438d8f59..b24ae92c 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -18,5 +18,5 @@ unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) mutex.unlock(); // return a random number from the interval [min, max] - return (unsigned int) (r % (max - min + 1)); + return (unsigned int) (r % (max - min + 1) + min); } From 800f7e637376632dd66957bc310244c20d4ab4dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Mon, 10 Mar 2014 14:13:46 +0100 Subject: [PATCH 15/55] Use distribution function with rejection sampling. --- common/rng_sfmt.cpp | 76 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 7 deletions(-) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index b24ae92c..72e9955a 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -1,7 +1,10 @@ #include "rng_sfmt.h" #include -#include -#include +#include + +// This is from gcc sources, namely from fixincludes/inclhack.def +// On C++11 systems, could be included instead. +#define UINT64_MAX (~(uint64_t)0) RNG_SFMT::RNG_SFMT(QObject *parent) : RNG_Abstract(parent) @@ -10,13 +13,72 @@ RNG_SFMT::RNG_SFMT(QObject *parent) sfmt_init_gen_rand(&sfmt, QDateTime::currentDateTime().toTime_t()); } +/** + * Much thought went into this, please read this comment before you modify the code. + * Let SFMT() be an alias for sfmt_genrand_uint64() aka SFMT's rand() function. + * + * SMFT() returns a uniformly distributed pseudorandom number from 0 to UINT64_MAX. + * As SFMT() operates on a limited integer range, it is a _discrete_ function. + * + * We want a random number from a given interval [min, max] though, so we need to + * implement the (discrete) cumulative distribution function SFMT(min, max), which + * returns a random number X from [min, max]. + * + * This CDF is by formal definition: + * SFMT(X; min, max) = (floor(X) - min + 1) / (max - min + 1) + * + * To get out the random variable, solve for X: + * floor(X) = SFMT(X; min, max) * (max - min + 1) + min - 1 + * So this is, what getNumber(min, max) should look like. + * Problem: SFMT(X; min, max) * (max - min + 1) could produce an integer overflow, + * so it is not safe. + * + * One solution is to divide the universe into buckets of equal size depending on the + * range [min, max] and assign X to the bucket that contains the number generated + * by SFMT(). This equals to modulo computation and is not satisfying: + * If the buckets don't divide the universe equally, because the bucket size is not + * a divisor of 2, there will be a range in the universe that is biased because one + * bucket is too small thus will be chosen less equally! + * + * This is solved by rejection sampling: + * As SFMT() is assumed to be unbiased, we are allowed to ignore those random numbers + * from SFMT() that would force us to have an unequal bucket and generate new random + * numbers until one number fits into one of the other buckets. + * This can be compared to an ideal six sided die that is rolled until only sides + * 1-5 show up, while 6 represents something that you don't want. So you basically roll + * a five sided die. + */ unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) { - // To make the random number generation thread safe, a mutex is created around the generation. + // This all makes no sense if min > max. + // So in debug mode Q_ASSERT will print a warning... + Q_ASSERT(min <= max); + // ... and at runtime min and max will be swapped; this should never happen. + if(min > max) + std::swap(min, max); + + // First compute the diameter (aka size, length) of the [min, max] interval + const unsigned int diameter = max - min + 1; + + // Compute how many buckets (each in size of the diameter) will fit into the + // universe. + // If the division has a remainder, the result is floored automatically. + const uint64_t buckets = UINT64_MAX / diameter; + + // Compute the last valid random number. All numbers beyond have to be ignored. + // If there was no remainder in the previous step, limit is equal to UINT64_MAX. + const uint64_t limit = diameter * buckets; + + uint64_t rand; + // To make the random number generation thread-safe, a mutex is created around + // the generation. Outside of the loop of course, to avoid lock/unlock overhead. mutex.lock(); - uint64_t r = sfmt_genrand_uint64(&sfmt); + do { + rand = sfmt_genrand_uint64(&sfmt); + } while (rand >= limit); mutex.unlock(); - - // return a random number from the interval [min, max] - return (unsigned int) (r % (max - min + 1) + min); + + // Now determine the bucket containing the SFMT() random number and after adding + // the lower bound, a random number from [min, max] can be returned. + return (unsigned int) (rand / buckets + min); } From 9a20e5e2e292b07dceabc0b2c9c44157cbf6f7ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Tue, 11 Mar 2014 08:18:54 +0100 Subject: [PATCH 16/55] Commented a pitfall in case of RNG replacement. --- common/rng_sfmt.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index 72e9955a..e2c38526 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -47,6 +47,13 @@ RNG_SFMT::RNG_SFMT(QObject *parent) * This can be compared to an ideal six sided die that is rolled until only sides * 1-5 show up, while 6 represents something that you don't want. So you basically roll * a five sided die. + * + * Note: If you replace the SFMT RNG with some other rand() function in the future, + * then you _need_ to change the UINT64_MAX constant to the largest possible random + * number which can be created by the new rand() function. This value is often defined + * in a RAND_MAX constant. + * Otherwise you will probably skew the outcome of the getNumber() method or worsen the + * performance of the application. */ unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) { From 4eb845d4387509f8258f64ae649942eaa450a184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Tue, 11 Mar 2014 09:41:37 +0100 Subject: [PATCH 17/55] Throw exception if RNG is used with invalid bounds. --- common/rng_sfmt.cpp | 18 ++++++++++++------ common/rng_sfmt.h | 9 ++++++++- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index e2c38526..2e93e44b 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -1,6 +1,7 @@ #include "rng_sfmt.h" #include #include +#include // This is from gcc sources, namely from fixincludes/inclhack.def // On C++11 systems, could be included instead. @@ -57,12 +58,17 @@ RNG_SFMT::RNG_SFMT(QObject *parent) */ unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) { - // This all makes no sense if min > max. - // So in debug mode Q_ASSERT will print a warning... - Q_ASSERT(min <= max); - // ... and at runtime min and max will be swapped; this should never happen. - if(min > max) - std::swap(min, max); + // This all makes no sense if min > max, which should never happen. + if(min > max) { + throw std::invalid_argument( + QString("Invalid bounds for RNG: min > max! Values were: min = " + + QString::number(min) + ", max = " + + QString::number(max) + + ". This is either a bug or something even more serious happened." + ).toStdString()); + // at this point, the method exits. No return value is needed, because + // basically the exception itself is returned. + } // First compute the diameter (aka size, length) of the [min, max] interval const unsigned int diameter = max - min + 1; diff --git a/common/rng_sfmt.h b/common/rng_sfmt.h index 80ff9f2f..3134e91d 100644 --- a/common/rng_sfmt.h +++ b/common/rng_sfmt.h @@ -7,7 +7,14 @@ /** * This class represents the random number generator. - * It uses the SIMD-oriented Fast Mersenne Twister code v1.4.1 from + * Usage instructions: + * Create an instance of RNG_SFMT, then call getNumber(min, max). + * You should never call this function with min > max, this throws a + * std::invalid_argument exception. It is best practice to use getNumber() in a try block + * and catch the exception if min, max are entered by the user or computed somehow. + * + * Technical details: + * The RNG uses the SIMD-oriented Fast Mersenne Twister code v1.4.1 from * http://www.math.sci.hiroshima-u.ac.jp/~%20m-mat/MT/SFMT/index.html * To use this RNG, the class needs a sfmt_t structure for the RNG's internal state. * It has to be initialized by sfmt_init_gen_rand() which is done in the constructor. From 082ab7315283b72b10895e2e053a6dc38d54da36 Mon Sep 17 00:00:00 2001 From: Matt Kelly Date: Thu, 13 Mar 2014 01:07:15 -0400 Subject: [PATCH 18/55] Add Tab shortcut for next phase --- cockatrice/src/tab_game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cockatrice/src/tab_game.cpp b/cockatrice/src/tab_game.cpp index f237589e..cee00037 100644 --- a/cockatrice/src/tab_game.cpp +++ b/cockatrice/src/tab_game.cpp @@ -532,7 +532,7 @@ void TabGame::retranslateUi() gameMenu->setTitle(tr("&Game")); if (aNextPhase) { aNextPhase->setText(tr("Next &phase")); - aNextPhase->setShortcut(tr("Ctrl+Space")); + aNextPhase->setShortcuts(QList() << QKeySequence(tr("Ctrl+Space")) << QKeySequence(tr("Tab"))); } if (aNextTurn) { aNextTurn->setText(tr("Next &turn")); From fbf54b62bc19db25bbe93ea238b0b9b6d96456f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Tue, 18 Mar 2014 20:41:39 +0100 Subject: [PATCH 19/55] Test if macro already exists to shutup warning. --- common/rng_sfmt.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index 2e93e44b..ad803b7d 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -5,7 +5,9 @@ // This is from gcc sources, namely from fixincludes/inclhack.def // On C++11 systems, could be included instead. +#ifndef UINT64_MAX #define UINT64_MAX (~(uint64_t)0) +#endif RNG_SFMT::RNG_SFMT(QObject *parent) : RNG_Abstract(parent) From f964dcc656e0d67c8b72b05a96ef9af82e186caf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Thu, 20 Mar 2014 15:37:21 +0100 Subject: [PATCH 20/55] Added additional bound checks. --- common/rng_sfmt.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index ad803b7d..fa97aa6b 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -61,7 +61,7 @@ RNG_SFMT::RNG_SFMT(QObject *parent) unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) { // This all makes no sense if min > max, which should never happen. - if(min > max) { + if(min > max || max >= UINT_MAX || min >= UINT_MAX) { throw std::invalid_argument( QString("Invalid bounds for RNG: min > max! Values were: min = " + QString::number(min) + ", max = " + From 2b7ea0c9837c85b158feca88a7d5870f7d20003c Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Mon, 24 Mar 2014 21:03:26 +0000 Subject: [PATCH 21/55] refactored deck editor UI key shortcuts The global shortcuts were removed in favor of key events which are only triggered when a widget has focus. This is necessary to allow different widgets to react differently to the 'enter' key. The current key configuration is: search edit focused: * left/right: decrease/increase card count for selected database card * enter: add selected card to deck * ctrl-enter: add selected card to deck sideboard * ctrl-left/right: decrease/increase card count in sideboard for selected card database focused: the same as with search edit. deckview focused: * left/right: decrease/increase card count for selected deckview card * enter: increase count for selected deckview card * delete/backspace: delete selected card from deck --- cockatrice/CMakeLists.txt | 2 + cockatrice/src/decklistmodel.cpp | 35 +++++++++- cockatrice/src/decklistmodel.h | 3 + cockatrice/src/filterbuilder.cpp | 5 +- cockatrice/src/filterbuilder.h | 2 +- cockatrice/src/keysignals.cpp | 49 ++++++++++++++ cockatrice/src/keysignals.h | 30 +++++++++ cockatrice/src/tab_deck_editor.cpp | 105 ++++++++++++++++++++++------- cockatrice/src/tab_deck_editor.h | 11 +++ 9 files changed, 212 insertions(+), 30 deletions(-) create mode 100644 cockatrice/src/keysignals.cpp create mode 100644 cockatrice/src/keysignals.h diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 4012795f..c90a00d7 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -26,6 +26,7 @@ SET(cockatrice_SOURCES src/handzone.cpp src/handcounter.cpp src/carddatabase.cpp + src/keysignals.cpp src/gameview.cpp src/gameselector.cpp src/decklistmodel.cpp @@ -110,6 +111,7 @@ SET(cockatrice_HEADERS src/handzone.h src/handcounter.h src/carddatabase.h + src/keysignals.h src/gameview.h src/gameselector.h src/decklistmodel.h diff --git a/cockatrice/src/decklistmodel.cpp b/cockatrice/src/decklistmodel.cpp index 6abbba86..68062ead 100644 --- a/cockatrice/src/decklistmodel.cpp +++ b/cockatrice/src/decklistmodel.cpp @@ -169,8 +169,7 @@ Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const return 0; Qt::ItemFlags result = Qt::ItemIsEnabled; - if (getNode(index)) - result |= Qt::ItemIsSelectable; + result |= Qt::ItemIsSelectable; return result; } @@ -236,6 +235,38 @@ InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerD return newNode; } +DecklistModelCardNode *DeckListModel::findCardNode(const QString &cardName, const QString &zoneName) const +{ + InnerDecklistNode *zoneNode, *typeNode; + CardInfo *info; + QString cardType; + + zoneNode = dynamic_cast(root->findChild(zoneName)); + if(!zoneNode) + return NULL; + + info = db->getCard(cardName); + if(!info) + return NULL; + + cardType = info->getMainCardType(); + typeNode = dynamic_cast(zoneNode->findChild(cardType)); + if(!typeNode) + return NULL; + + return dynamic_cast(typeNode->findChild(cardName)); +} + +QModelIndex DeckListModel::findCard(const QString &cardName, const QString &zoneName) const +{ + DecklistModelCardNode *cardNode; + + cardNode = findCardNode(cardName, zoneName); + if(!cardNode) + return QModelIndex(); + return nodeToIndex(cardNode); +} + QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName) { InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root); diff --git a/cockatrice/src/decklistmodel.h b/cockatrice/src/decklistmodel.h index 4d81d007..43c8e2a3 100644 --- a/cockatrice/src/decklistmodel.h +++ b/cockatrice/src/decklistmodel.h @@ -45,6 +45,8 @@ public: Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role); bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); + + QModelIndex findCard(const QString &cardName, const QString &zoneName) const; QModelIndex addCard(const QString &cardName, const QString &zoneName); void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); void cleanList(); @@ -56,6 +58,7 @@ private: InnerDecklistNode *root; InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent); QModelIndex nodeToIndex(AbstractDecklistNode *node) const; + DecklistModelCardNode *findCardNode(const QString &cardName, const QString &zoneName) const; void emitRecursiveUpdates(const QModelIndex &index); void sortHelper(InnerDecklistNode *node, Qt::SortOrder order); diff --git a/cockatrice/src/filterbuilder.cpp b/cockatrice/src/filterbuilder.cpp index 3b520663..2e0bc73d 100644 --- a/cockatrice/src/filterbuilder.cpp +++ b/cockatrice/src/filterbuilder.cpp @@ -41,7 +41,8 @@ FilterBuilder::FilterBuilder(QWidget *parent) layout->setAlignment(Qt::AlignTop); setLayout(layout); - connect(ok, SIGNAL(released()), this, SLOT(add_released())); + connect(edit, SIGNAL(returnPressed()), this, SLOT(emit_add())); + connect(ok, SIGNAL(released()), this, SLOT(emit_add())); connect(filterCombo, SIGNAL(currentIndexChanged(int)), edit, SLOT(clear())); fltr = NULL; } @@ -62,7 +63,7 @@ static int comboCurrentIntData(const QComboBox *combo) return combo->itemData(combo->currentIndex()).toInt(); } -void FilterBuilder::add_released() +void FilterBuilder::emit_add() { QString txt; diff --git a/cockatrice/src/filterbuilder.h b/cockatrice/src/filterbuilder.h index c126c82b..1d0565f3 100644 --- a/cockatrice/src/filterbuilder.h +++ b/cockatrice/src/filterbuilder.h @@ -28,7 +28,7 @@ signals: public slots: private slots: - void add_released(); + void emit_add(); protected: }; diff --git a/cockatrice/src/keysignals.cpp b/cockatrice/src/keysignals.cpp new file mode 100644 index 00000000..1994e387 --- /dev/null +++ b/cockatrice/src/keysignals.cpp @@ -0,0 +1,49 @@ +#include "keysignals.h" +#include + +bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event) { + QKeyEvent *kevent; + + if(event->type() != QEvent::KeyPress) + return false; + + kevent = static_cast(event); + switch(kevent->key()) { + case Qt::Key_Return: + case Qt::Key_Enter: + if(kevent->modifiers() & Qt::ControlModifier) + emit onCtrlEnter(); + else + emit onEnter(); + break; + case Qt::Key_Right: + if(kevent->modifiers() & Qt::ControlModifier) + emit onCtrlRight(); + else + emit onRight(); + + if(!filterLROn) + return false; + break; + case Qt::Key_Left: + if(kevent->modifiers() & Qt::ControlModifier) + emit onCtrlLeft(); + else + emit onLeft(); + + if(!filterLROn) + return false; + break; + case Qt::Key_Delete: + case Qt::Key_Backspace: + emit onDelete(); + + if(!filterDeleteOn) + return false; + break; + default: + return false; + } + + return true; +} diff --git a/cockatrice/src/keysignals.h b/cockatrice/src/keysignals.h new file mode 100644 index 00000000..006e0ce3 --- /dev/null +++ b/cockatrice/src/keysignals.h @@ -0,0 +1,30 @@ +#include +#include + +class KeySignals : public QObject { + Q_OBJECT + +private: + bool filterDeleteOn; + bool filterLROn; + +signals: + void onEnter(); + void onCtrlEnter(); + void onLeft(); + void onCtrlLeft(); + void onRight(); + void onCtrlRight(); + void onDelete(); + +protected: + virtual bool eventFilter(QObject *, QEvent *event); + +public: + KeySignals() + : filterDeleteOn(true) + , filterLROn(true) + {} + void filterDelete(bool on) { filterDeleteOn = on; } + void filterLeftRight(bool on) { filterLROn = on; } +}; diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 38179197..8454cd25 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -54,8 +54,15 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) searchLabel = new QLabel(); searchEdit = new SearchLineEdit; searchLabel->setBuddy(searchEdit); + searchKeySignals.filterDelete(false); + searchEdit->installEventFilter(&searchKeySignals); connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); - connect(searchEdit, SIGNAL(returnPressed()), this, SLOT(actAddCard())); + connect(&searchKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); + connect(&searchKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); + connect(&searchKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); + connect(&searchKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); + connect(&searchKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); + connect(&searchKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); QToolBar *deckEditToolBar = new QToolBar; deckEditToolBar->setOrientation(Qt::Horizontal); @@ -71,6 +78,7 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) databaseDisplayModel->setSourceModel(databaseModel); databaseDisplayModel->setFilterKeyColumn(0); databaseDisplayModel->sort(0, Qt::AscendingOrder); + databaseView = new QTreeView(); databaseView->setModel(databaseDisplayModel); databaseView->setUniformRowHeights(true); @@ -81,6 +89,14 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) databaseView->resizeColumnToContents(0); 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())); + databaseView->installEventFilter(&dbViewKeySignals); + connect(&dbViewKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); + connect(&dbViewKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); + connect(&dbViewKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); + connect(&dbViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); + connect(&dbViewKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); + connect(&dbViewKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); + searchEdit->setTreeView(databaseView); QVBoxLayout *leftFrame = new QVBoxLayout; @@ -121,7 +137,13 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) deckView->setModel(deckModel); deckView->setUniformRowHeights(true); deckView->header()->setResizeMode(QHeaderView::ResizeToContents); + deckViewKeySignals.filterLeftRight(false); + deckView->installEventFilter(&deckViewKeySignals); connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); + connect(&deckViewKeySignals, SIGNAL(onEnter()), this, SLOT(actIncrement())); + connect(&deckViewKeySignals, SIGNAL(onRight()), this, SLOT(actIncrement())); + connect(&deckViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrement())); + connect(&deckViewKeySignals, SIGNAL(onDelete()), this, SLOT(actRemoveCard())); nameLabel = new QLabel(); nameEdit = new QLineEdit; @@ -286,9 +308,8 @@ void TabDeckEditor::retranslateUi() aClose->setShortcut(tr("Ctrl+Q")); aAddCard->setText(tr("Add card to &maindeck")); - aAddCard->setShortcuts(QList() << QKeySequence(tr("Return")) << QKeySequence(tr("Enter"))); aAddCardToSideboard->setText(tr("Add card to &sideboard")); - aAddCardToSideboard->setShortcuts(QList() << QKeySequence(tr("Ctrl+Return")) << QKeySequence(tr("Ctrl+Enter"))); + aRemoveCard->setText(tr("&Remove row")); aRemoveCard->setShortcut(tr("Del")); aIncrement->setText(tr("&Increment number")); @@ -517,18 +538,27 @@ void TabDeckEditor::recursiveExpand(const QModelIndex &index) deckView->expand(index); } -void TabDeckEditor::addCardHelper(QString zoneName) +CardInfo *TabDeckEditor::currentCardInfo() const { const QModelIndex currentIndex = databaseView->selectionModel()->currentIndex(); if (!currentIndex.isValid()) - return; + return NULL; const QString cardName = currentIndex.sibling(currentIndex.row(), 0).data().toString(); - CardInfo *info = db->getCard(cardName); + return db->getCard(cardName); +} + +void TabDeckEditor::addCardHelper(QString zoneName) +{ + const CardInfo *info; + + info = currentCardInfo(); + if(!info) + return; if (info->getIsToken()) zoneName = "tokens"; - - QModelIndex newCardIndex = deckModel->addCard(cardName, zoneName); + + QModelIndex newCardIndex = deckModel->addCard(info->getName(), zoneName); recursiveExpand(newCardIndex); deckView->setCurrentIndex(newCardIndex); @@ -554,31 +584,56 @@ void TabDeckEditor::actRemoveCard() setModified(true); } +void TabDeckEditor::offsetCountAtIndex(const QModelIndex &idx, int offset) +{ + if (!idx.isValid() || offset == 0) + return; + + const QModelIndex numberIndex = idx.sibling(idx.row(), 0); + const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); + deckView->setCurrentIndex(numberIndex); + if ((count + offset) <= 0) + deckModel->removeRow(idx.row(), idx.parent()); + else + deckModel->setData(numberIndex, count + offset, Qt::EditRole); + setModified(true); +} + +void TabDeckEditor::decrementCardHelper(QString zoneName) +{ + const CardInfo *info; + QModelIndex idx; + + info = currentCardInfo(); + if(!info) + return; + if (info->getIsToken()) + zoneName = "tokens"; + + idx = deckModel->findCard(info->getName(), zoneName); + offsetCountAtIndex(idx, -1); +} + +void TabDeckEditor::actDecrementCard() +{ + decrementCardHelper("main"); +} + +void TabDeckEditor::actDecrementCardFromSideboard() +{ + decrementCardHelper("side"); +} + void TabDeckEditor::actIncrement() { const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - if (!currentIndex.isValid()) - return; - const QModelIndex numberIndex = currentIndex.sibling(currentIndex.row(), 0); - const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); - deckView->setCurrentIndex(numberIndex); - deckModel->setData(numberIndex, count + 1, Qt::EditRole); - setModified(true); + offsetCountAtIndex(currentIndex, 1); } void TabDeckEditor::actDecrement() { const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - if (!currentIndex.isValid()) - return; - const QModelIndex numberIndex = currentIndex.sibling(currentIndex.row(), 0); - const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); - deckView->setCurrentIndex(numberIndex); - if (count == 1) - deckModel->removeRow(currentIndex.row(), currentIndex.parent()); - else - deckModel->setData(numberIndex, count - 1, Qt::EditRole); - setModified(true); + offsetCountAtIndex(currentIndex, -1); } void TabDeckEditor::actUpdatePrices() diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 0821e605..8dde3e58 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -4,6 +4,7 @@ #include "tab.h" #include #include +#include "keysignals.h" class CardDatabaseModel; class CardDatabaseDisplayModel; @@ -16,6 +17,7 @@ class QLabel; class DeckLoader; class Response; class FilterTreeModel; +class CardInfo; class SearchLineEdit : public QLineEdit { private: @@ -56,6 +58,9 @@ private slots: void actRemoveCard(); void actIncrement(); void actDecrement(); + void actDecrementCard(); + void actDecrementCardFromSideboard(); + void actUpdatePrices(); void finishedUpdatingPrices(); @@ -63,7 +68,10 @@ private slots: void filterViewCustomContextMenu(const QPoint &point); void filterRemove(QAction *action); private: + CardInfo *currentCardInfo() const; void addCardHelper(QString zoneName); + void offsetCountAtIndex(const QModelIndex &idx, int offset); + void decrementCardHelper(QString zoneName); void recursiveExpand(const QModelIndex &index); bool confirmClose(); @@ -71,10 +79,13 @@ private: CardDatabaseDisplayModel *databaseDisplayModel; DeckListModel *deckModel; QTreeView *databaseView; + KeySignals dbViewKeySignals; QTreeView *deckView; + KeySignals deckViewKeySignals; CardFrame *cardInfo; QLabel *searchLabel; SearchLineEdit *searchEdit; + KeySignals searchKeySignals; QLabel *nameLabel; QLineEdit *nameEdit; QLabel *commentsLabel; From 610f0b6f6f7e50ee27610108e83596cfe568108e Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Mon, 24 Mar 2014 23:52:30 +0000 Subject: [PATCH 22/55] make sure filtertree stuff translates The logic types and attribute names were not previously being translated by the tr(...) function. --- cockatrice/src/filterbuilder.cpp | 8 ++++++-- cockatrice/src/filtertree.h | 11 ++++++----- cockatrice/src/filtertreemodel.cpp | 5 ++++- cockatrice/src/tab_deck_editor.cpp | 7 ++++--- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/cockatrice/src/filterbuilder.cpp b/cockatrice/src/filterbuilder.cpp index 2e0bc73d..128cd7bc 100644 --- a/cockatrice/src/filterbuilder.cpp +++ b/cockatrice/src/filterbuilder.cpp @@ -18,12 +18,16 @@ FilterBuilder::FilterBuilder(QWidget *parent) filterCombo = new QComboBox; for (i = 0; i < CardFilter::AttrEnd; i++) filterCombo->addItem( - CardFilter::attrName(static_cast(i)), QVariant(i)); + tr(CardFilter::attrName(static_cast(i))), + QVariant(i) + ); typeCombo = new QComboBox; for (i = 0; i < CardFilter::TypeEnd; i++) typeCombo->addItem( - CardFilter::typeName(static_cast(i)), QVariant(i)); + tr(CardFilter::typeName(static_cast(i))), + QVariant(i) + ); QPushButton *ok = new QPushButton("+"); ok->setMaximumSize(20, 20); diff --git a/cockatrice/src/filtertree.h b/cockatrice/src/filtertree.h index 816bf97a..a404e5a0 100644 --- a/cockatrice/src/filtertree.h +++ b/cockatrice/src/filtertree.h @@ -23,9 +23,9 @@ public: virtual int childCount() const { return 0; } virtual int childIndex(const FilterTreeNode *node) const { return -1; } virtual int index() const { return (parent() != NULL)? parent()->childIndex(this) : -1; } - virtual QString text() const { return ""; } + virtual QString text() const { return QString(textCStr()); } virtual bool isLeaf() const { return false; } - virtual const char *textCStr() const { return text().toStdString().c_str(); } + virtual const char *textCStr() const { return ""; } virtual void nodeChanged() const { if (parent() != NULL) parent()->nodeChanged(); } @@ -70,7 +70,7 @@ public: const FilterItemList *findTypeList(CardFilter::Type type) const; FilterItemList *typeList(CardFilter::Type type); FilterTreeNode *parent() const; - QString text() const { return QString(CardFilter::attrName(attr)); } + const char* textCStr() const { return CardFilter::attrName(attr); } }; class FilterItem; @@ -86,7 +86,7 @@ public: FilterTreeNode *parent() const { return p; } int termIndex(const QString &term) const; FilterTreeNode *termNode(const QString &term); - QString text() const { return QString(CardFilter::typeName(type)); } + const char *textCStr() const { return CardFilter::typeName(type); } bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const; bool testTypeAndNot(const CardInfo *info, CardFilter::Attr attr) const; @@ -107,6 +107,7 @@ public: CardFilter::Type type() const { return p->type; } FilterTreeNode *parent() const { return p; } QString text() const { return term; } + const char *textCStr() const { return term.toStdString().c_str(); } bool isLeaf() const { return true; } bool acceptName(const CardInfo *info) const; @@ -152,7 +153,7 @@ public: FilterTreeNode *termNode(const CardFilter *f); FilterTreeNode *attrTypeNode(CardFilter::Attr attr, CardFilter::Type type); - QString text() const { return QString("root"); } + const char *textCStr() { return "root"; } int index() const { return 0; } bool acceptsCard(const CardInfo *info) const; diff --git a/cockatrice/src/filtertreemodel.cpp b/cockatrice/src/filtertreemodel.cpp index d23c46ed..8b3c57a3 100644 --- a/cockatrice/src/filtertreemodel.cpp +++ b/cockatrice/src/filtertreemodel.cpp @@ -133,7 +133,10 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const case Qt::ToolTipRole: case Qt::StatusTipRole: case Qt::WhatsThisRole: - return node->text(); + if(!node->isLeaf()) + return tr(node->textCStr()); + else + return node->text(); case Qt::CheckStateRole: if (node->isEnabled()) return Qt::Checked; diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 8454cd25..75d6312b 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -285,7 +285,7 @@ TabDeckEditor::~TabDeckEditor() void TabDeckEditor::retranslateUi() { - aCardTextOnly->setText(tr("&Show card text only")); + aCardTextOnly->setText(tr("Show card text only")); aClearSearch->setText(tr("&Clear search")); searchLabel->setText(tr("&Search for:")); @@ -591,11 +591,12 @@ void TabDeckEditor::offsetCountAtIndex(const QModelIndex &idx, int offset) const QModelIndex numberIndex = idx.sibling(idx.row(), 0); const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); + const int new_count = count + offset; deckView->setCurrentIndex(numberIndex); - if ((count + offset) <= 0) + if (new_count <= 0) deckModel->removeRow(idx.row(), idx.parent()); else - deckModel->setData(numberIndex, count + offset, Qt::EditRole); + deckModel->setData(numberIndex, new_count, Qt::EditRole); setModified(true); } From 378cc91c176b7896b4c7f9b931ed2eda26a24af8 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Tue, 25 Mar 2014 00:07:58 +0000 Subject: [PATCH 23/55] delete debug printf statements this should fix the compilation issue mentioned by mattkelly --- cockatrice/src/filtertreemodel.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/cockatrice/src/filtertreemodel.cpp b/cockatrice/src/filtertreemodel.cpp index 8b3c57a3..c004ba22 100644 --- a/cockatrice/src/filtertreemodel.cpp +++ b/cockatrice/src/filtertreemodel.cpp @@ -262,13 +262,8 @@ bool FilterTreeModel::removeRows(int row, int count, const QModelIndex & parent) if (node == NULL || last >= node->childCount()) return false; - printf("delete children in %s\n", node->textCStr()); - fflush(stdout); - for (i = 0; i < count; i++) { - printf(" delete %d\n", i); - fflush(stdout); + for (i = 0; i < count; i++) node->deleteAt(row); - } if (node != fTree && node->childCount() < 1) return removeRow(parent.row(), parent.parent()); From 748aac7ee85073deb3b285f3fd59f78b4bcf060d Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Tue, 25 Mar 2014 01:13:41 +0000 Subject: [PATCH 24/55] whitespace modifications in preparation for merge --- cockatrice/src/carddatabasemodel.cpp | 224 +++---- cockatrice/src/carddatabasemodel.h | 66 +- cockatrice/src/decklistmodel.cpp | 598 +++++++++--------- cockatrice/src/decklistmodel.h | 84 +-- cockatrice/src/tab_deck_editor.cpp | 906 +++++++++++++-------------- cockatrice/src/tab_deck_editor.h | 148 ++--- 6 files changed, 1013 insertions(+), 1013 deletions(-) diff --git a/cockatrice/src/carddatabasemodel.cpp b/cockatrice/src/carddatabasemodel.cpp index ddddddfe..0abdf70a 100644 --- a/cockatrice/src/carddatabasemodel.cpp +++ b/cockatrice/src/carddatabasemodel.cpp @@ -2,12 +2,12 @@ #include "filtertree.h" CardDatabaseModel::CardDatabaseModel(CardDatabase *_db, QObject *parent) - : QAbstractListModel(parent), db(_db) + : QAbstractListModel(parent), db(_db) { - connect(db, SIGNAL(cardListChanged()), this, SLOT(updateCardList())); - connect(db, SIGNAL(cardAdded(CardInfo *)), this, SLOT(cardAdded(CardInfo *))); - connect(db, SIGNAL(cardRemoved(CardInfo *)), this, SLOT(cardRemoved(CardInfo *))); - updateCardList(); + connect(db, SIGNAL(cardListChanged()), this, SLOT(updateCardList())); + connect(db, SIGNAL(cardAdded(CardInfo *)), this, SLOT(cardAdded(CardInfo *))); + connect(db, SIGNAL(cardRemoved(CardInfo *)), this, SLOT(cardRemoved(CardInfo *))); + updateCardList(); } CardDatabaseModel::~CardDatabaseModel() @@ -16,164 +16,164 @@ CardDatabaseModel::~CardDatabaseModel() int CardDatabaseModel::rowCount(const QModelIndex &/*parent*/) const { - return cardList.size(); + return cardList.size(); } int CardDatabaseModel::columnCount(const QModelIndex &/*parent*/) const { - return 5; + return 5; } QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if ((index.row() >= cardList.size()) || (index.column() >= 5)) - return QVariant(); - if (role != Qt::DisplayRole) - return QVariant(); + if (!index.isValid()) + return QVariant(); + if ((index.row() >= cardList.size()) || (index.column() >= 5)) + return QVariant(); + if (role != Qt::DisplayRole) + return QVariant(); - CardInfo *card = cardList.at(index.row()); - switch (index.column()){ - case 0: return card->getName(); - case 1: { - QStringList setList; - const QList &sets = card->getSets(); - for (int i = 0; i < sets.size(); i++) - setList << sets[i]->getShortName(); - return setList.join(", "); - } - case 2: return card->getManaCost(); - case 3: return card->getCardType(); - case 4: return card->getPowTough(); - default: return QVariant(); - } + CardInfo *card = cardList.at(index.row()); + switch (index.column()){ + case 0: return card->getName(); + case 1: { + QStringList setList; + const QList &sets = card->getSets(); + for (int i = 0; i < sets.size(); i++) + setList << sets[i]->getShortName(); + return setList.join(", "); + } + case 2: return card->getManaCost(); + case 3: return card->getCardType(); + case 4: return card->getPowTough(); + default: return QVariant(); + } } QVariant CardDatabaseModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role != Qt::DisplayRole) - return QVariant(); - if (orientation != Qt::Horizontal) - return QVariant(); - switch (section) { - case 0: return QString(tr("Name")); - case 1: return QString(tr("Sets")); - case 2: return QString(tr("Mana cost")); - case 3: return QString(tr("Card type")); - case 4: return QString(tr("P/T")); - default: return QVariant(); - } + if (role != Qt::DisplayRole) + return QVariant(); + if (orientation != Qt::Horizontal) + return QVariant(); + switch (section) { + case 0: return QString(tr("Name")); + case 1: return QString(tr("Sets")); + case 2: return QString(tr("Mana cost")); + case 3: return QString(tr("Card type")); + case 4: return QString(tr("P/T")); + default: return QVariant(); + } } void CardDatabaseModel::updateCardList() { - for (int i = 0; i < cardList.size(); ++i) - disconnect(cardList[i], 0, this, 0); - - cardList = db->getCardList(); - for (int i = 0; i < cardList.size(); ++i) - connect(cardList[i], SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); - - reset(); + for (int i = 0; i < cardList.size(); ++i) + disconnect(cardList[i], 0, this, 0); + + cardList = db->getCardList(); + for (int i = 0; i < cardList.size(); ++i) + connect(cardList[i], SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); + + reset(); } void CardDatabaseModel::cardInfoChanged(CardInfo *card) { - const int row = cardList.indexOf(card); - if (row == -1) - return; - - emit dataChanged(index(row, 0), index(row, 4)); + const int row = cardList.indexOf(card); + if (row == -1) + return; + + emit dataChanged(index(row, 0), index(row, 4)); } void CardDatabaseModel::cardAdded(CardInfo *card) { - beginInsertRows(QModelIndex(), cardList.size(), cardList.size()); - cardList.append(card); - connect(card, SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); - endInsertRows(); + beginInsertRows(QModelIndex(), cardList.size(), cardList.size()); + cardList.append(card); + connect(card, SIGNAL(cardInfoChanged(CardInfo *)), this, SLOT(cardInfoChanged(CardInfo *))); + endInsertRows(); } void CardDatabaseModel::cardRemoved(CardInfo *card) { - const int row = cardList.indexOf(card); - if (row == -1) - return; - - beginRemoveRows(QModelIndex(), row, row); - cardList.removeAt(row); - endRemoveRows(); + const int row = cardList.indexOf(card); + if (row == -1) + return; + + beginRemoveRows(QModelIndex(), row, row); + cardList.removeAt(row); + endRemoveRows(); } CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) - : QSortFilterProxyModel(parent), - isToken(ShowAll) + : QSortFilterProxyModel(parent), + isToken(ShowAll) { - filterTree = NULL; - setFilterCaseSensitivity(Qt::CaseInsensitive); - setSortCaseSensitivity(Qt::CaseInsensitive); + filterTree = NULL; + setFilterCaseSensitivity(Qt::CaseInsensitive); + setSortCaseSensitivity(Qt::CaseInsensitive); } bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { - CardInfo const *info = static_cast(sourceModel())->getCard(sourceRow); + CardInfo const *info = static_cast(sourceModel())->getCard(sourceRow); - if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken())) - return false; - - if (!cardNameBeginning.isEmpty()) - if (!info->getName().startsWith(cardNameBeginning, Qt::CaseInsensitive)) - return false; - - if (!cardName.isEmpty()) - if (!info->getName().contains(cardName, Qt::CaseInsensitive)) - return false; - - if (!cardNameSet.isEmpty()) - if (!cardNameSet.contains(info->getName())) - return false; - - if (!cardText.isEmpty()) - if (!info->getText().contains(cardText, Qt::CaseInsensitive)) - return false; - - if (!cardColors.isEmpty()) - if (QSet::fromList(info->getColors()).intersect(cardColors).isEmpty() && !(info->getColors().isEmpty() && cardColors.contains("X"))) - return false; - - if (!cardTypes.isEmpty()) - if (!cardTypes.contains(info->getMainCardType())) - return false; + if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken())) + return false; + + if (!cardNameBeginning.isEmpty()) + if (!info->getName().startsWith(cardNameBeginning, Qt::CaseInsensitive)) + return false; + + if (!cardName.isEmpty()) + if (!info->getName().contains(cardName, Qt::CaseInsensitive)) + return false; + + if (!cardNameSet.isEmpty()) + if (!cardNameSet.contains(info->getName())) + return false; + + if (!cardText.isEmpty()) + if (!info->getText().contains(cardText, Qt::CaseInsensitive)) + return false; + + if (!cardColors.isEmpty()) + if (QSet::fromList(info->getColors()).intersect(cardColors).isEmpty() && !(info->getColors().isEmpty() && cardColors.contains("X"))) + return false; + + if (!cardTypes.isEmpty()) + if (!cardTypes.contains(info->getMainCardType())) + return false; - if (filterTree != NULL) - return filterTree->acceptsCard(info); + if (filterTree != NULL) + return filterTree->acceptsCard(info); - return true; + return true; } void CardDatabaseDisplayModel::clearSearch() { - cardName.clear(); - cardText.clear(); - cardTypes.clear(); - cardColors.clear(); - if (filterTree != NULL) - filterTree->clear(); - invalidateFilter(); + cardName.clear(); + cardText.clear(); + cardTypes.clear(); + cardColors.clear(); + if (filterTree != NULL) + filterTree->clear(); + invalidateFilter(); } void CardDatabaseDisplayModel::setFilterTree(FilterTree *filterTree) { - if (this->filterTree != NULL) - disconnect(this->filterTree, 0, this, 0); + if (this->filterTree != NULL) + disconnect(this->filterTree, 0, this, 0); - this->filterTree = filterTree; - connect(this->filterTree, SIGNAL(changed()), this, SLOT(filterTreeChanged())); - invalidate(); + this->filterTree = filterTree; + connect(this->filterTree, SIGNAL(changed()), this, SLOT(filterTreeChanged())); + invalidate(); } void CardDatabaseDisplayModel::filterTreeChanged() { - invalidate(); + invalidate(); } diff --git a/cockatrice/src/carddatabasemodel.h b/cockatrice/src/carddatabasemodel.h index 621eff5a..eb0f5bc2 100644 --- a/cockatrice/src/carddatabasemodel.h +++ b/cockatrice/src/carddatabasemodel.h @@ -10,50 +10,50 @@ class FilterTree; class CardDatabaseModel : public QAbstractListModel { - Q_OBJECT + Q_OBJECT public: - CardDatabaseModel(CardDatabase *_db, QObject *parent = 0); - ~CardDatabaseModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - CardDatabase *getDatabase() const { return db; } - CardInfo *getCard(int index) const { return cardList[index]; } + CardDatabaseModel(CardDatabase *_db, QObject *parent = 0); + ~CardDatabaseModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &parent = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + CardDatabase *getDatabase() const { return db; } + CardInfo *getCard(int index) const { return cardList[index]; } private: - QList cardList; - CardDatabase *db; + QList cardList; + CardDatabase *db; private slots: - void updateCardList(); - void cardAdded(CardInfo *card); - void cardRemoved(CardInfo *card); - void cardInfoChanged(CardInfo *card); + void updateCardList(); + void cardAdded(CardInfo *card); + void cardRemoved(CardInfo *card); + void cardInfoChanged(CardInfo *card); }; class CardDatabaseDisplayModel : public QSortFilterProxyModel { - Q_OBJECT + Q_OBJECT public: - enum FilterBool { ShowTrue, ShowFalse, ShowAll }; + enum FilterBool { ShowTrue, ShowFalse, ShowAll }; private: - FilterBool isToken; - QString cardNameBeginning, cardName, cardText; - QSet cardNameSet, cardTypes, cardColors; - FilterTree *filterTree; + FilterBool isToken; + QString cardNameBeginning, cardName, cardText; + QSet cardNameSet, cardTypes, cardColors; + FilterTree *filterTree; public: - CardDatabaseDisplayModel(QObject *parent = 0); - void setFilterTree(FilterTree *filterTree); - void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } - void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } - void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } - void setCardNameSet(const QSet &_cardNameSet) { cardNameSet = _cardNameSet; invalidate(); } - void setCardText(const QString &_cardText) { cardText = _cardText; invalidate(); } - void setCardTypes(const QSet &_cardTypes) { cardTypes = _cardTypes; invalidate(); } - void setCardColors(const QSet &_cardColors) { cardColors = _cardColors; invalidate(); } - void clearSearch(); + CardDatabaseDisplayModel(QObject *parent = 0); + void setFilterTree(FilterTree *filterTree); + void setIsToken(FilterBool _isToken) { isToken = _isToken; invalidate(); } + void setCardNameBeginning(const QString &_beginning) { cardNameBeginning = _beginning; invalidate(); } + void setCardName(const QString &_cardName) { cardName = _cardName; invalidate(); } + void setCardNameSet(const QSet &_cardNameSet) { cardNameSet = _cardNameSet; invalidate(); } + void setCardText(const QString &_cardText) { cardText = _cardText; invalidate(); } + void setCardTypes(const QSet &_cardTypes) { cardTypes = _cardTypes; invalidate(); } + void setCardColors(const QSet &_cardColors) { cardColors = _cardColors; invalidate(); } + void clearSearch(); protected: - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; private slots: - void filterTreeChanged(); + void filterTreeChanged(); }; #endif diff --git a/cockatrice/src/decklistmodel.cpp b/cockatrice/src/decklistmodel.cpp index 68062ead..e8518046 100644 --- a/cockatrice/src/decklistmodel.cpp +++ b/cockatrice/src/decklistmodel.cpp @@ -14,454 +14,454 @@ #include "deck_loader.h" DeckListModel::DeckListModel(QObject *parent) - : QAbstractItemModel(parent) + : QAbstractItemModel(parent) { - deckList = new DeckLoader; - connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); - connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); - root = new InnerDecklistNode; + deckList = new DeckLoader; + connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); + connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); + root = new InnerDecklistNode; } DeckListModel::~DeckListModel() { - delete root; - delete deckList; + delete root; + delete deckList; } void DeckListModel::rebuildTree() { - root->clearTree(); - InnerDecklistNode *listRoot = deckList->getRoot(); - for (int i = 0; i < listRoot->size(); i++) { - InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); - InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root); - for (int j = 0; j < currentZone->size(); j++) { - DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); - // XXX better sanity checking - if (!currentCard) - continue; + root->clearTree(); + InnerDecklistNode *listRoot = deckList->getRoot(); + for (int i = 0; i < listRoot->size(); i++) { + InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); + InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root); + for (int j = 0; j < currentZone->size(); j++) { + DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); + // XXX better sanity checking + if (!currentCard) + continue; - CardInfo *info = db->getCard(currentCard->getName()); - QString cardType; - if (!info) - cardType = "unknown"; - else - cardType = info->getMainCardType(); - InnerDecklistNode *cardTypeNode = dynamic_cast(node->findChild(cardType)); - if (!cardTypeNode) - cardTypeNode = new InnerDecklistNode(cardType, node); + CardInfo *info = db->getCard(currentCard->getName()); + QString cardType; + if (!info) + cardType = "unknown"; + else + cardType = info->getMainCardType(); + InnerDecklistNode *cardTypeNode = dynamic_cast(node->findChild(cardType)); + if (!cardTypeNode) + cardTypeNode = new InnerDecklistNode(cardType, node); - new DecklistModelCardNode(currentCard, cardTypeNode); - } - } + new DecklistModelCardNode(currentCard, cardTypeNode); + } + } - reset(); + reset(); } int DeckListModel::rowCount(const QModelIndex &parent) const { -// debugIndexInfo("rowCount", parent); - InnerDecklistNode *node = getNode(parent); - if (node) - return node->size(); - else - return 0; +// debugIndexInfo("rowCount", parent); + InnerDecklistNode *node = getNode(parent); + if (node) + return node->size(); + else + return 0; } int DeckListModel::columnCount(const QModelIndex &/*parent*/) const { - if (settingsCache->getPriceTagFeature()) - return 3; - else - return 2; + if (settingsCache->getPriceTagFeature()) + return 3; + else + return 2; } QVariant DeckListModel::data(const QModelIndex &index, int role) const { -// debugIndexInfo("data", index); - if (!index.isValid()) - return QVariant(); +// debugIndexInfo("data", index); + if (!index.isValid()) + return QVariant(); if (index.column() >= columnCount()) - return QVariant(); + return QVariant(); - AbstractDecklistNode *temp = static_cast(index.internalPointer()); - DecklistModelCardNode *card = dynamic_cast(temp); - if (!card) { - InnerDecklistNode *node = dynamic_cast(temp); - switch (role) { - case Qt::FontRole: { - QFont f; - f.setBold(true); - return f; - } - case Qt::DisplayRole: - case Qt::EditRole: - switch (index.column()) { + AbstractDecklistNode *temp = static_cast(index.internalPointer()); + DecklistModelCardNode *card = dynamic_cast(temp); + if (!card) { + InnerDecklistNode *node = dynamic_cast(temp); + switch (role) { + case Qt::FontRole: { + QFont f; + f.setBold(true); + return f; + } + case Qt::DisplayRole: + case Qt::EditRole: + switch (index.column()) { case 0: return node->recursiveCount(true); case 1: return node->getVisibleName(); case 2: return QString().sprintf("$%.2f", node->recursivePrice(true)); - default: return QVariant(); - } - case Qt::BackgroundRole: { - int color = 90 + 60 * node->depth(); - return QBrush(QColor(color, 255, color)); - } - default: return QVariant(); - } - } else { - switch (role) { - case Qt::DisplayRole: - case Qt::EditRole: { - switch (index.column()) { + default: return QVariant(); + } + case Qt::BackgroundRole: { + int color = 90 + 60 * node->depth(); + return QBrush(QColor(color, 255, color)); + } + default: return QVariant(); + } + } else { + switch (role) { + case Qt::DisplayRole: + case Qt::EditRole: { + switch (index.column()) { case 0: return card->getNumber(); case 1: return card->getName(); case 2: return QString().sprintf("$%.2f", card->getTotalPrice()); - default: return QVariant(); - } - } - case Qt::BackgroundRole: { - int color = 255 - (index.row() % 2) * 30; - return QBrush(QColor(color, color, color)); - } - default: return QVariant(); - } - } + default: return QVariant(); + } + } + case Qt::BackgroundRole: { + int color = 255 - (index.row() % 2) * 30; + return QBrush(QColor(color, color, color)); + } + default: return QVariant(); + } + } } QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) - return QVariant(); + if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) + return QVariant(); if (section >= columnCount()) - return QVariant(); - switch (section) { + return QVariant(); + switch (section) { case 0: return tr("Number"); case 1: return tr("Card"); case 2: return tr("Price"); - default: return QVariant(); - } + default: return QVariant(); + } } QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const { -// debugIndexInfo("index", parent); - if (!hasIndex(row, column, parent)) - return QModelIndex(); +// debugIndexInfo("index", parent); + if (!hasIndex(row, column, parent)) + return QModelIndex(); - InnerDecklistNode *parentNode = getNode(parent); - if (row >= parentNode->size()) - return QModelIndex(); + InnerDecklistNode *parentNode = getNode(parent); + if (row >= parentNode->size()) + return QModelIndex(); - return createIndex(row, column, parentNode->at(row)); + return createIndex(row, column, parentNode->at(row)); } QModelIndex DeckListModel::parent(const QModelIndex &ind) const { - if (!ind.isValid()) - return QModelIndex(); + if (!ind.isValid()) + return QModelIndex(); - return nodeToIndex(static_cast(ind.internalPointer())->getParent()); + return nodeToIndex(static_cast(ind.internalPointer())->getParent()); } Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - Qt::ItemFlags result = Qt::ItemIsEnabled; - result |= Qt::ItemIsSelectable; + Qt::ItemFlags result = Qt::ItemIsEnabled; + result |= Qt::ItemIsSelectable; - return result; + return result; } void DeckListModel::emitRecursiveUpdates(const QModelIndex &index) { - if (!index.isValid()) - return; - emit dataChanged(index, index); - emitRecursiveUpdates(index.parent()); + if (!index.isValid()) + return; + emit dataChanged(index, index); + emitRecursiveUpdates(index.parent()); } bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role) { - DecklistModelCardNode *node = getNode(index); - if (!node || (role != Qt::EditRole)) - return false; + DecklistModelCardNode *node = getNode(index); + if (!node || (role != Qt::EditRole)) + return false; - switch (index.column()) { + switch (index.column()) { case 0: node->setNumber(value.toInt()); break; case 1: node->setName(value.toString()); break; case 2: node->setPrice(value.toFloat()); break; - default: return false; - } - emitRecursiveUpdates(index); - deckList->updateDeckHash(); - return true; + default: return false; + } + emitRecursiveUpdates(index); + deckList->updateDeckHash(); + return true; } bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent) { - InnerDecklistNode *node = getNode(parent); - if (!node) - return false; - if (row + count > node->size()) - return false; + InnerDecklistNode *node = getNode(parent); + if (!node) + return false; + if (row + count > node->size()) + return false; - beginRemoveRows(parent, row, row + count - 1); - for (int i = 0; i < count; i++) { - AbstractDecklistNode *toDelete = node->takeAt(row); - if (DecklistModelCardNode *temp = dynamic_cast(toDelete)) - deckList->deleteNode(temp->getDataNode()); - delete toDelete; - } - endRemoveRows(); + beginRemoveRows(parent, row, row + count - 1); + for (int i = 0; i < count; i++) { + AbstractDecklistNode *toDelete = node->takeAt(row); + if (DecklistModelCardNode *temp = dynamic_cast(toDelete)) + deckList->deleteNode(temp->getDataNode()); + delete toDelete; + } + endRemoveRows(); - if (!node->size() && (node != root)) - removeRows(parent.row(), 1, parent.parent()); - else - emitRecursiveUpdates(parent); + if (!node->size() && (node != root)) + removeRows(parent.row(), 1, parent.parent()); + else + emitRecursiveUpdates(parent); - return true; + return true; } InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent) { - InnerDecklistNode *newNode = dynamic_cast(parent->findChild(name)); - if (!newNode) { - beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); - newNode = new InnerDecklistNode(name, parent); - endInsertRows(); - } - return newNode; + InnerDecklistNode *newNode = dynamic_cast(parent->findChild(name)); + if (!newNode) { + beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); + newNode = new InnerDecklistNode(name, parent); + endInsertRows(); + } + return newNode; } DecklistModelCardNode *DeckListModel::findCardNode(const QString &cardName, const QString &zoneName) const { - InnerDecklistNode *zoneNode, *typeNode; - CardInfo *info; - QString cardType; + InnerDecklistNode *zoneNode, *typeNode; + CardInfo *info; + QString cardType; - zoneNode = dynamic_cast(root->findChild(zoneName)); - if(!zoneNode) - return NULL; + zoneNode = dynamic_cast(root->findChild(zoneName)); + if(!zoneNode) + return NULL; - info = db->getCard(cardName); - if(!info) - return NULL; + info = db->getCard(cardName); + if(!info) + return NULL; - cardType = info->getMainCardType(); - typeNode = dynamic_cast(zoneNode->findChild(cardType)); - if(!typeNode) - return NULL; + cardType = info->getMainCardType(); + typeNode = dynamic_cast(zoneNode->findChild(cardType)); + if(!typeNode) + return NULL; - return dynamic_cast(typeNode->findChild(cardName)); + return dynamic_cast(typeNode->findChild(cardName)); } QModelIndex DeckListModel::findCard(const QString &cardName, const QString &zoneName) const { - DecklistModelCardNode *cardNode; + DecklistModelCardNode *cardNode; - cardNode = findCardNode(cardName, zoneName); - if(!cardNode) - return QModelIndex(); - return nodeToIndex(cardNode); + cardNode = findCardNode(cardName, zoneName); + if(!cardNode) + return QModelIndex(); + return nodeToIndex(cardNode); } QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName) { - InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root); + InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root); - CardInfo *info = db->getCard(cardName); - QString cardType = info->getMainCardType(); - InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode); + CardInfo *info = db->getCard(cardName); + QString cardType = info->getMainCardType(); + InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode); - DecklistModelCardNode *cardNode = dynamic_cast(cardTypeNode->findChild(cardName)); - if (!cardNode) { - DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName); - QModelIndex parentIndex = nodeToIndex(cardTypeNode); - beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size()); - cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode); - endInsertRows(); - sort(1); - emitRecursiveUpdates(parentIndex); - return nodeToIndex(cardNode); - } else { - cardNode->setNumber(cardNode->getNumber() + 1); - QModelIndex ind = nodeToIndex(cardNode); - emitRecursiveUpdates(ind); - deckList->updateDeckHash(); - return ind; - } + DecklistModelCardNode *cardNode = dynamic_cast(cardTypeNode->findChild(cardName)); + if (!cardNode) { + DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName); + QModelIndex parentIndex = nodeToIndex(cardTypeNode); + beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size()); + cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode); + endInsertRows(); + sort(1); + emitRecursiveUpdates(parentIndex); + return nodeToIndex(cardNode); + } else { + cardNode->setNumber(cardNode->getNumber() + 1); + QModelIndex ind = nodeToIndex(cardNode); + emitRecursiveUpdates(ind); + deckList->updateDeckHash(); + return ind; + } } QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const { - if (node == root) - return QModelIndex(); - return createIndex(node->getParent()->indexOf(node), 0, node); + if (node == root) + return QModelIndex(); + return createIndex(node->getParent()->indexOf(node), 0, node); } void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order) { - // Sort children of node and save the information needed to - // update the list of persistent indexes. - QVector > sortResult = node->sort(order); - - QModelIndexList from, to; - for (int i = sortResult.size() - 1; i >= 0; --i) { - const int fromRow = sortResult[i].first; - const int toRow = sortResult[i].second; - AbstractDecklistNode *temp = node->at(toRow); - for (int j = columnCount(); j; --j) { - from << createIndex(fromRow, 0, temp); - to << createIndex(toRow, 0, temp); - } - } - changePersistentIndexList(from, to); - - // Recursion - for (int i = node->size() - 1; i >= 0; --i) { - InnerDecklistNode *subNode = dynamic_cast(node->at(i)); - if (subNode) - sortHelper(subNode, order); - } + // Sort children of node and save the information needed to + // update the list of persistent indexes. + QVector > sortResult = node->sort(order); + + QModelIndexList from, to; + for (int i = sortResult.size() - 1; i >= 0; --i) { + const int fromRow = sortResult[i].first; + const int toRow = sortResult[i].second; + AbstractDecklistNode *temp = node->at(toRow); + for (int j = columnCount(); j; --j) { + from << createIndex(fromRow, 0, temp); + to << createIndex(toRow, 0, temp); + } + } + changePersistentIndexList(from, to); + + // Recursion + for (int i = node->size() - 1; i >= 0; --i) { + InnerDecklistNode *subNode = dynamic_cast(node->at(i)); + if (subNode) + sortHelper(subNode, order); + } } void DeckListModel::sort(int /*column*/, Qt::SortOrder order) { - emit layoutAboutToBeChanged(); - sortHelper(root, order); - emit layoutChanged(); + emit layoutAboutToBeChanged(); + sortHelper(root, order); + emit layoutChanged(); } void DeckListModel::cleanList() { - setDeckList(new DeckLoader); + setDeckList(new DeckLoader); } void DeckListModel::setDeckList(DeckLoader *_deck) { - delete deckList; - deckList = _deck; - connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); - connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); - rebuildTree(); + delete deckList; + deckList = _deck; + connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); + connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); + rebuildTree(); } void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node) { - const int totalColumns = settingsCache->getPriceTagFeature() ? 3 : 2; + const int totalColumns = settingsCache->getPriceTagFeature() ? 3 : 2; - if (node->height() == 1) { - QTextBlockFormat blockFormat; - QTextCharFormat charFormat; - charFormat.setFontPointSize(11); - charFormat.setFontWeight(QFont::Bold); - cursor->insertBlock(blockFormat, charFormat); - QString priceStr; - if (settingsCache->getPriceTagFeature()) - priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); + if (node->height() == 1) { + QTextBlockFormat blockFormat; + QTextCharFormat charFormat; + charFormat.setFontPointSize(11); + charFormat.setFontWeight(QFont::Bold); + cursor->insertBlock(blockFormat, charFormat); + QString priceStr; + if (settingsCache->getPriceTagFeature()) + priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr)); - QTextTableFormat tableFormat; - tableFormat.setCellPadding(0); - tableFormat.setCellSpacing(0); - tableFormat.setBorder(0); + QTextTableFormat tableFormat; + tableFormat.setCellPadding(0); + tableFormat.setCellSpacing(0); + tableFormat.setBorder(0); QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); - for (int i = 0; i < node->size(); i++) { - AbstractDecklistCardNode *card = dynamic_cast(node->at(i)); + for (int i = 0; i < node->size(); i++) { + AbstractDecklistCardNode *card = dynamic_cast(node->at(i)); - QTextCharFormat cellCharFormat; - cellCharFormat.setFontPointSize(9); + QTextCharFormat cellCharFormat; + cellCharFormat.setFontPointSize(9); - QTextTableCell cell = table->cellAt(i, 0); - cell.setFormat(cellCharFormat); - QTextCursor cellCursor = cell.firstCursorPosition(); - cellCursor.insertText(QString("%1 ").arg(card->getNumber())); + QTextTableCell cell = table->cellAt(i, 0); + cell.setFormat(cellCharFormat); + QTextCursor cellCursor = cell.firstCursorPosition(); + cellCursor.insertText(QString("%1 ").arg(card->getNumber())); - cell = table->cellAt(i, 1); - cell.setFormat(cellCharFormat); - cellCursor = cell.firstCursorPosition(); - cellCursor.insertText(card->getName()); + cell = table->cellAt(i, 1); + cell.setFormat(cellCharFormat); + cellCursor = cell.firstCursorPosition(); + cellCursor.insertText(card->getName()); - if (settingsCache->getPriceTagFeature()) { - cell = table->cellAt(i, 2); - cell.setFormat(cellCharFormat); - cellCursor = cell.firstCursorPosition(); - cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice())); - } - } - } else if (node->height() == 2) { - QTextBlockFormat blockFormat; - QTextCharFormat charFormat; - charFormat.setFontPointSize(14); - charFormat.setFontWeight(QFont::Bold); + if (settingsCache->getPriceTagFeature()) { + cell = table->cellAt(i, 2); + cell.setFormat(cellCharFormat); + cellCursor = cell.firstCursorPosition(); + cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice())); + } + } + } else if (node->height() == 2) { + QTextBlockFormat blockFormat; + QTextCharFormat charFormat; + charFormat.setFontPointSize(14); + charFormat.setFontWeight(QFont::Bold); - cursor->insertBlock(blockFormat, charFormat); - QString priceStr; - if (settingsCache->getPriceTagFeature()) - priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); + cursor->insertBlock(blockFormat, charFormat); + QString priceStr; + if (settingsCache->getPriceTagFeature()) + priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr)); - QTextTableFormat tableFormat; - tableFormat.setCellPadding(10); - tableFormat.setCellSpacing(0); - tableFormat.setBorder(0); - QVector constraints; - for (int i = 0; i < totalColumns; i++) - constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns); - tableFormat.setColumnWidthConstraints(constraints); + QTextTableFormat tableFormat; + tableFormat.setCellPadding(10); + tableFormat.setCellSpacing(0); + tableFormat.setBorder(0); + QVector constraints; + for (int i = 0; i < totalColumns; i++) + constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns); + tableFormat.setColumnWidthConstraints(constraints); - QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); - for (int i = 0; i < node->size(); i++) { - QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); - printDeckListNode(&cellCursor, dynamic_cast(node->at(i))); - } - } - cursor->movePosition(QTextCursor::End); + QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); + for (int i = 0; i < node->size(); i++) { + QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); + printDeckListNode(&cellCursor, dynamic_cast(node->at(i))); + } + } + cursor->movePosition(QTextCursor::End); } void DeckListModel::printDeckList(QPrinter *printer) { - QTextDocument doc; + QTextDocument doc; - QFont font("Serif"); - font.setStyleHint(QFont::Serif); - doc.setDefaultFont(font); + QFont font("Serif"); + font.setStyleHint(QFont::Serif); + doc.setDefaultFont(font); - QTextCursor cursor(&doc); + QTextCursor cursor(&doc); - QTextBlockFormat headerBlockFormat; - QTextCharFormat headerCharFormat; - headerCharFormat.setFontPointSize(16); - headerCharFormat.setFontWeight(QFont::Bold); + QTextBlockFormat headerBlockFormat; + QTextCharFormat headerCharFormat; + headerCharFormat.setFontPointSize(16); + headerCharFormat.setFontWeight(QFont::Bold); - cursor.insertBlock(headerBlockFormat, headerCharFormat); - cursor.insertText(deckList->getName()); + cursor.insertBlock(headerBlockFormat, headerCharFormat); + cursor.insertText(deckList->getName()); - headerCharFormat.setFontPointSize(12); - cursor.insertBlock(headerBlockFormat, headerCharFormat); - cursor.insertText(deckList->getComments()); - cursor.insertBlock(headerBlockFormat, headerCharFormat); + headerCharFormat.setFontPointSize(12); + cursor.insertBlock(headerBlockFormat, headerCharFormat); + cursor.insertText(deckList->getComments()); + cursor.insertBlock(headerBlockFormat, headerCharFormat); - for (int i = 0; i < root->size(); i++) { - cursor.insertHtml("
"); - //cursor.insertHtml("
"); - cursor.insertBlock(headerBlockFormat, headerCharFormat); + for (int i = 0; i < root->size(); i++) { + cursor.insertHtml("
"); + //cursor.insertHtml("
"); + cursor.insertBlock(headerBlockFormat, headerCharFormat); - printDeckListNode(&cursor, dynamic_cast(root->at(i))); - } + printDeckListNode(&cursor, dynamic_cast(root->at(i))); + } - doc.print(printer); + doc.print(printer); } void DeckListModel::pricesUpdated(InnerDecklistNode *node) { - if (!node) - node = root; - - if (node->isEmpty()) - return; - - emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last())); + if (!node) + node = root; + + if (node->isEmpty()) + return; + + emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last())); } diff --git a/cockatrice/src/decklistmodel.h b/cockatrice/src/decklistmodel.h index 43c8e2a3..3ef47642 100644 --- a/cockatrice/src/decklistmodel.h +++ b/cockatrice/src/decklistmodel.h @@ -13,63 +13,63 @@ class QTextCursor; class DecklistModelCardNode : public AbstractDecklistCardNode { private: - DecklistCardNode *dataNode; + DecklistCardNode *dataNode; public: - DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { } - int getNumber() const { return dataNode->getNumber(); } - void setNumber(int _number) { dataNode->setNumber(_number); } + DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { } + int getNumber() const { return dataNode->getNumber(); } + void setNumber(int _number) { dataNode->setNumber(_number); } float getPrice() const { return dataNode->getPrice(); } void setPrice(float _price) { dataNode->setPrice(_price); } - QString getName() const { return dataNode->getName(); } - void setName(const QString &_name) { dataNode->setName(_name); } - DecklistCardNode *getDataNode() const { return dataNode; } + QString getName() const { return dataNode->getName(); } + void setName(const QString &_name) { dataNode->setName(_name); } + DecklistCardNode *getDataNode() const { return dataNode; } }; class DeckListModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT private slots: - void rebuildTree(); + void rebuildTree(); public slots: - void printDeckList(QPrinter *printer); + void printDeckList(QPrinter *printer); signals: - void deckHashChanged(); + void deckHashChanged(); public: - DeckListModel(QObject *parent = 0); - ~DeckListModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; + DeckListModel(QObject *parent = 0); + ~DeckListModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + bool setData(const QModelIndex &index, const QVariant &value, int role); + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - QModelIndex findCard(const QString &cardName, const QString &zoneName) const; - QModelIndex addCard(const QString &cardName, const QString &zoneName); - void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); - void cleanList(); - DeckLoader *getDeckList() const { return deckList; } - void setDeckList(DeckLoader *_deck); - void pricesUpdated(InnerDecklistNode *node = 0); + QModelIndex findCard(const QString &cardName, const QString &zoneName) const; + QModelIndex addCard(const QString &cardName, const QString &zoneName); + void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); + void cleanList(); + DeckLoader *getDeckList() const { return deckList; } + void setDeckList(DeckLoader *_deck); + void pricesUpdated(InnerDecklistNode *node = 0); private: - DeckLoader *deckList; - InnerDecklistNode *root; - InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent); - QModelIndex nodeToIndex(AbstractDecklistNode *node) const; - DecklistModelCardNode *findCardNode(const QString &cardName, const QString &zoneName) const; - void emitRecursiveUpdates(const QModelIndex &index); - void sortHelper(InnerDecklistNode *node, Qt::SortOrder order); + DeckLoader *deckList; + InnerDecklistNode *root; + InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent); + QModelIndex nodeToIndex(AbstractDecklistNode *node) const; + DecklistModelCardNode *findCardNode(const QString &cardName, const QString &zoneName) const; + void emitRecursiveUpdates(const QModelIndex &index); + void sortHelper(InnerDecklistNode *node, Qt::SortOrder order); - void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node); + void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node); - template T getNode(const QModelIndex &index) const - { - if (!index.isValid()) - return dynamic_cast(root); - return dynamic_cast(static_cast(index.internalPointer())); - } + template T getNode(const QModelIndex &index) const + { + if (!index.isValid()) + return dynamic_cast(root); + return dynamic_cast(static_cast(index.internalPointer())); + } }; #endif diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 75d6312b..ee5c240c 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -39,665 +39,665 @@ void SearchLineEdit::keyPressEvent(QKeyEvent *event) { - if (treeView && ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down))) - QCoreApplication::sendEvent(treeView, event); - QLineEdit::keyPressEvent(event); + if (treeView && ((event->key() == Qt::Key_Up) || (event->key() == Qt::Key_Down))) + QCoreApplication::sendEvent(treeView, event); + QLineEdit::keyPressEvent(event); } TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) - : Tab(_tabSupervisor, parent), modified(false) + : Tab(_tabSupervisor, parent), modified(false) { - aClearSearch = new QAction(QString(), this); - aClearSearch->setIcon(QIcon(":/resources/icon_clearsearch.svg")); - connect(aClearSearch, SIGNAL(triggered()), this, SLOT(actClearSearch())); + aClearSearch = new QAction(QString(), this); + aClearSearch->setIcon(QIcon(":/resources/icon_clearsearch.svg")); + connect(aClearSearch, SIGNAL(triggered()), this, SLOT(actClearSearch())); - searchLabel = new QLabel(); - searchEdit = new SearchLineEdit; - searchLabel->setBuddy(searchEdit); - searchKeySignals.filterDelete(false); - searchEdit->installEventFilter(&searchKeySignals); - connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); - connect(&searchKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); - connect(&searchKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); - connect(&searchKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); - connect(&searchKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); - connect(&searchKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); - connect(&searchKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); + searchLabel = new QLabel(); + searchEdit = new SearchLineEdit; + searchLabel->setBuddy(searchEdit); + searchKeySignals.filterDelete(false); + searchEdit->installEventFilter(&searchKeySignals); + connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); + connect(&searchKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); + connect(&searchKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); + connect(&searchKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); + connect(&searchKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); + connect(&searchKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); + connect(&searchKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); - QToolBar *deckEditToolBar = new QToolBar; - deckEditToolBar->setOrientation(Qt::Horizontal); - deckEditToolBar->setIconSize(QSize(24, 24)); + QToolBar *deckEditToolBar = new QToolBar; + deckEditToolBar->setOrientation(Qt::Horizontal); + deckEditToolBar->setIconSize(QSize(24, 24)); - QHBoxLayout *searchLayout = new QHBoxLayout; - searchLayout->addWidget(deckEditToolBar); - searchLayout->addWidget(searchLabel); - searchLayout->addWidget(searchEdit); + QHBoxLayout *searchLayout = new QHBoxLayout; + searchLayout->addWidget(deckEditToolBar); + searchLayout->addWidget(searchLabel); + searchLayout->addWidget(searchEdit); - databaseModel = new CardDatabaseModel(db, this); - databaseDisplayModel = new CardDatabaseDisplayModel(this); - databaseDisplayModel->setSourceModel(databaseModel); - databaseDisplayModel->setFilterKeyColumn(0); - databaseDisplayModel->sort(0, Qt::AscendingOrder); + databaseModel = new CardDatabaseModel(db, this); + databaseDisplayModel = new CardDatabaseDisplayModel(this); + databaseDisplayModel->setSourceModel(databaseModel); + databaseDisplayModel->setFilterKeyColumn(0); + databaseDisplayModel->sort(0, Qt::AscendingOrder); - databaseView = new QTreeView(); - databaseView->setModel(databaseDisplayModel); - databaseView->setUniformRowHeights(true); - databaseView->setRootIsDecorated(false); - databaseView->setAlternatingRowColors(true); - databaseView->setSortingEnabled(true); - databaseView->sortByColumn(0, Qt::AscendingOrder); - databaseView->resizeColumnToContents(0); - 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())); - databaseView->installEventFilter(&dbViewKeySignals); - connect(&dbViewKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); - connect(&dbViewKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); - connect(&dbViewKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); - connect(&dbViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); - connect(&dbViewKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); - connect(&dbViewKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); + databaseView = new QTreeView(); + databaseView->setModel(databaseDisplayModel); + databaseView->setUniformRowHeights(true); + databaseView->setRootIsDecorated(false); + databaseView->setAlternatingRowColors(true); + databaseView->setSortingEnabled(true); + databaseView->sortByColumn(0, Qt::AscendingOrder); + databaseView->resizeColumnToContents(0); + 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())); + databaseView->installEventFilter(&dbViewKeySignals); + connect(&dbViewKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); + connect(&dbViewKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); + connect(&dbViewKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); + connect(&dbViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); + connect(&dbViewKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); + connect(&dbViewKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); - searchEdit->setTreeView(databaseView); + searchEdit->setTreeView(databaseView); - QVBoxLayout *leftFrame = new QVBoxLayout; - leftFrame->addLayout(searchLayout); - leftFrame->addWidget(databaseView); + QVBoxLayout *leftFrame = new QVBoxLayout; + leftFrame->addLayout(searchLayout); + leftFrame->addWidget(databaseView); - cardInfo = new CardFrame(250, 356); - aCardTextOnly = new QAction(QString(), this); - aCardTextOnly->setCheckable(true); - connect(aCardTextOnly, SIGNAL(triggered()), cardInfo, SLOT(toggleCardTextOnly())); + cardInfo = new CardFrame(250, 356); + aCardTextOnly = new QAction(QString(), this); + aCardTextOnly->setCheckable(true); + connect(aCardTextOnly, SIGNAL(triggered()), cardInfo, SLOT(toggleCardTextOnly())); - filterModel = new FilterTreeModel(); - databaseDisplayModel->setFilterTree(filterModel->filterTree()); - filterView = new QTreeView; - filterView->setModel(filterModel); - filterView->setMaximumWidth(250); - filterView->setUniformRowHeights(true); - filterView->setHeaderHidden(true); - filterView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(filterModel, SIGNAL(layoutChanged()), filterView, SLOT(expandAll())); - connect(filterView, SIGNAL(customContextMenuRequested(const QPoint &)), - this, SLOT(filterViewCustomContextMenu(const QPoint &))); - FilterBuilder *filterBuilder = new FilterBuilder; - filterBuilder->setMaximumWidth(250); - connect(filterBuilder, SIGNAL(add(const CardFilter *)), filterModel, SLOT(addFilter(const CardFilter *))); + filterModel = new FilterTreeModel(); + databaseDisplayModel->setFilterTree(filterModel->filterTree()); + filterView = new QTreeView; + filterView->setModel(filterModel); + filterView->setMaximumWidth(250); + filterView->setUniformRowHeights(true); + filterView->setHeaderHidden(true); + filterView->setContextMenuPolicy(Qt::CustomContextMenu); + connect(filterModel, SIGNAL(layoutChanged()), filterView, SLOT(expandAll())); + connect(filterView, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(filterViewCustomContextMenu(const QPoint &))); + FilterBuilder *filterBuilder = new FilterBuilder; + filterBuilder->setMaximumWidth(250); + connect(filterBuilder, SIGNAL(add(const CardFilter *)), filterModel, SLOT(addFilter(const CardFilter *))); - QVBoxLayout *filter = new QVBoxLayout; - filter->addWidget(filterBuilder, 0, Qt::AlignTop); - filter->addWidget(filterView, 10); + QVBoxLayout *filter = new QVBoxLayout; + filter->addWidget(filterBuilder, 0, Qt::AlignTop); + filter->addWidget(filterView, 10); - QVBoxLayout *middleFrame = new QVBoxLayout; - middleFrame->addWidget(cardInfo, 0, Qt::AlignTop); - middleFrame->addLayout(filter, 10); + QVBoxLayout *middleFrame = new QVBoxLayout; + middleFrame->addWidget(cardInfo, 0, Qt::AlignTop); + middleFrame->addLayout(filter, 10); - deckModel = new DeckListModel(this); - connect(deckModel, SIGNAL(deckHashChanged()), this, SLOT(updateHash())); - deckView = new QTreeView(); - deckView->setModel(deckModel); - deckView->setUniformRowHeights(true); - deckView->header()->setResizeMode(QHeaderView::ResizeToContents); - deckViewKeySignals.filterLeftRight(false); - deckView->installEventFilter(&deckViewKeySignals); - connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); - connect(&deckViewKeySignals, SIGNAL(onEnter()), this, SLOT(actIncrement())); - connect(&deckViewKeySignals, SIGNAL(onRight()), this, SLOT(actIncrement())); - connect(&deckViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrement())); - connect(&deckViewKeySignals, SIGNAL(onDelete()), this, SLOT(actRemoveCard())); + deckModel = new DeckListModel(this); + connect(deckModel, SIGNAL(deckHashChanged()), this, SLOT(updateHash())); + deckView = new QTreeView(); + deckView->setModel(deckModel); + deckView->setUniformRowHeights(true); + deckView->header()->setResizeMode(QHeaderView::ResizeToContents); + deckViewKeySignals.filterLeftRight(false); + deckView->installEventFilter(&deckViewKeySignals); + connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); + connect(&deckViewKeySignals, SIGNAL(onEnter()), this, SLOT(actIncrement())); + connect(&deckViewKeySignals, SIGNAL(onRight()), this, SLOT(actIncrement())); + connect(&deckViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrement())); + connect(&deckViewKeySignals, SIGNAL(onDelete()), this, SLOT(actRemoveCard())); - nameLabel = new QLabel(); - nameEdit = new QLineEdit; - nameLabel->setBuddy(nameEdit); - connect(nameEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateName(const QString &))); - commentsLabel = new QLabel(); - commentsEdit = new QTextEdit; - commentsEdit->setMaximumHeight(70); - commentsLabel->setBuddy(commentsEdit); - connect(commentsEdit, SIGNAL(textChanged()), this, SLOT(updateComments())); - hashLabel1 = new QLabel(); - hashLabel = new QLabel; + nameLabel = new QLabel(); + nameEdit = new QLineEdit; + nameLabel->setBuddy(nameEdit); + connect(nameEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateName(const QString &))); + commentsLabel = new QLabel(); + commentsEdit = new QTextEdit; + commentsEdit->setMaximumHeight(70); + commentsLabel->setBuddy(commentsEdit); + connect(commentsEdit, SIGNAL(textChanged()), this, SLOT(updateComments())); + hashLabel1 = new QLabel(); + hashLabel = new QLabel; - QGridLayout *grid = new QGridLayout; - grid->addWidget(nameLabel, 0, 0); - grid->addWidget(nameEdit, 0, 1); + QGridLayout *grid = new QGridLayout; + grid->addWidget(nameLabel, 0, 0); + grid->addWidget(nameEdit, 0, 1); - grid->addWidget(commentsLabel, 1, 0); - grid->addWidget(commentsEdit, 1, 1); + grid->addWidget(commentsLabel, 1, 0); + grid->addWidget(commentsEdit, 1, 1); - grid->addWidget(hashLabel1, 2, 0); - grid->addWidget(hashLabel, 2, 1); + grid->addWidget(hashLabel1, 2, 0); + grid->addWidget(hashLabel, 2, 1); - // Update price - aUpdatePrices = new QAction(QString(), this); - aUpdatePrices->setIcon(QIcon(":/resources/icon_update.png")); - connect(aUpdatePrices, SIGNAL(triggered()), this, SLOT(actUpdatePrices())); - if (!settingsCache->getPriceTagFeature()) - aUpdatePrices->setVisible(false); + // Update price + aUpdatePrices = new QAction(QString(), this); + aUpdatePrices->setIcon(QIcon(":/resources/icon_update.png")); + connect(aUpdatePrices, SIGNAL(triggered()), this, SLOT(actUpdatePrices())); + if (!settingsCache->getPriceTagFeature()) + aUpdatePrices->setVisible(false); - QToolBar *deckToolBar = new QToolBar; - deckToolBar->setOrientation(Qt::Vertical); - deckToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - deckToolBar->setIconSize(QSize(24, 24)); - deckToolBar->addAction(aUpdatePrices); - QHBoxLayout *deckToolbarLayout = new QHBoxLayout; - deckToolbarLayout->addStretch(); - deckToolbarLayout->addWidget(deckToolBar); - deckToolbarLayout->addStretch(); - - QVBoxLayout *rightFrame = new QVBoxLayout; - rightFrame->addLayout(grid); - rightFrame->addWidget(deckView, 10); - rightFrame->addLayout(deckToolbarLayout); + QToolBar *deckToolBar = new QToolBar; + deckToolBar->setOrientation(Qt::Vertical); + deckToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + deckToolBar->setIconSize(QSize(24, 24)); + deckToolBar->addAction(aUpdatePrices); + QHBoxLayout *deckToolbarLayout = new QHBoxLayout; + deckToolbarLayout->addStretch(); + deckToolbarLayout->addWidget(deckToolBar); + deckToolbarLayout->addStretch(); + + QVBoxLayout *rightFrame = new QVBoxLayout; + rightFrame->addLayout(grid); + rightFrame->addWidget(deckView, 10); + rightFrame->addLayout(deckToolbarLayout); - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addLayout(leftFrame, 10); - mainLayout->addLayout(middleFrame); - mainLayout->addLayout(rightFrame); - setLayout(mainLayout); - - aNewDeck = new QAction(QString(), this); - aNewDeck->setShortcuts(QKeySequence::New); - connect(aNewDeck, SIGNAL(triggered()), this, SLOT(actNewDeck())); - aLoadDeck = new QAction(QString(), this); - aLoadDeck->setShortcuts(QKeySequence::Open); - connect(aLoadDeck, SIGNAL(triggered()), this, SLOT(actLoadDeck())); - aSaveDeck = new QAction(QString(), this); - aSaveDeck->setShortcuts(QKeySequence::Save); - connect(aSaveDeck, SIGNAL(triggered()), this, SLOT(actSaveDeck())); - aSaveDeckAs = new QAction(QString(), this); -// aSaveDeckAs->setShortcuts(QKeySequence::SaveAs); - connect(aSaveDeckAs, SIGNAL(triggered()), this, SLOT(actSaveDeckAs())); - aLoadDeckFromClipboard = new QAction(QString(), this); - connect(aLoadDeckFromClipboard, SIGNAL(triggered()), this, SLOT(actLoadDeckFromClipboard())); - aLoadDeckFromClipboard->setShortcuts(QKeySequence::Paste); - aSaveDeckToClipboard = new QAction(QString(), this); - connect(aSaveDeckToClipboard, SIGNAL(triggered()), this, SLOT(actSaveDeckToClipboard())); - aSaveDeckToClipboard->setShortcuts(QKeySequence::Copy); - aPrintDeck = new QAction(QString(), this); - aPrintDeck->setShortcuts(QKeySequence::Print); - connect(aPrintDeck, SIGNAL(triggered()), this, SLOT(actPrintDeck())); - aAnalyzeDeck = new QAction(QString(), this); - connect(aAnalyzeDeck, SIGNAL(triggered()), this, SLOT(actAnalyzeDeck())); - aClose = new QAction(QString(), this); - connect(aClose, SIGNAL(triggered()), this, SLOT(closeRequest())); + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addLayout(leftFrame, 10); + mainLayout->addLayout(middleFrame); + mainLayout->addLayout(rightFrame); + setLayout(mainLayout); + + aNewDeck = new QAction(QString(), this); + aNewDeck->setShortcuts(QKeySequence::New); + connect(aNewDeck, SIGNAL(triggered()), this, SLOT(actNewDeck())); + aLoadDeck = new QAction(QString(), this); + aLoadDeck->setShortcuts(QKeySequence::Open); + connect(aLoadDeck, SIGNAL(triggered()), this, SLOT(actLoadDeck())); + aSaveDeck = new QAction(QString(), this); + aSaveDeck->setShortcuts(QKeySequence::Save); + connect(aSaveDeck, SIGNAL(triggered()), this, SLOT(actSaveDeck())); + aSaveDeckAs = new QAction(QString(), this); +// aSaveDeckAs->setShortcuts(QKeySequence::SaveAs); + connect(aSaveDeckAs, SIGNAL(triggered()), this, SLOT(actSaveDeckAs())); + aLoadDeckFromClipboard = new QAction(QString(), this); + connect(aLoadDeckFromClipboard, SIGNAL(triggered()), this, SLOT(actLoadDeckFromClipboard())); + aLoadDeckFromClipboard->setShortcuts(QKeySequence::Paste); + aSaveDeckToClipboard = new QAction(QString(), this); + connect(aSaveDeckToClipboard, SIGNAL(triggered()), this, SLOT(actSaveDeckToClipboard())); + aSaveDeckToClipboard->setShortcuts(QKeySequence::Copy); + aPrintDeck = new QAction(QString(), this); + aPrintDeck->setShortcuts(QKeySequence::Print); + connect(aPrintDeck, SIGNAL(triggered()), this, SLOT(actPrintDeck())); + aAnalyzeDeck = new QAction(QString(), this); + connect(aAnalyzeDeck, SIGNAL(triggered()), this, SLOT(actAnalyzeDeck())); + aClose = new QAction(QString(), this); + connect(aClose, SIGNAL(triggered()), this, SLOT(closeRequest())); - aEditSets = new QAction(QString(), this); - connect(aEditSets, SIGNAL(triggered()), this, SLOT(actEditSets())); - aEditTokens = new QAction(QString(), this); - connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens())); + aEditSets = new QAction(QString(), this); + connect(aEditSets, SIGNAL(triggered()), this, SLOT(actEditSets())); + aEditTokens = new QAction(QString(), this); + connect(aEditTokens, SIGNAL(triggered()), this, SLOT(actEditTokens())); - deckMenu = new QMenu(this); - deckMenu->addAction(aNewDeck); - deckMenu->addAction(aLoadDeck); - deckMenu->addAction(aSaveDeck); - deckMenu->addAction(aSaveDeckAs); - deckMenu->addSeparator(); - deckMenu->addAction(aLoadDeckFromClipboard); - deckMenu->addAction(aSaveDeckToClipboard); - deckMenu->addSeparator(); - deckMenu->addAction(aPrintDeck); - deckMenu->addSeparator(); - deckMenu->addAction(aAnalyzeDeck); - deckMenu->addSeparator(); - deckMenu->addAction(aClose); - addTabMenu(deckMenu); + deckMenu = new QMenu(this); + deckMenu->addAction(aNewDeck); + deckMenu->addAction(aLoadDeck); + deckMenu->addAction(aSaveDeck); + deckMenu->addAction(aSaveDeckAs); + deckMenu->addSeparator(); + deckMenu->addAction(aLoadDeckFromClipboard); + deckMenu->addAction(aSaveDeckToClipboard); + deckMenu->addSeparator(); + deckMenu->addAction(aPrintDeck); + deckMenu->addSeparator(); + deckMenu->addAction(aAnalyzeDeck); + deckMenu->addSeparator(); + deckMenu->addAction(aClose); + addTabMenu(deckMenu); - dbMenu = new QMenu(this); - dbMenu->addAction(aEditSets); - dbMenu->addAction(aEditTokens); - dbMenu->addSeparator(); - dbMenu->addAction(aClearSearch); - dbMenu->addAction(aCardTextOnly); - addTabMenu(dbMenu); + dbMenu = new QMenu(this); + dbMenu->addAction(aEditSets); + dbMenu->addAction(aEditTokens); + dbMenu->addSeparator(); + dbMenu->addAction(aClearSearch); + dbMenu->addAction(aCardTextOnly); + addTabMenu(dbMenu); - aAddCard = new QAction(QString(), this); - aAddCard->setIcon(QIcon(":/resources/arrow_right_green.svg")); - connect(aAddCard, SIGNAL(triggered()), this, SLOT(actAddCard())); - aAddCardToSideboard = new QAction(QString(), this); - aAddCardToSideboard->setIcon(QIcon(":/resources/add_to_sideboard.svg")); - connect(aAddCardToSideboard, SIGNAL(triggered()), this, SLOT(actAddCardToSideboard())); - aRemoveCard = new QAction(QString(), this); - aRemoveCard->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aRemoveCard, SIGNAL(triggered()), this, SLOT(actRemoveCard())); - aIncrement = new QAction(QString(), this); - aIncrement->setIcon(QIcon(":/resources/increment.svg")); - connect(aIncrement, SIGNAL(triggered()), this, SLOT(actIncrement())); - aDecrement = new QAction(QString(), this); - aDecrement->setIcon(QIcon(":/resources/decrement.svg")); - connect(aDecrement, SIGNAL(triggered()), this, SLOT(actDecrement())); + aAddCard = new QAction(QString(), this); + aAddCard->setIcon(QIcon(":/resources/arrow_right_green.svg")); + connect(aAddCard, SIGNAL(triggered()), this, SLOT(actAddCard())); + aAddCardToSideboard = new QAction(QString(), this); + aAddCardToSideboard->setIcon(QIcon(":/resources/add_to_sideboard.svg")); + connect(aAddCardToSideboard, SIGNAL(triggered()), this, SLOT(actAddCardToSideboard())); + aRemoveCard = new QAction(QString(), this); + aRemoveCard->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aRemoveCard, SIGNAL(triggered()), this, SLOT(actRemoveCard())); + aIncrement = new QAction(QString(), this); + aIncrement->setIcon(QIcon(":/resources/increment.svg")); + connect(aIncrement, SIGNAL(triggered()), this, SLOT(actIncrement())); + aDecrement = new QAction(QString(), this); + aDecrement->setIcon(QIcon(":/resources/decrement.svg")); + connect(aDecrement, SIGNAL(triggered()), this, SLOT(actDecrement())); - deckEditToolBar->addAction(aAddCard); - deckEditToolBar->addAction(aAddCardToSideboard); - deckEditToolBar->addAction(aRemoveCard); - deckEditToolBar->addAction(aIncrement); - deckEditToolBar->addAction(aDecrement); - deckEditToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - - retranslateUi(); - - resize(950, 700); + deckEditToolBar->addAction(aAddCard); + deckEditToolBar->addAction(aAddCardToSideboard); + deckEditToolBar->addAction(aRemoveCard); + deckEditToolBar->addAction(aIncrement); + deckEditToolBar->addAction(aDecrement); + deckEditToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + + retranslateUi(); + + resize(950, 700); } TabDeckEditor::~TabDeckEditor() { - emit deckEditorClosing(this); + emit deckEditorClosing(this); } void TabDeckEditor::retranslateUi() { - aCardTextOnly->setText(tr("Show card text only")); - aClearSearch->setText(tr("&Clear search")); - searchLabel->setText(tr("&Search for:")); - - nameLabel->setText(tr("Deck &name:")); - commentsLabel->setText(tr("&Comments:")); - hashLabel1->setText(tr("Hash:")); - - aUpdatePrices->setText(tr("&Update prices")); - aUpdatePrices->setShortcut(tr("Ctrl+U")); + aCardTextOnly->setText(tr("Show card text only")); + aClearSearch->setText(tr("&Clear search")); + searchLabel->setText(tr("&Search for:")); + + nameLabel->setText(tr("Deck &name:")); + commentsLabel->setText(tr("&Comments:")); + hashLabel1->setText(tr("Hash:")); + + aUpdatePrices->setText(tr("&Update prices")); + aUpdatePrices->setShortcut(tr("Ctrl+U")); - aNewDeck->setText(tr("&New deck")); - aLoadDeck->setText(tr("&Load deck...")); - aSaveDeck->setText(tr("&Save deck")); - aSaveDeckAs->setText(tr("Save deck &as...")); - aLoadDeckFromClipboard->setText(tr("Load deck from cl&ipboard...")); - aSaveDeckToClipboard->setText(tr("Save deck to clip&board")); - aPrintDeck->setText(tr("&Print deck...")); - aAnalyzeDeck->setText(tr("&Analyze deck on deckstats.net")); - aClose->setText(tr("&Close")); - aClose->setShortcut(tr("Ctrl+Q")); - - aAddCard->setText(tr("Add card to &maindeck")); - aAddCardToSideboard->setText(tr("Add card to &sideboard")); + aNewDeck->setText(tr("&New deck")); + aLoadDeck->setText(tr("&Load deck...")); + aSaveDeck->setText(tr("&Save deck")); + aSaveDeckAs->setText(tr("Save deck &as...")); + aLoadDeckFromClipboard->setText(tr("Load deck from cl&ipboard...")); + aSaveDeckToClipboard->setText(tr("Save deck to clip&board")); + aPrintDeck->setText(tr("&Print deck...")); + aAnalyzeDeck->setText(tr("&Analyze deck on deckstats.net")); + aClose->setText(tr("&Close")); + aClose->setShortcut(tr("Ctrl+Q")); + + aAddCard->setText(tr("Add card to &maindeck")); + aAddCardToSideboard->setText(tr("Add card to &sideboard")); - aRemoveCard->setText(tr("&Remove row")); - aRemoveCard->setShortcut(tr("Del")); - aIncrement->setText(tr("&Increment number")); - aIncrement->setShortcut(tr("+")); - aDecrement->setText(tr("&Decrement number")); - aDecrement->setShortcut(tr("-")); - - deckMenu->setTitle(tr("&Deck editor")); - dbMenu->setTitle(tr("C&ard database")); - - aEditSets->setText(tr("&Edit sets...")); - aEditTokens->setText(tr("Edit &tokens...")); + aRemoveCard->setText(tr("&Remove row")); + aRemoveCard->setShortcut(tr("Del")); + aIncrement->setText(tr("&Increment number")); + aIncrement->setShortcut(tr("+")); + aDecrement->setText(tr("&Decrement number")); + aDecrement->setShortcut(tr("-")); + + deckMenu->setTitle(tr("&Deck editor")); + dbMenu->setTitle(tr("C&ard database")); + + aEditSets->setText(tr("&Edit sets...")); + aEditTokens->setText(tr("Edit &tokens...")); } QString TabDeckEditor::getTabText() const { - QString result = tr("Deck: %1").arg(nameEdit->text()); - if (modified) - result.prepend("* "); - return result; + QString result = tr("Deck: %1").arg(nameEdit->text()); + if (modified) + result.prepend("* "); + return result; } void TabDeckEditor::updateName(const QString &name) { - deckModel->getDeckList()->setName(name); - setModified(true); + deckModel->getDeckList()->setName(name); + setModified(true); } void TabDeckEditor::updateComments() { - deckModel->getDeckList()->setComments(commentsEdit->toPlainText()); - setModified(true); + deckModel->getDeckList()->setComments(commentsEdit->toPlainText()); + setModified(true); } void TabDeckEditor::updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &/*previous*/) { - cardInfo->setCard(current.sibling(current.row(), 0).data().toString()); + cardInfo->setCard(current.sibling(current.row(), 0).data().toString()); } void TabDeckEditor::updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &/*previous*/) { - if (!current.isValid()) - return; - if (!current.model()->hasChildren(current.sibling(current.row(), 0))) - cardInfo->setCard(current.sibling(current.row(), 1).data().toString()); + if (!current.isValid()) + return; + if (!current.model()->hasChildren(current.sibling(current.row(), 0))) + cardInfo->setCard(current.sibling(current.row(), 1).data().toString()); } void TabDeckEditor::updateSearch(const QString &search) { - databaseDisplayModel->setCardNameBeginning(search); - QModelIndexList sel = databaseView->selectionModel()->selectedRows(); - if (sel.isEmpty() && databaseDisplayModel->rowCount()) - databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); + databaseDisplayModel->setCardNameBeginning(search); + QModelIndexList sel = databaseView->selectionModel()->selectedRows(); + if (sel.isEmpty() && databaseDisplayModel->rowCount()) + databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } void TabDeckEditor::updateHash() { - hashLabel->setText(deckModel->getDeckList()->getDeckHash()); + hashLabel->setText(deckModel->getDeckList()->getDeckHash()); } bool TabDeckEditor::confirmClose() { - if (modified) { - QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Are you sure?"), - tr("The decklist has been modified.\nDo you want to save the changes?"), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); - if (ret == QMessageBox::Save) - return actSaveDeck(); - else if (ret == QMessageBox::Cancel) - return false; - } - return true; + if (modified) { + QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("Are you sure?"), + tr("The decklist has been modified.\nDo you want to save the changes?"), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + if (ret == QMessageBox::Save) + return actSaveDeck(); + else if (ret == QMessageBox::Cancel) + return false; + } + return true; } void TabDeckEditor::closeRequest() { - if (confirmClose()) - deleteLater(); + if (confirmClose()) + deleteLater(); } void TabDeckEditor::actNewDeck() { - if (!confirmClose()) - return; + if (!confirmClose()) + return; - deckModel->cleanList(); - nameEdit->setText(QString()); - commentsEdit->setText(QString()); - hashLabel->setText(QString()); - setModified(false); + deckModel->cleanList(); + nameEdit->setText(QString()); + commentsEdit->setText(QString()); + hashLabel->setText(QString()); + setModified(false); } void TabDeckEditor::actLoadDeck() { - if (!confirmClose()) - return; + if (!confirmClose()) + return; - QFileDialog dialog(this, tr("Load deck")); - dialog.setDirectory(settingsCache->getDeckPath()); - dialog.setNameFilters(DeckLoader::fileNameFilters); - if (!dialog.exec()) - return; + QFileDialog dialog(this, tr("Load deck")); + dialog.setDirectory(settingsCache->getDeckPath()); + dialog.setNameFilters(DeckLoader::fileNameFilters); + if (!dialog.exec()) + return; - QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); - - DeckLoader *l = new DeckLoader; - if (l->loadFromFile(fileName, fmt)) - setDeck(l); - else - delete l; + QString fileName = dialog.selectedFiles().at(0); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); + + DeckLoader *l = new DeckLoader; + if (l->loadFromFile(fileName, fmt)) + setDeck(l); + else + delete l; } void TabDeckEditor::saveDeckRemoteFinished(const Response &response) { - if (response.response_code() != Response::RespOk) - QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.")); - else - setModified(false); + if (response.response_code() != Response::RespOk) + QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.")); + else + setModified(false); } bool TabDeckEditor::actSaveDeck() { - DeckLoader *const deck = deckModel->getDeckList(); - if (deck->getLastRemoteDeckId() != -1) { - Command_DeckUpload cmd; - cmd.set_deck_id(deck->getLastRemoteDeckId()); - cmd.set_deck_list(deck->writeToString_Native().toStdString()); - - PendingCommand *pend = AbstractClient::prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(saveDeckRemoteFinished(Response))); - tabSupervisor->getClient()->sendCommand(pend); - - return true; - } else if (deck->getLastFileName().isEmpty()) - return actSaveDeckAs(); - else if (deck->saveToFile(deck->getLastFileName(), deck->getLastFileFormat())) { - setModified(false); - return true; - } - QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); - return false; + DeckLoader *const deck = deckModel->getDeckList(); + if (deck->getLastRemoteDeckId() != -1) { + Command_DeckUpload cmd; + cmd.set_deck_id(deck->getLastRemoteDeckId()); + cmd.set_deck_list(deck->writeToString_Native().toStdString()); + + PendingCommand *pend = AbstractClient::prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(saveDeckRemoteFinished(Response))); + tabSupervisor->getClient()->sendCommand(pend); + + return true; + } else if (deck->getLastFileName().isEmpty()) + return actSaveDeckAs(); + else if (deck->saveToFile(deck->getLastFileName(), deck->getLastFileFormat())) { + setModified(false); + return true; + } + QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); + return false; } bool TabDeckEditor::actSaveDeckAs() { - QFileDialog dialog(this, tr("Save deck")); - dialog.setDirectory(settingsCache->getDeckPath()); - dialog.setAcceptMode(QFileDialog::AcceptSave); - dialog.setConfirmOverwrite(true); - dialog.setDefaultSuffix("cod"); - dialog.setNameFilters(DeckLoader::fileNameFilters); - dialog.selectFile(deckModel->getDeckList()->getName()); - if (!dialog.exec()) - return false; + QFileDialog dialog(this, tr("Save deck")); + dialog.setDirectory(settingsCache->getDeckPath()); + dialog.setAcceptMode(QFileDialog::AcceptSave); + dialog.setConfirmOverwrite(true); + dialog.setDefaultSuffix("cod"); + dialog.setNameFilters(DeckLoader::fileNameFilters); + dialog.selectFile(deckModel->getDeckList()->getName()); + if (!dialog.exec()) + return false; - QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); + QString fileName = dialog.selectedFiles().at(0); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); - if (!deckModel->getDeckList()->saveToFile(fileName, fmt)) { - QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); - return false; - } - setModified(false); - return true; + if (!deckModel->getDeckList()->saveToFile(fileName, fmt)) { + QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); + return false; + } + setModified(false); + return true; } void TabDeckEditor::actLoadDeckFromClipboard() { - if (!confirmClose()) - return; - - DlgLoadDeckFromClipboard dlg; - if (!dlg.exec()) - return; - - setDeck(dlg.getDeckList()); - setModified(true); + if (!confirmClose()) + return; + + DlgLoadDeckFromClipboard dlg; + if (!dlg.exec()) + return; + + setDeck(dlg.getDeckList()); + setModified(true); } void TabDeckEditor::actSaveDeckToClipboard() { - QString buffer; - QTextStream stream(&buffer); - deckModel->getDeckList()->saveToStream_Plain(stream); - QApplication::clipboard()->setText(buffer, QClipboard::Clipboard); - QApplication::clipboard()->setText(buffer, QClipboard::Selection); + QString buffer; + QTextStream stream(&buffer); + deckModel->getDeckList()->saveToStream_Plain(stream); + QApplication::clipboard()->setText(buffer, QClipboard::Clipboard); + QApplication::clipboard()->setText(buffer, QClipboard::Selection); } void TabDeckEditor::actPrintDeck() { - QPrintPreviewDialog *dlg = new QPrintPreviewDialog(this); - connect(dlg, SIGNAL(paintRequested(QPrinter *)), deckModel, SLOT(printDeckList(QPrinter *))); - dlg->exec(); + QPrintPreviewDialog *dlg = new QPrintPreviewDialog(this); + connect(dlg, SIGNAL(paintRequested(QPrinter *)), deckModel, SLOT(printDeckList(QPrinter *))); + dlg->exec(); } void TabDeckEditor::actAnalyzeDeck() { - DeckStatsInterface *interface = new DeckStatsInterface(this); // it deletes itself when done - interface->analyzeDeck(deckModel->getDeckList()); + DeckStatsInterface *interface = new DeckStatsInterface(this); // it deletes itself when done + interface->analyzeDeck(deckModel->getDeckList()); } void TabDeckEditor::actEditSets() { - WndSets *w = new WndSets; - w->setWindowModality(Qt::WindowModal); - w->show(); + WndSets *w = new WndSets; + w->setWindowModality(Qt::WindowModal); + w->show(); } void TabDeckEditor::actEditTokens() { - DlgEditTokens dlg(databaseModel); - dlg.exec(); - db->saveToFile(settingsCache->getTokenDatabasePath(), true); + DlgEditTokens dlg(databaseModel); + dlg.exec(); + db->saveToFile(settingsCache->getTokenDatabasePath(), true); } void TabDeckEditor::actClearSearch() { - databaseDisplayModel->clearSearch(); + databaseDisplayModel->clearSearch(); } void TabDeckEditor::recursiveExpand(const QModelIndex &index) { - if (index.parent().isValid()) - recursiveExpand(index.parent()); - deckView->expand(index); + if (index.parent().isValid()) + recursiveExpand(index.parent()); + deckView->expand(index); } CardInfo *TabDeckEditor::currentCardInfo() const { - const QModelIndex currentIndex = databaseView->selectionModel()->currentIndex(); - if (!currentIndex.isValid()) - return NULL; - const QString cardName = currentIndex.sibling(currentIndex.row(), 0).data().toString(); - - return db->getCard(cardName); + const QModelIndex currentIndex = databaseView->selectionModel()->currentIndex(); + if (!currentIndex.isValid()) + return NULL; + const QString cardName = currentIndex.sibling(currentIndex.row(), 0).data().toString(); + + return db->getCard(cardName); } void TabDeckEditor::addCardHelper(QString zoneName) { - const CardInfo *info; + const CardInfo *info; - info = currentCardInfo(); - if(!info) - return; - if (info->getIsToken()) - zoneName = "tokens"; + info = currentCardInfo(); + if(!info) + return; + if (info->getIsToken()) + zoneName = "tokens"; - QModelIndex newCardIndex = deckModel->addCard(info->getName(), zoneName); - recursiveExpand(newCardIndex); - deckView->setCurrentIndex(newCardIndex); + QModelIndex newCardIndex = deckModel->addCard(info->getName(), zoneName); + recursiveExpand(newCardIndex); + deckView->setCurrentIndex(newCardIndex); - setModified(true); + setModified(true); } void TabDeckEditor::actAddCard() { - addCardHelper("main"); + addCardHelper("main"); } void TabDeckEditor::actAddCardToSideboard() { - addCardHelper("side"); + addCardHelper("side"); } void TabDeckEditor::actRemoveCard() { - const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - if (!currentIndex.isValid() || deckModel->hasChildren(currentIndex)) - return; - deckModel->removeRow(currentIndex.row(), currentIndex.parent()); - setModified(true); + const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); + if (!currentIndex.isValid() || deckModel->hasChildren(currentIndex)) + return; + deckModel->removeRow(currentIndex.row(), currentIndex.parent()); + setModified(true); } void TabDeckEditor::offsetCountAtIndex(const QModelIndex &idx, int offset) { - if (!idx.isValid() || offset == 0) - return; + if (!idx.isValid() || offset == 0) + return; - const QModelIndex numberIndex = idx.sibling(idx.row(), 0); - const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); - const int new_count = count + offset; - deckView->setCurrentIndex(numberIndex); - if (new_count <= 0) - deckModel->removeRow(idx.row(), idx.parent()); - else - deckModel->setData(numberIndex, new_count, Qt::EditRole); - setModified(true); + const QModelIndex numberIndex = idx.sibling(idx.row(), 0); + const int count = deckModel->data(numberIndex, Qt::EditRole).toInt(); + const int new_count = count + offset; + deckView->setCurrentIndex(numberIndex); + if (new_count <= 0) + deckModel->removeRow(idx.row(), idx.parent()); + else + deckModel->setData(numberIndex, new_count, Qt::EditRole); + setModified(true); } void TabDeckEditor::decrementCardHelper(QString zoneName) { - const CardInfo *info; - QModelIndex idx; + const CardInfo *info; + QModelIndex idx; - info = currentCardInfo(); - if(!info) - return; - if (info->getIsToken()) - zoneName = "tokens"; + info = currentCardInfo(); + if(!info) + return; + if (info->getIsToken()) + zoneName = "tokens"; - idx = deckModel->findCard(info->getName(), zoneName); - offsetCountAtIndex(idx, -1); + idx = deckModel->findCard(info->getName(), zoneName); + offsetCountAtIndex(idx, -1); } void TabDeckEditor::actDecrementCard() { - decrementCardHelper("main"); + decrementCardHelper("main"); } void TabDeckEditor::actDecrementCardFromSideboard() { - decrementCardHelper("side"); + decrementCardHelper("side"); } void TabDeckEditor::actIncrement() { - const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - offsetCountAtIndex(currentIndex, 1); + const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); + offsetCountAtIndex(currentIndex, 1); } void TabDeckEditor::actDecrement() { - const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); - offsetCountAtIndex(currentIndex, -1); + const QModelIndex ¤tIndex = deckView->selectionModel()->currentIndex(); + offsetCountAtIndex(currentIndex, -1); } void TabDeckEditor::actUpdatePrices() { - aUpdatePrices->setDisabled(true); - PriceUpdater *up = new PriceUpdater(deckModel->getDeckList()); - connect(up, SIGNAL(finishedUpdate()), this, SLOT(finishedUpdatingPrices())); - up->updatePrices(); + aUpdatePrices->setDisabled(true); + PriceUpdater *up = new PriceUpdater(deckModel->getDeckList()); + connect(up, SIGNAL(finishedUpdate()), this, SLOT(finishedUpdatingPrices())); + up->updatePrices(); } void TabDeckEditor::finishedUpdatingPrices() { - deckModel->pricesUpdated(); - setModified(true); - aUpdatePrices->setDisabled(false); + deckModel->pricesUpdated(); + setModified(true); + aUpdatePrices->setDisabled(false); } void TabDeckEditor::setDeck(DeckLoader *_deck) { - deckModel->setDeckList(_deck); + deckModel->setDeckList(_deck); - nameEdit->setText(deckModel->getDeckList()->getName()); - commentsEdit->setText(deckModel->getDeckList()->getComments()); - updateHash(); - deckModel->sort(1); - deckView->expandAll(); - setModified(false); - - db->cacheCardPixmaps(deckModel->getDeckList()->getCardList()); - deckView->expandAll(); - setModified(false); + nameEdit->setText(deckModel->getDeckList()->getName()); + commentsEdit->setText(deckModel->getDeckList()->getComments()); + updateHash(); + deckModel->sort(1); + deckView->expandAll(); + setModified(false); + + db->cacheCardPixmaps(deckModel->getDeckList()->getCardList()); + deckView->expandAll(); + setModified(false); } void TabDeckEditor::setModified(bool _modified) { - modified = _modified; - emit tabTextChanged(this, getTabText()); + modified = _modified; + emit tabTextChanged(this, getTabText()); } void TabDeckEditor::filterViewCustomContextMenu(const QPoint &point) { - QMenu menu; - QAction *action; - QModelIndex idx; + QMenu menu; + QAction *action; + QModelIndex idx; - idx = filterView->indexAt(point); - if (!idx.isValid()) - return; + idx = filterView->indexAt(point); + if (!idx.isValid()) + return; - action = menu.addAction(QString("delete")); - action->setData(point); - connect(&menu, SIGNAL(triggered(QAction *)), - this, SLOT(filterRemove(QAction *))); - menu.exec(filterView->mapToGlobal(point)); + action = menu.addAction(QString("delete")); + action->setData(point); + connect(&menu, SIGNAL(triggered(QAction *)), + this, SLOT(filterRemove(QAction *))); + menu.exec(filterView->mapToGlobal(point)); } void TabDeckEditor::filterRemove(QAction *action) { - QPoint point; - QModelIndex idx; + QPoint point; + QModelIndex idx; - point = action->data().toPoint(); - idx = filterView->indexAt(point); - if (!idx.isValid()) - return; + point = action->data().toPoint(); + idx = filterView->indexAt(point); + if (!idx.isValid()) + return; - filterModel->removeRow(idx.row(), idx.parent()); + filterModel->removeRow(idx.row(), idx.parent()); } diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 8dde3e58..349f28eb 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -20,98 +20,98 @@ class FilterTreeModel; class CardInfo; class SearchLineEdit : public QLineEdit { - private: - QTreeView *treeView; - protected: - void keyPressEvent(QKeyEvent *event); - public: - SearchLineEdit() : QLineEdit(), treeView(0) { } - void setTreeView(QTreeView *_treeView) { treeView = _treeView; } + private: + QTreeView *treeView; + protected: + void keyPressEvent(QKeyEvent *event); + public: + SearchLineEdit() : QLineEdit(), treeView(0) { } + void setTreeView(QTreeView *_treeView) { treeView = _treeView; } }; class TabDeckEditor : public Tab { - Q_OBJECT + Q_OBJECT private slots: - void updateName(const QString &name); - void updateComments(); - void updateHash(); - void updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &previous); - void updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &previous); - void updateSearch(const QString &search); + void updateName(const QString &name); + void updateComments(); + void updateHash(); + void updateCardInfoLeft(const QModelIndex ¤t, const QModelIndex &previous); + void updateCardInfoRight(const QModelIndex ¤t, const QModelIndex &previous); + void updateSearch(const QString &search); - void actNewDeck(); - void actLoadDeck(); - bool actSaveDeck(); - bool actSaveDeckAs(); - void actLoadDeckFromClipboard(); - void actSaveDeckToClipboard(); - void actPrintDeck(); - void actAnalyzeDeck(); + void actNewDeck(); + void actLoadDeck(); + bool actSaveDeck(); + bool actSaveDeckAs(); + void actLoadDeckFromClipboard(); + void actSaveDeckToClipboard(); + void actPrintDeck(); + void actAnalyzeDeck(); - void actEditSets(); - void actEditTokens(); - - void actClearSearch(); + void actEditSets(); + void actEditTokens(); + + void actClearSearch(); - void actAddCard(); - void actAddCardToSideboard(); - void actRemoveCard(); - void actIncrement(); - void actDecrement(); - void actDecrementCard(); - void actDecrementCardFromSideboard(); + void actAddCard(); + void actAddCardToSideboard(); + void actRemoveCard(); + void actIncrement(); + void actDecrement(); + void actDecrementCard(); + void actDecrementCardFromSideboard(); void actUpdatePrices(); void finishedUpdatingPrices(); - void saveDeckRemoteFinished(const Response &r); - void filterViewCustomContextMenu(const QPoint &point); - void filterRemove(QAction *action); + void saveDeckRemoteFinished(const Response &r); + void filterViewCustomContextMenu(const QPoint &point); + void filterRemove(QAction *action); private: - CardInfo *currentCardInfo() const; - void addCardHelper(QString zoneName); - void offsetCountAtIndex(const QModelIndex &idx, int offset); - void decrementCardHelper(QString zoneName); - void recursiveExpand(const QModelIndex &index); - bool confirmClose(); + CardInfo *currentCardInfo() const; + void addCardHelper(QString zoneName); + void offsetCountAtIndex(const QModelIndex &idx, int offset); + void decrementCardHelper(QString zoneName); + void recursiveExpand(const QModelIndex &index); + bool confirmClose(); - CardDatabaseModel *databaseModel; - CardDatabaseDisplayModel *databaseDisplayModel; - DeckListModel *deckModel; - QTreeView *databaseView; - KeySignals dbViewKeySignals; - QTreeView *deckView; - KeySignals deckViewKeySignals; - CardFrame *cardInfo; - QLabel *searchLabel; - SearchLineEdit *searchEdit; - KeySignals searchKeySignals; - QLabel *nameLabel; - QLineEdit *nameEdit; - QLabel *commentsLabel; - QTextEdit *commentsEdit; - QLabel *hashLabel1; - QLabel *hashLabel; - FilterTreeModel *filterModel; - QTreeView *filterView; + CardDatabaseModel *databaseModel; + CardDatabaseDisplayModel *databaseDisplayModel; + DeckListModel *deckModel; + QTreeView *databaseView; + KeySignals dbViewKeySignals; + QTreeView *deckView; + KeySignals deckViewKeySignals; + CardFrame *cardInfo; + QLabel *searchLabel; + SearchLineEdit *searchEdit; + KeySignals searchKeySignals; + QLabel *nameLabel; + QLineEdit *nameEdit; + QLabel *commentsLabel; + QTextEdit *commentsEdit; + QLabel *hashLabel1; + QLabel *hashLabel; + FilterTreeModel *filterModel; + QTreeView *filterView; - QMenu *deckMenu, *dbMenu; - QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; - QAction *aEditSets, *aEditTokens, *aClearSearch, *aCardTextOnly; + QMenu *deckMenu, *dbMenu; + QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; + QAction *aEditSets, *aEditTokens, *aClearSearch, *aCardTextOnly; QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement, *aUpdatePrices; - - bool modified; + + bool modified; public: - TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent = 0); - ~TabDeckEditor(); - void retranslateUi(); - QString getTabText() const; - void setDeck(DeckLoader *_deckLoader); - void setModified(bool _windowModified); + TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent = 0); + ~TabDeckEditor(); + void retranslateUi(); + QString getTabText() const; + void setDeck(DeckLoader *_deckLoader); + void setModified(bool _windowModified); public slots: - void closeRequest(); + void closeRequest(); signals: - void deckEditorClosing(TabDeckEditor *tab); + void deckEditorClosing(TabDeckEditor *tab); }; #endif From cd4d04be3ee9533a01fec58d2d3e7bacc7f6ba34 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Tue, 25 Mar 2014 02:28:42 +0000 Subject: [PATCH 25/55] change tabs into 4 spaces in new files --- cockatrice/src/cardfilter.cpp | 56 ++--- cockatrice/src/cardfilter.h | 56 ++--- cockatrice/src/cardframe.cpp | 56 ++--- cockatrice/src/cardframe.h | 28 +-- cockatrice/src/cardinfopicture.cpp | 56 ++--- cockatrice/src/cardinfopicture.h | 18 +- cockatrice/src/cardinfotext.cpp | 88 ++++---- cockatrice/src/cardinfotext.h | 22 +- cockatrice/src/filterbuilder.cpp | 94 ++++---- cockatrice/src/filterbuilder.h | 18 +- cockatrice/src/filtertree.cpp | 340 ++++++++++++++--------------- cockatrice/src/filtertree.h | 204 ++++++++--------- cockatrice/src/filtertreemodel.cpp | 328 ++++++++++++++-------------- cockatrice/src/filtertreemodel.h | 44 ++-- cockatrice/src/keysignals.cpp | 76 +++---- cockatrice/src/keysignals.h | 34 +-- 16 files changed, 759 insertions(+), 759 deletions(-) diff --git a/cockatrice/src/cardfilter.cpp b/cockatrice/src/cardfilter.cpp index 38017377..fb59adcf 100644 --- a/cockatrice/src/cardfilter.cpp +++ b/cockatrice/src/cardfilter.cpp @@ -2,36 +2,36 @@ const char *CardFilter::typeName(Type t) { - switch (t) { - case TypeAnd: - return "and"; - case TypeOr: - return "or"; - case TypeAndNot: - return "and not"; - case TypeOrNot: - return "or not"; - default: - return ""; - } + switch (t) { + case TypeAnd: + return "and"; + case TypeOr: + return "or"; + case TypeAndNot: + return "and not"; + case TypeOrNot: + return "or not"; + default: + return ""; + } } const char *CardFilter::attrName(Attr a) { - switch (a) { - case AttrName: - return "name"; - case AttrType: - return "type"; - case AttrColor: - return "color"; - case AttrText: - return "text"; - case AttrSet: - return "set"; - case AttrManaCost: - return "mana cost"; - default: - return ""; - } + switch (a) { + case AttrName: + return "name"; + case AttrType: + return "type"; + case AttrColor: + return "color"; + case AttrText: + return "text"; + case AttrSet: + return "set"; + case AttrManaCost: + return "mana cost"; + default: + return ""; + } } diff --git a/cockatrice/src/cardfilter.h b/cockatrice/src/cardfilter.h index 539cdb0c..47a85ea6 100644 --- a/cockatrice/src/cardfilter.h +++ b/cockatrice/src/cardfilter.h @@ -5,40 +5,40 @@ class CardFilter { public: - enum Type { - TypeAnd = 0, - TypeOr, - TypeAndNot, - TypeOrNot, - TypeEnd - }; + enum Type { + TypeAnd = 0, + TypeOr, + TypeAndNot, + TypeOrNot, + TypeEnd + }; - /* if you add an atribute here you also need to - * add its string representation in attrName */ - enum Attr { - AttrName = 0, - AttrType, - AttrColor, - AttrText, - AttrSet, - AttrManaCost, - AttrEnd - }; + /* if you add an atribute here you also need to + * add its string representation in attrName */ + enum Attr { + AttrName = 0, + AttrType, + AttrColor, + AttrText, + AttrSet, + AttrManaCost, + AttrEnd + }; private: - enum Type t; - enum Attr a; - QString trm; - + enum Type t; + enum Attr a; + QString trm; + public: - CardFilter(QString term, Type type, Attr attr) : trm(term), t(type), a(attr) {}; + CardFilter(QString term, Type type, Attr attr) : trm(term), t(type), a(attr) {}; - Type type() const { return t; } - const QString &term() const { return trm; } - Attr attr() const { return a; } + Type type() const { return t; } + const QString &term() const { return trm; } + Attr attr() const { return a; } - static const char *typeName(Type t); - static const char *attrName(Attr a); + static const char *typeName(Type t); + static const char *attrName(Attr a); }; #endif diff --git a/cockatrice/src/cardframe.cpp b/cockatrice/src/cardframe.cpp index 89b3cb6b..2ec2b42c 100644 --- a/cockatrice/src/cardframe.cpp +++ b/cockatrice/src/cardframe.cpp @@ -7,53 +7,53 @@ #include "cardinfotext.h" CardFrame::CardFrame(int width, int height, - const QString &cardName, QWidget *parent) - : QStackedWidget(parent) - , info(0) - , cardTextOnly(false) + const QString &cardName, QWidget *parent) + : QStackedWidget(parent) + , info(0) + , cardTextOnly(false) { - setFrameStyle(QFrame::Panel | QFrame::Raised); - setMaximumWidth(width); - setMinimumWidth(width); - setMaximumHeight(height); - setMinimumHeight(height); - pic = new CardInfoPicture(width); - addWidget(pic); - text = new CardInfoText(); - addWidget(text); - connect(pic, SIGNAL(hasPictureChanged()), this, SLOT(hasPictureChanged())); - setCard(db->getCard(cardName)); + setFrameStyle(QFrame::Panel | QFrame::Raised); + setMaximumWidth(width); + setMinimumWidth(width); + setMaximumHeight(height); + setMinimumHeight(height); + pic = new CardInfoPicture(width); + addWidget(pic); + text = new CardInfoText(); + addWidget(text); + connect(pic, SIGNAL(hasPictureChanged()), this, SLOT(hasPictureChanged())); + setCard(db->getCard(cardName)); } void CardFrame::setCard(CardInfo *card) { - if (info) - disconnect(info, 0, this, 0); - info = card; - connect(info, SIGNAL(destroyed()), this, SLOT(clear())); - text->setCard(info); - pic->setCard(info); + if (info) + disconnect(info, 0, this, 0); + info = card; + connect(info, SIGNAL(destroyed()), this, SLOT(clear())); + text->setCard(info); + pic->setCard(info); } void CardFrame::setCard(const QString &cardName) { - setCard(db->getCard(cardName)); + setCard(db->getCard(cardName)); } void CardFrame::setCard(AbstractCardItem *card) { - setCard(card->getInfo()); + setCard(card->getInfo()); } void CardFrame::clear() { - setCard(db->getCard()); + setCard(db->getCard()); } void CardFrame::hasPictureChanged() { - if (pic->hasPicture() && !cardTextOnly) - setCurrentWidget(pic); - else - setCurrentWidget(text); + if (pic->hasPicture() && !cardTextOnly) + setCurrentWidget(pic); + else + setCurrentWidget(text); } diff --git a/cockatrice/src/cardframe.h b/cockatrice/src/cardframe.h index c241c51a..d75ce45a 100644 --- a/cockatrice/src/cardframe.h +++ b/cockatrice/src/cardframe.h @@ -9,28 +9,28 @@ class CardInfoPicture; class CardInfoText; class CardFrame : public QStackedWidget { - Q_OBJECT + Q_OBJECT private: - CardInfo *info; - CardInfoPicture *pic; - CardInfoText *text; - bool cardTextOnly; + CardInfo *info; + CardInfoPicture *pic; + CardInfoText *text; + bool cardTextOnly; public: - CardFrame(int width, int height, const QString &cardName = QString(), - QWidget *parent = 0); - void setCardTextOnly(bool status) { cardTextOnly = status; hasPictureChanged(); } + CardFrame(int width, int height, const QString &cardName = QString(), + QWidget *parent = 0); + void setCardTextOnly(bool status) { cardTextOnly = status; hasPictureChanged(); } public slots: - void setCard(CardInfo *card); - void setCard(const QString &cardName); - void setCard(AbstractCardItem *card); - void clear(); + void setCard(CardInfo *card); + void setCard(const QString &cardName); + void setCard(AbstractCardItem *card); + void clear(); private slots: - void hasPictureChanged(); - void toggleCardTextOnly() { setCardTextOnly(!cardTextOnly); } + void hasPictureChanged(); + void toggleCardTextOnly() { setCardTextOnly(!cardTextOnly); } }; #endif diff --git a/cockatrice/src/cardinfopicture.cpp b/cockatrice/src/cardinfopicture.cpp index 7a7d6195..8b560958 100644 --- a/cockatrice/src/cardinfopicture.cpp +++ b/cockatrice/src/cardinfopicture.cpp @@ -6,48 +6,48 @@ #include "main.h" CardInfoPicture::CardInfoPicture(int maximumWidth, QWidget *parent) - : QLabel(parent) - , info(0) - , noPicture(true) + : QLabel(parent) + , info(0) + , noPicture(true) { - setMaximumWidth(maximumWidth); + setMaximumWidth(maximumWidth); } void CardInfoPicture::setNoPicture(bool status) { - if (noPicture != status) { - noPicture = status; - emit hasPictureChanged(); - } + if (noPicture != status) { + noPicture = status; + emit hasPictureChanged(); + } } void CardInfoPicture::setCard(CardInfo *card) { - if (info) - disconnect(info, 0, this, 0); - info = card; - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); + if (info) + disconnect(info, 0, this, 0); + info = card; + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); - updatePixmap(); + updatePixmap(); } void CardInfoPicture::updatePixmap() { - qreal aspectRatio = (qreal) CARD_HEIGHT / (qreal) CARD_WIDTH; - qreal pixmapWidth = this->width(); + qreal aspectRatio = (qreal) CARD_HEIGHT / (qreal) CARD_WIDTH; + qreal pixmapWidth = this->width(); - if (pixmapWidth == 0) { - setNoPicture(true); - return; - } + if (pixmapWidth == 0) { + setNoPicture(true); + return; + } - QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); - if (resizedPixmap) { - setNoPicture(false); - this->setPixmap(*resizedPixmap); - } - else { - setNoPicture(true); - this->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); - } + QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); + if (resizedPixmap) { + setNoPicture(false); + this->setPixmap(*resizedPixmap); + } + else { + setNoPicture(true); + this->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); + } } diff --git a/cockatrice/src/cardinfopicture.h b/cockatrice/src/cardinfopicture.h index 9f34da94..2773f99f 100644 --- a/cockatrice/src/cardinfopicture.h +++ b/cockatrice/src/cardinfopicture.h @@ -7,27 +7,27 @@ class AbstractCardItem; class CardInfo; class CardInfoPicture : public QLabel { - Q_OBJECT + Q_OBJECT signals: - void hasPictureChanged(); + void hasPictureChanged(); private: - CardInfo *info; - bool noPicture; + CardInfo *info; + bool noPicture; public: - CardInfoPicture(int maximumWidth, QWidget *parent = 0); - bool hasPicture() const { return !noPicture; } + CardInfoPicture(int maximumWidth, QWidget *parent = 0); + bool hasPicture() const { return !noPicture; } private: - void setNoPicture(bool status); + void setNoPicture(bool status); public slots: - void setCard(CardInfo *card); + void setCard(CardInfo *card); private slots: - void updatePixmap(); + void updatePixmap(); }; diff --git a/cockatrice/src/cardinfotext.cpp b/cockatrice/src/cardinfotext.cpp index 9e59f33b..21336a83 100644 --- a/cockatrice/src/cardinfotext.cpp +++ b/cockatrice/src/cardinfotext.cpp @@ -8,60 +8,60 @@ #include "main.h" CardInfoText::CardInfoText(QWidget *parent) - : QFrame(parent) - , info(0) + : QFrame(parent) + , info(0) { - nameLabel1 = new QLabel; - nameLabel2 = new QLabel; - nameLabel2->setWordWrap(true); - manacostLabel1 = new QLabel; - manacostLabel2 = new QLabel; - manacostLabel2->setWordWrap(true); - cardtypeLabel1 = new QLabel; - cardtypeLabel2 = new QLabel; - cardtypeLabel2->setWordWrap(true); - powtoughLabel1 = new QLabel; - powtoughLabel2 = new QLabel; - loyaltyLabel1 = new QLabel; - loyaltyLabel2 = new QLabel; + nameLabel1 = new QLabel; + nameLabel2 = new QLabel; + nameLabel2->setWordWrap(true); + manacostLabel1 = new QLabel; + manacostLabel2 = new QLabel; + manacostLabel2->setWordWrap(true); + cardtypeLabel1 = new QLabel; + cardtypeLabel2 = new QLabel; + cardtypeLabel2->setWordWrap(true); + powtoughLabel1 = new QLabel; + powtoughLabel2 = new QLabel; + loyaltyLabel1 = new QLabel; + loyaltyLabel2 = new QLabel; - textLabel = new QTextEdit(); - textLabel->setReadOnly(true); + textLabel = new QTextEdit(); + textLabel->setReadOnly(true); - QGridLayout *grid = new QGridLayout(this); - int row = 0; - grid->addWidget(nameLabel1, row, 0); - grid->addWidget(nameLabel2, row++, 1); - grid->addWidget(manacostLabel1, row, 0); - grid->addWidget(manacostLabel2, row++, 1); - grid->addWidget(cardtypeLabel1, row, 0); - grid->addWidget(cardtypeLabel2, row++, 1); - grid->addWidget(powtoughLabel1, row, 0); - grid->addWidget(powtoughLabel2, row++, 1); - grid->addWidget(loyaltyLabel1, row, 0); - grid->addWidget(loyaltyLabel2, row++, 1); - grid->addWidget(textLabel, row, 0, -1, 2); - grid->setRowStretch(row, 1); - grid->setColumnStretch(1, 1); + QGridLayout *grid = new QGridLayout(this); + int row = 0; + grid->addWidget(nameLabel1, row, 0); + grid->addWidget(nameLabel2, row++, 1); + grid->addWidget(manacostLabel1, row, 0); + grid->addWidget(manacostLabel2, row++, 1); + grid->addWidget(cardtypeLabel1, row, 0); + grid->addWidget(cardtypeLabel2, row++, 1); + grid->addWidget(powtoughLabel1, row, 0); + grid->addWidget(powtoughLabel2, row++, 1); + grid->addWidget(loyaltyLabel1, row, 0); + grid->addWidget(loyaltyLabel2, row++, 1); + grid->addWidget(textLabel, row, 0, -1, 2); + grid->setRowStretch(row, 1); + grid->setColumnStretch(1, 1); - retranslateUi(); + retranslateUi(); } void CardInfoText::setCard(CardInfo *card) { - nameLabel2->setText(card->getName()); - manacostLabel2->setText(card->getManaCost()); - cardtypeLabel2->setText(card->getCardType()); - powtoughLabel2->setText(card->getPowTough()); - loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); - textLabel->setText(card->getText()); + nameLabel2->setText(card->getName()); + manacostLabel2->setText(card->getManaCost()); + cardtypeLabel2->setText(card->getCardType()); + powtoughLabel2->setText(card->getPowTough()); + loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); + textLabel->setText(card->getText()); } void CardInfoText::retranslateUi() { - nameLabel1->setText(tr("Name:")); - manacostLabel1->setText(tr("Mana cost:")); - cardtypeLabel1->setText(tr("Card type:")); - powtoughLabel1->setText(tr("P / T:")); - loyaltyLabel1->setText(tr("Loyalty:")); + nameLabel1->setText(tr("Name:")); + manacostLabel1->setText(tr("Mana cost:")); + cardtypeLabel1->setText(tr("Card type:")); + powtoughLabel1->setText(tr("P / T:")); + loyaltyLabel1->setText(tr("Loyalty:")); } diff --git a/cockatrice/src/cardinfotext.h b/cockatrice/src/cardinfotext.h index 0b555230..c0f59480 100644 --- a/cockatrice/src/cardinfotext.h +++ b/cockatrice/src/cardinfotext.h @@ -8,24 +8,24 @@ class QTextEdit; class CardInfo; class CardInfoText : public QFrame { - Q_OBJECT + Q_OBJECT private: - QLabel *nameLabel1, *nameLabel2; - QLabel *manacostLabel1, *manacostLabel2; - QLabel *cardtypeLabel1, *cardtypeLabel2; - QLabel *powtoughLabel1, *powtoughLabel2; - QLabel *loyaltyLabel1, *loyaltyLabel2; - QTextEdit *textLabel; + QLabel *nameLabel1, *nameLabel2; + QLabel *manacostLabel1, *manacostLabel2; + QLabel *cardtypeLabel1, *cardtypeLabel2; + QLabel *powtoughLabel1, *powtoughLabel2; + QLabel *loyaltyLabel1, *loyaltyLabel2; + QTextEdit *textLabel; - CardInfo *info; + CardInfo *info; public: - CardInfoText(QWidget *parent = 0); - void retranslateUi(); + CardInfoText(QWidget *parent = 0); + void retranslateUi(); public slots: - void setCard(CardInfo *card); + void setCard(CardInfo *card); }; #endif diff --git a/cockatrice/src/filterbuilder.cpp b/cockatrice/src/filterbuilder.cpp index 128cd7bc..f594a5de 100644 --- a/cockatrice/src/filterbuilder.cpp +++ b/cockatrice/src/filterbuilder.cpp @@ -8,77 +8,77 @@ #include "cardfilter.h" FilterBuilder::FilterBuilder(QWidget *parent) - : QFrame(parent) -{ - int i; + : QFrame(parent) +{ + int i; - QVBoxLayout *layout = new QVBoxLayout; - QHBoxLayout *addFilter = new QHBoxLayout; + QVBoxLayout *layout = new QVBoxLayout; + QHBoxLayout *addFilter = new QHBoxLayout; - filterCombo = new QComboBox; - for (i = 0; i < CardFilter::AttrEnd; i++) - filterCombo->addItem( - tr(CardFilter::attrName(static_cast(i))), - QVariant(i) - ); + filterCombo = new QComboBox; + for (i = 0; i < CardFilter::AttrEnd; i++) + filterCombo->addItem( + tr(CardFilter::attrName(static_cast(i))), + QVariant(i) + ); - typeCombo = new QComboBox; - for (i = 0; i < CardFilter::TypeEnd; i++) - typeCombo->addItem( - tr(CardFilter::typeName(static_cast(i))), - QVariant(i) - ); + typeCombo = new QComboBox; + for (i = 0; i < CardFilter::TypeEnd; i++) + typeCombo->addItem( + tr(CardFilter::typeName(static_cast(i))), + QVariant(i) + ); - QPushButton *ok = new QPushButton("+"); - ok->setMaximumSize(20, 20); + QPushButton *ok = new QPushButton("+"); + ok->setMaximumSize(20, 20); - addFilter->addWidget(ok); - addFilter->addWidget(typeCombo); - addFilter->addWidget(filterCombo, Qt::AlignLeft); + addFilter->addWidget(ok); + addFilter->addWidget(typeCombo); + addFilter->addWidget(filterCombo, Qt::AlignLeft); - edit = new QLineEdit; - edit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - layout->addLayout(addFilter); - layout->addWidget(edit); + edit = new QLineEdit; + edit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + layout->addLayout(addFilter); + layout->addWidget(edit); - setFrameStyle(QFrame::Panel | QFrame::Raised); - layout->setAlignment(Qt::AlignTop); - setLayout(layout); + setFrameStyle(QFrame::Panel | QFrame::Raised); + layout->setAlignment(Qt::AlignTop); + setLayout(layout); - connect(edit, SIGNAL(returnPressed()), this, SLOT(emit_add())); - connect(ok, SIGNAL(released()), this, SLOT(emit_add())); - connect(filterCombo, SIGNAL(currentIndexChanged(int)), edit, SLOT(clear())); - fltr = NULL; + connect(edit, SIGNAL(returnPressed()), this, SLOT(emit_add())); + connect(ok, SIGNAL(released()), this, SLOT(emit_add())); + connect(filterCombo, SIGNAL(currentIndexChanged(int)), edit, SLOT(clear())); + fltr = NULL; } FilterBuilder::~FilterBuilder() { - destroyFilter(); + destroyFilter(); } void FilterBuilder::destroyFilter() { - if (fltr) - delete fltr; + if (fltr) + delete fltr; } static int comboCurrentIntData(const QComboBox *combo) { - return combo->itemData(combo->currentIndex()).toInt(); + return combo->itemData(combo->currentIndex()).toInt(); } void FilterBuilder::emit_add() { - QString txt; + QString txt; - txt = edit->text(); - if (txt.length() < 1) - return; + txt = edit->text(); + if (txt.length() < 1) + return; - destroyFilter(); - fltr = new CardFilter(txt, - static_cast(comboCurrentIntData(typeCombo)), - static_cast(comboCurrentIntData(filterCombo))); - emit add(fltr); - edit->clear(); + destroyFilter(); + fltr = new CardFilter(txt, + static_cast(comboCurrentIntData(typeCombo)), + static_cast(comboCurrentIntData(filterCombo))); + emit add(fltr); + edit->clear(); } diff --git a/cockatrice/src/filterbuilder.h b/cockatrice/src/filterbuilder.h index 1d0565f3..6438e383 100644 --- a/cockatrice/src/filterbuilder.h +++ b/cockatrice/src/filterbuilder.h @@ -9,26 +9,26 @@ class QLineEdit; class CardFilter; class FilterBuilder : public QFrame { - Q_OBJECT + Q_OBJECT private: - QComboBox *typeCombo; - QComboBox *filterCombo; - QLineEdit *edit; - CardFilter *fltr; + QComboBox *typeCombo; + QComboBox *filterCombo; + QLineEdit *edit; + CardFilter *fltr; - void destroyFilter(); + void destroyFilter(); public: - FilterBuilder(QWidget *parent = 0); - ~FilterBuilder(); + FilterBuilder(QWidget *parent = 0); + ~FilterBuilder(); signals: void add(const CardFilter *f); public slots: private slots: - void emit_add(); + void emit_add(); protected: }; diff --git a/cockatrice/src/filtertree.cpp b/cockatrice/src/filtertree.cpp index 9e647e82..e1dc3101 100644 --- a/cockatrice/src/filtertree.cpp +++ b/cockatrice/src/filtertree.cpp @@ -7,223 +7,223 @@ template FilterTreeNode *FilterTreeBranch::nodeAt(int i) const { - return ((childNodes.size() > i)? childNodes.at(i) : NULL); + return ((childNodes.size() > i)? childNodes.at(i) : NULL); } template void FilterTreeBranch::deleteAt(int i) { - preRemoveChild(this, i); - delete childNodes.takeAt(i); - postRemoveChild(this, i); - nodeChanged(); + preRemoveChild(this, i); + delete childNodes.takeAt(i); + postRemoveChild(this, i); + nodeChanged(); } template int FilterTreeBranch::childIndex(const FilterTreeNode *node) const { - FilterTreeNode *unconst; - T downcasted; + FilterTreeNode *unconst; + T downcasted; - /* to do the dynamic cast to T we will lose const'ness, but we can - * trust QList::indexOf */ - unconst = (FilterTreeNode *) node; - downcasted = dynamic_cast(unconst); - if (downcasted == NULL) - return -1; - return childNodes.indexOf(downcasted); + /* to do the dynamic cast to T we will lose const'ness, but we can + * trust QList::indexOf */ + unconst = (FilterTreeNode *) node; + downcasted = dynamic_cast(unconst); + if (downcasted == NULL) + return -1; + return childNodes.indexOf(downcasted); } template FilterTreeBranch::~FilterTreeBranch() { - while (!childNodes.isEmpty()) - delete childNodes.takeFirst(); + while (!childNodes.isEmpty()) + delete childNodes.takeFirst(); } const FilterItemList *LogicMap::findTypeList(CardFilter::Type type) const { - QList::const_iterator i; + QList::const_iterator i; - for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - if ((*i)->type == type) - return *i; + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + if ((*i)->type == type) + return *i; - return NULL; + return NULL; } FilterItemList *LogicMap::typeList(CardFilter::Type type) { - QList::iterator i; - int count; + QList::iterator i; + int count; - count = 0; - for (i = childNodes.begin(); i != childNodes.end(); i++) { - if ((*i)->type == type) - break; - count++; - } - if (i == childNodes.end()) { - preInsertChild(this, count); - i = childNodes.insert(i, new FilterItemList(type, this)); - postInsertChild(this, count); - nodeChanged(); - } + count = 0; + for (i = childNodes.begin(); i != childNodes.end(); i++) { + if ((*i)->type == type) + break; + count++; + } + if (i == childNodes.end()) { + preInsertChild(this, count); + i = childNodes.insert(i, new FilterItemList(type, this)); + postInsertChild(this, count); + nodeChanged(); + } - return *i; + return *i; } FilterTreeNode *LogicMap::parent() const { - return p; + return p; } int FilterItemList::termIndex(const QString &term) const { - int i; + int i; - for (i = 0; i < childNodes.count(); i++) - if ((childNodes.at(i))->term == term) - return i; + for (i = 0; i < childNodes.count(); i++) + if ((childNodes.at(i))->term == term) + return i; - return -1; + return -1; } FilterTreeNode *FilterItemList::termNode(const QString &term) { - int i, count; - FilterItem *fi; + int i, count; + FilterItem *fi; - i = termIndex(term); - if (i < 0) { - fi = new FilterItem(term, this); - count = childNodes.count(); - preInsertChild(this, count); - childNodes.append(fi); - postInsertChild(this, count); - nodeChanged(); - return fi; - } + i = termIndex(term); + if (i < 0) { + fi = new FilterItem(term, this); + count = childNodes.count(); + preInsertChild(this, count); + childNodes.append(fi); + postInsertChild(this, count); + nodeChanged(); + return fi; + } - return childNodes.at(i); + return childNodes.at(i); } bool FilterItemList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const { - QList::const_iterator i; + QList::const_iterator i; - for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - if (!(*i)->acceptCardAttr(info, attr)) - return false; + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + if (!(*i)->acceptCardAttr(info, attr)) + return false; - return true; + return true; } bool FilterItemList::testTypeAndNot(const CardInfo *info, CardFilter::Attr attr) const { - // if any one in the list is true, return false - return !testTypeOr(info, attr); + // if any one in the list is true, return false + return !testTypeOr(info, attr); } bool FilterItemList::testTypeOr(const CardInfo *info, CardFilter::Attr attr) const { - QList::const_iterator i; + QList::const_iterator i; - for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - if ((*i)->acceptCardAttr(info, attr)) - return true; + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + if ((*i)->acceptCardAttr(info, attr)) + return true; - return false; + return false; } bool FilterItemList::testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const { - // if any one in the list is false, return true - return !testTypeAnd(info, attr); + // if any one in the list is false, return true + return !testTypeAnd(info, attr); } bool FilterItem::acceptName(const CardInfo *info) const { - return info->getName().contains(term, Qt::CaseInsensitive); + return info->getName().contains(term, Qt::CaseInsensitive); } bool FilterItem::acceptType(const CardInfo *info) const { - return info->getCardType().contains(term, Qt::CaseInsensitive); + return info->getCardType().contains(term, Qt::CaseInsensitive); } bool FilterItem::acceptColor(const CardInfo *info) const { - QStringList::const_iterator i; - bool status; + QStringList::const_iterator i; + bool status; - status = false; - for (i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) - if ((*i).contains(term, Qt::CaseInsensitive)) { - status = true; - break; - } + status = false; + for (i = info->getColors().constBegin(); i != info->getColors().constEnd(); i++) + if ((*i).contains(term, Qt::CaseInsensitive)) { + status = true; + break; + } - return status; + return status; } bool FilterItem::acceptText(const CardInfo *info) const { - return info->getText().contains(term, Qt::CaseInsensitive); + return info->getText().contains(term, Qt::CaseInsensitive); } bool FilterItem::acceptSet(const CardInfo *info) const { - SetList::const_iterator i; - bool status; + SetList::const_iterator i; + bool status; - status = false; - for (i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) - if ((*i)->getShortName() == term - || (*i)->getLongName().contains(term, Qt::CaseInsensitive)) { - status = true; - break; - } + status = false; + for (i = info->getSets().constBegin(); i != info->getSets().constEnd(); i++) + if ((*i)->getShortName() == term + || (*i)->getLongName().contains(term, Qt::CaseInsensitive)) { + status = true; + break; + } - return status; + return status; } bool FilterItem::acceptManaCost(const CardInfo *info) const { - return (info->getManaCost() == term); + return (info->getManaCost() == term); } bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const { - bool status; + bool status; - if (!isEnabled()) - return true; + if (!isEnabled()) + return true; - switch (attr) { - case CardFilter::AttrName: - status = acceptName(info); - break; - case CardFilter::AttrType: - status = acceptType(info); - break; - case CardFilter::AttrColor: - status = acceptColor(info); - break; - case CardFilter::AttrText: - status = acceptText(info); - break; - case CardFilter::AttrSet: - status = acceptSet(info); - break; - case CardFilter::AttrManaCost: - status = acceptManaCost(info); - break; - default: - status = true; /* ignore this attribute */ - } + switch (attr) { + case CardFilter::AttrName: + status = acceptName(info); + break; + case CardFilter::AttrType: + status = acceptType(info); + break; + case CardFilter::AttrColor: + status = acceptColor(info); + break; + case CardFilter::AttrText: + status = acceptText(info); + break; + case CardFilter::AttrSet: + status = acceptSet(info); + break; + case CardFilter::AttrManaCost: + status = acceptManaCost(info); + break; + default: + status = true; /* ignore this attribute */ + } - return status; + return status; } /* need to define these here to make QT happy, otherwise @@ -234,103 +234,103 @@ FilterTree::~FilterTree() {} LogicMap *FilterTree::attrLogicMap(CardFilter::Attr attr) { - QList::iterator i; - int count; + QList::iterator i; + int count; - count = 0; - for (i = childNodes.begin(); i != childNodes.end(); i++) { - if ((*i)->attr == attr) - break; - count++; - } + count = 0; + for (i = childNodes.begin(); i != childNodes.end(); i++) { + if ((*i)->attr == attr) + break; + count++; + } - if (i == childNodes.end()) { - preInsertChild(this, count); - i = childNodes.insert(i, new LogicMap(attr, this)); - postInsertChild(this, count); - nodeChanged(); - } + if (i == childNodes.end()) { + preInsertChild(this, count); + i = childNodes.insert(i, new LogicMap(attr, this)); + postInsertChild(this, count); + nodeChanged(); + } - return *i; + return *i; } FilterItemList *FilterTree::attrTypeList(CardFilter::Attr attr, - CardFilter::Type type) + CardFilter::Type type) { - return attrLogicMap(attr)->typeList(type); + return attrLogicMap(attr)->typeList(type); } int FilterTree::findTermIndex(CardFilter::Attr attr, CardFilter::Type type, - const QString &term) + const QString &term) { - attrTypeList(attr, type)->termIndex(term); + attrTypeList(attr, type)->termIndex(term); } int FilterTree::findTermIndex(const CardFilter *f) { - return findTermIndex(f->attr(), f->type(), f->term()); + return findTermIndex(f->attr(), f->type(), f->term()); } FilterTreeNode *FilterTree::termNode(CardFilter::Attr attr, CardFilter::Type type, - const QString &term) + const QString &term) { - return attrTypeList(attr, type)->termNode(term); + return attrTypeList(attr, type)->termNode(term); } FilterTreeNode *FilterTree::termNode(const CardFilter *f) { - return termNode(f->attr(), f->type(), f->term()); + return termNode(f->attr(), f->type(), f->term()); } FilterTreeNode *FilterTree::attrTypeNode(CardFilter::Attr attr, - CardFilter::Type type) + CardFilter::Type type) { - return attrTypeList(attr, type); + return attrTypeList(attr, type); } bool FilterTree::testAttr(const CardInfo *info, const LogicMap *lm) const { - const FilterItemList *fil; - bool status; + const FilterItemList *fil; + bool status; - status = true; + status = true; - fil = lm->findTypeList(CardFilter::TypeAnd); - if (fil != NULL && fil->isEnabled() && !fil->testTypeAnd(info, lm->attr)) - return false; + fil = lm->findTypeList(CardFilter::TypeAnd); + if (fil != NULL && fil->isEnabled() && !fil->testTypeAnd(info, lm->attr)) + return false; - fil = lm->findTypeList(CardFilter::TypeAndNot); - if (fil != NULL && fil->isEnabled() && !fil->testTypeAndNot(info, lm->attr)) - return false; + fil = lm->findTypeList(CardFilter::TypeAndNot); + if (fil != NULL && fil->isEnabled() && !fil->testTypeAndNot(info, lm->attr)) + return false; - fil = lm->findTypeList(CardFilter::TypeOr); - if (fil != NULL && fil->isEnabled()) { - status = false; - // if this is true we can return because it is OR'd with the OrNot list - if (fil->testTypeOr(info, lm->attr)) - return true; - } + fil = lm->findTypeList(CardFilter::TypeOr); + if (fil != NULL && fil->isEnabled()) { + status = false; + // if this is true we can return because it is OR'd with the OrNot list + if (fil->testTypeOr(info, lm->attr)) + return true; + } - fil = lm->findTypeList(CardFilter::TypeOrNot); - if (fil != NULL && fil->isEnabled() && fil->testTypeOrNot(info, lm->attr)) - return true; + fil = lm->findTypeList(CardFilter::TypeOrNot); + if (fil != NULL && fil->isEnabled() && fil->testTypeOrNot(info, lm->attr)) + return true; - return status; + return status; } bool FilterTree::acceptsCard(const CardInfo *info) const { - QList::const_iterator i; + QList::const_iterator i; - for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) - if ((*i)->isEnabled() && !testAttr(info, *i)) - return false; + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + if ((*i)->isEnabled() && !testAttr(info, *i)) + return false; - return true; + return true; } void FilterTree::clear() { - while(childCount() > 0) - deleteAt(0); + while(childCount() > 0) + deleteAt(0); } diff --git a/cockatrice/src/filtertree.h b/cockatrice/src/filtertree.h index a404e5a0..9a5fc531 100644 --- a/cockatrice/src/filtertree.h +++ b/cockatrice/src/filtertree.h @@ -11,48 +11,48 @@ class CardInfo; class FilterTreeNode { private: - bool enabled; + bool enabled; public: - FilterTreeNode() : enabled(true) {} - virtual bool isEnabled() const { return enabled; } - virtual void enable() { enabled = true; nodeChanged(); } - virtual void disable() { enabled = false; nodeChanged(); } - virtual FilterTreeNode *parent() const { return NULL; } - virtual FilterTreeNode *nodeAt(int i) const { return NULL; } - virtual void deleteAt(int i) {} - virtual int childCount() const { return 0; } - virtual int childIndex(const FilterTreeNode *node) const { return -1; } - virtual int index() const { return (parent() != NULL)? parent()->childIndex(this) : -1; } - virtual QString text() const { return QString(textCStr()); } - virtual bool isLeaf() const { return false; } - virtual const char *textCStr() const { return ""; } - virtual void nodeChanged() const { - if (parent() != NULL) parent()->nodeChanged(); - } - virtual void preInsertChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->preInsertChild(p, i); - } - virtual void postInsertChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->postInsertChild(p, i); - } - virtual void preRemoveChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->preRemoveChild(p, i); - } - virtual void postRemoveChild(const FilterTreeNode *p, int i) const { - if (parent() != NULL) parent()->postRemoveChild(p, i); - } + FilterTreeNode() : enabled(true) {} + virtual bool isEnabled() const { return enabled; } + virtual void enable() { enabled = true; nodeChanged(); } + virtual void disable() { enabled = false; nodeChanged(); } + virtual FilterTreeNode *parent() const { return NULL; } + virtual FilterTreeNode *nodeAt(int i) const { return NULL; } + virtual void deleteAt(int i) {} + virtual int childCount() const { return 0; } + virtual int childIndex(const FilterTreeNode *node) const { return -1; } + virtual int index() const { return (parent() != NULL)? parent()->childIndex(this) : -1; } + virtual QString text() const { return QString(textCStr()); } + virtual bool isLeaf() const { return false; } + virtual const char *textCStr() const { return ""; } + virtual void nodeChanged() const { + if (parent() != NULL) parent()->nodeChanged(); + } + virtual void preInsertChild(const FilterTreeNode *p, int i) const { + if (parent() != NULL) parent()->preInsertChild(p, i); + } + virtual void postInsertChild(const FilterTreeNode *p, int i) const { + if (parent() != NULL) parent()->postInsertChild(p, i); + } + virtual void preRemoveChild(const FilterTreeNode *p, int i) const { + if (parent() != NULL) parent()->preRemoveChild(p, i); + } + virtual void postRemoveChild(const FilterTreeNode *p, int i) const { + if (parent() != NULL) parent()->postRemoveChild(p, i); + } }; template class FilterTreeBranch : public FilterTreeNode { protected: - QList childNodes; + QList childNodes; public: - ~FilterTreeBranch(); - FilterTreeNode *nodeAt(int i) const; - void deleteAt(int i); - int childCount() const { return childNodes.size(); } - int childIndex(const FilterTreeNode *node) const; + ~FilterTreeBranch(); + FilterTreeNode *nodeAt(int i) const; + void deleteAt(int i); + int childCount() const { return childNodes.size(); } + int childIndex(const FilterTreeNode *node) const; }; class FilterItemList; @@ -60,104 +60,104 @@ class FilterTree; class LogicMap : public FilterTreeBranch { private: - FilterTree *const p; + FilterTree *const p; public: - const CardFilter::Attr attr; + const CardFilter::Attr attr; - LogicMap(CardFilter::Attr a, FilterTree *parent) - : attr(a), p(parent) {} - const FilterItemList *findTypeList(CardFilter::Type type) const; - FilterItemList *typeList(CardFilter::Type type); - FilterTreeNode *parent() const; - const char* textCStr() const { return CardFilter::attrName(attr); } + LogicMap(CardFilter::Attr a, FilterTree *parent) + : attr(a), p(parent) {} + const FilterItemList *findTypeList(CardFilter::Type type) const; + FilterItemList *typeList(CardFilter::Type type); + FilterTreeNode *parent() const; + const char* textCStr() const { return CardFilter::attrName(attr); } }; class FilterItem; class FilterItemList : public FilterTreeBranch { private: - LogicMap *const p; + LogicMap *const p; public: - const CardFilter::Type type; + const CardFilter::Type type; - FilterItemList(CardFilter::Type t, LogicMap *parent) - : type(t), p(parent) {} - CardFilter::Attr attr() const { return p->attr; } - FilterTreeNode *parent() const { return p; } - int termIndex(const QString &term) const; - FilterTreeNode *termNode(const QString &term); - const char *textCStr() const { return CardFilter::typeName(type); } + FilterItemList(CardFilter::Type t, LogicMap *parent) + : type(t), p(parent) {} + CardFilter::Attr attr() const { return p->attr; } + FilterTreeNode *parent() const { return p; } + int termIndex(const QString &term) const; + FilterTreeNode *termNode(const QString &term); + const char *textCStr() const { return CardFilter::typeName(type); } - bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const; - bool testTypeAndNot(const CardInfo *info, CardFilter::Attr attr) const; - bool testTypeOr(const CardInfo *info, CardFilter::Attr attr) const; - bool testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const; + bool testTypeAnd(const CardInfo *info, CardFilter::Attr attr) const; + bool testTypeAndNot(const CardInfo *info, CardFilter::Attr attr) const; + bool testTypeOr(const CardInfo *info, CardFilter::Attr attr) const; + bool testTypeOrNot(const CardInfo *info, CardFilter::Attr attr) const; }; class FilterItem : public FilterTreeNode { private: - FilterItemList *const p; + FilterItemList *const p; public: - const QString term; + const QString term; - FilterItem(QString trm, FilterItemList *parent) - : p(parent), term(trm) {} + FilterItem(QString trm, FilterItemList *parent) + : p(parent), term(trm) {} - CardFilter::Attr attr() const { return p->attr(); } - CardFilter::Type type() const { return p->type; } - FilterTreeNode *parent() const { return p; } - QString text() const { return term; } - const char *textCStr() const { return term.toStdString().c_str(); } - bool isLeaf() const { return true; } + CardFilter::Attr attr() const { return p->attr(); } + CardFilter::Type type() const { return p->type; } + FilterTreeNode *parent() const { return p; } + QString text() const { return term; } + const char *textCStr() const { return term.toStdString().c_str(); } + bool isLeaf() const { return true; } - bool acceptName(const CardInfo *info) const; - bool acceptType(const CardInfo *info) const; - bool acceptColor(const CardInfo *info) const; - bool acceptText(const CardInfo *info) const; - bool acceptSet(const CardInfo *info) const; - bool acceptManaCost(const CardInfo *info) const; - bool acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const; + bool acceptName(const CardInfo *info) const; + bool acceptType(const CardInfo *info) const; + bool acceptColor(const CardInfo *info) const; + bool acceptText(const CardInfo *info) const; + bool acceptSet(const CardInfo *info) const; + bool acceptManaCost(const CardInfo *info) const; + bool acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) const; }; class FilterTree : public QObject, public FilterTreeBranch { - Q_OBJECT + Q_OBJECT signals: - void preInsertRow(const FilterTreeNode *parent, int i) const; - void postInsertRow(const FilterTreeNode *parent, int i) const; - void preRemoveRow(const FilterTreeNode *parent, int i) const; - void postRemoveRow(const FilterTreeNode *parent, int i) const; - void changed() const; + void preInsertRow(const FilterTreeNode *parent, int i) const; + void postInsertRow(const FilterTreeNode *parent, int i) const; + void preRemoveRow(const FilterTreeNode *parent, int i) const; + void postRemoveRow(const FilterTreeNode *parent, int i) const; + void changed() const; private: - LogicMap *attrLogicMap(CardFilter::Attr attr); - FilterItemList *attrTypeList(CardFilter::Attr attr, - CardFilter::Type type); + LogicMap *attrLogicMap(CardFilter::Attr attr); + FilterItemList *attrTypeList(CardFilter::Attr attr, + CardFilter::Type type); - bool testAttr(const CardInfo *info, const LogicMap *lm) const; + bool testAttr(const CardInfo *info, const LogicMap *lm) const; - void nodeChanged() const { emit changed(); } - void preInsertChild(const FilterTreeNode *p, int i) const { emit preInsertRow(p, i); } - void postInsertChild(const FilterTreeNode *p, int i) const { emit postInsertRow(p, i); } - void preRemoveChild(const FilterTreeNode *p, int i) const { emit preRemoveRow(p, i); } - void postRemoveChild(const FilterTreeNode *p, int i) const { emit postRemoveRow(p, i); } + void nodeChanged() const { emit changed(); } + void preInsertChild(const FilterTreeNode *p, int i) const { emit preInsertRow(p, i); } + void postInsertChild(const FilterTreeNode *p, int i) const { emit postInsertRow(p, i); } + void preRemoveChild(const FilterTreeNode *p, int i) const { emit preRemoveRow(p, i); } + void postRemoveChild(const FilterTreeNode *p, int i) const { emit postRemoveRow(p, i); } public: - FilterTree(); - ~FilterTree(); - int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, - const QString &term); - int findTermIndex(const CardFilter *f); - FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, - const QString &term); - FilterTreeNode *termNode(const CardFilter *f); - FilterTreeNode *attrTypeNode(CardFilter::Attr attr, - CardFilter::Type type); - const char *textCStr() { return "root"; } - int index() const { return 0; } + FilterTree(); + ~FilterTree(); + int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, + const QString &term); + int findTermIndex(const CardFilter *f); + FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, + const QString &term); + FilterTreeNode *termNode(const CardFilter *f); + FilterTreeNode *attrTypeNode(CardFilter::Attr attr, + CardFilter::Type type); + const char *textCStr() { return "root"; } + int index() const { return 0; } - bool acceptsCard(const CardInfo *info) const; - void clear(); + bool acceptsCard(const CardInfo *info) const; + void clear(); }; #endif diff --git a/cockatrice/src/filtertreemodel.cpp b/cockatrice/src/filtertreemodel.cpp index c004ba22..5fed7766 100644 --- a/cockatrice/src/filtertreemodel.cpp +++ b/cockatrice/src/filtertreemodel.cpp @@ -4,269 +4,269 @@ #include "cardfilter.h" FilterTreeModel::FilterTreeModel(QObject *parent) - : QAbstractItemModel(parent) + : QAbstractItemModel(parent) { - fTree = new FilterTree; - connect(fTree, - SIGNAL(preInsertRow(const FilterTreeNode *, int)), - this, SLOT(proxyBeginInsertRow(const FilterTreeNode *, int))); - connect(fTree, - SIGNAL(postInsertRow(const FilterTreeNode *, int)), - this, SLOT(proxyEndInsertRow(const FilterTreeNode *, int))); - connect(fTree, - SIGNAL(preRemoveRow(const FilterTreeNode *, int)), - this, SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int))); - connect(fTree, - SIGNAL(postRemoveRow(const FilterTreeNode *, int)), - this, SLOT(proxyEndRemoveRow(const FilterTreeNode *, int))); + fTree = new FilterTree; + connect(fTree, + SIGNAL(preInsertRow(const FilterTreeNode *, int)), + this, SLOT(proxyBeginInsertRow(const FilterTreeNode *, int))); + connect(fTree, + SIGNAL(postInsertRow(const FilterTreeNode *, int)), + this, SLOT(proxyEndInsertRow(const FilterTreeNode *, int))); + connect(fTree, + SIGNAL(preRemoveRow(const FilterTreeNode *, int)), + this, SLOT(proxyBeginRemoveRow(const FilterTreeNode *, int))); + connect(fTree, + SIGNAL(postRemoveRow(const FilterTreeNode *, int)), + this, SLOT(proxyEndRemoveRow(const FilterTreeNode *, int))); } FilterTreeModel::~FilterTreeModel() { - delete fTree; + delete fTree; } void FilterTreeModel::proxyBeginInsertRow(const FilterTreeNode *node, int i) { - int idx; + int idx; - idx = node->index(); - if (idx >= 0) - beginInsertRows(createIndex(idx, 0, (void *) node), i, i); + idx = node->index(); + if (idx >= 0) + beginInsertRows(createIndex(idx, 0, (void *) node), i, i); } void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int) { - int idx; + int idx; - idx = node->index(); - if (idx >= 0) - endInsertRows(); + idx = node->index(); + if (idx >= 0) + endInsertRows(); } void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i) { - int idx; + int idx; - idx = node->index(); - if (idx >= 0) - beginRemoveRows(createIndex(idx, 0, (void *) node), i, i); + idx = node->index(); + if (idx >= 0) + beginRemoveRows(createIndex(idx, 0, (void *) node), i, i); } void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int) { - int idx; + int idx; - idx = node->index(); - if (idx >= 0) - endRemoveRows(); + idx = node->index(); + if (idx >= 0) + endRemoveRows(); } FilterTreeNode *FilterTreeModel::indexToNode(const QModelIndex &idx) const { - void *ip; - FilterTreeNode *node; + void *ip; + FilterTreeNode *node; - if (!idx.isValid()) - return fTree; + if (!idx.isValid()) + return fTree; - ip = idx.internalPointer(); - if (ip == NULL) - return fTree; + ip = idx.internalPointer(); + if (ip == NULL) + return fTree; - node = static_cast(ip); - return node; + node = static_cast(ip); + return node; } void FilterTreeModel::addFilter(const CardFilter *f) { - emit layoutAboutToBeChanged(); - fTree->termNode(f); - emit layoutChanged(); + emit layoutAboutToBeChanged(); + fTree->termNode(f); + emit layoutChanged(); } int FilterTreeModel::rowCount(const QModelIndex &parent) const { - const FilterTreeNode *node; - int result; + const FilterTreeNode *node; + int result; - if (parent.column() > 0) - return 0; + if (parent.column() > 0) + return 0; - node = indexToNode(parent); - if (node) - result = node->childCount(); - else - result = 0; + node = indexToNode(parent); + if (node) + result = node->childCount(); + else + result = 0; - return result; + return result; } int FilterTreeModel::columnCount(const QModelIndex &/*parent*/) const { - return 1; + return 1; } QVariant FilterTreeModel::data(const QModelIndex &index, int role) const { - const FilterTreeNode *node; + const FilterTreeNode *node; - if (!index.isValid()) - return QVariant(); - if (index.column() >= columnCount()) - return QVariant(); + if (!index.isValid()) + return QVariant(); + if (index.column() >= columnCount()) + return QVariant(); - node = indexToNode(index); - if (node == NULL) - return QVariant(); + node = indexToNode(index); + if (node == NULL) + return QVariant(); - switch (role) { - case Qt::FontRole: - if (!node->isLeaf()) { - QFont f; - f.setBold(true); - return f; - } - break; - case Qt::DisplayRole: - case Qt::EditRole: - case Qt::ToolTipRole: - case Qt::StatusTipRole: - case Qt::WhatsThisRole: - if(!node->isLeaf()) - return tr(node->textCStr()); - else - return node->text(); - case Qt::CheckStateRole: - if (node->isEnabled()) - return Qt::Checked; - else - return Qt::Unchecked; - default: - return QVariant(); - } + switch (role) { + case Qt::FontRole: + if (!node->isLeaf()) { + QFont f; + f.setBold(true); + return f; + } + break; + case Qt::DisplayRole: + case Qt::EditRole: + case Qt::ToolTipRole: + case Qt::StatusTipRole: + case Qt::WhatsThisRole: + if(!node->isLeaf()) + return tr(node->textCStr()); + else + return node->text(); + case Qt::CheckStateRole: + if (node->isEnabled()) + return Qt::Checked; + else + return Qt::Unchecked; + default: + return QVariant(); + } - return QVariant(); + return QVariant(); } bool FilterTreeModel::setData(const QModelIndex &index, - const QVariant &value, int role) + const QVariant &value, int role) { - FilterTreeNode *node; + FilterTreeNode *node; - if (!index.isValid()) - return false; - if (index.column() >= columnCount()) - return false; - if (role != Qt::CheckStateRole ) - return false; + if (!index.isValid()) + return false; + if (index.column() >= columnCount()) + return false; + if (role != Qt::CheckStateRole ) + return false; - node = indexToNode(index); - if (node == NULL || node == fTree) - return false; + node = indexToNode(index); + if (node == NULL || node == fTree) + return false; - Qt::CheckState state = static_cast(value.toInt()); - if (state == Qt::Checked) - node->enable(); - else - node->disable(); + Qt::CheckState state = static_cast(value.toInt()); + if (state == Qt::Checked) + node->enable(); + else + node->disable(); - emit dataChanged(index, index); - return true; -} + emit dataChanged(index, index); + return true; +} Qt::ItemFlags FilterTreeModel::flags(const QModelIndex &index) const { - const FilterTreeNode *node; - Qt::ItemFlags result; + const FilterTreeNode *node; + Qt::ItemFlags result; - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - node = indexToNode(index); - if (node == NULL) - return 0; + node = indexToNode(index); + if (node == NULL) + return 0; - result = Qt::ItemIsEnabled; - if (node == fTree) - return result; + result = Qt::ItemIsEnabled; + if (node == fTree) + return result; - result |= Qt::ItemIsSelectable; - result |= Qt::ItemIsUserCheckable; + result |= Qt::ItemIsSelectable; + result |= Qt::ItemIsUserCheckable; - return result; + return result; } QModelIndex FilterTreeModel::nodeIndex(const FilterTreeNode *node, int row, int column) const { - FilterTreeNode *child; + FilterTreeNode *child; - if (column > 0 || row >= node->childCount()) - return QModelIndex(); + if (column > 0 || row >= node->childCount()) + return QModelIndex(); - child = node->nodeAt(row); - return createIndex(row, column, child); + child = node->nodeAt(row); + return createIndex(row, column, child); } QModelIndex FilterTreeModel::index(int row, int column, - const QModelIndex &parent) const + const QModelIndex &parent) const { - const FilterTreeNode *node; + const FilterTreeNode *node; - if (!hasIndex(row, column, parent)) - return QModelIndex(); + if (!hasIndex(row, column, parent)) + return QModelIndex(); - node = indexToNode(parent); - if (node == NULL) - return QModelIndex(); + node = indexToNode(parent); + if (node == NULL) + return QModelIndex(); - return nodeIndex(node, row, column); + return nodeIndex(node, row, column); } QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const { - const FilterTreeNode *node; - FilterTreeNode *parent; - int row; - QModelIndex idx; + const FilterTreeNode *node; + FilterTreeNode *parent; + int row; + QModelIndex idx; - if (!ind.isValid()) - return QModelIndex(); + if (!ind.isValid()) + return QModelIndex(); - node = indexToNode(ind); - if (node == NULL || node == fTree) - return QModelIndex(); + node = indexToNode(ind); + if (node == NULL || node == fTree) + return QModelIndex(); - parent = node->parent(); - if (parent) { - row = parent->index(); - if (row < 0) - return QModelIndex(); - idx = createIndex(row, 0, parent); - return idx; - } + parent = node->parent(); + if (parent) { + row = parent->index(); + if (row < 0) + return QModelIndex(); + idx = createIndex(row, 0, parent); + return idx; + } - return QModelIndex(); + return QModelIndex(); } bool FilterTreeModel::removeRows(int row, int count, const QModelIndex & parent) { - FilterTreeNode *node; - int i, last; + FilterTreeNode *node; + int i, last; - last = row+count-1; - if (!parent.isValid() || count < 1 || row < 0) - return false; + last = row+count-1; + if (!parent.isValid() || count < 1 || row < 0) + return false; - node = indexToNode(parent); - if (node == NULL || last >= node->childCount()) - return false; + node = indexToNode(parent); + if (node == NULL || last >= node->childCount()) + return false; - for (i = 0; i < count; i++) - node->deleteAt(row); + for (i = 0; i < count; i++) + node->deleteAt(row); - if (node != fTree && node->childCount() < 1) - return removeRow(parent.row(), parent.parent()); + if (node != fTree && node->childCount() < 1) + return removeRow(parent.row(), parent.parent()); - return true; + return true; } diff --git a/cockatrice/src/filtertreemodel.h b/cockatrice/src/filtertreemodel.h index 7e49e9b1..ac90db57 100644 --- a/cockatrice/src/filtertreemodel.h +++ b/cockatrice/src/filtertreemodel.h @@ -8,37 +8,37 @@ class CardFilter; class FilterTreeNode; class FilterTreeModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT private: - FilterTree *fTree; + FilterTree *fTree; public slots: - void addFilter(const CardFilter *f); + void addFilter(const CardFilter *f); private slots: - void proxyBeginInsertRow(const FilterTreeNode *, int); - void proxyEndInsertRow(const FilterTreeNode *, int); - void proxyBeginRemoveRow(const FilterTreeNode *, int); - void proxyEndRemoveRow(const FilterTreeNode *, int); + void proxyBeginInsertRow(const FilterTreeNode *, int); + void proxyEndInsertRow(const FilterTreeNode *, int); + void proxyBeginRemoveRow(const FilterTreeNode *, int); + void proxyEndRemoveRow(const FilterTreeNode *, int); private: - FilterTreeNode *indexToNode(const QModelIndex &idx) const; - QModelIndex nodeIndex(const FilterTreeNode *node, int row, int column) const; + FilterTreeNode *indexToNode(const QModelIndex &idx) const; + QModelIndex nodeIndex(const FilterTreeNode *node, int row, int column) const; public: - FilterTreeModel(QObject *parent = 0); - ~FilterTreeModel(); - FilterTree *filterTree() const { return fTree; } - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - bool setData(const QModelIndex &index, const QVariant &value, - int role = Qt::EditRole); - Qt::ItemFlags flags(const QModelIndex &index) const; - QModelIndex parent(const QModelIndex &ind) const; - QModelIndex index(int row, int column, - const QModelIndex &parent) const; - bool removeRows(int row, int count, const QModelIndex & parent); + FilterTreeModel(QObject *parent = 0); + ~FilterTreeModel(); + FilterTree *filterTree() const { return fTree; } + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role) const; + bool setData(const QModelIndex &index, const QVariant &value, + int role = Qt::EditRole); + Qt::ItemFlags flags(const QModelIndex &index) const; + QModelIndex parent(const QModelIndex &ind) const; + QModelIndex index(int row, int column, + const QModelIndex &parent) const; + bool removeRows(int row, int count, const QModelIndex & parent); }; #endif diff --git a/cockatrice/src/keysignals.cpp b/cockatrice/src/keysignals.cpp index 1994e387..326b006e 100644 --- a/cockatrice/src/keysignals.cpp +++ b/cockatrice/src/keysignals.cpp @@ -2,48 +2,48 @@ #include bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event) { - QKeyEvent *kevent; + QKeyEvent *kevent; - if(event->type() != QEvent::KeyPress) - return false; + if(event->type() != QEvent::KeyPress) + return false; - kevent = static_cast(event); - switch(kevent->key()) { - case Qt::Key_Return: - case Qt::Key_Enter: - if(kevent->modifiers() & Qt::ControlModifier) - emit onCtrlEnter(); - else - emit onEnter(); - break; - case Qt::Key_Right: - if(kevent->modifiers() & Qt::ControlModifier) - emit onCtrlRight(); - else - emit onRight(); + kevent = static_cast(event); + switch(kevent->key()) { + case Qt::Key_Return: + case Qt::Key_Enter: + if(kevent->modifiers() & Qt::ControlModifier) + emit onCtrlEnter(); + else + emit onEnter(); + break; + case Qt::Key_Right: + if(kevent->modifiers() & Qt::ControlModifier) + emit onCtrlRight(); + else + emit onRight(); - if(!filterLROn) - return false; - break; - case Qt::Key_Left: - if(kevent->modifiers() & Qt::ControlModifier) - emit onCtrlLeft(); - else - emit onLeft(); + if(!filterLROn) + return false; + break; + case Qt::Key_Left: + if(kevent->modifiers() & Qt::ControlModifier) + emit onCtrlLeft(); + else + emit onLeft(); - if(!filterLROn) - return false; - break; - case Qt::Key_Delete: - case Qt::Key_Backspace: - emit onDelete(); + if(!filterLROn) + return false; + break; + case Qt::Key_Delete: + case Qt::Key_Backspace: + emit onDelete(); - if(!filterDeleteOn) - return false; - break; - default: - return false; - } + if(!filterDeleteOn) + return false; + break; + default: + return false; + } - return true; + return true; } diff --git a/cockatrice/src/keysignals.h b/cockatrice/src/keysignals.h index 006e0ce3..78ddf1e2 100644 --- a/cockatrice/src/keysignals.h +++ b/cockatrice/src/keysignals.h @@ -2,29 +2,29 @@ #include class KeySignals : public QObject { - Q_OBJECT + Q_OBJECT private: - bool filterDeleteOn; - bool filterLROn; + bool filterDeleteOn; + bool filterLROn; signals: - void onEnter(); - void onCtrlEnter(); - void onLeft(); - void onCtrlLeft(); - void onRight(); - void onCtrlRight(); - void onDelete(); + void onEnter(); + void onCtrlEnter(); + void onLeft(); + void onCtrlLeft(); + void onRight(); + void onCtrlRight(); + void onDelete(); protected: - virtual bool eventFilter(QObject *, QEvent *event); + virtual bool eventFilter(QObject *, QEvent *event); public: - KeySignals() - : filterDeleteOn(true) - , filterLROn(true) - {} - void filterDelete(bool on) { filterDeleteOn = on; } - void filterLeftRight(bool on) { filterLROn = on; } + KeySignals() + : filterDeleteOn(true) + , filterLROn(true) + {} + void filterDelete(bool on) { filterDeleteOn = on; } + void filterLeftRight(bool on) { filterLROn = on; } }; From 040d9d15a3579c644abe9d475666da514944ba32 Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Thu, 24 Apr 2014 19:49:50 +0000 Subject: [PATCH 26/55] bug fix: move isEnabled test out of acceptCardAttr in the case of AND'ed filter terms, returning true from acceptCardAttr will be equivalent to ignoring the disabled term, but in the case of OR'ed terms, returning true will incorrectly cause all cards to be accepted. the fix is to test for whether the term is enabled before calling acceptCardAttr and continue if disabled. --- cockatrice/src/filtertree.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/cockatrice/src/filtertree.cpp b/cockatrice/src/filtertree.cpp index e1dc3101..4c28028b 100644 --- a/cockatrice/src/filtertree.cpp +++ b/cockatrice/src/filtertree.cpp @@ -112,9 +112,12 @@ bool FilterItemList::testTypeAnd(const CardInfo *info, CardFilter::Attr attr) co { QList::const_iterator i; - for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) { + if (!(*i)->isEnabled()) + continue; if (!(*i)->acceptCardAttr(info, attr)) return false; + } return true; } @@ -129,9 +132,12 @@ bool FilterItemList::testTypeOr(const CardInfo *info, CardFilter::Attr attr) con { QList::const_iterator i; - for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) + for (i = childNodes.constBegin(); i != childNodes.constEnd(); i++) { + if (!(*i)->isEnabled()) + continue; if ((*i)->acceptCardAttr(info, attr)) return true; + } return false; } @@ -197,9 +203,6 @@ bool FilterItem::acceptCardAttr(const CardInfo *info, CardFilter::Attr attr) con { bool status; - if (!isEnabled()) - return true; - switch (attr) { case CardFilter::AttrName: status = acceptName(info); From 841847cda4eb7fe9512514d4ad79aa88e1af49cb Mon Sep 17 00:00:00 2001 From: sylvanbasilisk Date: Thu, 24 Apr 2014 20:17:21 +0000 Subject: [PATCH 27/55] update to hotkey settings in deck editor tab removed LEFT/RIGHT increment/decrement while the card database/quicksearch edit have focus. LEFT/RIGHT increment/decrement remains while the deck view has focus. also, now the card database delegates focus the quicksearch editor so that any characters typed while the card database has focus will narrow the search down using the quicksearch filter. `control`+`alt`+`-`/`=` now increment/decrement the mainboard and `control`+`alt`+`[`/`]` now increment/decrement the sideboard (alt could not be used alone as OSX inserts special characters using alt. --- cockatrice/src/keysignals.cpp | 48 ++++++++++++++++++++---------- cockatrice/src/keysignals.h | 19 ++++-------- cockatrice/src/tab_deck_editor.cpp | 23 +++++++------- cockatrice/src/tab_deck_editor.h | 1 - 4 files changed, 47 insertions(+), 44 deletions(-) diff --git a/cockatrice/src/keysignals.cpp b/cockatrice/src/keysignals.cpp index 326b006e..5db58cb5 100644 --- a/cockatrice/src/keysignals.cpp +++ b/cockatrice/src/keysignals.cpp @@ -11,39 +11,55 @@ bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event) { switch(kevent->key()) { case Qt::Key_Return: case Qt::Key_Enter: - if(kevent->modifiers() & Qt::ControlModifier) + if (kevent->modifiers().testFlag(Qt::AltModifier) + && kevent->modifiers().testFlag(Qt::ControlModifier) ) + emit onCtrlAltEnter(); + else if (kevent->modifiers() & Qt::ControlModifier) emit onCtrlEnter(); else emit onEnter(); + break; case Qt::Key_Right: - if(kevent->modifiers() & Qt::ControlModifier) - emit onCtrlRight(); - else - emit onRight(); + emit onRight(); - if(!filterLROn) - return false; break; case Qt::Key_Left: - if(kevent->modifiers() & Qt::ControlModifier) - emit onCtrlLeft(); - else - emit onLeft(); + emit onLeft(); - if(!filterLROn) - return false; break; case Qt::Key_Delete: case Qt::Key_Backspace: emit onDelete(); - if(!filterDeleteOn) - return false; + break; + case Qt::Key_Minus: + if (kevent->modifiers().testFlag(Qt::AltModifier) + && kevent->modifiers().testFlag(Qt::ControlModifier) ) + emit onCtrlAltMinus(); + + break; + case Qt::Key_Equal: + if (kevent->modifiers().testFlag(Qt::AltModifier) + && kevent->modifiers().testFlag(Qt::ControlModifier) ) + emit onCtrlAltEqual(); + + break; + case Qt::Key_BracketLeft: + if (kevent->modifiers().testFlag(Qt::AltModifier) + && kevent->modifiers().testFlag(Qt::ControlModifier) ) + emit onCtrlAltLBracket(); + + break; + case Qt::Key_BracketRight: + if (kevent->modifiers().testFlag(Qt::AltModifier) + && kevent->modifiers().testFlag(Qt::ControlModifier) ) + emit onCtrlAltRBracket(); + break; default: return false; } - return true; + return false; } diff --git a/cockatrice/src/keysignals.h b/cockatrice/src/keysignals.h index 78ddf1e2..23a07b77 100644 --- a/cockatrice/src/keysignals.h +++ b/cockatrice/src/keysignals.h @@ -4,27 +4,18 @@ class KeySignals : public QObject { Q_OBJECT -private: - bool filterDeleteOn; - bool filterLROn; - signals: void onEnter(); void onCtrlEnter(); + void onCtrlAltEnter(); void onLeft(); - void onCtrlLeft(); void onRight(); - void onCtrlRight(); void onDelete(); + void onCtrlAltMinus(); + void onCtrlAltEqual(); + void onCtrlAltLBracket(); + void onCtrlAltRBracket(); protected: virtual bool eventFilter(QObject *, QEvent *event); - -public: - KeySignals() - : filterDeleteOn(true) - , filterLROn(true) - {} - void filterDelete(bool on) { filterDeleteOn = on; } - void filterLeftRight(bool on) { filterLROn = on; } }; diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index 075ee918..91c8819e 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -54,15 +54,17 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) searchLabel = new QLabel(); searchEdit = new SearchLineEdit; searchLabel->setBuddy(searchEdit); + setFocusProxy(searchEdit); + setFocusPolicy(Qt::ClickFocus); - searchKeySignals.filterDelete(false); searchEdit->installEventFilter(&searchKeySignals); connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); connect(&searchKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); - connect(&searchKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); - connect(&searchKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); - connect(&searchKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); - connect(&searchKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); + connect(&searchKeySignals, SIGNAL(onCtrlAltEqual()), this, SLOT(actAddCard())); + connect(&searchKeySignals, SIGNAL(onCtrlAltRBracket()), this, SLOT(actAddCardToSideboard())); + connect(&searchKeySignals, SIGNAL(onCtrlAltMinus()), this, SLOT(actDecrementCard())); + connect(&searchKeySignals, SIGNAL(onCtrlAltLBracket()), this, SLOT(actDecrementCardFromSideboard())); + connect(&searchKeySignals, SIGNAL(onCtrlAltEnter()), this, SLOT(actAddCardToSideboard())); connect(&searchKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); QToolBar *deckEditToolBar = new QToolBar; @@ -81,6 +83,7 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) databaseDisplayModel->sort(0, Qt::AscendingOrder); databaseView = new QTreeView(); + databaseView->setFocusProxy(searchEdit); databaseView->setModel(databaseDisplayModel); databaseView->setUniformRowHeights(true); databaseView->setRootIsDecorated(false); @@ -90,13 +93,6 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) databaseView->resizeColumnToContents(0); 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())); - databaseView->installEventFilter(&dbViewKeySignals); - connect(&dbViewKeySignals, SIGNAL(onEnter()), this, SLOT(actAddCard())); - connect(&dbViewKeySignals, SIGNAL(onRight()), this, SLOT(actAddCard())); - connect(&dbViewKeySignals, SIGNAL(onCtrlRight()), this, SLOT(actAddCardToSideboard())); - connect(&dbViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); - connect(&dbViewKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); - connect(&dbViewKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); searchEdit->setTreeView(databaseView); QVBoxLayout *leftFrame = new QVBoxLayout; @@ -137,10 +133,11 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) deckView->setModel(deckModel); deckView->setUniformRowHeights(true); deckView->header()->setResizeMode(QHeaderView::ResizeToContents); - deckViewKeySignals.filterLeftRight(false); deckView->installEventFilter(&deckViewKeySignals); connect(deckView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updateCardInfoRight(const QModelIndex &, const QModelIndex &))); connect(&deckViewKeySignals, SIGNAL(onEnter()), this, SLOT(actIncrement())); + connect(&deckViewKeySignals, SIGNAL(onCtrlAltEqual()), this, SLOT(actIncrement())); + connect(&deckViewKeySignals, SIGNAL(onCtrlAltMinus()), this, SLOT(actDecrement())); connect(&deckViewKeySignals, SIGNAL(onRight()), this, SLOT(actIncrement())); connect(&deckViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrement())); connect(&deckViewKeySignals, SIGNAL(onDelete()), this, SLOT(actRemoveCard())); diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index bcdca8d3..3acf1d15 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -80,7 +80,6 @@ private: DeckListModel *deckModel; QTreeView *databaseView; - KeySignals dbViewKeySignals; QTreeView *deckView; KeySignals deckViewKeySignals; CardFrame *cardInfo; From 69201460e6f961b9b0f3aac986f8712ab536dd6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Sun, 18 May 2014 10:54:41 +0200 Subject: [PATCH 28/55] Included climits for UINT_MAX non-aware compilers. --- common/rng_sfmt.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index fa97aa6b..8176cba7 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -1,6 +1,7 @@ #include "rng_sfmt.h" #include #include +#include #include // This is from gcc sources, namely from fixincludes/inclhack.def From bf6ec478cb000687ed46327450e7f654f0aeb78a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Sun, 18 May 2014 11:10:29 +0200 Subject: [PATCH 29/55] Dealt with SFMT compile warnings. --- CMakeLists.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 69d22d76..5ca2192d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,10 @@ cmake_minimum_required(VERSION 2.6) + +IF(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") +# GNU systems need to define the Mersenne exponent for the RNG to compile w/o warning + ADD_DEFINITIONS("-DSFMT_MEXP=19937") +ENDIF() + add_subdirectory(common) if(WITH_SERVER) add_subdirectory(servatrice) From 197dd0f3c81eb57cdfb5c3bfd8cd758605c0036e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Fri, 30 May 2014 11:48:07 +0200 Subject: [PATCH 30/55] Remove useless bound checks. --- common/rng_sfmt.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index 8176cba7..ce734c4d 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -62,7 +62,7 @@ RNG_SFMT::RNG_SFMT(QObject *parent) unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) { // This all makes no sense if min > max, which should never happen. - if(min > max || max >= UINT_MAX || min >= UINT_MAX) { + if(min > max) { throw std::invalid_argument( QString("Invalid bounds for RNG: min > max! Values were: min = " + QString::number(min) + ", max = " + From ccab97ca7dfd266dacbb284e36d8dd6a30d3c275 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mark=20Morschh=C3=A4user?= Date: Mon, 9 Jun 2014 13:31:21 +0200 Subject: [PATCH 31/55] RNG: added additional checks (which forced an interface redesign), updated comments --- common/rng_abstract.cpp | 4 ++-- common/rng_abstract.h | 2 +- common/rng_sfmt.cpp | 48 +++++++++++++++++++++++++++++++++----- common/rng_sfmt.h | 31 +++++++++++++----------- common/server_cardzone.cpp | 2 +- common/server_player.cpp | 4 ++-- 6 files changed, 65 insertions(+), 26 deletions(-) diff --git a/common/rng_abstract.cpp b/common/rng_abstract.cpp index 2919d437..4c51143a 100644 --- a/common/rng_abstract.cpp +++ b/common/rng_abstract.cpp @@ -7,9 +7,9 @@ QVector RNG_Abstract::makeNumbersVector(int n, int min, int max) const int bins = max - min + 1; QVector result(bins); for (int i = 0; i < n; ++i) { - int number = getNumber(min, max); + int number = rand(min, max); if ((number < min) || (number > max)) - qDebug() << "getNumber(" << min << "," << max << ") returned " << number; + qDebug() << "rand(" << min << "," << max << ") returned " << number; else result[number - min]++; } diff --git a/common/rng_abstract.h b/common/rng_abstract.h index 5d60033f..f2017819 100644 --- a/common/rng_abstract.h +++ b/common/rng_abstract.h @@ -8,7 +8,7 @@ class RNG_Abstract : public QObject { Q_OBJECT public: RNG_Abstract(QObject *parent = 0) : QObject(parent) { } - virtual unsigned int getNumber(unsigned int min, unsigned int max) = 0; + virtual unsigned int rand(int min, int max) = 0; QVector makeNumbersVector(int n, int min, int max); double testRandom(const QVector &numbers) const; }; diff --git a/common/rng_sfmt.cpp b/common/rng_sfmt.cpp index ce734c4d..d3d55d1c 100644 --- a/common/rng_sfmt.cpp +++ b/common/rng_sfmt.cpp @@ -17,6 +17,44 @@ RNG_SFMT::RNG_SFMT(QObject *parent) sfmt_init_gen_rand(&sfmt, QDateTime::currentDateTime().toTime_t()); } +/** + * This method is the rand() equivalent which calls the cdf with proper bounds. + * + * It is possible to generate random numbers from [-min, +/-max] though the RNG uses + * unsigned numbers only, so this wrapper handles some special cases for min and max. + * + * It is only necessary that the upper bound is larger or equal to the lower bound - with the exception + * that someone wants something like rand() % -foo. + */ +unsigned int RNG_SFMT::rand(int min, int max) { + /* If min is negative, it would be possible to calculate + * cdf(0, max - min) + min + * There has been no use for negative random numbers with rand() though, so it's treated as error. + */ + if(min < 0) { + throw std::invalid_argument( + QString("Invalid bounds for RNG: Got min " + + QString::number(min) + " < 0!\n").toStdString()); + // at this point, the method exits. No return value is needed, because + // basically the exception itself is returned. + } + + // For complete fairness and equal timing, this should be a roll, but let's skip it anyway + if(min == max) + return max; + + // This is actually not used in Cockatrice: + // Someone wants rand() % -foo, so we compute -rand(0, +foo) + // This is the only time where min > max is (sort of) legal. + // Not handling this will cause the application to crash. + if(min == 0 && max < 0) { + return -cdf(0, -max); + } + + // No special cases are left, except !(min > max) which is caught in the cdf itself. + return cdf(min, max); +} + /** * Much thought went into this, please read this comment before you modify the code. * Let SFMT() be an alias for sfmt_genrand_uint64() aka SFMT's rand() function. @@ -33,7 +71,7 @@ RNG_SFMT::RNG_SFMT(QObject *parent) * * To get out the random variable, solve for X: * floor(X) = SFMT(X; min, max) * (max - min + 1) + min - 1 - * So this is, what getNumber(min, max) should look like. + * So this is, what rand(min, max) should look like. * Problem: SFMT(X; min, max) * (max - min + 1) could produce an integer overflow, * so it is not safe. * @@ -56,19 +94,17 @@ RNG_SFMT::RNG_SFMT(QObject *parent) * then you _need_ to change the UINT64_MAX constant to the largest possible random * number which can be created by the new rand() function. This value is often defined * in a RAND_MAX constant. - * Otherwise you will probably skew the outcome of the getNumber() method or worsen the + * Otherwise you will probably skew the outcome of the rand() method or worsen the * performance of the application. */ -unsigned int RNG_SFMT::getNumber(unsigned int min, unsigned int max) +unsigned int RNG_SFMT::cdf(unsigned int min, unsigned int max) { // This all makes no sense if min > max, which should never happen. if(min > max) { throw std::invalid_argument( QString("Invalid bounds for RNG: min > max! Values were: min = " + QString::number(min) + ", max = " + - QString::number(max) + - ". This is either a bug or something even more serious happened." - ).toStdString()); + QString::number(max)).toStdString()); // at this point, the method exits. No return value is needed, because // basically the exception itself is returned. } diff --git a/common/rng_sfmt.h b/common/rng_sfmt.h index 3134e91d..d35ce97d 100644 --- a/common/rng_sfmt.h +++ b/common/rng_sfmt.h @@ -1,27 +1,28 @@ #ifndef RNG_SFMT_H #define RNG_SFMT_H +#include +#include #include "sfmt/SFMT.h" #include "rng_abstract.h" -#include /** - * This class represents the random number generator. - * Usage instructions: - * Create an instance of RNG_SFMT, then call getNumber(min, max). - * You should never call this function with min > max, this throws a - * std::invalid_argument exception. It is best practice to use getNumber() in a try block - * and catch the exception if min, max are entered by the user or computed somehow. + * This class encapsulates a state of the art PRNG and can be used + * to return uniformly distributed integer random numbers from a range [min, max]. + * Though technically possible, min must be >= 0 and max should always be > 0. + * If max < 0 and min == 0 it is assumed that rand() % -max is wanted and the result will + * be -rand(0, -max). + * This is the only exception to the rule that !(min > max) and is actually unused in + * Cockatrice. * * Technical details: * The RNG uses the SIMD-oriented Fast Mersenne Twister code v1.4.1 from * http://www.math.sci.hiroshima-u.ac.jp/~%20m-mat/MT/SFMT/index.html - * To use this RNG, the class needs a sfmt_t structure for the RNG's internal state. - * It has to be initialized by sfmt_init_gen_rand() which is done in the constructor. - * The function sfmt_genrand_uint64() can then be used to create a 64 bit unsigned int - * pseudorandom number. This is done in getNumber(). - * For more information see the author's website and look at the documentation and - * examples that are part of the official downloads. + * The SFMT RNG creates unsigned int 64bit pseudo random numbers. + * + * These are mapped to values from the interval [min, max] without bias by using Knuth's + * "Algorithm S (Selection sampling technique)" from "The Art of Computer Programming 3rd + * Edition Volume 2 / Seminumerical Algorithms". */ class RNG_SFMT : public RNG_Abstract { @@ -29,9 +30,11 @@ class RNG_SFMT : public RNG_Abstract { private: QMutex mutex; sfmt_t sfmt; + // The discrete cumulative distribution function for the RNG + unsigned int cdf(unsigned int min, unsigned int max); public: RNG_SFMT(QObject *parent = 0); - unsigned int getNumber(unsigned int min, unsigned int max); + unsigned int rand(int min, int max); }; #endif diff --git a/common/server_cardzone.cpp b/common/server_cardzone.cpp index 018abae8..4a9345b3 100644 --- a/common/server_cardzone.cpp +++ b/common/server_cardzone.cpp @@ -45,7 +45,7 @@ void Server_CardZone::shuffle() { QList temp; for (int i = cards.size(); i; i--) - temp.append(cards.takeAt(rng->getNumber(0, i - 1))); + temp.append(cards.takeAt(rng->rand(0, i - 1))); cards = temp; playersWithWritePermission.clear(); diff --git a/common/server_player.cpp b/common/server_player.cpp index 489c3dcb..a029abed 100644 --- a/common/server_player.cpp +++ b/common/server_player.cpp @@ -844,7 +844,7 @@ Response::ResponseCode Server_Player::cmdRollDie(const Command_RollDie &cmd, Res Event_RollDie event; event.set_sides(cmd.sides()); - event.set_value(rng->getNumber(1, cmd.sides())); + event.set_value(rng->rand(1, cmd.sides())); ges.enqueueGameEvent(event, playerId); return Response::RespOk; @@ -1524,7 +1524,7 @@ Response::ResponseCode Server_Player::cmdRevealCards(const Command_RevealCards & else if (cmd.card_id() == -2) { if (zone->getCards().isEmpty()) return Response::RespContextError; - cardsToReveal.append(zone->getCards().at(rng->getNumber(0, zone->getCards().size() - 1))); + cardsToReveal.append(zone->getCards().at(rng->rand(0, zone->getCards().size() - 1))); } else { Server_Card *card = zone->getCard(cmd.card_id()); if (!card) From 4fc6831784eeea4912ba09b0475813e05177a74e Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 11:42:41 +0200 Subject: [PATCH 32/55] Avoid using gcc-specific flags on not-gnu compilers --- cockatrice/CMakeLists.txt | 281 +++++++++++++++++++------------------- oracle/CMakeLists.txt | 8 +- 2 files changed, 150 insertions(+), 139 deletions(-) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 70de75a5..418becec 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -3,158 +3,158 @@ set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) PROJECT(cockatrice) SET(cockatrice_SOURCES - src/abstractcounter.cpp - src/counter_general.cpp - src/dlg_creategame.cpp + src/abstractcounter.cpp + src/counter_general.cpp + src/dlg_creategame.cpp src/dlg_filter_games.cpp - src/dlg_connect.cpp - src/dlg_create_token.cpp + src/dlg_connect.cpp + src/dlg_create_token.cpp src/dlg_edit_tokens.cpp - src/abstractclient.cpp - src/remoteclient.cpp - src/main.cpp - src/window_main.cpp - src/gamesmodel.cpp - src/player.cpp - src/playertarget.cpp - src/cardzone.cpp - src/selectzone.cpp - src/cardlist.cpp - src/abstractcarditem.cpp - src/carditem.cpp - src/tablezone.cpp - src/handzone.cpp - src/handcounter.cpp - src/carddatabase.cpp - src/gameview.cpp - src/gameselector.cpp - src/decklistmodel.cpp - src/deck_loader.cpp - src/dlg_load_deck_from_clipboard.cpp - src/dlg_load_remote_deck.cpp - src/cardinfowidget.cpp - src/messagelogwidget.cpp - src/zoneviewzone.cpp - src/zoneviewwidget.cpp - src/pilezone.cpp - src/stackzone.cpp - src/carddragitem.cpp - src/carddatabasemodel.cpp - src/setsmodel.cpp - src/window_sets.cpp - src/abstractgraphicsitem.cpp - src/abstractcarddragitem.cpp - src/dlg_settings.cpp - src/dlg_cardsearch.cpp - src/phasestoolbar.cpp - src/gamescene.cpp - src/arrowitem.cpp - src/arrowtarget.cpp - src/tab.cpp - src/tab_server.cpp - src/tab_room.cpp - src/tab_message.cpp - src/tab_game.cpp - src/tab_deck_storage.cpp - src/tab_replays.cpp - src/tab_supervisor.cpp - src/tab_admin.cpp - src/tab_userlists.cpp + src/abstractclient.cpp + src/remoteclient.cpp + src/main.cpp + src/window_main.cpp + src/gamesmodel.cpp + src/player.cpp + src/playertarget.cpp + src/cardzone.cpp + src/selectzone.cpp + src/cardlist.cpp + src/abstractcarditem.cpp + src/carditem.cpp + src/tablezone.cpp + src/handzone.cpp + src/handcounter.cpp + src/carddatabase.cpp + src/gameview.cpp + src/gameselector.cpp + src/decklistmodel.cpp + src/deck_loader.cpp + src/dlg_load_deck_from_clipboard.cpp + src/dlg_load_remote_deck.cpp + src/cardinfowidget.cpp + src/messagelogwidget.cpp + src/zoneviewzone.cpp + src/zoneviewwidget.cpp + src/pilezone.cpp + src/stackzone.cpp + src/carddragitem.cpp + src/carddatabasemodel.cpp + src/setsmodel.cpp + src/window_sets.cpp + src/abstractgraphicsitem.cpp + src/abstractcarddragitem.cpp + src/dlg_settings.cpp + src/dlg_cardsearch.cpp + src/phasestoolbar.cpp + src/gamescene.cpp + src/arrowitem.cpp + src/arrowtarget.cpp + src/tab.cpp + src/tab_server.cpp + src/tab_room.cpp + src/tab_message.cpp + src/tab_game.cpp + src/tab_deck_storage.cpp + src/tab_replays.cpp + src/tab_supervisor.cpp + src/tab_admin.cpp + src/tab_userlists.cpp src/tab_deck_editor.cpp src/replay_timeline_widget.cpp src/deckstats_interface.cpp - src/chatview.cpp - src/userlist.cpp - src/userinfobox.cpp + src/chatview.cpp + src/userlist.cpp + src/userinfobox.cpp src/user_context_menu.cpp - src/remotedecklist_treewidget.cpp - src/remotereplaylist_treewidget.cpp - src/deckview.cpp - src/playerlistwidget.cpp - src/pixmapgenerator.cpp - src/settingscache.cpp - src/localserver.cpp - src/localserverinterface.cpp - src/localclient.cpp - src/priceupdater.cpp + src/remotedecklist_treewidget.cpp + src/remotereplaylist_treewidget.cpp + src/deckview.cpp + src/playerlistwidget.cpp + src/pixmapgenerator.cpp + src/settingscache.cpp + src/localserver.cpp + src/localserverinterface.cpp + src/localclient.cpp + src/priceupdater.cpp src/qt-json/json.cpp src/soundengine.cpp ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ) SET(cockatrice_HEADERS - src/abstractcounter.h - src/counter_general.h - src/dlg_creategame.h - src/dlg_filter_games.h - src/dlg_connect.h - src/dlg_create_token.h + src/abstractcounter.h + src/counter_general.h + src/dlg_creategame.h + src/dlg_filter_games.h + src/dlg_connect.h + src/dlg_create_token.h src/dlg_edit_tokens.h - src/gamesmodel.h - src/abstractclient.h - src/remoteclient.h - src/window_main.h - src/cardzone.h - src/selectzone.h - src/player.h - src/playertarget.h - src/abstractcarditem.h - src/carditem.h - src/tablezone.h - src/handzone.h - src/handcounter.h - src/carddatabase.h - src/gameview.h - src/gameselector.h - src/decklistmodel.h - src/deck_loader.h - src/dlg_load_deck_from_clipboard.h - src/dlg_load_remote_deck.h - src/cardinfowidget.h - src/messagelogwidget.h - src/zoneviewzone.h - src/zoneviewwidget.h - src/pilezone.h - src/stackzone.h - src/carddragitem.h - src/carddatabasemodel.h - src/setsmodel.h - src/window_sets.h - src/abstractgraphicsitem.h - src/abstractcarddragitem.h - src/dlg_settings.h - src/dlg_cardsearch.h - src/phasestoolbar.h - src/gamescene.h - src/arrowitem.h - src/arrowtarget.h - src/tab.h - src/tab_server.h - src/tab_room.h - src/tab_message.h - src/tab_game.h - src/tab_deck_storage.h - src/tab_replays.h - src/tab_supervisor.h - src/tab_admin.h - src/tab_userlists.h + src/gamesmodel.h + src/abstractclient.h + src/remoteclient.h + src/window_main.h + src/cardzone.h + src/selectzone.h + src/player.h + src/playertarget.h + src/abstractcarditem.h + src/carditem.h + src/tablezone.h + src/handzone.h + src/handcounter.h + src/carddatabase.h + src/gameview.h + src/gameselector.h + src/decklistmodel.h + src/deck_loader.h + src/dlg_load_deck_from_clipboard.h + src/dlg_load_remote_deck.h + src/cardinfowidget.h + src/messagelogwidget.h + src/zoneviewzone.h + src/zoneviewwidget.h + src/pilezone.h + src/stackzone.h + src/carddragitem.h + src/carddatabasemodel.h + src/setsmodel.h + src/window_sets.h + src/abstractgraphicsitem.h + src/abstractcarddragitem.h + src/dlg_settings.h + src/dlg_cardsearch.h + src/phasestoolbar.h + src/gamescene.h + src/arrowitem.h + src/arrowtarget.h + src/tab.h + src/tab_server.h + src/tab_room.h + src/tab_message.h + src/tab_game.h + src/tab_deck_storage.h + src/tab_replays.h + src/tab_supervisor.h + src/tab_admin.h + src/tab_userlists.h src/tab_deck_editor.h src/replay_timeline_widget.h src/deckstats_interface.h - src/chatview.h - src/userlist.h - src/userinfobox.h + src/chatview.h + src/userlist.h + src/userinfobox.h src/user_context_menu.h - src/remotedecklist_treewidget.h - src/remotereplaylist_treewidget.h - src/deckview.h - src/playerlistwidget.h - src/settingscache.h - src/localserver.h - src/localserverinterface.h - src/localclient.h - src/priceupdater.h - src/soundengine.h - src/pending_command.h + src/remotedecklist_treewidget.h + src/remotereplaylist_treewidget.h + src/deckview.h + src/playerlistwidget.h + src/settingscache.h + src/localserver.h + src/localserverinterface.h + src/localclient.h + src/priceupdater.h + src/soundengine.h + src/pending_command.h ) if (UNIX AND NOT APPLE) @@ -199,8 +199,13 @@ endif (NOT QT_QTMULTIMEDIA_FOUND) FIND_PACKAGE(Protobuf REQUIRED) FIND_PACKAGE(Threads) -set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") -set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") +IF (CMAKE_COMPILER_IS_GNUCC) + set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") + set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") +ELSE (CMAKE_COMPILER_IS_GNUCC) + set(CMAKE_CXX_FLAGS_RELEASE "-O2") + set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") +ENDIF (CMAKE_COMPILER_IS_GNUCC) # paths set(ICONDIR share/icons CACHE STRING "icon dir") diff --git a/oracle/CMakeLists.txt b/oracle/CMakeLists.txt index 41338903..6f4e18c9 100644 --- a/oracle/CMakeLists.txt +++ b/oracle/CMakeLists.txt @@ -13,7 +13,13 @@ SET(QT_USE_QTSVG TRUE) FIND_PACKAGE(Qt4 REQUIRED) set(CMAKE_BUILD_TYPE Release) -set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") +IF (CMAKE_COMPILER_IS_GNUCC) + set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") + set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") +ELSE (CMAKE_COMPILER_IS_GNUCC) + set(CMAKE_CXX_FLAGS_RELEASE "-O2") + set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") +ENDIF (CMAKE_COMPILER_IS_GNUCC) QT4_WRAP_CPP(oracle_HEADERS_MOC ${oracle_HEADERS}) INCLUDE(${QT_USE_FILE}) From 79c805b8357e79f683838dcc81a5aada7f65a755 Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 14:11:16 +0200 Subject: [PATCH 33/55] Create sounds/zonebg CMakeLists.txt --- CMakeLists.txt | 7 ++----- sounds/CMakeLists.txt | 2 ++ zonebg/CMakeLists.txt | 2 ++ 3 files changed, 6 insertions(+), 5 deletions(-) create mode 100644 sounds/CMakeLists.txt create mode 100644 zonebg/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 69d22d76..d924d307 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,12 +6,9 @@ endif(WITH_SERVER) if (NOT WITHOUT_CLIENT) add_subdirectory(cockatrice) add_subdirectory(oracle) + add_subdirectory(sounds) + add_subdirectory(zonebg) endif(NOT WITHOUT_CLIENT) if (WITH_TESTCLIENT) add_subdirectory(testclient) endif(WITH_TESTCLIENT) - -FILE(GLOB sounds "${CMAKE_CURRENT_SOURCE_DIR}/sounds/*.raw") -INSTALL(FILES ${sounds} DESTINATION share/cockatrice/sounds) -FILE(GLOB zonebg "${CMAKE_CURRENT_SOURCE_DIR}/zonebg/*.*") -INSTALL(FILES ${zonebg} DESTINATION share/cockatrice/zonebg) diff --git a/sounds/CMakeLists.txt b/sounds/CMakeLists.txt new file mode 100644 index 00000000..56a4a029 --- /dev/null +++ b/sounds/CMakeLists.txt @@ -0,0 +1,2 @@ +FILE(GLOB sounds "${CMAKE_CURRENT_SOURCE_DIR}/sounds/*.raw") +INSTALL(FILES ${sounds} DESTINATION share/cockatrice/sounds) diff --git a/zonebg/CMakeLists.txt b/zonebg/CMakeLists.txt new file mode 100644 index 00000000..b3e23a50 --- /dev/null +++ b/zonebg/CMakeLists.txt @@ -0,0 +1,2 @@ +FILE(GLOB zonebg "${CMAKE_CURRENT_SOURCE_DIR}/zonebg/*.*") +INSTALL(FILES ${zonebg} DESTINATION share/cockatrice/zonebg) From e2d17e983f658a8a076b83bb5456d75dffccf817 Mon Sep 17 00:00:00 2001 From: ctrlaltca Date: Tue, 10 Jun 2014 20:05:24 +0200 Subject: [PATCH 34/55] Restored whitespaces in CMakeLists.txt --- cockatrice/CMakeLists.txt | 272 +++++++++++++++++++------------------- 1 file changed, 136 insertions(+), 136 deletions(-) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 418becec..0fcbc115 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -3,158 +3,158 @@ set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) PROJECT(cockatrice) SET(cockatrice_SOURCES - src/abstractcounter.cpp - src/counter_general.cpp - src/dlg_creategame.cpp + src/abstractcounter.cpp + src/counter_general.cpp + src/dlg_creategame.cpp src/dlg_filter_games.cpp - src/dlg_connect.cpp - src/dlg_create_token.cpp + src/dlg_connect.cpp + src/dlg_create_token.cpp src/dlg_edit_tokens.cpp - src/abstractclient.cpp - src/remoteclient.cpp - src/main.cpp - src/window_main.cpp - src/gamesmodel.cpp - src/player.cpp - src/playertarget.cpp - src/cardzone.cpp - src/selectzone.cpp - src/cardlist.cpp - src/abstractcarditem.cpp - src/carditem.cpp - src/tablezone.cpp - src/handzone.cpp - src/handcounter.cpp - src/carddatabase.cpp - src/gameview.cpp - src/gameselector.cpp - src/decklistmodel.cpp - src/deck_loader.cpp - src/dlg_load_deck_from_clipboard.cpp - src/dlg_load_remote_deck.cpp - src/cardinfowidget.cpp - src/messagelogwidget.cpp - src/zoneviewzone.cpp - src/zoneviewwidget.cpp - src/pilezone.cpp - src/stackzone.cpp - src/carddragitem.cpp - src/carddatabasemodel.cpp - src/setsmodel.cpp - src/window_sets.cpp - src/abstractgraphicsitem.cpp - src/abstractcarddragitem.cpp - src/dlg_settings.cpp - src/dlg_cardsearch.cpp - src/phasestoolbar.cpp - src/gamescene.cpp - src/arrowitem.cpp - src/arrowtarget.cpp - src/tab.cpp - src/tab_server.cpp - src/tab_room.cpp - src/tab_message.cpp - src/tab_game.cpp - src/tab_deck_storage.cpp - src/tab_replays.cpp - src/tab_supervisor.cpp - src/tab_admin.cpp - src/tab_userlists.cpp + src/abstractclient.cpp + src/remoteclient.cpp + src/main.cpp + src/window_main.cpp + src/gamesmodel.cpp + src/player.cpp + src/playertarget.cpp + src/cardzone.cpp + src/selectzone.cpp + src/cardlist.cpp + src/abstractcarditem.cpp + src/carditem.cpp + src/tablezone.cpp + src/handzone.cpp + src/handcounter.cpp + src/carddatabase.cpp + src/gameview.cpp + src/gameselector.cpp + src/decklistmodel.cpp + src/deck_loader.cpp + src/dlg_load_deck_from_clipboard.cpp + src/dlg_load_remote_deck.cpp + src/cardinfowidget.cpp + src/messagelogwidget.cpp + src/zoneviewzone.cpp + src/zoneviewwidget.cpp + src/pilezone.cpp + src/stackzone.cpp + src/carddragitem.cpp + src/carddatabasemodel.cpp + src/setsmodel.cpp + src/window_sets.cpp + src/abstractgraphicsitem.cpp + src/abstractcarddragitem.cpp + src/dlg_settings.cpp + src/dlg_cardsearch.cpp + src/phasestoolbar.cpp + src/gamescene.cpp + src/arrowitem.cpp + src/arrowtarget.cpp + src/tab.cpp + src/tab_server.cpp + src/tab_room.cpp + src/tab_message.cpp + src/tab_game.cpp + src/tab_deck_storage.cpp + src/tab_replays.cpp + src/tab_supervisor.cpp + src/tab_admin.cpp + src/tab_userlists.cpp src/tab_deck_editor.cpp src/replay_timeline_widget.cpp src/deckstats_interface.cpp - src/chatview.cpp - src/userlist.cpp - src/userinfobox.cpp + src/chatview.cpp + src/userlist.cpp + src/userinfobox.cpp src/user_context_menu.cpp - src/remotedecklist_treewidget.cpp - src/remotereplaylist_treewidget.cpp - src/deckview.cpp - src/playerlistwidget.cpp - src/pixmapgenerator.cpp - src/settingscache.cpp - src/localserver.cpp - src/localserverinterface.cpp - src/localclient.cpp - src/priceupdater.cpp + src/remotedecklist_treewidget.cpp + src/remotereplaylist_treewidget.cpp + src/deckview.cpp + src/playerlistwidget.cpp + src/pixmapgenerator.cpp + src/settingscache.cpp + src/localserver.cpp + src/localserverinterface.cpp + src/localclient.cpp + src/priceupdater.cpp src/qt-json/json.cpp src/soundengine.cpp ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ) SET(cockatrice_HEADERS - src/abstractcounter.h - src/counter_general.h - src/dlg_creategame.h - src/dlg_filter_games.h - src/dlg_connect.h - src/dlg_create_token.h + src/abstractcounter.h + src/counter_general.h + src/dlg_creategame.h + src/dlg_filter_games.h + src/dlg_connect.h + src/dlg_create_token.h src/dlg_edit_tokens.h - src/gamesmodel.h - src/abstractclient.h - src/remoteclient.h - src/window_main.h - src/cardzone.h - src/selectzone.h - src/player.h - src/playertarget.h - src/abstractcarditem.h - src/carditem.h - src/tablezone.h - src/handzone.h - src/handcounter.h - src/carddatabase.h - src/gameview.h - src/gameselector.h - src/decklistmodel.h - src/deck_loader.h - src/dlg_load_deck_from_clipboard.h - src/dlg_load_remote_deck.h - src/cardinfowidget.h - src/messagelogwidget.h - src/zoneviewzone.h - src/zoneviewwidget.h - src/pilezone.h - src/stackzone.h - src/carddragitem.h - src/carddatabasemodel.h - src/setsmodel.h - src/window_sets.h - src/abstractgraphicsitem.h - src/abstractcarddragitem.h - src/dlg_settings.h - src/dlg_cardsearch.h - src/phasestoolbar.h - src/gamescene.h - src/arrowitem.h - src/arrowtarget.h - src/tab.h - src/tab_server.h - src/tab_room.h - src/tab_message.h - src/tab_game.h - src/tab_deck_storage.h - src/tab_replays.h - src/tab_supervisor.h - src/tab_admin.h - src/tab_userlists.h + src/gamesmodel.h + src/abstractclient.h + src/remoteclient.h + src/window_main.h + src/cardzone.h + src/selectzone.h + src/player.h + src/playertarget.h + src/abstractcarditem.h + src/carditem.h + src/tablezone.h + src/handzone.h + src/handcounter.h + src/carddatabase.h + src/gameview.h + src/gameselector.h + src/decklistmodel.h + src/deck_loader.h + src/dlg_load_deck_from_clipboard.h + src/dlg_load_remote_deck.h + src/cardinfowidget.h + src/messagelogwidget.h + src/zoneviewzone.h + src/zoneviewwidget.h + src/pilezone.h + src/stackzone.h + src/carddragitem.h + src/carddatabasemodel.h + src/setsmodel.h + src/window_sets.h + src/abstractgraphicsitem.h + src/abstractcarddragitem.h + src/dlg_settings.h + src/dlg_cardsearch.h + src/phasestoolbar.h + src/gamescene.h + src/arrowitem.h + src/arrowtarget.h + src/tab.h + src/tab_server.h + src/tab_room.h + src/tab_message.h + src/tab_game.h + src/tab_deck_storage.h + src/tab_replays.h + src/tab_supervisor.h + src/tab_admin.h + src/tab_userlists.h src/tab_deck_editor.h src/replay_timeline_widget.h src/deckstats_interface.h - src/chatview.h - src/userlist.h - src/userinfobox.h + src/chatview.h + src/userlist.h + src/userinfobox.h src/user_context_menu.h - src/remotedecklist_treewidget.h - src/remotereplaylist_treewidget.h - src/deckview.h - src/playerlistwidget.h - src/settingscache.h - src/localserver.h - src/localserverinterface.h - src/localclient.h - src/priceupdater.h - src/soundengine.h - src/pending_command.h + src/remotedecklist_treewidget.h + src/remotereplaylist_treewidget.h + src/deckview.h + src/playerlistwidget.h + src/settingscache.h + src/localserver.h + src/localserverinterface.h + src/localclient.h + src/priceupdater.h + src/soundengine.h + src/pending_command.h ) if (UNIX AND NOT APPLE) From 20b9a538faed0ac709ae6108087eff0704abff8a Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 22:33:21 +0200 Subject: [PATCH 35/55] Split PendingCommand 's implementation to its own cpp to permit automoc --- cockatrice/src/pending_command.cpp | 31 ++++++++++++++++++++++++++++++ cockatrice/src/pending_command.h | 17 ++++++---------- 2 files changed, 37 insertions(+), 11 deletions(-) create mode 100644 cockatrice/src/pending_command.cpp diff --git a/cockatrice/src/pending_command.cpp b/cockatrice/src/pending_command.cpp new file mode 100644 index 00000000..0ebb1d82 --- /dev/null +++ b/cockatrice/src/pending_command.cpp @@ -0,0 +1,31 @@ +#include "pending_command.h" + +PendingCommand::PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData) + : commandContainer(_commandContainer), extraData(_extraData), ticks(0) +{ + +} + +CommandContainer & PendingCommand::getCommandContainer() +{ + return commandContainer; +} + +void PendingCommand::setExtraData(const QVariant &_extraData) { + extraData = _extraData; +} + +QVariant PendingCommand::getExtraData() const { + return extraData; +} + +void PendingCommand::processResponse(const Response &response) +{ + emit finished(response, commandContainer, extraData); + emit finished(response.response_code()); +} + +int PendingCommand::tick() +{ + return ++ticks; +} diff --git a/cockatrice/src/pending_command.h b/cockatrice/src/pending_command.h index 9b092dcd..4ca9035b 100644 --- a/cockatrice/src/pending_command.h +++ b/cockatrice/src/pending_command.h @@ -15,17 +15,12 @@ private: QVariant extraData; int ticks; public: - PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant()) - : commandContainer(_commandContainer), extraData(_extraData), ticks(0) { } - CommandContainer &getCommandContainer() { return commandContainer; } - void setExtraData(const QVariant &_extraData) { extraData = _extraData; } - QVariant getExtraData() const { return extraData; } - void processResponse(const Response &response) - { - emit finished(response, commandContainer, extraData); - emit finished(response.response_code()); - } - int tick() { return ++ticks; } + PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant()); + CommandContainer &getCommandContainer(); + void setExtraData(const QVariant &_extraData); + QVariant getExtraData() const; + void processResponse(const Response &response); + int tick(); }; #endif From 84503483eb61f561fbf5a69a84c80d44c9718f6b Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 23:25:59 +0200 Subject: [PATCH 36/55] Added missing ifdefs around keysignals.h --- cockatrice/src/keysignals.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cockatrice/src/keysignals.h b/cockatrice/src/keysignals.h index 23a07b77..693488c5 100644 --- a/cockatrice/src/keysignals.h +++ b/cockatrice/src/keysignals.h @@ -1,3 +1,6 @@ +#ifndef KEYSIGNALS_H +#define KEYSIGNALS_H + #include #include @@ -19,3 +22,5 @@ signals: protected: virtual bool eventFilter(QObject *, QEvent *event); }; + +#endif From c9f10554c6f8d7af4606624730cffcba4da69e26 Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 23:26:37 +0200 Subject: [PATCH 37/55] comment in sounds and zonebg's CMakeLists.txt --- sounds/CMakeLists.txt | 4 ++++ zonebg/CMakeLists.txt | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/sounds/CMakeLists.txt b/sounds/CMakeLists.txt index 56a4a029..6dd10f87 100644 --- a/sounds/CMakeLists.txt +++ b/sounds/CMakeLists.txt @@ -1,2 +1,6 @@ +# CMakeLists for sounds/ directory +# +# Installs default sound files + FILE(GLOB sounds "${CMAKE_CURRENT_SOURCE_DIR}/sounds/*.raw") INSTALL(FILES ${sounds} DESTINATION share/cockatrice/sounds) diff --git a/zonebg/CMakeLists.txt b/zonebg/CMakeLists.txt index b3e23a50..76c7c356 100644 --- a/zonebg/CMakeLists.txt +++ b/zonebg/CMakeLists.txt @@ -1,2 +1,6 @@ +# CMakeLists for zonebg/ directory +# +# Installs default "zone background" files + FILE(GLOB zonebg "${CMAKE_CURRENT_SOURCE_DIR}/zonebg/*.*") INSTALL(FILES ${zonebg} DESTINATION share/cockatrice/zonebg) From 4c1687264d1e9566676ced21ee20769925bf64de Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 23:29:24 +0200 Subject: [PATCH 38/55] main CMakeLists.txt: major overhaul MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * define CMAKE_INSTALL_PREFIX * define compilation flags * find needed libraries * enable Qt4’s automoc * Added comments --- CMakeLists.txt | 62 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0540ff8b..5004ae66 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,20 +1,80 @@ +# Cockatrice's main CMakeLists.txt +# +# This is basically a wrapper to enable/disable the compilation +# of the different projects: servatrice, cockatrice, test +# This file sets all the variables shared between the projects +# like the installation path, compilation flags etc.. + cmake_minimum_required(VERSION 2.6) -IF(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") +# Set conventional loops +set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true) + +# Define a proper install path +if(UNIX) + if(APPLE) + # MacOS X + # Due to the special bundle structure ignore + # the prefix eventually set by the user. + set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/release) + else() + # Linux / BSD + if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + #fix package build + if(PREFIX) + set(CMAKE_INSTALL_PREFIX ${PREFIX}) + else() + set(CMAKE_INSTALL_PREFIX /usr/local) + endif() + endif() + endif() +elseif(WIN32) + set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/release) +endif() + +# Force "Release" build type by default +set(CMAKE_BUILD_TYPE Release) + +# Define proper compilation flags +IF (CMAKE_COMPILER_IS_GNUCC) + # linux/gcc, bsd/gcc, windows/mingw + set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") + set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") +else() + # other: osx/llvm, bsd/llvm + set(CMAKE_CXX_FLAGS_RELEASE "-O2") + set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") +ENDIF (CMAKE_COMPILER_IS_GNUCC) + # GNU systems need to define the Mersenne exponent for the RNG to compile w/o warning +IF(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") ADD_DEFINITIONS("-DSFMT_MEXP=19937") ENDIF() +#Find Qt4 and enable the needed features +FIND_PACKAGE(Qt4 REQUIRED) + +set(CMAKE_AUTOMOC TRUE) + +# Find other needed libraries +FIND_PACKAGE(Protobuf REQUIRED) +FIND_PACKAGE(Threads) + +# Compile servatrice (default off) add_subdirectory(common) if(WITH_SERVER) add_subdirectory(servatrice) endif(WITH_SERVER) + +# Compile cockatrice+oracle (default on) if (NOT WITHOUT_CLIENT) add_subdirectory(cockatrice) add_subdirectory(oracle) add_subdirectory(sounds) add_subdirectory(zonebg) endif(NOT WITHOUT_CLIENT) + +# Compile testclient (default off) if (WITH_TESTCLIENT) add_subdirectory(testclient) endif(WITH_TESTCLIENT) From 0dd6567583e609200cad3febae6892ee3ac08b0d Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 23:32:52 +0200 Subject: [PATCH 39/55] cockatrice's CMakeLists.txt: major overhaul * Remove cockatrice_HEADERS (obsoleted by automoc) * Remove compilation flags definition and Qt4 finding calls * Make use of CMAKE_INSTALL_PREFIX * use INSTALL(TARGETS) in place of INSTALL(PROGRAM) * Osx: create a proper application bundle * Added comments --- cockatrice/CMakeLists.txt | 164 +++++++++++++------------------------- 1 file changed, 56 insertions(+), 108 deletions(-) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index d25b9d7c..da75ebd3 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -1,5 +1,7 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 2.6) -set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +# CMakeLists for cockatrice directory +# +# provides the cockatrice binary + PROJECT(cockatrice) SET(cockatrice_SOURCES @@ -87,91 +89,9 @@ SET(cockatrice_SOURCES src/priceupdater.cpp src/qt-json/json.cpp src/soundengine.cpp + src/pending_command.cpp ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ) -SET(cockatrice_HEADERS - src/abstractcounter.h - src/counter_general.h - src/dlg_creategame.h - src/dlg_filter_games.h - src/dlg_connect.h - src/dlg_create_token.h - src/dlg_edit_tokens.h - src/gamesmodel.h - src/abstractclient.h - src/remoteclient.h - src/window_main.h - src/cardzone.h - src/selectzone.h - src/player.h - src/playertarget.h - src/abstractcarditem.h - src/carditem.h - src/tablezone.h - src/handzone.h - src/handcounter.h - src/carddatabase.h - src/keysignals.h - src/gameview.h - src/gameselector.h - src/decklistmodel.h - src/deck_loader.h - src/dlg_load_deck_from_clipboard.h - src/dlg_load_remote_deck.h - src/cardinfowidget.h - src/cardframe.h - src/cardinfopicture.h - src/cardinfotext.h - src/filterbuilder.h - src/cardfilter.h - src/filtertreemodel.h - src/filtertree.h - src/messagelogwidget.h - src/zoneviewzone.h - src/zoneviewwidget.h - src/pilezone.h - src/stackzone.h - src/carddragitem.h - src/carddatabasemodel.h - src/setsmodel.h - src/window_sets.h - src/abstractgraphicsitem.h - src/abstractcarddragitem.h - src/dlg_settings.h - src/dlg_cardsearch.h - src/phasestoolbar.h - src/gamescene.h - src/arrowitem.h - src/arrowtarget.h - src/tab.h - src/tab_server.h - src/tab_room.h - src/tab_message.h - src/tab_game.h - src/tab_deck_storage.h - src/tab_replays.h - src/tab_supervisor.h - src/tab_admin.h - src/tab_userlists.h - src/tab_deck_editor.h - src/replay_timeline_widget.h - src/deckstats_interface.h - src/chatview.h - src/userlist.h - src/userinfobox.h - src/user_context_menu.h - src/remotedecklist_treewidget.h - src/remotereplaylist_treewidget.h - src/deckview.h - src/playerlistwidget.h - src/settingscache.h - src/localserver.h - src/localserverinterface.h - src/localclient.h - src/priceupdater.h - src/soundengine.h - src/pending_command.h -) if (UNIX AND NOT APPLE) set_source_files_properties(src/main.cpp PROPERTIES COMPILE_FLAGS -DTRANSLATION_PATH=\\"${CMAKE_INSTALL_PREFIX}/share/cockatrice/translations\\") @@ -204,34 +124,26 @@ if(APPLE) set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/resources/appicon.icns PROPERTIES MACOSX_PACKAGE_LOCATION Resources) set(cockatrice_SOURCES ${cockatrice_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/resources/appicon.icns) ENDIF(APPLE) + +if (NOT QT_QTMULTIMEDIA_FOUND) + FIND_PACKAGE(QtMobility REQUIRED) +endif (NOT QT_QTMULTIMEDIA_FOUND) + SET(QT_USE_QTNETWORK TRUE) SET(QT_USE_QTMULTIMEDIA TRUE) SET(QT_USE_QTXML TRUE) SET(QT_USE_QTSVG TRUE) -FIND_PACKAGE(Qt4 REQUIRED) -if (NOT QT_QTMULTIMEDIA_FOUND) - FIND_PACKAGE(QtMobility REQUIRED) -endif (NOT QT_QTMULTIMEDIA_FOUND) -FIND_PACKAGE(Protobuf REQUIRED) -FIND_PACKAGE(Threads) -IF (CMAKE_COMPILER_IS_GNUCC) - set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") - set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") -ELSE (CMAKE_COMPILER_IS_GNUCC) - set(CMAKE_CXX_FLAGS_RELEASE "-O2") - set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") -ENDIF (CMAKE_COMPILER_IS_GNUCC) - -# paths +# Declare path variables set(ICONDIR share/icons CACHE STRING "icon dir") set(DESKTOPDIR share/applications CACHE STRING "desktop file destination") - -QT4_WRAP_CPP(cockatrice_HEADERS_MOC ${cockatrice_HEADERS}) +# Let cmake chew Qt4's translations and resource files +# Note: header files are MOC-ed automatically by cmake QT4_ADD_TRANSLATION(cockatrice_QM ${cockatrice_TS}) QT4_ADD_RESOURCES(cockatrice_RESOURCES_RCC ${cockatrice_RESOURCES}) +# Include directories INCLUDE(${QT_USE_FILE}) INCLUDE_DIRECTORIES(../common) INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) @@ -240,14 +152,22 @@ INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) INCLUDE_DIRECTORIES(${QT_MOBILITY_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${QT_MOBILITY_MULTIMEDIAKIT_INCLUDE_DIR}) -ADD_EXECUTABLE(cockatrice WIN32 MACOSX_BUNDLE ${cockatrice_SOURCES} ${cockatrice_QM} ${cockatrice_RESOURCES_RCC} ${cockatrice_HEADERS_MOC}) +# Build cockatrice binary and link it +ADD_EXECUTABLE(cockatrice WIN32 MACOSX_BUNDLE ${cockatrice_SOURCES} ${cockatrice_QM} ${cockatrice_RESOURCES_RCC} ${cockatrice_MOC_SRCS}) TARGET_LINK_LIBRARIES(cockatrice cockatrice_common ${QT_LIBRARIES} ${QT_MOBILITY_MULTIMEDIAKIT_LIBRARY} ${CMAKE_THREAD_LIBS_INIT}) -IF (NOT APPLE) - INSTALL(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/cockatrice DESTINATION bin) -ELSE (APPLE) - INSTALL(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/cockatrice.app DESTINATION bin) -ENDIF (NOT APPLE) + +if(UNIX) + if(APPLE) + INSTALL(TARGETS cockatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + # Assume linux + INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + endif() +elseif(WIN32) + INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif() + if (NOT WIN32 AND NOT APPLE) INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.png DESTINATION ${ICONDIR}/hicolor/48x48/apps) INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.svg DESTINATION ${ICONDIR}/hicolor/scalable/apps) @@ -260,3 +180,31 @@ add_custom_command( COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/../common/getversion.cmake ) +if(APPLE) + set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Plugins) + set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Resources) + + # note: no codecs in qt5 + # note: phonon_backend => mediaservice + # note: needs platform on osx + + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") + else() + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") + endif() + + install(CODE " + file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] +Plugins = Plugins\") + " COMPONENT Runtime) + + install(CODE " + file(GLOB_RECURSE QTPLUGINS + \"${plugin_dest_dir}/*.dylib\") + include(BundleUtilities) + fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/cockatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + " COMPONENT Runtime) +endif() From 0f02c6b0a2a3ab1168a862c2820eab1c0692bdcb Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 23:33:33 +0200 Subject: [PATCH 40/55] oracle's CMakeLists.txt: major overhaul * Remove cockatrice_HEADERS (obsoleted by automoc) * Remove compilation flags definition and Qt4 finding calls * Make use of CMAKE_INSTALL_PREFIX * use INSTALL(TARGETS) in place of INSTALL(PROGRAM) * Osx: create a proper application bundle * Added comments --- oracle/CMakeLists.txt | 73 ++++++++++++++++++++++++++++++++----------- 1 file changed, 54 insertions(+), 19 deletions(-) diff --git a/oracle/CMakeLists.txt b/oracle/CMakeLists.txt index 6f4e18c9..66587765 100644 --- a/oracle/CMakeLists.txt +++ b/oracle/CMakeLists.txt @@ -1,38 +1,73 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +# CMakeLists for oracle directory +# +# provides the oracle binary + PROJECT(oracle) # paths set(DESKTOPDIR share/applications CACHE STRING "path to .desktop files") -SET(oracle_SOURCES src/main.cpp src/oracleimporter.cpp src/window_main.cpp ../cockatrice/src/carddatabase.cpp ../cockatrice/src/settingscache.cpp) -SET(oracle_HEADERS src/oracleimporter.h src/window_main.h ../cockatrice/src/carddatabase.h ../cockatrice/src/settingscache.h) +SET(oracle_SOURCES + src/main.cpp + src/oracleimporter.cpp + src/window_main.cpp + ../cockatrice/src/carddatabase.cpp + ../cockatrice/src/settingscache.cpp + ) SET(QT_USE_QTNETWORK TRUE) SET(QT_USE_QTXML TRUE) SET(QT_USE_QTSVG TRUE) FIND_PACKAGE(Qt4 REQUIRED) -set(CMAKE_BUILD_TYPE Release) -IF (CMAKE_COMPILER_IS_GNUCC) - set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") - set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") -ELSE (CMAKE_COMPILER_IS_GNUCC) - set(CMAKE_CXX_FLAGS_RELEASE "-O2") - set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") -ENDIF (CMAKE_COMPILER_IS_GNUCC) - -QT4_WRAP_CPP(oracle_HEADERS_MOC ${oracle_HEADERS}) +# Include directories INCLUDE(${QT_USE_FILE}) INCLUDE_DIRECTORIES(../cockatrice/src) -ADD_EXECUTABLE(oracle WIN32 MACOSX_BUNDLE ${oracle_SOURCES} ${oracle_HEADERS_MOC}) +# Build oracle binary and link it +ADD_EXECUTABLE(oracle WIN32 MACOSX_BUNDLE ${oracle_SOURCES} ${oracle_MOC_SRCS}) TARGET_LINK_LIBRARIES(oracle ${QT_LIBRARIES}) -IF (NOT APPLE) - INSTALL(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/oracle DESTINATION bin) -ELSE (APPLE) - INSTALL(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/oracle.app DESTINATION bin) -ENDIF (NOT APPLE) +if(UNIX) + if(APPLE) + INSTALL(TARGETS oracle BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + # Assume linux + INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + endif() +elseif(WIN32) + INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif() + IF (NOT WIN32 AND NOT APPLE) INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/oracle.desktop DESTINATION ${DESKTOPDIR}) ENDIF (NOT WIN32 AND NOT APPLE) + +if(APPLE) + set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) + set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) + + # note: no codecs in qt5 + # note: phonon_backend => mediaservice + # note: needs platform on osx + + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") + else() + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") + endif() + + install(CODE " + file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] +Plugins = Plugins\") + " COMPONENT Runtime) + + install(CODE " + file(GLOB_RECURSE QTPLUGINS + \"${plugin_dest_dir}/*.dylib\") + include(BundleUtilities) + fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + " COMPONENT Runtime) +endif() From 4b49458eebc875e942eb02afa5c94b76a3a67c9d Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Tue, 10 Jun 2014 23:34:01 +0200 Subject: [PATCH 41/55] servatrice's CMakeLists.txt: major overhaul * Remove cockatrice_HEADERS (obsoleted by automoc) * Remove compilation flags definition and Qt4 finding calls * Make use of CMAKE_INSTALL_PREFIX * use INSTALL(TARGETS) in place of INSTALL(PROGRAM) * Osx: create a proper application bundle * Added comments --- servatrice/CMakeLists.txt | 79 ++++++++++++++++++++++++++------------- 1 file changed, 52 insertions(+), 27 deletions(-) diff --git a/servatrice/CMakeLists.txt b/servatrice/CMakeLists.txt index 8af8fc4a..41c42952 100644 --- a/servatrice/CMakeLists.txt +++ b/servatrice/CMakeLists.txt @@ -1,44 +1,30 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 2.6) -SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +# CMakeLists for servatrice directory +# +# provides the servatrice binary + PROJECT(servatrice) -# cmake modules -include(GNUInstallDirs) +# cmake module for libgcrypt is included in current directory +SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +FIND_PACKAGE(Libgcrypt REQUIRED) SET(servatrice_SOURCES src/main.cpp src/passwordhasher.cpp - src/servatrice.cpp + src/servatrice.cpp src/servatrice_connection_pool.cpp src/servatrice_database_interface.cpp - src/server_logger.cpp - src/serversocketinterface.cpp + src/server_logger.cpp + src/serversocketinterface.cpp src/isl_interface.cpp ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ) -SET(servatrice_HEADERS - src/servatrice.h - src/servatrice_connection_pool.h - src/servatrice_database_interface.h - src/server_logger.h - src/serversocketinterface.h - src/isl_interface.h -) SET(QT_DONTUSE_QTGUI) SET(QT_USE_QTNETWORK TRUE) SET(QT_USE_QTSQL TRUE) -FIND_PACKAGE(Qt4 REQUIRED) -FIND_PACKAGE(Protobuf REQUIRED) -FIND_PACKAGE(Libgcrypt REQUIRED) -FIND_PACKAGE(Threads) - -#set(CMAKE_BUILD_TYPE Release) -set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O2") -set(CMAKE_CXX_FLAGS_RELEASE "-O2") - -QT4_WRAP_CPP(servatrice_HEADERS_MOC ${servatrice_HEADERS}) +# Include directories INCLUDE(${QT_USE_FILE}) INCLUDE_DIRECTORIES(../common) INCLUDE_DIRECTORIES(${LIBGCRYPT_INCLUDE_DIR}) @@ -46,7 +32,8 @@ INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}/../common) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) -ADD_EXECUTABLE(servatrice ${servatrice_SOURCES} ${servatrice_HEADERS_MOC}) +# Build servatrice binary and link it +ADD_EXECUTABLE(servatrice MACOSX_BUNDLE ${servatrice_SOURCES} ${servatrice_MOC_SRCS}) TARGET_LINK_LIBRARIES(servatrice cockatrice_common ${QT_LIBRARIES} ${LIBGCRYPT_LIBRARY} ${CMAKE_THREAD_LIBS_INIT}) #add_custom_target(versionheader ALL DEPENDS version_header) @@ -56,4 +43,42 @@ add_custom_command( ) # install rules -INSTALL(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/servatrice DESTINATION ${CMAKE_INSTALL_BINDIR}) +if(UNIX) + if(APPLE) + INSTALL(TARGETS servatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + # Assume linux + INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + endif() +elseif(WIN32) + INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) +endif() + +if(APPLE) + set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Plugins) + set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Resources) + + # note: no codecs in qt5 + # note: phonon_backend => mediaservice + # note: needs platform on osx + + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") + else() + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") + endif() + + install(CODE " + file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] +Plugins = Plugins\") + " COMPONENT Runtime) + + install(CODE " + file(GLOB_RECURSE QTPLUGINS + \"${plugin_dest_dir}/*.dylib\") + include(BundleUtilities) + fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/servatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + " COMPONENT Runtime) +endif() From b2ead4ffd2828d50ca84fabe375943640ec78ec4 Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 01:14:43 +0200 Subject: [PATCH 42/55] Ignore multiple build directories (used when cross compiling) --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 78301957..1753f78c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ tags -build +build* *.qm .directory From 5cd363e5907d05b81f1786835d53c81fc428b96d Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 01:15:14 +0200 Subject: [PATCH 43/55] Removed duplicate FindQt4 --- oracle/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/oracle/CMakeLists.txt b/oracle/CMakeLists.txt index 66587765..336e6e3c 100644 --- a/oracle/CMakeLists.txt +++ b/oracle/CMakeLists.txt @@ -18,7 +18,6 @@ SET(oracle_SOURCES SET(QT_USE_QTNETWORK TRUE) SET(QT_USE_QTXML TRUE) SET(QT_USE_QTSVG TRUE) -FIND_PACKAGE(Qt4 REQUIRED) # Include directories INCLUDE(${QT_USE_FILE}) From 62f756e698fc85cebc4e64c592d5bbc4506c2a4d Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 01:20:19 +0200 Subject: [PATCH 44/55] Remove pthread detection and linking: it's unused --- CMakeLists.txt | 1 - cockatrice/CMakeLists.txt | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5004ae66..76c672d8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,7 +58,6 @@ set(CMAKE_AUTOMOC TRUE) # Find other needed libraries FIND_PACKAGE(Protobuf REQUIRED) -FIND_PACKAGE(Threads) # Compile servatrice (default off) add_subdirectory(common) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index da75ebd3..16592c43 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -154,7 +154,7 @@ INCLUDE_DIRECTORIES(${QT_MOBILITY_MULTIMEDIAKIT_INCLUDE_DIR}) # Build cockatrice binary and link it ADD_EXECUTABLE(cockatrice WIN32 MACOSX_BUNDLE ${cockatrice_SOURCES} ${cockatrice_QM} ${cockatrice_RESOURCES_RCC} ${cockatrice_MOC_SRCS}) -TARGET_LINK_LIBRARIES(cockatrice cockatrice_common ${QT_LIBRARIES} ${QT_MOBILITY_MULTIMEDIAKIT_LIBRARY} ${CMAKE_THREAD_LIBS_INIT}) +TARGET_LINK_LIBRARIES(cockatrice cockatrice_common ${QT_LIBRARIES} ${QT_MOBILITY_MULTIMEDIAKIT_LIBRARY}) if(UNIX) From 4fd8c94df01468df328d428b7a1197cc4917fb1c Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 01:24:34 +0200 Subject: [PATCH 45/55] Overhaul common's CMakeLists.txt * Use automoc instead of a manual list of headers * Remove Qt4 detection * Created missing .cpp for .h files (for automoc detection) * Remove pthread linking * Forcing -lprotobuf is not needed for mingw; msvc only? --- common/CMakeLists.txt | 28 ++++------------------------ common/pb/CMakeLists.txt | 5 ++--- common/server_arrowtarget.cpp | 2 ++ common/server_database_interface.cpp | 2 ++ 4 files changed, 10 insertions(+), 27 deletions(-) create mode 100644 common/server_arrowtarget.cpp create mode 100644 common/server_database_interface.cpp diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 17d3fa46..e43c240a 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -9,10 +9,12 @@ SET(common_SOURCES server.cpp server_abstractuserinterface.cpp server_arrow.cpp + server_arrowtarget.h server_card.cpp server_cardzone.cpp server_counter.cpp server_game.cpp + server_database_interface.cpp server_player.cpp server_protocolhandler.cpp server_remoteuserinterface.cpp @@ -21,34 +23,12 @@ SET(common_SOURCES serverinfo_user_container.cpp sfmt/SFMT.c ) -SET(common_HEADERS - decklist.h - rng_abstract.h - rng_sfmt.h - server.h - server_arrowtarget.h - server_card.h - server_database_interface.h - server_game.h - server_player.h - server_protocolhandler.h - server_room.h -) -FIND_PACKAGE(Qt4 REQUIRED) -FIND_PACKAGE(Protobuf REQUIRED) - -QT4_WRAP_CPP(common_HEADERS_MOC ${common_HEADERS}) INCLUDE(${QT_USE_FILE}) INCLUDE_DIRECTORIES(pb) INCLUDE_DIRECTORIES(sfmt) INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) -add_library(cockatrice_common ${common_SOURCES} ${common_HEADERS_MOC}) -# Without this check, Linux will put -pthread out of order in link.txt and build will fail -if (UNIX) - target_link_libraries(cockatrice_common cockatrice_protocol pthread) -else (UNIX) - target_link_libraries(cockatrice_common cockatrice_protocol) -endif (UNIX) +add_library(cockatrice_common ${common_SOURCES} ${common_MOC_SRCS}) +target_link_libraries(cockatrice_common cockatrice_protocol) diff --git a/common/pb/CMakeLists.txt b/common/pb/CMakeLists.txt index e109a58b..b654443e 100644 --- a/common/pb/CMakeLists.txt +++ b/common/pb/CMakeLists.txt @@ -144,14 +144,13 @@ SET(PROTO_FILES session_event.proto ) -find_package(Protobuf REQUIRED) include_directories(${PROTOBUF_INCLUDE_DIRS}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS ${PROTO_FILES}) add_library(cockatrice_protocol ${PROTO_SRCS} ${PROTO_HDRS}) set(cockatrice_protocol_LIBS ${PROTOBUF_LIBRARIES}) -if (WIN32) +if (MSVC) set(cockatrice_protocol_LIBS ${cockatrice_protocol_LIBS} -lprotobuf) -endif (WIN32) +endif (MSVC) target_link_libraries(cockatrice_protocol ${cockatrice_protocol_LIBS}) diff --git a/common/server_arrowtarget.cpp b/common/server_arrowtarget.cpp new file mode 100644 index 00000000..aa7789dd --- /dev/null +++ b/common/server_arrowtarget.cpp @@ -0,0 +1,2 @@ + +#include "server_arrowtarget.h" \ No newline at end of file diff --git a/common/server_database_interface.cpp b/common/server_database_interface.cpp new file mode 100644 index 00000000..a375f603 --- /dev/null +++ b/common/server_database_interface.cpp @@ -0,0 +1,2 @@ + +#include "server_database_interface.h" From ed0311d59e770f151ba06f4b29fcdd4fa8c52d2b Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 01:26:54 +0200 Subject: [PATCH 46/55] Added comments for comment's CMakeLists.txt --- common/CMakeLists.txt | 4 ++++ common/pb/CMakeLists.txt | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index e43c240a..d7373115 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -1,3 +1,7 @@ +# CMakeLists for common directory +# +# provides the common library + CMAKE_MINIMUM_REQUIRED(VERSION 2.6) add_subdirectory(pb) diff --git a/common/pb/CMakeLists.txt b/common/pb/CMakeLists.txt index b654443e..455f161f 100644 --- a/common/pb/CMakeLists.txt +++ b/common/pb/CMakeLists.txt @@ -1,3 +1,7 @@ +# CMakeLists for common directory +# +# provides the protobuf interfaces + CMAKE_MINIMUM_REQUIRED(VERSION 2.6) SET(PROTO_FILES From 721cf6fe4ffd2eb5d70f717c99a241da5244577f Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 18:08:30 +0200 Subject: [PATCH 47/55] Re-indent CMakeLists.txt using spaces --- CMakeLists.txt | 60 ++++---- cockatrice/CMakeLists.txt | 280 ++++++++++++++++++------------------- common/CMakeLists.txt | 40 +++--- common/pb/CMakeLists.txt | 284 +++++++++++++++++++------------------- oracle/CMakeLists.txt | 74 +++++----- servatrice/CMakeLists.txt | 105 +++++++++----- 6 files changed, 436 insertions(+), 407 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 76c672d8..c746074a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,24 +12,24 @@ set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true) # Define a proper install path if(UNIX) - if(APPLE) - # MacOS X - # Due to the special bundle structure ignore - # the prefix eventually set by the user. - set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/release) - else() - # Linux / BSD - if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - #fix package build - if(PREFIX) - set(CMAKE_INSTALL_PREFIX ${PREFIX}) - else() - set(CMAKE_INSTALL_PREFIX /usr/local) - endif() - endif() - endif() + if(APPLE) + # MacOS X + # Due to the special bundle structure ignore + # the prefix eventually set by the user. + set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/release) + else() + # Linux / BSD + if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + #fix package build + if(PREFIX) + set(CMAKE_INSTALL_PREFIX ${PREFIX}) + else() + set(CMAKE_INSTALL_PREFIX /usr/local) + endif() + endif() + endif() elseif(WIN32) - set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/release) + set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/release) endif() # Force "Release" build type by default @@ -37,18 +37,18 @@ set(CMAKE_BUILD_TYPE Release) # Define proper compilation flags IF (CMAKE_COMPILER_IS_GNUCC) - # linux/gcc, bsd/gcc, windows/mingw - set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") - set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") + # linux/gcc, bsd/gcc, windows/mingw + set(CMAKE_CXX_FLAGS_RELEASE "-s -O2") + set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -O0") else() - # other: osx/llvm, bsd/llvm - set(CMAKE_CXX_FLAGS_RELEASE "-O2") - set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") + # other: osx/llvm, bsd/llvm + set(CMAKE_CXX_FLAGS_RELEASE "-O2") + set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") ENDIF (CMAKE_COMPILER_IS_GNUCC) # GNU systems need to define the Mersenne exponent for the RNG to compile w/o warning IF(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") - ADD_DEFINITIONS("-DSFMT_MEXP=19937") + ADD_DEFINITIONS("-DSFMT_MEXP=19937") ENDIF() #Find Qt4 and enable the needed features @@ -62,18 +62,18 @@ FIND_PACKAGE(Protobuf REQUIRED) # Compile servatrice (default off) add_subdirectory(common) if(WITH_SERVER) - add_subdirectory(servatrice) + add_subdirectory(servatrice) endif(WITH_SERVER) # Compile cockatrice+oracle (default on) if (NOT WITHOUT_CLIENT) - add_subdirectory(cockatrice) - add_subdirectory(oracle) - add_subdirectory(sounds) - add_subdirectory(zonebg) + add_subdirectory(cockatrice) + add_subdirectory(oracle) + add_subdirectory(sounds) + add_subdirectory(zonebg) endif(NOT WITHOUT_CLIENT) # Compile testclient (default off) if (WITH_TESTCLIENT) - add_subdirectory(testclient) + add_subdirectory(testclient) endif(WITH_TESTCLIENT) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 16592c43..38497e53 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -5,128 +5,128 @@ PROJECT(cockatrice) SET(cockatrice_SOURCES - src/abstractcounter.cpp - src/counter_general.cpp - src/dlg_creategame.cpp - src/dlg_filter_games.cpp - src/dlg_connect.cpp - src/dlg_create_token.cpp - src/dlg_edit_tokens.cpp - src/abstractclient.cpp - src/remoteclient.cpp - src/main.cpp - src/window_main.cpp - src/gamesmodel.cpp - src/player.cpp - src/playertarget.cpp - src/cardzone.cpp - src/selectzone.cpp - src/cardlist.cpp - src/abstractcarditem.cpp - src/carditem.cpp - src/tablezone.cpp - src/handzone.cpp - src/handcounter.cpp - src/carddatabase.cpp - src/keysignals.cpp - src/gameview.cpp - src/gameselector.cpp - src/decklistmodel.cpp - src/deck_loader.cpp - src/dlg_load_deck_from_clipboard.cpp - src/dlg_load_remote_deck.cpp - src/cardinfowidget.cpp - src/cardframe.cpp - src/cardinfopicture.cpp - src/cardinfotext.cpp - src/filterbuilder.cpp - src/cardfilter.cpp - src/filtertreemodel.cpp - src/filtertree.cpp - src/messagelogwidget.cpp - src/zoneviewzone.cpp - src/zoneviewwidget.cpp - src/pilezone.cpp - src/stackzone.cpp - src/carddragitem.cpp - src/carddatabasemodel.cpp - src/setsmodel.cpp - src/window_sets.cpp - src/abstractgraphicsitem.cpp - src/abstractcarddragitem.cpp - src/dlg_settings.cpp - src/dlg_cardsearch.cpp - src/phasestoolbar.cpp - src/gamescene.cpp - src/arrowitem.cpp - src/arrowtarget.cpp - src/tab.cpp - src/tab_server.cpp - src/tab_room.cpp - src/tab_message.cpp - src/tab_game.cpp - src/tab_deck_storage.cpp - src/tab_replays.cpp - src/tab_supervisor.cpp - src/tab_admin.cpp - src/tab_userlists.cpp - src/tab_deck_editor.cpp - src/replay_timeline_widget.cpp - src/deckstats_interface.cpp - src/chatview.cpp - src/userlist.cpp - src/userinfobox.cpp - src/user_context_menu.cpp - src/remotedecklist_treewidget.cpp - src/remotereplaylist_treewidget.cpp - src/deckview.cpp - src/playerlistwidget.cpp - src/pixmapgenerator.cpp - src/settingscache.cpp - src/localserver.cpp - src/localserverinterface.cpp - src/localclient.cpp - src/priceupdater.cpp - src/qt-json/json.cpp - src/soundengine.cpp - src/pending_command.cpp - ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp + src/abstractcounter.cpp + src/counter_general.cpp + src/dlg_creategame.cpp + src/dlg_filter_games.cpp + src/dlg_connect.cpp + src/dlg_create_token.cpp + src/dlg_edit_tokens.cpp + src/abstractclient.cpp + src/remoteclient.cpp + src/main.cpp + src/window_main.cpp + src/gamesmodel.cpp + src/player.cpp + src/playertarget.cpp + src/cardzone.cpp + src/selectzone.cpp + src/cardlist.cpp + src/abstractcarditem.cpp + src/carditem.cpp + src/tablezone.cpp + src/handzone.cpp + src/handcounter.cpp + src/carddatabase.cpp + src/keysignals.cpp + src/gameview.cpp + src/gameselector.cpp + src/decklistmodel.cpp + src/deck_loader.cpp + src/dlg_load_deck_from_clipboard.cpp + src/dlg_load_remote_deck.cpp + src/cardinfowidget.cpp + src/cardframe.cpp + src/cardinfopicture.cpp + src/cardinfotext.cpp + src/filterbuilder.cpp + src/cardfilter.cpp + src/filtertreemodel.cpp + src/filtertree.cpp + src/messagelogwidget.cpp + src/zoneviewzone.cpp + src/zoneviewwidget.cpp + src/pilezone.cpp + src/stackzone.cpp + src/carddragitem.cpp + src/carddatabasemodel.cpp + src/setsmodel.cpp + src/window_sets.cpp + src/abstractgraphicsitem.cpp + src/abstractcarddragitem.cpp + src/dlg_settings.cpp + src/dlg_cardsearch.cpp + src/phasestoolbar.cpp + src/gamescene.cpp + src/arrowitem.cpp + src/arrowtarget.cpp + src/tab.cpp + src/tab_server.cpp + src/tab_room.cpp + src/tab_message.cpp + src/tab_game.cpp + src/tab_deck_storage.cpp + src/tab_replays.cpp + src/tab_supervisor.cpp + src/tab_admin.cpp + src/tab_userlists.cpp + src/tab_deck_editor.cpp + src/replay_timeline_widget.cpp + src/deckstats_interface.cpp + src/chatview.cpp + src/userlist.cpp + src/userinfobox.cpp + src/user_context_menu.cpp + src/remotedecklist_treewidget.cpp + src/remotereplaylist_treewidget.cpp + src/deckview.cpp + src/playerlistwidget.cpp + src/pixmapgenerator.cpp + src/settingscache.cpp + src/localserver.cpp + src/localserverinterface.cpp + src/localclient.cpp + src/priceupdater.cpp + src/qt-json/json.cpp + src/soundengine.cpp + src/pending_command.cpp + ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ) if (UNIX AND NOT APPLE) - set_source_files_properties(src/main.cpp PROPERTIES COMPILE_FLAGS -DTRANSLATION_PATH=\\"${CMAKE_INSTALL_PREFIX}/share/cockatrice/translations\\") + set_source_files_properties(src/main.cpp PROPERTIES COMPILE_FLAGS -DTRANSLATION_PATH=\\"${CMAKE_INSTALL_PREFIX}/share/cockatrice/translations\\") endif (UNIX AND NOT APPLE) set(cockatrice_RESOURCES cockatrice.qrc) set(cockatrice_TS -# translations/cockatrice_cs.ts - translations/cockatrice_de.ts - translations/cockatrice_en.ts - translations/cockatrice_es.ts -# translations/cockatrice_fr.ts - translations/cockatrice_it.ts - translations/cockatrice_ja.ts -# translations/cockatrice_pl.ts -# translations/cockatrice_pt-br.ts - translations/cockatrice_pt.ts -# translations/cockatrice_ru.ts -# translations/cockatrice_sk.ts - translations/cockatrice_sv.ts -# translations/cockatrice_zh_CN.ts +# translations/cockatrice_cs.ts + translations/cockatrice_de.ts + translations/cockatrice_en.ts + translations/cockatrice_es.ts +# translations/cockatrice_fr.ts + translations/cockatrice_it.ts + translations/cockatrice_ja.ts +# translations/cockatrice_pl.ts +# translations/cockatrice_pt-br.ts + translations/cockatrice_pt.ts +# translations/cockatrice_ru.ts +# translations/cockatrice_sk.ts + translations/cockatrice_sv.ts +# translations/cockatrice_zh_CN.ts ) if(WIN32) - set(cockatrice_SOURCES ${cockatrice_SOURCES} cockatrice.rc) + set(cockatrice_SOURCES ${cockatrice_SOURCES} cockatrice.rc) endif(WIN32) if(APPLE) - set(MACOSX_BUNDLE_ICON_FILE appicon.icns) - set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/resources/appicon.icns PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - set(cockatrice_SOURCES ${cockatrice_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/resources/appicon.icns) + set(MACOSX_BUNDLE_ICON_FILE appicon.icns) + set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/resources/appicon.icns PROPERTIES MACOSX_PACKAGE_LOCATION Resources) + set(cockatrice_SOURCES ${cockatrice_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/resources/appicon.icns) ENDIF(APPLE) if (NOT QT_QTMULTIMEDIA_FOUND) - FIND_PACKAGE(QtMobility REQUIRED) + FIND_PACKAGE(QtMobility REQUIRED) endif (NOT QT_QTMULTIMEDIA_FOUND) SET(QT_USE_QTNETWORK TRUE) @@ -158,53 +158,53 @@ TARGET_LINK_LIBRARIES(cockatrice cockatrice_common ${QT_LIBRARIES} ${QT_MOBILITY if(UNIX) - if(APPLE) - INSTALL(TARGETS cockatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) - else() - # Assume linux - INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) - endif() + if(APPLE) + INSTALL(TARGETS cockatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + # Assume linux + INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + endif() elseif(WIN32) - INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) endif() if (NOT WIN32 AND NOT APPLE) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.png DESTINATION ${ICONDIR}/hicolor/48x48/apps) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.svg DESTINATION ${ICONDIR}/hicolor/scalable/apps) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cockatrice.desktop DESTINATION ${DESKTOPDIR}) - INSTALL(FILES ${cockatrice_QM} DESTINATION share/cockatrice/translations) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.png DESTINATION ${ICONDIR}/hicolor/48x48/apps) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.svg DESTINATION ${ICONDIR}/hicolor/scalable/apps) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cockatrice.desktop DESTINATION ${DESKTOPDIR}) + INSTALL(FILES ${cockatrice_QM} DESTINATION share/cockatrice/translations) ENDIF(NOT WIN32 AND NOT APPLE) add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ${CMAKE_CURRENT_BINARY_DIR}/version_string.h - COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/../common/getversion.cmake + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ${CMAKE_CURRENT_BINARY_DIR}/version_string.h + COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/../common/getversion.cmake ) if(APPLE) - set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Plugins) - set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Resources) + set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Plugins) + set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Resources) - # note: no codecs in qt5 - # note: phonon_backend => mediaservice - # note: needs platform on osx + # note: no codecs in qt5 + # note: phonon_backend => mediaservice + # note: needs platform on osx - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") - else() - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") - endif() + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") + else() + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") + endif() - install(CODE " - file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] + install(CODE " + file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] Plugins = Plugins\") - " COMPONENT Runtime) + " COMPONENT Runtime) - install(CODE " - file(GLOB_RECURSE QTPLUGINS - \"${plugin_dest_dir}/*.dylib\") - include(BundleUtilities) - fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/cockatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") - " COMPONENT Runtime) + install(CODE " + file(GLOB_RECURSE QTPLUGINS + \"${plugin_dest_dir}/*.dylib\") + include(BundleUtilities) + fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/cockatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + " COMPONENT Runtime) endif() diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index d7373115..3f0d8c6c 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -6,26 +6,26 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.6) add_subdirectory(pb) SET(common_SOURCES - decklist.cpp - get_pb_extension.cpp - rng_abstract.cpp - rng_sfmt.cpp - server.cpp - server_abstractuserinterface.cpp - server_arrow.cpp - server_arrowtarget.h - server_card.cpp - server_cardzone.cpp - server_counter.cpp - server_game.cpp - server_database_interface.cpp - server_player.cpp - server_protocolhandler.cpp - server_remoteuserinterface.cpp - server_response_containers.cpp - server_room.cpp - serverinfo_user_container.cpp - sfmt/SFMT.c + decklist.cpp + get_pb_extension.cpp + rng_abstract.cpp + rng_sfmt.cpp + server.cpp + server_abstractuserinterface.cpp + server_arrow.cpp + server_arrowtarget.h + server_card.cpp + server_cardzone.cpp + server_counter.cpp + server_game.cpp + server_database_interface.cpp + server_player.cpp + server_protocolhandler.cpp + server_remoteuserinterface.cpp + server_response_containers.cpp + server_room.cpp + serverinfo_user_container.cpp + sfmt/SFMT.c ) INCLUDE(${QT_USE_FILE}) diff --git a/common/pb/CMakeLists.txt b/common/pb/CMakeLists.txt index 455f161f..2930326d 100644 --- a/common/pb/CMakeLists.txt +++ b/common/pb/CMakeLists.txt @@ -5,147 +5,147 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.6) SET(PROTO_FILES - admin_commands.proto - card_attributes.proto - color.proto - command_attach_card.proto - command_change_zone_properties.proto - command_concede.proto - command_create_arrow.proto - command_create_counter.proto - command_create_token.proto - command_deck_del_dir.proto - command_deck_del.proto - command_deck_download.proto - command_deck_list.proto - command_deck_new_dir.proto - command_deck_select.proto - command_deck_upload.proto - command_del_counter.proto - command_delete_arrow.proto - command_draw_cards.proto - command_dump_zone.proto - command_flip_card.proto - command_game_say.proto - command_inc_card_counter.proto - command_inc_counter.proto - command_kick_from_game.proto - command_leave_game.proto - command_move_card.proto - command_mulligan.proto - command_next_turn.proto - command_ready_start.proto - command_replay_delete_match.proto - command_replay_list.proto - command_replay_download.proto - command_replay_modify_match.proto - command_reveal_cards.proto - command_roll_die.proto - command_set_active_phase.proto - command_set_card_attr.proto - command_set_card_counter.proto - command_set_counter.proto - command_set_sideboard_plan.proto - command_set_sideboard_lock.proto - command_shuffle.proto - commands.proto - command_stop_dump_zone.proto - command_undo_draw.proto - context_concede.proto - context_connection_state_changed.proto - context_deck_select.proto - context_move_card.proto - context_mulligan.proto - context_ping_changed.proto - context_ready_start.proto - context_set_sideboard_lock.proto - context_undo_draw.proto - event_add_to_list.proto - event_attach_card.proto - event_change_zone_properties.proto - event_connection_closed.proto - event_create_arrow.proto - event_create_counter.proto - event_create_token.proto - event_del_counter.proto - event_delete_arrow.proto - event_destroy_card.proto - event_draw_cards.proto - event_dump_zone.proto - event_flip_card.proto - event_game_closed.proto - event_game_host_changed.proto - event_game_joined.proto - event_game_say.proto - event_game_state_changed.proto - event_join.proto - event_join_room.proto - event_kicked.proto - event_leave.proto - event_leave_room.proto - event_list_games.proto - event_list_rooms.proto - event_move_card.proto - event_player_properties_changed.proto - event_remove_from_list.proto - event_replay_added.proto - event_reveal_cards.proto - event_roll_die.proto - event_room_say.proto - event_server_complete_list.proto - event_server_identification.proto - event_server_message.proto - event_server_shutdown.proto - event_set_active_phase.proto - event_set_active_player.proto - event_set_card_attr.proto - event_set_card_counter.proto - event_set_counter.proto - event_shuffle.proto - event_stop_dump_zone.proto - event_user_joined.proto - event_user_left.proto - event_user_message.proto - game_commands.proto - game_event_container.proto - game_event_context.proto - game_event.proto - game_replay.proto - isl_message.proto - moderator_commands.proto - move_card_to_zone.proto - response_deck_download.proto - response_deck_list.proto - response_deck_upload.proto - response_dump_zone.proto - response_get_games_of_user.proto - response_get_user_info.proto - response_join_room.proto - response_list_users.proto - response_login.proto - response_replay_download.proto - response_replay_list.proto - response.proto - room_commands.proto - room_event.proto - serverinfo_arrow.proto - serverinfo_cardcounter.proto - serverinfo_card.proto - serverinfo_counter.proto - serverinfo_deckstorage.proto - serverinfo_game.proto - serverinfo_gametype.proto - serverinfo_playerping.proto - serverinfo_playerproperties.proto - serverinfo_player.proto - serverinfo_replay.proto - serverinfo_replay_match.proto - serverinfo_room.proto - serverinfo_user.proto - serverinfo_zone.proto - server_message.proto - session_commands.proto - session_event.proto + admin_commands.proto + card_attributes.proto + color.proto + command_attach_card.proto + command_change_zone_properties.proto + command_concede.proto + command_create_arrow.proto + command_create_counter.proto + command_create_token.proto + command_deck_del_dir.proto + command_deck_del.proto + command_deck_download.proto + command_deck_list.proto + command_deck_new_dir.proto + command_deck_select.proto + command_deck_upload.proto + command_del_counter.proto + command_delete_arrow.proto + command_draw_cards.proto + command_dump_zone.proto + command_flip_card.proto + command_game_say.proto + command_inc_card_counter.proto + command_inc_counter.proto + command_kick_from_game.proto + command_leave_game.proto + command_move_card.proto + command_mulligan.proto + command_next_turn.proto + command_ready_start.proto + command_replay_delete_match.proto + command_replay_list.proto + command_replay_download.proto + command_replay_modify_match.proto + command_reveal_cards.proto + command_roll_die.proto + command_set_active_phase.proto + command_set_card_attr.proto + command_set_card_counter.proto + command_set_counter.proto + command_set_sideboard_plan.proto + command_set_sideboard_lock.proto + command_shuffle.proto + commands.proto + command_stop_dump_zone.proto + command_undo_draw.proto + context_concede.proto + context_connection_state_changed.proto + context_deck_select.proto + context_move_card.proto + context_mulligan.proto + context_ping_changed.proto + context_ready_start.proto + context_set_sideboard_lock.proto + context_undo_draw.proto + event_add_to_list.proto + event_attach_card.proto + event_change_zone_properties.proto + event_connection_closed.proto + event_create_arrow.proto + event_create_counter.proto + event_create_token.proto + event_del_counter.proto + event_delete_arrow.proto + event_destroy_card.proto + event_draw_cards.proto + event_dump_zone.proto + event_flip_card.proto + event_game_closed.proto + event_game_host_changed.proto + event_game_joined.proto + event_game_say.proto + event_game_state_changed.proto + event_join.proto + event_join_room.proto + event_kicked.proto + event_leave.proto + event_leave_room.proto + event_list_games.proto + event_list_rooms.proto + event_move_card.proto + event_player_properties_changed.proto + event_remove_from_list.proto + event_replay_added.proto + event_reveal_cards.proto + event_roll_die.proto + event_room_say.proto + event_server_complete_list.proto + event_server_identification.proto + event_server_message.proto + event_server_shutdown.proto + event_set_active_phase.proto + event_set_active_player.proto + event_set_card_attr.proto + event_set_card_counter.proto + event_set_counter.proto + event_shuffle.proto + event_stop_dump_zone.proto + event_user_joined.proto + event_user_left.proto + event_user_message.proto + game_commands.proto + game_event_container.proto + game_event_context.proto + game_event.proto + game_replay.proto + isl_message.proto + moderator_commands.proto + move_card_to_zone.proto + response_deck_download.proto + response_deck_list.proto + response_deck_upload.proto + response_dump_zone.proto + response_get_games_of_user.proto + response_get_user_info.proto + response_join_room.proto + response_list_users.proto + response_login.proto + response_replay_download.proto + response_replay_list.proto + response.proto + room_commands.proto + room_event.proto + serverinfo_arrow.proto + serverinfo_cardcounter.proto + serverinfo_card.proto + serverinfo_counter.proto + serverinfo_deckstorage.proto + serverinfo_game.proto + serverinfo_gametype.proto + serverinfo_playerping.proto + serverinfo_playerproperties.proto + serverinfo_player.proto + serverinfo_replay.proto + serverinfo_replay_match.proto + serverinfo_room.proto + serverinfo_user.proto + serverinfo_zone.proto + server_message.proto + session_commands.proto + session_event.proto ) include_directories(${PROTOBUF_INCLUDE_DIRS}) @@ -155,6 +155,6 @@ PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS ${PROTO_FILES}) add_library(cockatrice_protocol ${PROTO_SRCS} ${PROTO_HDRS}) set(cockatrice_protocol_LIBS ${PROTOBUF_LIBRARIES}) if (MSVC) - set(cockatrice_protocol_LIBS ${cockatrice_protocol_LIBS} -lprotobuf) + set(cockatrice_protocol_LIBS ${cockatrice_protocol_LIBS} -lprotobuf) endif (MSVC) target_link_libraries(cockatrice_protocol ${cockatrice_protocol_LIBS}) diff --git a/oracle/CMakeLists.txt b/oracle/CMakeLists.txt index 336e6e3c..ad9c16ee 100644 --- a/oracle/CMakeLists.txt +++ b/oracle/CMakeLists.txt @@ -8,11 +8,11 @@ PROJECT(oracle) set(DESKTOPDIR share/applications CACHE STRING "path to .desktop files") SET(oracle_SOURCES - src/main.cpp - src/oracleimporter.cpp - src/window_main.cpp - ../cockatrice/src/carddatabase.cpp - ../cockatrice/src/settingscache.cpp + src/main.cpp + src/oracleimporter.cpp + src/window_main.cpp + ../cockatrice/src/carddatabase.cpp + ../cockatrice/src/settingscache.cpp ) SET(QT_USE_QTNETWORK TRUE) @@ -28,45 +28,45 @@ ADD_EXECUTABLE(oracle WIN32 MACOSX_BUNDLE ${oracle_SOURCES} ${oracle_MOC_SRCS}) TARGET_LINK_LIBRARIES(oracle ${QT_LIBRARIES}) if(UNIX) - if(APPLE) - INSTALL(TARGETS oracle BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) - else() - # Assume linux - INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) - endif() + if(APPLE) + INSTALL(TARGETS oracle BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + # Assume linux + INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + endif() elseif(WIN32) - INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) endif() IF (NOT WIN32 AND NOT APPLE) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/oracle.desktop DESTINATION ${DESKTOPDIR}) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/oracle.desktop DESTINATION ${DESKTOPDIR}) ENDIF (NOT WIN32 AND NOT APPLE) -if(APPLE) - set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) - set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) +#if(APPLE) +# set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) +# set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) - # note: no codecs in qt5 - # note: phonon_backend => mediaservice - # note: needs platform on osx + # note: no codecs in qt5 + # note: phonon_backend => mediaservice + # note: needs platform on osx - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") - else() - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") - endif() +# if (CMAKE_BUILD_TYPE STREQUAL "Debug") +# install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime +# FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") +# else() +# install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime +# FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") +# endif() - install(CODE " - file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] -Plugins = Plugins\") - " COMPONENT Runtime) +# install(CODE " +# file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] +#Plugins = Plugins\") +# " COMPONENT Runtime) - install(CODE " - file(GLOB_RECURSE QTPLUGINS - \"${plugin_dest_dir}/*.dylib\") - include(BundleUtilities) - fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") - " COMPONENT Runtime) -endif() +# install(CODE " +# file(GLOB_RECURSE QTPLUGINS +# \"${plugin_dest_dir}/*.dylib\") +# include(BundleUtilities) +# fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") +# " COMPONENT Runtime) +#endif() diff --git a/servatrice/CMakeLists.txt b/servatrice/CMakeLists.txt index 41c42952..95f24e33 100644 --- a/servatrice/CMakeLists.txt +++ b/servatrice/CMakeLists.txt @@ -9,15 +9,15 @@ SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) FIND_PACKAGE(Libgcrypt REQUIRED) SET(servatrice_SOURCES - src/main.cpp - src/passwordhasher.cpp - src/servatrice.cpp - src/servatrice_connection_pool.cpp - src/servatrice_database_interface.cpp - src/server_logger.cpp - src/serversocketinterface.cpp - src/isl_interface.cpp - ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp + src/main.cpp + src/passwordhasher.cpp + src/servatrice.cpp + src/servatrice_connection_pool.cpp + src/servatrice_database_interface.cpp + src/server_logger.cpp + src/serversocketinterface.cpp + src/isl_interface.cpp + ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ) SET(QT_DONTUSE_QTGUI) @@ -38,47 +38,76 @@ TARGET_LINK_LIBRARIES(servatrice cockatrice_common ${QT_LIBRARIES} ${LIBGCRYPT_L #add_custom_target(versionheader ALL DEPENDS version_header) add_custom_command( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version_string.h ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp - COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/../common/getversion.cmake + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version_string.h ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp + COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/../common/getversion.cmake ) # install rules if(UNIX) - if(APPLE) - INSTALL(TARGETS servatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) - else() - # Assume linux - INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) - endif() + if(APPLE) + INSTALL(TARGETS servatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + # Assume linux + INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + endif() elseif(WIN32) - INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) endif() if(APPLE) - set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Plugins) - set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Resources) + set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Plugins) + set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Resources) - # note: no codecs in qt5 - # note: phonon_backend => mediaservice - # note: needs platform on osx + # note: no codecs in qt5 + # note: phonon_backend => mediaservice + # note: needs platform on osx - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") - else() - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") - endif() + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") + else() + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") + endif() - install(CODE " - file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] + install(CODE " + file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] Plugins = Plugins\") - " COMPONENT Runtime) + " COMPONENT Runtime) - install(CODE " - file(GLOB_RECURSE QTPLUGINS + install(CODE " + file(GLOB_RECURSE QTPLUGINS \"${plugin_dest_dir}/*.dylib\") - include(BundleUtilities) - fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/servatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") - " COMPONENT Runtime) + include(BundleUtilities) + fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/servatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + " COMPONENT Runtime) endif() + +if(APPLE) + set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) + set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) + + # note: no codecs in qt5 + # note: phonon_backend => mediaservice + # note: needs platform on osx + + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") + else() + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") + endif() + + install(CODE " + file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] +Plugins = Plugins\") + " COMPONENT Runtime) + + install(CODE " + file(GLOB_RECURSE QTPLUGINS + \"${plugin_dest_dir}/*.dylib\") + include(BundleUtilities) + fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + " COMPONENT Runtime) +endif() \ No newline at end of file From 84fe5f464c45343c7cf5224f53f18e1a7edfd01a Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 18:20:34 +0200 Subject: [PATCH 48/55] Removed unnecessary comments in previous commit --- oracle/CMakeLists.txt | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/oracle/CMakeLists.txt b/oracle/CMakeLists.txt index ad9c16ee..6ed1f327 100644 --- a/oracle/CMakeLists.txt +++ b/oracle/CMakeLists.txt @@ -42,31 +42,31 @@ IF (NOT WIN32 AND NOT APPLE) INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/oracle.desktop DESTINATION ${DESKTOPDIR}) ENDIF (NOT WIN32 AND NOT APPLE) -#if(APPLE) -# set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) -# set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) +if(APPLE) + set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) + set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) # note: no codecs in qt5 # note: phonon_backend => mediaservice # note: needs platform on osx -# if (CMAKE_BUILD_TYPE STREQUAL "Debug") -# install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime -# FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") -# else() -# install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime -# FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") -# endif() + if (CMAKE_BUILD_TYPE STREQUAL "Debug") + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") + else() + install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime + FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") + endif() -# install(CODE " -# file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] -#Plugins = Plugins\") -# " COMPONENT Runtime) + install(CODE " + file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] +Plugins = Plugins\") + " COMPONENT Runtime) -# install(CODE " -# file(GLOB_RECURSE QTPLUGINS -# \"${plugin_dest_dir}/*.dylib\") -# include(BundleUtilities) -# fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") -# " COMPONENT Runtime) -#endif() + install(CODE " + file(GLOB_RECURSE QTPLUGINS + \"${plugin_dest_dir}/*.dylib\") + include(BundleUtilities) + fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + " COMPONENT Runtime) +endif() From dfdfe602024d11735de821eb6d78becfdabc644b Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Wed, 11 Jun 2014 18:20:48 +0200 Subject: [PATCH 49/55] Properly install sounds and zonebg files --- sounds/CMakeLists.txt | 14 ++++++++++++-- zonebg/CMakeLists.txt | 14 ++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/sounds/CMakeLists.txt b/sounds/CMakeLists.txt index 6dd10f87..14b83b60 100644 --- a/sounds/CMakeLists.txt +++ b/sounds/CMakeLists.txt @@ -2,5 +2,15 @@ # # Installs default sound files -FILE(GLOB sounds "${CMAKE_CURRENT_SOURCE_DIR}/sounds/*.raw") -INSTALL(FILES ${sounds} DESTINATION share/cockatrice/sounds) +FILE(GLOB sounds "${CMAKE_CURRENT_SOURCE_DIR}/*.raw") + +if(UNIX) + if(APPLE) + INSTALL(FILES ${sounds} DESTINATION ${CMAKE_INSTALL_PREFIX}/sounds) + else() + # Assume linux + INSTALL(FILES ${sounds} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/cockatrice/sounds) + endif() +elseif(WIN32) + INSTALL(FILES ${sounds} DESTINATION ${CMAKE_INSTALL_PREFIX}/sounds) +endif() \ No newline at end of file diff --git a/zonebg/CMakeLists.txt b/zonebg/CMakeLists.txt index 76c7c356..4478238f 100644 --- a/zonebg/CMakeLists.txt +++ b/zonebg/CMakeLists.txt @@ -2,5 +2,15 @@ # # Installs default "zone background" files -FILE(GLOB zonebg "${CMAKE_CURRENT_SOURCE_DIR}/zonebg/*.*") -INSTALL(FILES ${zonebg} DESTINATION share/cockatrice/zonebg) +FILE(GLOB zonebg "${CMAKE_CURRENT_SOURCE_DIR}/*.*") + +if(UNIX) + if(APPLE) + INSTALL(FILES ${zonebg} DESTINATION ${CMAKE_INSTALL_PREFIX}/zonebg) + else() + # Assume linux + INSTALL(FILES ${zonebg} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/cockatrice/zonebg) + endif() +elseif(WIN32) + INSTALL(FILES ${zonebg} DESTINATION ${CMAKE_INSTALL_PREFIX}/zonebg) +endif() \ No newline at end of file From eca318c34d0f166f28f69eaa227f779675c51810 Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Thu, 12 Jun 2014 23:29:42 +0200 Subject: [PATCH 50/55] Make install paths relative to prepare for CPack --- cockatrice/CMakeLists.txt | 12 ++++++------ oracle/CMakeLists.txt | 12 ++++++------ servatrice/CMakeLists.txt | 41 ++++++--------------------------------- sounds/CMakeLists.txt | 6 +++--- zonebg/CMakeLists.txt | 6 +++--- 5 files changed, 24 insertions(+), 53 deletions(-) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 38497e53..38df523e 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -159,13 +159,13 @@ TARGET_LINK_LIBRARIES(cockatrice cockatrice_common ${QT_LIBRARIES} ${QT_MOBILITY if(UNIX) if(APPLE) - INSTALL(TARGETS cockatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS cockatrice BUNDLE DESTINATION ./) else() # Assume linux - INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + INSTALL(TARGETS cockatrice RUNTIME DESTINATION bin/) endif() elseif(WIN32) - INSTALL(TARGETS cockatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS cockatrice RUNTIME DESTINATION ./) endif() if (NOT WIN32 AND NOT APPLE) @@ -181,8 +181,8 @@ add_custom_command( ) if(APPLE) - set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Plugins) - set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/cockatrice.app/Contents/Resources) + set(plugin_dest_dir ./cockatrice.app/Contents/Plugins) + set(qtconf_dest_dir ./cockatrice.app/Contents/Resources) # note: no codecs in qt5 # note: phonon_backend => mediaservice @@ -205,6 +205,6 @@ Plugins = Plugins\") file(GLOB_RECURSE QTPLUGINS \"${plugin_dest_dir}/*.dylib\") include(BundleUtilities) - fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/cockatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/cockatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") " COMPONENT Runtime) endif() diff --git a/oracle/CMakeLists.txt b/oracle/CMakeLists.txt index 6ed1f327..340ce16a 100644 --- a/oracle/CMakeLists.txt +++ b/oracle/CMakeLists.txt @@ -29,13 +29,13 @@ TARGET_LINK_LIBRARIES(oracle ${QT_LIBRARIES}) if(UNIX) if(APPLE) - INSTALL(TARGETS oracle BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS oracle BUNDLE DESTINATION ./) else() # Assume linux - INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + INSTALL(TARGETS oracle RUNTIME DESTINATION bin/) endif() elseif(WIN32) - INSTALL(TARGETS oracle RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS oracle RUNTIME DESTINATION ./) endif() IF (NOT WIN32 AND NOT APPLE) @@ -43,8 +43,8 @@ IF (NOT WIN32 AND NOT APPLE) ENDIF (NOT WIN32 AND NOT APPLE) if(APPLE) - set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) - set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) + set(plugin_dest_dir ./oracle.app/Contents/Plugins) + set(qtconf_dest_dir ./oracle.app/Contents/Resources) # note: no codecs in qt5 # note: phonon_backend => mediaservice @@ -67,6 +67,6 @@ Plugins = Plugins\") file(GLOB_RECURSE QTPLUGINS \"${plugin_dest_dir}/*.dylib\") include(BundleUtilities) - fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") " COMPONENT Runtime) endif() diff --git a/servatrice/CMakeLists.txt b/servatrice/CMakeLists.txt index 95f24e33..799cecbd 100644 --- a/servatrice/CMakeLists.txt +++ b/servatrice/CMakeLists.txt @@ -45,18 +45,18 @@ add_custom_command( # install rules if(UNIX) if(APPLE) - INSTALL(TARGETS servatrice BUNDLE DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS servatrice BUNDLE DESTINATION ./) else() # Assume linux - INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) + INSTALL(TARGETS servatrice RUNTIME DESTINATION bin/) endif() elseif(WIN32) - INSTALL(TARGETS servatrice RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + INSTALL(TARGETS servatrice RUNTIME DESTINATION ./) endif() if(APPLE) - set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Plugins) - set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/servatrice.app/Contents/Resources) + set(plugin_dest_dir ./servatrice.app/Contents/Plugins) + set(qtconf_dest_dir ./servatrice.app/Contents/Resources) # note: no codecs in qt5 # note: phonon_backend => mediaservice @@ -79,35 +79,6 @@ Plugins = Plugins\") file(GLOB_RECURSE QTPLUGINS \"${plugin_dest_dir}/*.dylib\") include(BundleUtilities) - fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/servatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/servatrice.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") " COMPONENT Runtime) endif() - -if(APPLE) - set(plugin_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Plugins) - set(qtconf_dest_dir ${CMAKE_INSTALL_PREFIX}/oracle.app/Contents/Resources) - - # note: no codecs in qt5 - # note: phonon_backend => mediaservice - # note: needs platform on osx - - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/.*_debug\\.dylib") - else() - install(DIRECTORY "${QT_PLUGINS_DIR}/" DESTINATION ${plugin_dest_dir} COMPONENT Runtime - FILES_MATCHING REGEX "(codecs|iconengines|imageformats|mediaservice|phonon_backend|platforms)/[^_]*\\.dylib") - endif() - - install(CODE " - file(WRITE \"${qtconf_dest_dir}/qt.conf\" \"[Paths] -Plugins = Plugins\") - " COMPONENT Runtime) - - install(CODE " - file(GLOB_RECURSE QTPLUGINS - \"${plugin_dest_dir}/*.dylib\") - include(BundleUtilities) - fixup_bundle(\"${CMAKE_INSTALL_PREFIX}/oracle.app\" \"\${QTPLUGINS}\" \"${QT_LIBRARY_DIR}\") - " COMPONENT Runtime) -endif() \ No newline at end of file diff --git a/sounds/CMakeLists.txt b/sounds/CMakeLists.txt index 14b83b60..e38c9090 100644 --- a/sounds/CMakeLists.txt +++ b/sounds/CMakeLists.txt @@ -6,11 +6,11 @@ FILE(GLOB sounds "${CMAKE_CURRENT_SOURCE_DIR}/*.raw") if(UNIX) if(APPLE) - INSTALL(FILES ${sounds} DESTINATION ${CMAKE_INSTALL_PREFIX}/sounds) + INSTALL(FILES ${sounds} DESTINATION sounds/) else() # Assume linux - INSTALL(FILES ${sounds} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/cockatrice/sounds) + INSTALL(FILES ${sounds} DESTINATION share/cockatrice/sounds/) endif() elseif(WIN32) - INSTALL(FILES ${sounds} DESTINATION ${CMAKE_INSTALL_PREFIX}/sounds) + INSTALL(FILES ${sounds} DESTINATION sounds/) endif() \ No newline at end of file diff --git a/zonebg/CMakeLists.txt b/zonebg/CMakeLists.txt index 4478238f..961c4e12 100644 --- a/zonebg/CMakeLists.txt +++ b/zonebg/CMakeLists.txt @@ -6,11 +6,11 @@ FILE(GLOB zonebg "${CMAKE_CURRENT_SOURCE_DIR}/*.*") if(UNIX) if(APPLE) - INSTALL(FILES ${zonebg} DESTINATION ${CMAKE_INSTALL_PREFIX}/zonebg) + INSTALL(FILES ${zonebg} DESTINATION zonebg/) else() # Assume linux - INSTALL(FILES ${zonebg} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/cockatrice/zonebg) + INSTALL(FILES ${zonebg} DESTINATION share/cockatrice/zonebg/) endif() elseif(WIN32) - INSTALL(FILES ${zonebg} DESTINATION ${CMAKE_INSTALL_PREFIX}/zonebg) + INSTALL(FILES ${zonebg} DESTINATION zonebg/) endif() \ No newline at end of file From ddec7e65612524154ae511caca11182f01e02b3b Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Thu, 12 Jun 2014 23:31:30 +0200 Subject: [PATCH 51/55] Create CMake options for components --- CMakeLists.txt | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c746074a..1cfff669 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,20 +60,28 @@ set(CMAKE_AUTOMOC TRUE) FIND_PACKAGE(Protobuf REQUIRED) # Compile servatrice (default off) +option(WITH_SERVER "build servatrice" OFF) add_subdirectory(common) if(WITH_SERVER) add_subdirectory(servatrice) -endif(WITH_SERVER) +endif() -# Compile cockatrice+oracle (default on) -if (NOT WITHOUT_CLIENT) +# Compile cockatrice (default on) +option(WITH_CLIENT "build cockatrice" ON) +if(WITH_CLIENT) add_subdirectory(cockatrice) - add_subdirectory(oracle) add_subdirectory(sounds) add_subdirectory(zonebg) -endif(NOT WITHOUT_CLIENT) +endif() + +# Compile oracle (default on) +option(WITH_ORACLE "build oracle" ON) +if(WITH_ORACLE) + add_subdirectory(oracle) +endif() # Compile testclient (default off) +option(WITH_TESTCLIENT "build testclient" OFF) if (WITH_TESTCLIENT) add_subdirectory(testclient) -endif(WITH_TESTCLIENT) +endif() \ No newline at end of file From 660ff349abf031617e1028362d1e7e913d1848ef Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Thu, 12 Jun 2014 23:32:12 +0200 Subject: [PATCH 52/55] Add a proper, top-level project name --- CMakeLists.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1cfff669..8c3219cc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,6 +7,15 @@ cmake_minimum_required(VERSION 2.6) +set(PROJECT_NAME "Cockatrice") +set(PROJECT_VERSION_MAJOR 0) +set(PROJECT_VERSION_MINOR 0) +set(PROJECT_VERSION_PATCH 1) +set(PROJECT_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH} ) + +# A project name is needed for CPack +PROJECT("${PROJECT_NAME}") + # Set conventional loops set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true) From dd768ba7bdee5162bc7fce0c3da1f892e97a1ef2 Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Thu, 12 Jun 2014 23:42:20 +0200 Subject: [PATCH 53/55] OSX: Move translations inside app bundle Additional: remove duplicate if(linux) and merge rules together --- cockatrice/CMakeLists.txt | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 38df523e..1d915bdb 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -160,21 +160,20 @@ TARGET_LINK_LIBRARIES(cockatrice cockatrice_common ${QT_LIBRARIES} ${QT_MOBILITY if(UNIX) if(APPLE) INSTALL(TARGETS cockatrice BUNDLE DESTINATION ./) + INSTALL(FILES ${cockatrice_QM} DESTINATION ./cockatrice.app/Contents/Resources/translations) else() # Assume linux INSTALL(TARGETS cockatrice RUNTIME DESTINATION bin/) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.png DESTINATION ${ICONDIR}/hicolor/48x48/apps) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.svg DESTINATION ${ICONDIR}/hicolor/scalable/apps) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cockatrice.desktop DESTINATION ${DESKTOPDIR}) + INSTALL(FILES ${cockatrice_QM} DESTINATION share/cockatrice/translations) endif() elseif(WIN32) INSTALL(TARGETS cockatrice RUNTIME DESTINATION ./) + INSTALL(FILES ${cockatrice_QM} DESTINATION ./translations) endif() -if (NOT WIN32 AND NOT APPLE) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.png DESTINATION ${ICONDIR}/hicolor/48x48/apps) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resources/cockatrice.svg DESTINATION ${ICONDIR}/hicolor/scalable/apps) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/cockatrice.desktop DESTINATION ${DESKTOPDIR}) - INSTALL(FILES ${cockatrice_QM} DESTINATION share/cockatrice/translations) -ENDIF(NOT WIN32 AND NOT APPLE) - add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version_string.cpp ${CMAKE_CURRENT_BINARY_DIR}/version_string.h COMMAND ${CMAKE_COMMAND} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/../common/getversion.cmake From a4fbf8b67737b46b10c2fe0e30d12bbb0c3bb8fc Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Fri, 13 Jun 2014 19:09:33 +0200 Subject: [PATCH 54/55] Force linking with pthread under unix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Protobuf depends on pthread under unix, but cmake’s FindProtobuf doesn’t add -lpthread to link flags --- common/pb/CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/common/pb/CMakeLists.txt b/common/pb/CMakeLists.txt index 2930326d..7b005157 100644 --- a/common/pb/CMakeLists.txt +++ b/common/pb/CMakeLists.txt @@ -157,4 +157,7 @@ set(cockatrice_protocol_LIBS ${PROTOBUF_LIBRARIES}) if (MSVC) set(cockatrice_protocol_LIBS ${cockatrice_protocol_LIBS} -lprotobuf) endif (MSVC) +if (UNIX) + set(cockatrice_protocol_LIBS ${cockatrice_protocol_LIBS} -lpthread) +endif (UNIX) target_link_libraries(cockatrice_protocol ${cockatrice_protocol_LIBS}) From a35b62509abb12573bc977ff02884711cbdcdc82 Mon Sep 17 00:00:00 2001 From: Fabio Bas Date: Sat, 14 Jun 2014 10:35:18 +0200 Subject: [PATCH 55/55] Handle correctly user-defined CMAKE_BUILD_TYPE --- CMakeLists.txt | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c3219cc..6c1063ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,6 +13,14 @@ set(PROJECT_VERSION_MINOR 0) set(PROJECT_VERSION_PATCH 1) set(PROJECT_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH} ) +# Defualt to "Release" build type +# User-provided value for CMAKE_BUILD_TYPE must be checked before the PROJECT() call +IF(DEFINED CMAKE_BUILD_TYPE) + SET(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Type of build") +ELSE() + SET(CMAKE_BUILD_TYPE Release CACHE STRING "Type of build") +ENDIF() + # A project name is needed for CPack PROJECT("${PROJECT_NAME}") @@ -41,9 +49,6 @@ elseif(WIN32) set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/release) endif() -# Force "Release" build type by default -set(CMAKE_BUILD_TYPE Release) - # Define proper compilation flags IF (CMAKE_COMPILER_IS_GNUCC) # linux/gcc, bsd/gcc, windows/mingw