Commit 1bc48a78 authored by Matt Kelly's avatar Matt Kelly
Browse files

Convert rest of source to 4-space indent

parent a171df74
...@@ -14,51 +14,51 @@ class QResizeEvent; ...@@ -14,51 +14,51 @@ class QResizeEvent;
class QMouseEvent; class QMouseEvent;
class CardInfoWidget : public QFrame { class CardInfoWidget : public QFrame {
Q_OBJECT Q_OBJECT
public: public:
enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp }; enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp };
private: private:
int pixmapWidth; int pixmapWidth;
qreal cardHeightOffset; qreal cardHeightOffset;
qreal aspectRatio; qreal aspectRatio;
// XXX: Why isn't this an eunm? // XXX: Why isn't this an eunm?
int minimized; // 0 - card, 1 - oracle only, 2 - full int minimized; // 0 - card, 1 - oracle only, 2 - full
ResizeMode mode; ResizeMode mode;
QComboBox *dropList; QComboBox *dropList;
QLabel *cardPicture; QLabel *cardPicture;
QLabel *nameLabel1, *nameLabel2; QLabel *nameLabel1, *nameLabel2;
QLabel *manacostLabel1, *manacostLabel2; QLabel *manacostLabel1, *manacostLabel2;
QLabel *cardtypeLabel1, *cardtypeLabel2; QLabel *cardtypeLabel1, *cardtypeLabel2;
QLabel *powtoughLabel1, *powtoughLabel2; QLabel *powtoughLabel1, *powtoughLabel2;
QLabel *loyaltyLabel1, *loyaltyLabel2; QLabel *loyaltyLabel1, *loyaltyLabel2;
QTextEdit *textLabel; QTextEdit *textLabel;
bool shouldShowPowTough(); bool shouldShowPowTough();
bool shouldShowLoyalty(); bool shouldShowLoyalty();
CardInfo *info; CardInfo *info;
void setMinimized(int _minimized); void setMinimized(int _minimized);
public: public:
CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0); CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0);
void retranslateUi(); void retranslateUi();
QString getCardName() const; QString getCardName() const;
public slots: public slots:
void setCard(CardInfo *card); void setCard(CardInfo *card);
void setCard(const QString &cardName); void setCard(const QString &cardName);
void setCard(AbstractCardItem *card); void setCard(AbstractCardItem *card);
private slots: private slots:
void clear(); void clear();
void updatePixmap(); void updatePixmap();
void minimizeClicked(int newMinimized); void minimizeClicked(int newMinimized);
protected: protected:
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent *event);
}; };
#endif #endif
...@@ -18,374 +18,374 @@ ...@@ -18,374 +18,374 @@
#include "pb/serverinfo_card.pb.h" #include "pb/serverinfo_card.pb.h"
CardItem::CardItem(Player *_owner, const QString &_name, int _cardid, bool _revealedCard, QGraphicsItem *parent) CardItem::CardItem(Player *_owner, const QString &_name, int _cardid, bool _revealedCard, QGraphicsItem *parent)
: AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false), destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0) : AbstractCardItem(_name, _owner, _cardid, parent), zone(0), revealedCard(_revealedCard), attacking(false), destroyOnZoneChange(false), doesntUntap(false), dragItem(0), attachedTo(0)
{ {
owner->addCard(this); owner->addCard(this);
cardMenu = new QMenu; cardMenu = new QMenu;
ptMenu = new QMenu; ptMenu = new QMenu;
moveMenu = new QMenu; moveMenu = new QMenu;
retranslateUi(); retranslateUi();
emit updateCardMenu(this); emit updateCardMenu(this);
} }
CardItem::~CardItem() CardItem::~CardItem()
{ {
prepareDelete(); prepareDelete();
if (scene()) if (scene())
static_cast<GameScene *>(scene())->unregisterAnimationItem(this); static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
delete cardMenu; delete cardMenu;
delete ptMenu; delete ptMenu;
delete moveMenu; delete moveMenu;
deleteDragItem(); deleteDragItem();
} }
void CardItem::prepareDelete() void CardItem::prepareDelete()
{ {
if (owner) { if (owner) {
if (owner->getCardMenu() == cardMenu) { if (owner->getCardMenu() == cardMenu) {
owner->setCardMenu(0); owner->setCardMenu(0);
owner->getGame()->setActiveCard(0); owner->getGame()->setActiveCard(0);
} }
owner = 0; owner = 0;
} }
while (!attachedCards.isEmpty()) { while (!attachedCards.isEmpty()) {
attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards() attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards()
attachedCards.first()->setAttachedTo(0); attachedCards.first()->setAttachedTo(0);
} }
if (attachedTo) { if (attachedTo) {
attachedTo->removeAttachedCard(this); attachedTo->removeAttachedCard(this);
attachedTo = 0; attachedTo = 0;
} }
} }
void CardItem::deleteLater() void CardItem::deleteLater()
{ {
prepareDelete(); prepareDelete();
AbstractCardItem::deleteLater(); AbstractCardItem::deleteLater();
} }
void CardItem::setZone(CardZone *_zone) void CardItem::setZone(CardZone *_zone)
{ {
zone = _zone; zone = _zone;
emit updateCardMenu(this); emit updateCardMenu(this);
} }
void CardItem::retranslateUi() void CardItem::retranslateUi()
{ {
moveMenu->setTitle(tr("&Move to")); moveMenu->setTitle(tr("&Move to"));
ptMenu->setTitle(tr("&Power / toughness")); ptMenu->setTitle(tr("&Power / toughness"));
} }
void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{ {
painter->save(); painter->save();
AbstractCardItem::paint(painter, option, widget); AbstractCardItem::paint(painter, option, widget);
int i = 0; int i = 0;
QMapIterator<int, int> counterIterator(counters); QMapIterator<int, int> counterIterator(counters);
while (counterIterator.hasNext()) { while (counterIterator.hasNext()) {
counterIterator.next(); counterIterator.next();
QColor color; QColor color;
color.setHsv(counterIterator.key() * 60, 150, 255); color.setHsv(counterIterator.key() * 60, 150, 255);
paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter); paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter);
++i; ++i;
} }
QSizeF translatedSize = getTranslatedSize(painter); QSizeF translatedSize = getTranslatedSize(painter);
qreal scaleFactor = translatedSize.width() / boundingRect().width(); qreal scaleFactor = translatedSize.width() / boundingRect().width();
if (!pt.isEmpty()) { if (!pt.isEmpty()) {
painter->save(); painter->save();
transformPainter(painter, translatedSize, tapAngle); transformPainter(painter, translatedSize, tapAngle);
painter->setBackground(Qt::black); painter->setBackground(Qt::black);
painter->setBackgroundMode(Qt::OpaqueMode); painter->setBackgroundMode(Qt::OpaqueMode);
painter->setPen(Qt::white); painter->setPen(Qt::white);
painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignRight | Qt::AlignBottom, pt); painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignRight | Qt::AlignBottom, pt);
painter->restore(); painter->restore();
} }
if (!annotation.isEmpty()) { if (!annotation.isEmpty()) {
painter->save(); painter->save();
transformPainter(painter, translatedSize, tapAngle); transformPainter(painter, translatedSize, tapAngle);
painter->setBackground(Qt::black); painter->setBackground(Qt::black);
painter->setBackgroundMode(Qt::OpaqueMode); painter->setBackgroundMode(Qt::OpaqueMode);
painter->setPen(Qt::white); painter->setPen(Qt::white);
painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignCenter | Qt::TextWrapAnywhere, annotation); painter->drawText(QRectF(4 * scaleFactor, 4 * scaleFactor, translatedSize.width() - 8 * scaleFactor, translatedSize.height() - 8 * scaleFactor), Qt::AlignCenter | Qt::TextWrapAnywhere, annotation);
painter->restore(); painter->restore();
} }
if (getBeingPointedAt()) if (getBeingPointedAt())
painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
painter->restore(); painter->restore();
} }
void CardItem::setAttacking(bool _attacking) void CardItem::setAttacking(bool _attacking)
{ {
attacking = _attacking; attacking = _attacking;
update(); update();
} }
void CardItem::setCounter(int _id, int _value) void CardItem::setCounter(int _id, int _value)
{ {
if (_value) if (_value)
counters.insert(_id, _value); counters.insert(_id, _value);
else else
counters.remove(_id); counters.remove(_id);
update(); update();
} }
void CardItem::setAnnotation(const QString &_annotation) void CardItem::setAnnotation(const QString &_annotation)
{ {
annotation = _annotation; annotation = _annotation;
update(); update();
} }
void CardItem::setDoesntUntap(bool _doesntUntap) void CardItem::setDoesntUntap(bool _doesntUntap)
{ {
doesntUntap = _doesntUntap; doesntUntap = _doesntUntap;
} }
void CardItem::setPT(const QString &_pt) void CardItem::setPT(const QString &_pt)
{ {
pt = _pt; pt = _pt;
update(); update();
} }
void CardItem::setAttachedTo(CardItem *_attachedTo) void CardItem::setAttachedTo(CardItem *_attachedTo)
{ {
if (attachedTo) if (attachedTo)
attachedTo->removeAttachedCard(this); attachedTo->removeAttachedCard(this);
gridPoint.setX(-1); gridPoint.setX(-1);
attachedTo = _attachedTo; attachedTo = _attachedTo;
if (attachedTo) { if (attachedTo) {
setParentItem(attachedTo->getZone()); setParentItem(attachedTo->getZone());
attachedTo->addAttachedCard(this); attachedTo->addAttachedCard(this);
if (zone != attachedTo->getZone()) if (zone != attachedTo->getZone())
attachedTo->getZone()->reorganizeCards(); attachedTo->getZone()->reorganizeCards();
} else } else
setParentItem(zone); setParentItem(zone);
if (zone) if (zone)
zone->reorganizeCards(); zone->reorganizeCards();
emit updateCardMenu(this); emit updateCardMenu(this);
} }
void CardItem::resetState() void CardItem::resetState()
{ {
attacking = false; attacking = false;
facedown = false; facedown = false;
counters.clear(); counters.clear();
pt.clear(); pt.clear();
annotation.clear(); annotation.clear();
attachedTo = 0; attachedTo = 0;
attachedCards.clear(); attachedCards.clear();
setTapped(false, false); setTapped(false, false);
setDoesntUntap(false); setDoesntUntap(false);
if (scene()) if (scene())
static_cast<GameScene *>(scene())->unregisterAnimationItem(this); static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
update(); update();
} }
void CardItem::processCardInfo(const ServerInfo_Card &info) void CardItem::processCardInfo(const ServerInfo_Card &info)
{ {
counters.clear(); counters.clear();
const int counterListSize = info.counter_list_size(); const int counterListSize = info.counter_list_size();
for (int i = 0; i < counterListSize; ++i) { for (int i = 0; i < counterListSize; ++i) {
const ServerInfo_CardCounter &counterInfo = info.counter_list(i); const ServerInfo_CardCounter &counterInfo = info.counter_list(i);
counters.insert(counterInfo.id(), counterInfo.value()); counters.insert(counterInfo.id(), counterInfo.value());
} }
setId(info.id()); setId(info.id());
setName(QString::fromStdString(info.name())); setName(QString::fromStdString(info.name()));
setAttacking(info.attacking()); setAttacking(info.attacking());
setFaceDown(info.face_down()); setFaceDown(info.face_down());
setPT(QString::fromStdString(info.pt())); setPT(QString::fromStdString(info.pt()));
setAnnotation(QString::fromStdString(info.annotation())); setAnnotation(QString::fromStdString(info.annotation()));
setColor(QString::fromStdString(info.color())); setColor(QString::fromStdString(info.color()));
setTapped(info.tapped()); setTapped(info.tapped());
setDestroyOnZoneChange(info.destroy_on_zone_change()); setDestroyOnZoneChange(info.destroy_on_zone_change());
setDoesntUntap(info.doesnt_untap()); setDoesntUntap(info.doesnt_untap());
} }
CardDragItem *CardItem::createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown) CardDragItem *CardItem::createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown)
{ {
deleteDragItem(); deleteDragItem();
dragItem = new CardDragItem(this, _id, _pos, faceDown); dragItem = new CardDragItem(this, _id, _pos, faceDown);
dragItem->setVisible(false); dragItem->setVisible(false);
scene()->addItem(dragItem); scene()->addItem(dragItem);
dragItem->updatePosition(_scenePos); dragItem->updatePosition(_scenePos);
dragItem->setVisible(true); dragItem->setVisible(true);
return dragItem; return dragItem;
} }
void CardItem::deleteDragItem() void CardItem::deleteDragItem()
{ {
dragItem->deleteLater(); dragItem->deleteLater();
dragItem = NULL; dragItem = NULL;
} }
void CardItem::drawArrow(const QColor &arrowColor) void CardItem::drawArrow(const QColor &arrowColor)
{ {
if (static_cast<TabGame *>(owner->parent())->getSpectator()) if (static_cast<TabGame *>(owner->parent())->getSpectator())
return; return;
Player *arrowOwner = static_cast<TabGame *>(owner->parent())->getActiveLocalPlayer(); Player *arrowOwner = static_cast<TabGame *>(owner->parent())->getActiveLocalPlayer();
ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor); ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor);
scene()->addItem(arrow); scene()->addItem(arrow);
arrow->grabMouse(); arrow->grabMouse();
QListIterator<QGraphicsItem *> itemIterator(scene()->selectedItems()); QListIterator<QGraphicsItem *> itemIterator(scene()->selectedItems());
while (itemIterator.hasNext()) { while (itemIterator.hasNext()) {
CardItem *c = qgraphicsitem_cast<CardItem *>(itemIterator.next()); CardItem *c = qgraphicsitem_cast<CardItem *>(itemIterator.next());
if (!c || (c == this)) if (!c || (c == this))
continue; continue;
if (c->getZone() != zone) if (c->getZone() != zone)
continue; continue;
ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor); ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor);
scene()->addItem(childArrow); scene()->addItem(childArrow);
arrow->addChildArrow(childArrow); arrow->addChildArrow(childArrow);
} }
} }
void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->buttons().testFlag(Qt::RightButton)) { if (event->buttons().testFlag(Qt::RightButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance()) if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance())
return; return;
QColor arrowColor = Qt::red; QColor arrowColor = Qt::red;
if (event->modifiers().testFlag(Qt::ControlModifier)) if (event->modifiers().testFlag(Qt::ControlModifier))
arrowColor = Qt::yellow; arrowColor = Qt::yellow;
else if (event->modifiers().testFlag(Qt::AltModifier)) else if (event->modifiers().testFlag(Qt::AltModifier))
arrowColor = Qt::blue; arrowColor = Qt::blue;
else if (event->modifiers().testFlag(Qt::ShiftModifier)) else if (event->modifiers().testFlag(Qt::ShiftModifier))
arrowColor = Qt::green; arrowColor = Qt::green;
drawArrow(arrowColor); drawArrow(arrowColor);
} else if (event->buttons().testFlag(Qt::LeftButton)) { } else if (event->buttons().testFlag(Qt::LeftButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance())
return; return;
if (zone->getIsView()) { if (zone->getIsView()) {
const ZoneViewZone *const view = static_cast<const ZoneViewZone *const>(zone); const ZoneViewZone *const view = static_cast<const ZoneViewZone *const>(zone);
if (view->getRevealZone() && !view->getWriteableRevealZone()) if (view->getRevealZone() && !view->getWriteableRevealZone())
return; return;
} else if (!owner->getLocal()) } else if (!owner->getLocal())
return; return;
bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier); bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier);
createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown); createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown);
dragItem->grabMouse(); dragItem->grabMouse();
QList<QGraphicsItem *> sel = scene()->selectedItems(); QList<QGraphicsItem *> sel = scene()->selectedItems();
int j = 0; int j = 0;
for (int i = 0; i < sel.size(); i++) { for (int i = 0; i < sel.size(); i++) {
CardItem *c = (CardItem *) sel.at(i); CardItem *c = (CardItem *) sel.at(i);
if ((c == this) || (c->getZone() != zone)) if ((c == this) || (c->getZone() != zone))
continue; continue;
++j; ++j;
QPointF childPos; QPointF childPos;
if (zone->getHasCardAttr()) if (zone->getHasCardAttr())
childPos = c->pos() - pos(); childPos = c->pos() - pos();
else else
childPos = QPointF(j * CARD_WIDTH / 2, 0); childPos = QPointF(j * CARD_WIDTH / 2, 0);
CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem); CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem);
drag->setPos(dragItem->pos() + childPos); drag->setPos(dragItem->pos() + childPos);
scene()->addItem(drag); scene()->addItem(drag);
} }
} }
setCursor(Qt::OpenHandCursor); setCursor(Qt::OpenHandCursor);
} }
void CardItem::playCard(bool faceDown) void CardItem::playCard(bool faceDown)
{ {
// Do nothing if the card belongs to another player // Do nothing if the card belongs to another player
if (!owner->getLocal()) if (!owner->getLocal())
return; return;
TableZone *tz = qobject_cast<TableZone *>(zone); TableZone *tz = qobject_cast<TableZone *>(zone);
if (tz) if (tz)
tz->toggleTapped(); tz->toggleTapped();
else else
zone->getPlayer()->playCard(this, faceDown, info->getCipt()); zone->getPlayer()->playCard(this, faceDown, info->getCipt());
} }
void CardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void CardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->button() == Qt::RightButton) { if (event->button() == Qt::RightButton) {
if (cardMenu) if (cardMenu)
if (!cardMenu->isEmpty()) if (!cardMenu->isEmpty())
cardMenu->exec(event->screenPos()); cardMenu->exec(event->screenPos());
} else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) { } else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) {
bool hideCard = false; bool hideCard = false;
if (zone->getIsView()) { if (zone->getIsView()) {
ZoneViewZone *view = static_cast<ZoneViewZone *>(zone); ZoneViewZone *view = static_cast<ZoneViewZone *>(zone);
if (view->getRevealZone() && !view->getWriteableRevealZone()) if (view->getRevealZone() && !view->getWriteableRevealZone())
hideCard = true; hideCard = true;
} }
if (hideCard) if (hideCard)
zone->removeCard(this); zone->removeCard(this);
else else
playCard(event->modifiers().testFlag(Qt::ShiftModifier)); playCard(event->modifiers().testFlag(Qt::ShiftModifier));
} }
setCursor(Qt::OpenHandCursor); setCursor(Qt::OpenHandCursor);
AbstractCardItem::mouseReleaseEvent(event); AbstractCardItem::mouseReleaseEvent(event);
} }
void CardItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) void CardItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{ {
if (settingsCache->getDoubleClickToPlay()) { if (settingsCache->getDoubleClickToPlay()) {
if (revealedCard) if (revealedCard)
zone->removeCard(this); zone->removeCard(this);
else else
playCard(event->modifiers().testFlag(Qt::ShiftModifier)); playCard(event->modifiers().testFlag(Qt::ShiftModifier));
} }
event->accept(); event->accept();
} }
bool CardItem::animationEvent() bool CardItem::animationEvent()
{ {
int delta = 18; int delta = 18;
if (!tapped) if (!tapped)
delta *= -1; delta *= -1;
tapAngle += delta; tapAngle += delta;
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
setHovered(false); setHovered(false);
update(); update();
if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0))) if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0)))
return false; return false;
return true; return true;
} }
QVariant CardItem::itemChange(GraphicsItemChange change, const QVariant &value) QVariant CardItem::itemChange(GraphicsItemChange change, const QVariant &value)
{ {
if ((change == ItemSelectedHasChanged) && owner) { if ((change == ItemSelectedHasChanged) && owner) {
if (value == true) { if (value == true) {
owner->setCardMenu(cardMenu); owner->setCardMenu(cardMenu);
owner->getGame()->setActiveCard(this); owner->getGame()->setActiveCard(this);
} else if (owner->getCardMenu() == cardMenu) { } else if (owner->getCardMenu() == cardMenu) {
owner->setCardMenu(0); owner->setCardMenu(0);
owner->getGame()->setActiveCard(0); owner->getGame()->setActiveCard(0);
} }
} }
return QGraphicsItem::itemChange(change, value); return QGraphicsItem::itemChange(change, value);
} }
...@@ -14,75 +14,75 @@ class QColor; ...@@ -14,75 +14,75 @@ class QColor;
const int MAX_COUNTERS_ON_CARD = 999; const int MAX_COUNTERS_ON_CARD = 999;
class CardItem : public AbstractCardItem { class CardItem : public AbstractCardItem {
Q_OBJECT Q_OBJECT
private: private:
CardZone *zone; CardZone *zone;
bool revealedCard; bool revealedCard;
bool attacking; bool attacking;
QMap<int, int> counters; QMap<int, int> counters;
QString annotation; QString annotation;
QString pt; QString pt;
bool destroyOnZoneChange; bool destroyOnZoneChange;
bool doesntUntap; bool doesntUntap;
QPoint gridPoint; QPoint gridPoint;
CardDragItem *dragItem; CardDragItem *dragItem;
CardItem *attachedTo; CardItem *attachedTo;
QList<CardItem *> attachedCards; QList<CardItem *> attachedCards;
QMenu *cardMenu, *ptMenu, *moveMenu; QMenu *cardMenu, *ptMenu, *moveMenu;
void prepareDelete(); void prepareDelete();
public slots: public slots:
void deleteLater(); void deleteLater();
public: public:
enum { Type = typeCard }; enum { Type = typeCard };
int type() const { return Type; } int type() const { return Type; }
CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0); CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0);
~CardItem(); ~CardItem();
void retranslateUi(); void retranslateUi();
CardZone *getZone() const { return zone; } CardZone *getZone() const { return zone; }
void setZone(CardZone *_zone); void setZone(CardZone *_zone);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QPoint getGridPoint() const { return gridPoint; } QPoint getGridPoint() const { return gridPoint; }
void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; } void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; }
QPoint getGridPos() const { return gridPoint; } QPoint getGridPos() const { return gridPoint; }
Player *getOwner() const { return owner; } Player *getOwner() const { return owner; }
void setOwner(Player *_owner) { owner = _owner; } void setOwner(Player *_owner) { owner = _owner; }
bool getRevealedCard() const { return revealedCard; } bool getRevealedCard() const { return revealedCard; }
bool getAttacking() const { return attacking; } bool getAttacking() const { return attacking; }
void setAttacking(bool _attacking); void setAttacking(bool _attacking);
const QMap<int, int> &getCounters() const { return counters; } const QMap<int, int> &getCounters() const { return counters; }
void setCounter(int _id, int _value); void setCounter(int _id, int _value);
QString getAnnotation() const { return annotation; } QString getAnnotation() const { return annotation; }
void setAnnotation(const QString &_annotation); void setAnnotation(const QString &_annotation);
bool getDoesntUntap() const { return doesntUntap; } bool getDoesntUntap() const { return doesntUntap; }
void setDoesntUntap(bool _doesntUntap); void setDoesntUntap(bool _doesntUntap);
QString getPT() const { return pt; } QString getPT() const { return pt; }
void setPT(const QString &_pt); void setPT(const QString &_pt);
bool getDestroyOnZoneChange() const { return destroyOnZoneChange; } bool getDestroyOnZoneChange() const { return destroyOnZoneChange; }
void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; } void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; }
CardItem *getAttachedTo() const { return attachedTo; } CardItem *getAttachedTo() const { return attachedTo; }
void setAttachedTo(CardItem *_attachedTo); void setAttachedTo(CardItem *_attachedTo);
void addAttachedCard(CardItem *card) { attachedCards.append(card); } void addAttachedCard(CardItem *card) { attachedCards.append(card); }
void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); } void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); }
const QList<CardItem *> &getAttachedCards() const { return attachedCards; } const QList<CardItem *> &getAttachedCards() const { return attachedCards; }
void resetState(); void resetState();
void processCardInfo(const ServerInfo_Card &info); void processCardInfo(const ServerInfo_Card &info);
QMenu *getCardMenu() const { return cardMenu; } QMenu *getCardMenu() const { return cardMenu; }
QMenu *getPTMenu() const { return ptMenu; } QMenu *getPTMenu() const { return ptMenu; }
QMenu *getMoveMenu() const { return moveMenu; } QMenu *getMoveMenu() const { return moveMenu; }
bool animationEvent(); bool animationEvent();
CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown); CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown);
void deleteDragItem(); void deleteDragItem();
void drawArrow(const QColor &arrowColor); void drawArrow(const QColor &arrowColor);
void playCard(bool faceDown); void playCard(bool faceDown);
protected: protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
QVariant itemChange(GraphicsItemChange change, const QVariant &value); QVariant itemChange(GraphicsItemChange change, const QVariant &value);
}; };
#endif #endif
...@@ -3,57 +3,57 @@ ...@@ -3,57 +3,57 @@
#include "carddatabase.h" #include "carddatabase.h"
CardList::CardList(bool _contentsKnown) CardList::CardList(bool _contentsKnown)
: QList<CardItem *>(), contentsKnown(_contentsKnown) : QList<CardItem *>(), contentsKnown(_contentsKnown)
{ {
} }
CardItem *CardList::findCard(const int id, const bool remove, int *position) CardItem *CardList::findCard(const int id, const bool remove, int *position)
{ {
if (!contentsKnown) { if (!contentsKnown) {
if (empty()) if (empty())
return 0; return 0;
CardItem *temp = at(0); CardItem *temp = at(0);
if (remove) if (remove)
removeAt(0); removeAt(0);
if (position) if (position)
*position = id; *position = id;
return temp; return temp;
} else } else
for (int i = 0; i < size(); i++) { for (int i = 0; i < size(); i++) {
CardItem *temp = at(i); CardItem *temp = at(i);
if (temp->getId() == id) { if (temp->getId() == id) {
if (remove) if (remove)
removeAt(i); removeAt(i);
if (position) if (position)
*position = i; *position = i;
return temp; return temp;
} }
} }
return 0; return 0;
} }
class CardList::compareFunctor { class CardList::compareFunctor {
private: private:
int flags; int flags;
public: public:
compareFunctor(int _flags) : flags(_flags) compareFunctor(int _flags) : flags(_flags)
{ {
} }
inline bool operator()(CardItem *a, CardItem *b) const inline bool operator()(CardItem *a, CardItem *b) const
{ {
if (flags & SortByType) { if (flags & SortByType) {
QString t1 = a->getInfo()->getMainCardType(); QString t1 = a->getInfo()->getMainCardType();
QString t2 = b->getInfo()->getMainCardType(); QString t2 = b->getInfo()->getMainCardType();
if ((t1 == t2) && (flags & SortByName)) if ((t1 == t2) && (flags & SortByName))
return a->getName() < b->getName(); return a->getName() < b->getName();
return t1 < t2; return t1 < t2;
} else } else
return a->getName() < b->getName(); return a->getName() < b->getName();
} }
}; };
void CardList::sort(int flags) void CardList::sort(int flags)
{ {
compareFunctor cf(flags); compareFunctor cf(flags);
qSort(begin(), end(), cf); qSort(begin(), end(), cf);
} }
...@@ -7,15 +7,15 @@ class CardItem; ...@@ -7,15 +7,15 @@ class CardItem;
class CardList : public QList<CardItem *> { class CardList : public QList<CardItem *> {
private: private:
class compareFunctor; class compareFunctor;
protected: protected:
bool contentsKnown; bool contentsKnown;
public: public:
enum SortFlags { SortByName = 1, SortByType = 2 }; enum SortFlags { SortByName = 1, SortByType = 2 };
CardList(bool _contentsKnown); CardList(bool _contentsKnown);
CardItem *findCard(const int id, const bool remove, int *position = NULL); CardItem *findCard(const int id, const bool remove, int *position = NULL);
bool getContentsKnown() const { return contentsKnown; } bool getContentsKnown() const { return contentsKnown; }
void sort(int flags = SortByName); void sort(int flags = SortByName);
}; };
#endif #endif
...@@ -14,56 +14,56 @@ class QPainter; ...@@ -14,56 +14,56 @@ class QPainter;
class CardDragItem; class CardDragItem;
class CardZone : public AbstractGraphicsItem { class CardZone : public AbstractGraphicsItem {
Q_OBJECT Q_OBJECT
protected: protected:
Player *player; Player *player;
QString name; QString name;
CardList cards; CardList cards;
ZoneViewZone *view; ZoneViewZone *view;
QMenu *menu; QMenu *menu;
QAction *doubleClickAction; QAction *doubleClickAction;
bool hasCardAttr; bool hasCardAttr;
bool isShufflable; bool isShufflable;
bool isView; bool isView;
bool alwaysRevealTopCard; bool alwaysRevealTopCard;
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
void mousePressEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event);
virtual void addCardImpl(CardItem *card, int x, int y) = 0; virtual void addCardImpl(CardItem *card, int x, int y) = 0;
signals: signals:
void cardCountChanged(); void cardCountChanged();
public slots: public slots:
void moveAllToZone(); void moveAllToZone();
bool showContextMenu(const QPoint &screenPos); bool showContextMenu(const QPoint &screenPos);
public: public:
enum { Type = typeZone }; enum { Type = typeZone };
int type() const { return Type; } int type() const { return Type; }
virtual void handleDropEvent(const QList<CardDragItem *> &dragItem, CardZone *startZone, const QPoint &dropPoint) = 0; virtual void handleDropEvent(const QList<CardDragItem *> &dragItem, CardZone *startZone, const QPoint &dropPoint) = 0;
CardZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool _isView = false); CardZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool _isView = false);
~CardZone(); ~CardZone();
void retranslateUi(); void retranslateUi();
void clearContents(); void clearContents();
bool getHasCardAttr() const { return hasCardAttr; } bool getHasCardAttr() const { return hasCardAttr; }
bool getIsShufflable() const { return isShufflable; } bool getIsShufflable() const { return isShufflable; }
QMenu *getMenu() const { return menu; } QMenu *getMenu() const { return menu; }
void setMenu(QMenu *_menu, QAction *_doubleClickAction = 0) { menu = _menu; doubleClickAction = _doubleClickAction; } void setMenu(QMenu *_menu, QAction *_doubleClickAction = 0) { menu = _menu; doubleClickAction = _doubleClickAction; }
QString getName() const { return name; } QString getName() const { return name; }
QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const; QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const;
Player *getPlayer() const { return player; } Player *getPlayer() const { return player; }
bool contentsKnown() const { return cards.getContentsKnown(); } bool contentsKnown() const { return cards.getContentsKnown(); }
const CardList &getCards() const { return cards; } const CardList &getCards() const { return cards; }
void addCard(CardItem *card, bool reorganize, int x, int y = -1); void addCard(CardItem *card, bool reorganize, int x, int y = -1);
// getCard() finds a card by id. // getCard() finds a card by id.
CardItem *getCard(int cardId, const QString &cardName); CardItem *getCard(int cardId, const QString &cardName);
// takeCard() finds a card by position and removes it from the zone and from all of its views. // takeCard() finds a card by position and removes it from the zone and from all of its views.
virtual CardItem *takeCard(int position, int cardId, bool canResize = true); virtual CardItem *takeCard(int position, int cardId, bool canResize = true);
void removeCard(CardItem *card); void removeCard(CardItem *card);
ZoneViewZone *getView() const { return view; } ZoneViewZone *getView() const { return view; }
void setView(ZoneViewZone *_view) { view = _view; } void setView(ZoneViewZone *_view) { view = _view; }
virtual void reorganizeCards() = 0; virtual void reorganizeCards() = 0;
virtual QPointF closestGridPoint(const QPointF &point); virtual QPointF closestGridPoint(const QPointF &point);
bool getIsView() const { return isView; } bool getIsView() const { return isView; }
bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; } bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; }
void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; } void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; }
}; };
#endif #endif
...@@ -10,256 +10,256 @@ ...@@ -10,256 +10,256 @@
#include "pixmapgenerator.h" #include "pixmapgenerator.h"
ChatView::ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent) ChatView::ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent)
: QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), evenNumber(true), showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing) : QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), evenNumber(true), showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing)
{ {
document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }"); document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }");
userContextMenu = new UserContextMenu(tabSupervisor, this, game); userContextMenu = new UserContextMenu(tabSupervisor, this, game);
connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool)));
viewport()->setCursor(Qt::IBeamCursor); viewport()->setCursor(Qt::IBeamCursor);
setReadOnly(true); setReadOnly(true);
setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse);
setOpenLinks(false); setOpenLinks(false);
connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &))); connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &)));
} }
void ChatView::retranslateUi() void ChatView::retranslateUi()
{ {
userContextMenu->retranslateUi(); userContextMenu->retranslateUi();
} }
QTextCursor ChatView::prepareBlock(bool same) QTextCursor ChatView::prepareBlock(bool same)
{ {
lastSender.clear(); lastSender.clear();
QTextCursor cursor(document()->lastBlock()); QTextCursor cursor(document()->lastBlock());
cursor.movePosition(QTextCursor::End); cursor.movePosition(QTextCursor::End);
if (!same) { if (!same) {
QTextBlockFormat blockFormat; QTextBlockFormat blockFormat;
if ((evenNumber = !evenNumber)) if ((evenNumber = !evenNumber))
blockFormat.setBackground(palette().alternateBase()); blockFormat.setBackground(palette().alternateBase());
blockFormat.setBottomMargin(2); blockFormat.setBottomMargin(2);
cursor.insertBlock(blockFormat); cursor.insertBlock(blockFormat);
} else } else
cursor.insertHtml("<br>"); cursor.insertHtml("<br>");
return cursor; return cursor;
} }
void ChatView::appendHtml(const QString &html) void ChatView::appendHtml(const QString &html)
{ {
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
prepareBlock().insertHtml(html); prepareBlock().insertHtml(html);
if (atBottom) if (atBottom)
verticalScrollBar()->setValue(verticalScrollBar()->maximum()); verticalScrollBar()->setValue(verticalScrollBar()->maximum());
} }
void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName) void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName)
{ {
QTextCharFormat oldFormat = cursor.charFormat(); QTextCharFormat oldFormat = cursor.charFormat();
QTextCharFormat anchorFormat = oldFormat; QTextCharFormat anchorFormat = oldFormat;
anchorFormat.setForeground(Qt::blue); anchorFormat.setForeground(Qt::blue);
anchorFormat.setAnchor(true); anchorFormat.setAnchor(true);
anchorFormat.setAnchorHref("card://" + cardName); anchorFormat.setAnchorHref("card://" + cardName);
cursor.setCharFormat(anchorFormat); cursor.setCharFormat(anchorFormat);
cursor.insertText(cardName); cursor.insertText(cardName);
cursor.setCharFormat(oldFormat); cursor.setCharFormat(oldFormat);
} }
void ChatView::appendUrlTag(QTextCursor &cursor, QString url) void ChatView::appendUrlTag(QTextCursor &cursor, QString url)
{ {
if (!url.contains("://")) if (!url.contains("://"))
url.prepend("http://"); url.prepend("http://");
QTextCharFormat oldFormat = cursor.charFormat(); QTextCharFormat oldFormat = cursor.charFormat();
QTextCharFormat anchorFormat = oldFormat; QTextCharFormat anchorFormat = oldFormat;
anchorFormat.setForeground(Qt::blue); anchorFormat.setForeground(Qt::blue);
anchorFormat.setAnchor(true); anchorFormat.setAnchor(true);
anchorFormat.setAnchorHref(url); anchorFormat.setAnchorHref(url);
cursor.setCharFormat(anchorFormat); cursor.setCharFormat(anchorFormat);
cursor.insertText(url); cursor.insertText(url);
cursor.setCharFormat(oldFormat); cursor.setCharFormat(oldFormat);
} }
void ChatView::appendMessage(QString message, QString sender, UserLevelFlags userLevel, bool playerBold) void ChatView::appendMessage(QString message, QString sender, UserLevelFlags userLevel, bool playerBold)
{ {
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
bool sameSender = (sender == lastSender) && !lastSender.isEmpty(); bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
QTextCursor cursor = prepareBlock(sameSender); QTextCursor cursor = prepareBlock(sameSender);
lastSender = sender; lastSender = sender;
if (showTimestamps && !sameSender) { if (showTimestamps && !sameSender) {
QTextCharFormat timeFormat; QTextCharFormat timeFormat;
timeFormat.setForeground(Qt::black); timeFormat.setForeground(Qt::black);
cursor.setCharFormat(timeFormat); cursor.setCharFormat(timeFormat);
cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] ")); cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] "));
} }
QTextCharFormat senderFormat; QTextCharFormat senderFormat;
if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) { if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) {
senderFormat.setFontWeight(QFont::Bold); senderFormat.setFontWeight(QFont::Bold);
senderFormat.setForeground(Qt::red); senderFormat.setForeground(Qt::red);
} else { } else {
senderFormat.setForeground(Qt::blue); senderFormat.setForeground(Qt::blue);
if (playerBold) if (playerBold)
senderFormat.setFontWeight(QFont::Bold); senderFormat.setFontWeight(QFont::Bold);
} }
senderFormat.setAnchor(true); senderFormat.setAnchor(true);
senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender); senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender);
if (!sameSender) { if (!sameSender) {
if (!sender.isEmpty()) { if (!sender.isEmpty()) {
const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize(); const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel)); cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel));
cursor.insertText(" "); cursor.insertText(" ");
} }
cursor.setCharFormat(senderFormat); cursor.setCharFormat(senderFormat);
if (!sender.isEmpty()) if (!sender.isEmpty())
sender.append(": "); sender.append(": ");
cursor.insertText(sender); cursor.insertText(sender);
} else } else
cursor.insertText(" "); cursor.insertText(" ");
QTextCharFormat messageFormat; QTextCharFormat messageFormat;
if (sender.isEmpty()) if (sender.isEmpty())
messageFormat.setForeground(Qt::darkGreen); messageFormat.setForeground(Qt::darkGreen);
cursor.setCharFormat(messageFormat); cursor.setCharFormat(messageFormat);
int from = 0, index = 0; int from = 0, index = 0;
while ((index = message.indexOf('[', from)) != -1) { while ((index = message.indexOf('[', from)) != -1) {
cursor.insertText(message.left(index)); cursor.insertText(message.left(index));
message = message.mid(index); message = message.mid(index);
if (message.isEmpty()) if (message.isEmpty())
break; break;
if (message.startsWith("[card]")) { if (message.startsWith("[card]")) {
message = message.mid(6); message = message.mid(6);
int closeTagIndex = message.indexOf("[/card]"); int closeTagIndex = message.indexOf("[/card]");
QString cardName = message.left(closeTagIndex); QString cardName = message.left(closeTagIndex);
if (closeTagIndex == -1) if (closeTagIndex == -1)
message.clear(); message.clear();
else else
message = message.mid(closeTagIndex + 7); message = message.mid(closeTagIndex + 7);
appendCardTag(cursor, cardName); appendCardTag(cursor, cardName);
} else if (message.startsWith("[[")) { } else if (message.startsWith("[[")) {
message = message.mid(2); message = message.mid(2);
int closeTagIndex = message.indexOf("]]"); int closeTagIndex = message.indexOf("]]");
QString cardName = message.left(closeTagIndex); QString cardName = message.left(closeTagIndex);
if (closeTagIndex == -1) if (closeTagIndex == -1)
message.clear(); message.clear();
else else
message = message.mid(closeTagIndex + 2); message = message.mid(closeTagIndex + 2);
appendCardTag(cursor, cardName); appendCardTag(cursor, cardName);
} else if (message.startsWith("[url]")) { } else if (message.startsWith("[url]")) {
message = message.mid(5); message = message.mid(5);
int closeTagIndex = message.indexOf("[/url]"); int closeTagIndex = message.indexOf("[/url]");
QString url = message.left(closeTagIndex); QString url = message.left(closeTagIndex);
if (closeTagIndex == -1) if (closeTagIndex == -1)
message.clear(); message.clear();
else else
message = message.mid(closeTagIndex + 6); message = message.mid(closeTagIndex + 6);
appendUrlTag(cursor, url); appendUrlTag(cursor, url);
} else } else
from = 1; from = 1;
} }
if (!message.isEmpty()) if (!message.isEmpty())
cursor.insertText(message); cursor.insertText(message);
if (atBottom) if (atBottom)
verticalScrollBar()->setValue(verticalScrollBar()->maximum()); verticalScrollBar()->setValue(verticalScrollBar()->maximum());
} }
void ChatView::enterEvent(QEvent * /*event*/) void ChatView::enterEvent(QEvent * /*event*/)
{ {
setMouseTracking(true); setMouseTracking(true);
} }
void ChatView::leaveEvent(QEvent * /*event*/) void ChatView::leaveEvent(QEvent * /*event*/)
{ {
setMouseTracking(false); setMouseTracking(false);
} }
QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const
{ {
QTextCursor cursor(cursorForPosition(pos)); QTextCursor cursor(cursorForPosition(pos));
QTextBlock block(cursor.block()); QTextBlock block(cursor.block());
QTextBlock::iterator it; QTextBlock::iterator it;
for (it = block.begin(); !(it.atEnd()); ++it) { for (it = block.begin(); !(it.atEnd()); ++it) {
QTextFragment frag = it.fragment(); QTextFragment frag = it.fragment();
if (frag.contains(cursor.position())) if (frag.contains(cursor.position()))
return frag; return frag;
} }
return QTextFragment(); return QTextFragment();
} }
void ChatView::mouseMoveEvent(QMouseEvent *event) void ChatView::mouseMoveEvent(QMouseEvent *event)
{ {
QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref(); QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref();
if (!anchorHref.isEmpty()) { if (!anchorHref.isEmpty()) {
const int delimiterIndex = anchorHref.indexOf("://"); const int delimiterIndex = anchorHref.indexOf("://");
if (delimiterIndex != -1) { if (delimiterIndex != -1) {
const QString scheme = anchorHref.left(delimiterIndex); const QString scheme = anchorHref.left(delimiterIndex);
hoveredContent = anchorHref.mid(delimiterIndex + 3); hoveredContent = anchorHref.mid(delimiterIndex + 3);
if (scheme == "card") { if (scheme == "card") {
hoveredItemType = HoveredCard; hoveredItemType = HoveredCard;
emit cardNameHovered(hoveredContent); emit cardNameHovered(hoveredContent);
} else if (scheme == "user") } else if (scheme == "user")
hoveredItemType = HoveredUser; hoveredItemType = HoveredUser;
else else
hoveredItemType = HoveredUrl; hoveredItemType = HoveredUrl;
viewport()->setCursor(Qt::PointingHandCursor); viewport()->setCursor(Qt::PointingHandCursor);
} else { } else {
hoveredItemType = HoveredNothing; hoveredItemType = HoveredNothing;
viewport()->setCursor(Qt::IBeamCursor); viewport()->setCursor(Qt::IBeamCursor);
} }
} else { } else {
hoveredItemType = HoveredNothing; hoveredItemType = HoveredNothing;
viewport()->setCursor(Qt::IBeamCursor); viewport()->setCursor(Qt::IBeamCursor);
} }
QTextBrowser::mouseMoveEvent(event); QTextBrowser::mouseMoveEvent(event);
} }
void ChatView::mousePressEvent(QMouseEvent *event) void ChatView::mousePressEvent(QMouseEvent *event)
{ {
switch (hoveredItemType) { switch (hoveredItemType) {
case HoveredCard: { case HoveredCard: {
if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton))
emit showCardInfoPopup(event->globalPos(), hoveredContent); emit showCardInfoPopup(event->globalPos(), hoveredContent);
break; break;
} }
case HoveredUser: { case HoveredUser: {
if (event->button() == Qt::RightButton) { if (event->button() == Qt::RightButton) {
const int delimiterIndex = hoveredContent.indexOf("_"); const int delimiterIndex = hoveredContent.indexOf("_");
UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt()); UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt());
const QString userName = hoveredContent.mid(delimiterIndex + 1); const QString userName = hoveredContent.mid(delimiterIndex + 1);
userContextMenu->showContextMenu(event->globalPos(), userName, userLevel); userContextMenu->showContextMenu(event->globalPos(), userName, userLevel);
} }
break; break;
} }
default: { default: {
QTextBrowser::mousePressEvent(event); QTextBrowser::mousePressEvent(event);
} }
} }
} }
void ChatView::mouseReleaseEvent(QMouseEvent *event) void ChatView::mouseReleaseEvent(QMouseEvent *event)
{ {
if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton))
emit deleteCardInfoPopup(QString("_")); emit deleteCardInfoPopup(QString("_"));
QTextBrowser::mouseReleaseEvent(event); QTextBrowser::mouseReleaseEvent(event);
} }
void ChatView::openLink(const QUrl &link) void ChatView::openLink(const QUrl &link)
{ {
if ((link.scheme() == "card") || (link.scheme() == "user")) if ((link.scheme() == "card") || (link.scheme() == "user"))
return; return;
QDesktopServices::openUrl(link); QDesktopServices::openUrl(link);
} }
...@@ -14,40 +14,40 @@ class TabSupervisor; ...@@ -14,40 +14,40 @@ class TabSupervisor;
class TabGame; class TabGame;
class ChatView : public QTextBrowser { class ChatView : public QTextBrowser {
Q_OBJECT Q_OBJECT
protected: protected:
const TabSupervisor * const tabSupervisor; const TabSupervisor * const tabSupervisor;
TabGame * const game; TabGame * const game;
private: private:
enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser }; enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser };
UserContextMenu *userContextMenu; UserContextMenu *userContextMenu;
QString lastSender; QString lastSender;
bool evenNumber; bool evenNumber;
bool showTimestamps; bool showTimestamps;
HoveredItemType hoveredItemType; HoveredItemType hoveredItemType;
QString hoveredContent; QString hoveredContent;
QTextFragment getFragmentUnderMouse(const QPoint &pos) const; QTextFragment getFragmentUnderMouse(const QPoint &pos) const;
QTextCursor prepareBlock(bool same = false); QTextCursor prepareBlock(bool same = false);
void appendCardTag(QTextCursor &cursor, const QString &cardName); void appendCardTag(QTextCursor &cursor, const QString &cardName);
void appendUrlTag(QTextCursor &cursor, QString url); void appendUrlTag(QTextCursor &cursor, QString url);
private slots: private slots:
void openLink(const QUrl &link); void openLink(const QUrl &link);
public: public:
ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0); ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0);
void retranslateUi(); void retranslateUi();
void appendHtml(const QString &html); void appendHtml(const QString &html);
void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false); void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false);
protected: protected:
void enterEvent(QEvent *event); void enterEvent(QEvent *event);
void leaveEvent(QEvent *event); void leaveEvent(QEvent *event);
void mouseMoveEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event);
signals: signals:
void openMessageDialog(const QString &userName, bool focus); void openMessageDialog(const QString &userName, bool focus);
void cardNameHovered(QString cardName); void cardNameHovered(QString cardName);
void showCardInfoPopup(QPoint pos, QString cardName); void showCardInfoPopup(QPoint pos, QString cardName);
void deleteCardInfoPopup(QString cardName); void deleteCardInfoPopup(QString cardName);
}; };
#endif #endif
...@@ -3,34 +3,34 @@ ...@@ -3,34 +3,34 @@
#include <QPainter> #include <QPainter>
GeneralCounter::GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent) GeneralCounter::GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent)
: AbstractCounter(_player, _id, _name, true, _value, parent), color(_color), radius(_radius) : AbstractCounter(_player, _id, _name, true, _value, parent), color(_color), radius(_radius)
{ {
setCacheMode(DeviceCoordinateCache); setCacheMode(DeviceCoordinateCache);
} }
QRectF GeneralCounter::boundingRect() const QRectF GeneralCounter::boundingRect() const
{ {
return QRectF(0, 0, radius * 2, radius * 2); return QRectF(0, 0, radius * 2, radius * 2);
} }
void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/)
{ {
QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); QRectF mapRect = painter->combinedTransform().mapRect(boundingRect());
int translatedHeight = mapRect.size().height(); int translatedHeight = mapRect.size().height();
qreal scaleFactor = translatedHeight / boundingRect().height(); qreal scaleFactor = translatedHeight / boundingRect().height();
QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered);
painter->save(); painter->save();
painter->resetTransform(); painter->resetTransform();
painter->drawPixmap(QPoint(0, 0), pixmap); painter->drawPixmap(QPoint(0, 0), pixmap);
if (value) { if (value) {
QFont f("Serif"); QFont f("Serif");
f.setPixelSize(qMax((int) (radius * scaleFactor), 10)); f.setPixelSize(qMax((int) (radius * scaleFactor), 10));
f.setWeight(QFont::Bold); f.setWeight(QFont::Bold);
painter->setPen(Qt::black); painter->setPen(Qt::black);
painter->setFont(f); painter->setFont(f);
painter->drawText(mapRect, Qt::AlignCenter, QString::number(value)); painter->drawText(mapRect, Qt::AlignCenter, QString::number(value));
} }
painter->restore(); painter->restore();
} }
...@@ -4,14 +4,14 @@ ...@@ -4,14 +4,14 @@
#include "abstractcounter.h" #include "abstractcounter.h"
class GeneralCounter : public AbstractCounter { class GeneralCounter : public AbstractCounter {
Q_OBJECT Q_OBJECT
private: private:
QColor color; QColor color;
int radius; int radius;
public: public:
GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0); GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0);
QRectF boundingRect() const; QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
}; };
#endif #endif
...@@ -4,96 +4,96 @@ ...@@ -4,96 +4,96 @@
#include "decklist.h" #include "decklist.h"
const QStringList DeckLoader::fileNameFilters = QStringList() const QStringList DeckLoader::fileNameFilters = QStringList()
<< QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)") << QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)")
<< QObject::tr("All files (*.*)"); << QObject::tr("All files (*.*)");
DeckLoader::DeckLoader() DeckLoader::DeckLoader()
: DeckList(), : DeckList(),
lastFileName(QString()), lastFileName(QString()),
lastFileFormat(CockatriceFormat), lastFileFormat(CockatriceFormat),
lastRemoteDeckId(-1) lastRemoteDeckId(-1)
{ {
} }
DeckLoader::DeckLoader(const QString &nativeString) DeckLoader::DeckLoader(const QString &nativeString)
: DeckList(nativeString), : DeckList(nativeString),
lastFileName(QString()), lastFileName(QString()),
lastFileFormat(CockatriceFormat), lastFileFormat(CockatriceFormat),
lastRemoteDeckId(-1) lastRemoteDeckId(-1)
{ {
} }
DeckLoader::DeckLoader(const DeckList &other) DeckLoader::DeckLoader(const DeckList &other)
: DeckList(other), : DeckList(other),
lastFileName(QString()), lastFileName(QString()),
lastFileFormat(CockatriceFormat), lastFileFormat(CockatriceFormat),
lastRemoteDeckId(-1) lastRemoteDeckId(-1)
{ {
} }
DeckLoader::DeckLoader(const DeckLoader &other) DeckLoader::DeckLoader(const DeckLoader &other)
: DeckList(other), : DeckList(other),
lastFileName(other.lastFileName), lastFileName(other.lastFileName),
lastFileFormat(other.lastFileFormat), lastFileFormat(other.lastFileFormat),
lastRemoteDeckId(other.lastRemoteDeckId) lastRemoteDeckId(other.lastRemoteDeckId)
{ {
} }
bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt) bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt)
{ {
QFile file(fileName); QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false; return false;
bool result = false; bool result = false;
switch (fmt) { switch (fmt) {
case PlainTextFormat: result = loadFromFile_Plain(&file); break; case PlainTextFormat: result = loadFromFile_Plain(&file); break;
case CockatriceFormat: result = loadFromFile_Native(&file); break; case CockatriceFormat: result = loadFromFile_Native(&file); break;
} }
if (result) { if (result) {
lastFileName = fileName; lastFileName = fileName;
lastFileFormat = fmt; lastFileFormat = fmt;
emit deckLoaded(); emit deckLoaded();
} }
return result; return result;
} }
bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId)
{ {
bool result = loadFromString_Native(nativeString); bool result = loadFromString_Native(nativeString);
if (result) { if (result) {
lastFileName = QString(); lastFileName = QString();
lastFileFormat = CockatriceFormat; lastFileFormat = CockatriceFormat;
lastRemoteDeckId = remoteDeckId; lastRemoteDeckId = remoteDeckId;
emit deckLoaded(); emit deckLoaded();
} }
return result; return result;
} }
bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt)
{ {
QFile file(fileName); QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false; return false;
bool result = false; bool result = false;
switch (fmt) { switch (fmt) {
case PlainTextFormat: result = saveToFile_Plain(&file); break; case PlainTextFormat: result = saveToFile_Plain(&file); break;
case CockatriceFormat: result = saveToFile_Native(&file); break; case CockatriceFormat: result = saveToFile_Native(&file); break;
} }
if (result) { if (result) {
lastFileName = fileName; lastFileName = fileName;
lastFileFormat = fmt; lastFileFormat = fmt;
} }
return result; return result;
} }
DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName) DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName)
{ {
if (fileName.endsWith(".cod", Qt::CaseInsensitive)) { if (fileName.endsWith(".cod", Qt::CaseInsensitive)) {
return CockatriceFormat; return CockatriceFormat;
} }
return PlainTextFormat; return PlainTextFormat;
} }
...@@ -4,30 +4,30 @@ ...@@ -4,30 +4,30 @@
#include "decklist.h" #include "decklist.h"
class DeckLoader : public DeckList { class DeckLoader : public DeckList {
Q_OBJECT Q_OBJECT
signals: signals:
void deckLoaded(); void deckLoaded();
public: public:
enum FileFormat { PlainTextFormat, CockatriceFormat }; enum FileFormat { PlainTextFormat, CockatriceFormat };
static const QStringList fileNameFilters; static const QStringList fileNameFilters;
private: private:
QString lastFileName; QString lastFileName;
FileFormat lastFileFormat; FileFormat lastFileFormat;
int lastRemoteDeckId; int lastRemoteDeckId;
public: public:
DeckLoader(); DeckLoader();
DeckLoader(const QString &nativeString); DeckLoader(const QString &nativeString);
DeckLoader(const DeckList &other); DeckLoader(const DeckList &other);
DeckLoader(const DeckLoader &other); DeckLoader(const DeckLoader &other);
const QString &getLastFileName() const { return lastFileName; } const QString &getLastFileName() const { return lastFileName; }
FileFormat getLastFileFormat() const { return lastFileFormat; } FileFormat getLastFileFormat() const { return lastFileFormat; }
int getLastRemoteDeckId() const { return lastRemoteDeckId; } int getLastRemoteDeckId() const { return lastRemoteDeckId; }
static FileFormat getFormatFromName(const QString &fileName); static FileFormat getFormatFromName(const QString &fileName);
bool loadFromFile(const QString &fileName, FileFormat fmt); bool loadFromFile(const QString &fileName, FileFormat fmt);
bool loadFromRemote(const QString &nativeString, int remoteDeckId); bool loadFromRemote(const QString &nativeString, int remoteDeckId);
bool saveToFile(const QString &fileName, FileFormat fmt); bool saveToFile(const QString &fileName, FileFormat fmt);
}; };
#endif #endif
...@@ -14,423 +14,423 @@ ...@@ -14,423 +14,423 @@
#include "deck_loader.h" #include "deck_loader.h"
DeckListModel::DeckListModel(QObject *parent) DeckListModel::DeckListModel(QObject *parent)
: QAbstractItemModel(parent) : QAbstractItemModel(parent)
{ {
deckList = new DeckLoader; deckList = new DeckLoader;
connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree()));
connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged()));
root = new InnerDecklistNode; root = new InnerDecklistNode;
} }
DeckListModel::~DeckListModel() DeckListModel::~DeckListModel()
{ {
delete root; delete root;
delete deckList; delete deckList;
} }
void DeckListModel::rebuildTree() void DeckListModel::rebuildTree()
{ {
root->clearTree(); root->clearTree();
InnerDecklistNode *listRoot = deckList->getRoot(); InnerDecklistNode *listRoot = deckList->getRoot();
for (int i = 0; i < listRoot->size(); i++) { for (int i = 0; i < listRoot->size(); i++) {
InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i)); InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root); InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root);
for (int j = 0; j < currentZone->size(); j++) { for (int j = 0; j < currentZone->size(); j++) {
DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j)); DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
// XXX better sanity checking // XXX better sanity checking
if (!currentCard) if (!currentCard)
continue; continue;
CardInfo *info = db->getCard(currentCard->getName()); CardInfo *info = db->getCard(currentCard->getName());
QString cardType; QString cardType;
if (!info) if (!info)
cardType = "unknown"; cardType = "unknown";
else else
cardType = info->getMainCardType(); cardType = info->getMainCardType();
InnerDecklistNode *cardTypeNode = dynamic_cast<InnerDecklistNode *>(node->findChild(cardType)); InnerDecklistNode *cardTypeNode = dynamic_cast<InnerDecklistNode *>(node->findChild(cardType));
if (!cardTypeNode) if (!cardTypeNode)
cardTypeNode = new InnerDecklistNode(cardType, node); cardTypeNode = new InnerDecklistNode(cardType, node);
new DecklistModelCardNode(currentCard, cardTypeNode); new DecklistModelCardNode(currentCard, cardTypeNode);
} }
} }
reset(); reset();
} }
int DeckListModel::rowCount(const QModelIndex &parent) const int DeckListModel::rowCount(const QModelIndex &parent) const
{ {
// debugIndexInfo("rowCount", parent); // debugIndexInfo("rowCount", parent);
InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent); InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent);
if (node) if (node)
return node->size(); return node->size();
else else
return 0; return 0;
} }
int DeckListModel::columnCount(const QModelIndex &/*parent*/) const int DeckListModel::columnCount(const QModelIndex &/*parent*/) const
{ {
if (settingsCache->getPriceTagFeature()) if (settingsCache->getPriceTagFeature())
return 3; return 3;
else else
return 2; return 2;
} }
QVariant DeckListModel::data(const QModelIndex &index, int role) const QVariant DeckListModel::data(const QModelIndex &index, int role) const
{ {
// debugIndexInfo("data", index); // debugIndexInfo("data", index);
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
if (index.column() >= columnCount()) if (index.column() >= columnCount())
return QVariant(); return QVariant();
AbstractDecklistNode *temp = static_cast<AbstractDecklistNode *>(index.internalPointer()); AbstractDecklistNode *temp = static_cast<AbstractDecklistNode *>(index.internalPointer());
DecklistModelCardNode *card = dynamic_cast<DecklistModelCardNode *>(temp); DecklistModelCardNode *card = dynamic_cast<DecklistModelCardNode *>(temp);
if (!card) { if (!card) {
InnerDecklistNode *node = dynamic_cast<InnerDecklistNode *>(temp); InnerDecklistNode *node = dynamic_cast<InnerDecklistNode *>(temp);
switch (role) { switch (role) {
case Qt::FontRole: { case Qt::FontRole: {
QFont f; QFont f;
f.setBold(true); f.setBold(true);
return f; return f;
} }
case Qt::DisplayRole: case Qt::DisplayRole:
case Qt::EditRole: case Qt::EditRole:
switch (index.column()) { switch (index.column()) {
case 0: return node->recursiveCount(true); case 0: return node->recursiveCount(true);
case 1: return node->getVisibleName(); case 1: return node->getVisibleName();
case 2: return QString().sprintf("$%.2f", node->recursivePrice(true)); case 2: return QString().sprintf("$%.2f", node->recursivePrice(true));
default: return QVariant(); default: return QVariant();
} }
case Qt::BackgroundRole: { case Qt::BackgroundRole: {
int color = 90 + 60 * node->depth(); int color = 90 + 60 * node->depth();
return QBrush(QColor(color, 255, color)); return QBrush(QColor(color, 255, color));
} }
default: return QVariant(); default: return QVariant();
} }
} else { } else {
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
case Qt::EditRole: { case Qt::EditRole: {
switch (index.column()) { switch (index.column()) {
case 0: return card->getNumber(); case 0: return card->getNumber();
case 1: return card->getName(); case 1: return card->getName();
case 2: return QString().sprintf("$%.2f", card->getTotalPrice()); case 2: return QString().sprintf("$%.2f", card->getTotalPrice());
default: return QVariant(); default: return QVariant();
} }
} }
case Qt::BackgroundRole: { case Qt::BackgroundRole: {
int color = 255 - (index.row() % 2) * 30; int color = 255 - (index.row() % 2) * 30;
return QBrush(QColor(color, color, color)); return QBrush(QColor(color, color, color));
} }
default: return QVariant(); default: return QVariant();
} }
} }
} }
QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const QVariant DeckListModel::headerData(int section, Qt::Orientation orientation, int role) const
{ {
if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal))
return QVariant(); return QVariant();
if (section >= columnCount()) if (section >= columnCount())
return QVariant(); return QVariant();
switch (section) { switch (section) {
case 0: return tr("Number"); case 0: return tr("Number");
case 1: return tr("Card"); case 1: return tr("Card");
case 2: return tr("Price"); case 2: return tr("Price");
default: return QVariant(); default: return QVariant();
} }
} }
QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) const
{ {
// debugIndexInfo("index", parent); // debugIndexInfo("index", parent);
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent))
return QModelIndex(); return QModelIndex();
InnerDecklistNode *parentNode = getNode<InnerDecklistNode *>(parent); InnerDecklistNode *parentNode = getNode<InnerDecklistNode *>(parent);
if (row >= parentNode->size()) if (row >= parentNode->size())
return QModelIndex(); return QModelIndex();
return createIndex(row, column, parentNode->at(row)); return createIndex(row, column, parentNode->at(row));
} }
QModelIndex DeckListModel::parent(const QModelIndex &ind) const QModelIndex DeckListModel::parent(const QModelIndex &ind) const
{ {
if (!ind.isValid()) if (!ind.isValid())
return QModelIndex(); return QModelIndex();
return nodeToIndex(static_cast<AbstractDecklistNode *>(ind.internalPointer())->getParent()); return nodeToIndex(static_cast<AbstractDecklistNode *>(ind.internalPointer())->getParent());
} }
Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const Qt::ItemFlags DeckListModel::flags(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid())
return 0; return 0;
Qt::ItemFlags result = Qt::ItemIsEnabled; Qt::ItemFlags result = Qt::ItemIsEnabled;
if (getNode<DecklistModelCardNode *>(index)) if (getNode<DecklistModelCardNode *>(index))
result |= Qt::ItemIsSelectable; result |= Qt::ItemIsSelectable;
return result; return result;
} }
void DeckListModel::emitRecursiveUpdates(const QModelIndex &index) void DeckListModel::emitRecursiveUpdates(const QModelIndex &index)
{ {
if (!index.isValid()) if (!index.isValid())
return; return;
emit dataChanged(index, index); emit dataChanged(index, index);
emitRecursiveUpdates(index.parent()); emitRecursiveUpdates(index.parent());
} }
bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role) bool DeckListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{ {
DecklistModelCardNode *node = getNode<DecklistModelCardNode *>(index); DecklistModelCardNode *node = getNode<DecklistModelCardNode *>(index);
if (!node || (role != Qt::EditRole)) if (!node || (role != Qt::EditRole))
return false; return false;
switch (index.column()) { switch (index.column()) {
case 0: node->setNumber(value.toInt()); break; case 0: node->setNumber(value.toInt()); break;
case 1: node->setName(value.toString()); break; case 1: node->setName(value.toString()); break;
case 2: node->setPrice(value.toFloat()); break; case 2: node->setPrice(value.toFloat()); break;
default: return false; default: return false;
} }
emitRecursiveUpdates(index); emitRecursiveUpdates(index);
deckList->updateDeckHash(); deckList->updateDeckHash();
return true; return true;
} }
bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent) bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent)
{ {
InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent); InnerDecklistNode *node = getNode<InnerDecklistNode *>(parent);
if (!node) if (!node)
return false; return false;
if (row + count > node->size()) if (row + count > node->size())
return false; return false;
beginRemoveRows(parent, row, row + count - 1); beginRemoveRows(parent, row, row + count - 1);
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
AbstractDecklistNode *toDelete = node->takeAt(row); AbstractDecklistNode *toDelete = node->takeAt(row);
if (DecklistModelCardNode *temp = dynamic_cast<DecklistModelCardNode *>(toDelete)) if (DecklistModelCardNode *temp = dynamic_cast<DecklistModelCardNode *>(toDelete))
deckList->deleteNode(temp->getDataNode()); deckList->deleteNode(temp->getDataNode());
delete toDelete; delete toDelete;
} }
endRemoveRows(); endRemoveRows();
if (!node->size() && (node != root)) if (!node->size() && (node != root))
removeRows(parent.row(), 1, parent.parent()); removeRows(parent.row(), 1, parent.parent());
else else
emitRecursiveUpdates(parent); emitRecursiveUpdates(parent);
return true; return true;
} }
InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent) InnerDecklistNode *DeckListModel::createNodeIfNeeded(const QString &name, InnerDecklistNode *parent)
{ {
InnerDecklistNode *newNode = dynamic_cast<InnerDecklistNode *>(parent->findChild(name)); InnerDecklistNode *newNode = dynamic_cast<InnerDecklistNode *>(parent->findChild(name));
if (!newNode) { if (!newNode) {
beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); beginInsertRows(nodeToIndex(parent), parent->size(), parent->size());
newNode = new InnerDecklistNode(name, parent); newNode = new InnerDecklistNode(name, parent);
endInsertRows(); endInsertRows();
} }
return newNode; return newNode;
} }
QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName) QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName)
{ {
InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root); InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root);
CardInfo *info = db->getCard(cardName); CardInfo *info = db->getCard(cardName);
QString cardType = info->getMainCardType(); QString cardType = info->getMainCardType();
InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode); InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode);
DecklistModelCardNode *cardNode = dynamic_cast<DecklistModelCardNode *>(cardTypeNode->findChild(cardName)); DecklistModelCardNode *cardNode = dynamic_cast<DecklistModelCardNode *>(cardTypeNode->findChild(cardName));
if (!cardNode) { if (!cardNode) {
DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName); DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName);
QModelIndex parentIndex = nodeToIndex(cardTypeNode); QModelIndex parentIndex = nodeToIndex(cardTypeNode);
beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size()); beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size());
cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode); cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode);
endInsertRows(); endInsertRows();
sort(1); sort(1);
emitRecursiveUpdates(parentIndex); emitRecursiveUpdates(parentIndex);
return nodeToIndex(cardNode); return nodeToIndex(cardNode);
} else { } else {
cardNode->setNumber(cardNode->getNumber() + 1); cardNode->setNumber(cardNode->getNumber() + 1);
QModelIndex ind = nodeToIndex(cardNode); QModelIndex ind = nodeToIndex(cardNode);
emitRecursiveUpdates(ind); emitRecursiveUpdates(ind);
deckList->updateDeckHash(); deckList->updateDeckHash();
return ind; return ind;
} }
} }
QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const QModelIndex DeckListModel::nodeToIndex(AbstractDecklistNode *node) const
{ {
if (node == root) if (node == root)
return QModelIndex(); return QModelIndex();
return createIndex(node->getParent()->indexOf(node), 0, node); return createIndex(node->getParent()->indexOf(node), 0, node);
} }
void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order) void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order)
{ {
// Sort children of node and save the information needed to // Sort children of node and save the information needed to
// update the list of persistent indexes. // update the list of persistent indexes.
QVector<QPair<int, int> > sortResult = node->sort(order); QVector<QPair<int, int> > sortResult = node->sort(order);
QModelIndexList from, to; QModelIndexList from, to;
for (int i = sortResult.size() - 1; i >= 0; --i) { for (int i = sortResult.size() - 1; i >= 0; --i) {
const int fromRow = sortResult[i].first; const int fromRow = sortResult[i].first;
const int toRow = sortResult[i].second; const int toRow = sortResult[i].second;
AbstractDecklistNode *temp = node->at(toRow); AbstractDecklistNode *temp = node->at(toRow);
for (int j = columnCount(); j; --j) { for (int j = columnCount(); j; --j) {
from << createIndex(fromRow, 0, temp); from << createIndex(fromRow, 0, temp);
to << createIndex(toRow, 0, temp); to << createIndex(toRow, 0, temp);
} }
} }
changePersistentIndexList(from, to); changePersistentIndexList(from, to);
// Recursion // Recursion
for (int i = node->size() - 1; i >= 0; --i) { for (int i = node->size() - 1; i >= 0; --i) {
InnerDecklistNode *subNode = dynamic_cast<InnerDecklistNode *>(node->at(i)); InnerDecklistNode *subNode = dynamic_cast<InnerDecklistNode *>(node->at(i));
if (subNode) if (subNode)
sortHelper(subNode, order); sortHelper(subNode, order);
} }
} }
void DeckListModel::sort(int /*column*/, Qt::SortOrder order) void DeckListModel::sort(int /*column*/, Qt::SortOrder order)
{ {
emit layoutAboutToBeChanged(); emit layoutAboutToBeChanged();
sortHelper(root, order); sortHelper(root, order);
emit layoutChanged(); emit layoutChanged();
} }
void DeckListModel::cleanList() void DeckListModel::cleanList()
{ {
setDeckList(new DeckLoader); setDeckList(new DeckLoader);
} }
void DeckListModel::setDeckList(DeckLoader *_deck) void DeckListModel::setDeckList(DeckLoader *_deck)
{ {
delete deckList; delete deckList;
deckList = _deck; deckList = _deck;
connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree())); connect(deckList, SIGNAL(deckLoaded()), this, SLOT(rebuildTree()));
connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged())); connect(deckList, SIGNAL(deckHashChanged()), this, SIGNAL(deckHashChanged()));
rebuildTree(); rebuildTree();
} }
void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node) 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) { if (node->height() == 1) {
QTextBlockFormat blockFormat; QTextBlockFormat blockFormat;
QTextCharFormat charFormat; QTextCharFormat charFormat;
charFormat.setFontPointSize(11); charFormat.setFontPointSize(11);
charFormat.setFontWeight(QFont::Bold); charFormat.setFontWeight(QFont::Bold);
cursor->insertBlock(blockFormat, charFormat); cursor->insertBlock(blockFormat, charFormat);
QString priceStr; QString priceStr;
if (settingsCache->getPriceTagFeature()) if (settingsCache->getPriceTagFeature())
priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr)); cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr));
QTextTableFormat tableFormat; QTextTableFormat tableFormat;
tableFormat.setCellPadding(0); tableFormat.setCellPadding(0);
tableFormat.setCellSpacing(0); tableFormat.setCellSpacing(0);
tableFormat.setBorder(0); tableFormat.setBorder(0);
QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat);
for (int i = 0; i < node->size(); i++) { for (int i = 0; i < node->size(); i++) {
AbstractDecklistCardNode *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i)); AbstractDecklistCardNode *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i));
QTextCharFormat cellCharFormat; QTextCharFormat cellCharFormat;
cellCharFormat.setFontPointSize(9); cellCharFormat.setFontPointSize(9);
QTextTableCell cell = table->cellAt(i, 0); QTextTableCell cell = table->cellAt(i, 0);
cell.setFormat(cellCharFormat); cell.setFormat(cellCharFormat);
QTextCursor cellCursor = cell.firstCursorPosition(); QTextCursor cellCursor = cell.firstCursorPosition();
cellCursor.insertText(QString("%1 ").arg(card->getNumber())); cellCursor.insertText(QString("%1 ").arg(card->getNumber()));
cell = table->cellAt(i, 1); cell = table->cellAt(i, 1);
cell.setFormat(cellCharFormat); cell.setFormat(cellCharFormat);
cellCursor = cell.firstCursorPosition(); cellCursor = cell.firstCursorPosition();
cellCursor.insertText(card->getName()); cellCursor.insertText(card->getName());
if (settingsCache->getPriceTagFeature()) { if (settingsCache->getPriceTagFeature()) {
cell = table->cellAt(i, 2); cell = table->cellAt(i, 2);
cell.setFormat(cellCharFormat); cell.setFormat(cellCharFormat);
cellCursor = cell.firstCursorPosition(); cellCursor = cell.firstCursorPosition();
cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice())); cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice()));
} }
} }
} else if (node->height() == 2) { } else if (node->height() == 2) {
QTextBlockFormat blockFormat; QTextBlockFormat blockFormat;
QTextCharFormat charFormat; QTextCharFormat charFormat;
charFormat.setFontPointSize(14); charFormat.setFontPointSize(14);
charFormat.setFontWeight(QFont::Bold); charFormat.setFontWeight(QFont::Bold);
cursor->insertBlock(blockFormat, charFormat); cursor->insertBlock(blockFormat, charFormat);
QString priceStr; QString priceStr;
if (settingsCache->getPriceTagFeature()) if (settingsCache->getPriceTagFeature())
priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true)); priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr)); cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr));
QTextTableFormat tableFormat; QTextTableFormat tableFormat;
tableFormat.setCellPadding(10); tableFormat.setCellPadding(10);
tableFormat.setCellSpacing(0); tableFormat.setCellSpacing(0);
tableFormat.setBorder(0); tableFormat.setBorder(0);
QVector<QTextLength> constraints; QVector<QTextLength> constraints;
for (int i = 0; i < totalColumns; i++) for (int i = 0; i < totalColumns; i++)
constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns); constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns);
tableFormat.setColumnWidthConstraints(constraints); tableFormat.setColumnWidthConstraints(constraints);
QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat);
for (int i = 0; i < node->size(); i++) { for (int i = 0; i < node->size(); i++) {
QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition();
printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i))); printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i)));
} }
} }
cursor->movePosition(QTextCursor::End); cursor->movePosition(QTextCursor::End);
} }
void DeckListModel::printDeckList(QPrinter *printer) void DeckListModel::printDeckList(QPrinter *printer)
{ {
QTextDocument doc; QTextDocument doc;
QFont font("Serif"); QFont font("Serif");
font.setStyleHint(QFont::Serif); font.setStyleHint(QFont::Serif);
doc.setDefaultFont(font); doc.setDefaultFont(font);
QTextCursor cursor(&doc); QTextCursor cursor(&doc);
QTextBlockFormat headerBlockFormat; QTextBlockFormat headerBlockFormat;
QTextCharFormat headerCharFormat; QTextCharFormat headerCharFormat;
headerCharFormat.setFontPointSize(16); headerCharFormat.setFontPointSize(16);
headerCharFormat.setFontWeight(QFont::Bold); headerCharFormat.setFontWeight(QFont::Bold);
cursor.insertBlock(headerBlockFormat, headerCharFormat); cursor.insertBlock(headerBlockFormat, headerCharFormat);
cursor.insertText(deckList->getName()); cursor.insertText(deckList->getName());
headerCharFormat.setFontPointSize(12); headerCharFormat.setFontPointSize(12);
cursor.insertBlock(headerBlockFormat, headerCharFormat); cursor.insertBlock(headerBlockFormat, headerCharFormat);
cursor.insertText(deckList->getComments()); cursor.insertText(deckList->getComments());
cursor.insertBlock(headerBlockFormat, headerCharFormat); cursor.insertBlock(headerBlockFormat, headerCharFormat);
for (int i = 0; i < root->size(); i++) { for (int i = 0; i < root->size(); i++) {
cursor.insertHtml("<br><img src=:/resources/hr.jpg>"); cursor.insertHtml("<br><img src=:/resources/hr.jpg>");
//cursor.insertHtml("<hr>"); //cursor.insertHtml("<hr>");
cursor.insertBlock(headerBlockFormat, headerCharFormat); cursor.insertBlock(headerBlockFormat, headerCharFormat);
printDeckListNode(&cursor, dynamic_cast<InnerDecklistNode *>(root->at(i))); printDeckListNode(&cursor, dynamic_cast<InnerDecklistNode *>(root->at(i)));
} }
doc.print(printer); doc.print(printer);
} }
void DeckListModel::pricesUpdated(InnerDecklistNode *node) void DeckListModel::pricesUpdated(InnerDecklistNode *node)
{ {
if (!node) if (!node)
node = root; node = root;
if (node->isEmpty()) if (node->isEmpty())
return; return;
emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last())); emit dataChanged(createIndex(0, 2, node->at(0)), createIndex(node->size() - 1, 2, node->last()));
} }
...@@ -13,60 +13,60 @@ class QTextCursor; ...@@ -13,60 +13,60 @@ class QTextCursor;
class DecklistModelCardNode : public AbstractDecklistCardNode { class DecklistModelCardNode : public AbstractDecklistCardNode {
private: private:
DecklistCardNode *dataNode; DecklistCardNode *dataNode;
public: public:
DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { } DecklistModelCardNode(DecklistCardNode *_dataNode, InnerDecklistNode *_parent) : AbstractDecklistCardNode(_parent), dataNode(_dataNode) { }
int getNumber() const { return dataNode->getNumber(); } int getNumber() const { return dataNode->getNumber(); }
void setNumber(int _number) { dataNode->setNumber(_number); } void setNumber(int _number) { dataNode->setNumber(_number); }
float getPrice() const { return dataNode->getPrice(); } float getPrice() const { return dataNode->getPrice(); }
void setPrice(float _price) { dataNode->setPrice(_price); } void setPrice(float _price) { dataNode->setPrice(_price); }
QString getName() const { return dataNode->getName(); } QString getName() const { return dataNode->getName(); }
void setName(const QString &_name) { dataNode->setName(_name); } void setName(const QString &_name) { dataNode->setName(_name); }
DecklistCardNode *getDataNode() const { return dataNode; } DecklistCardNode *getDataNode() const { return dataNode; }
}; };
class DeckListModel : public QAbstractItemModel { class DeckListModel : public QAbstractItemModel {
Q_OBJECT Q_OBJECT
private slots: private slots:
void rebuildTree(); void rebuildTree();
public slots: public slots:
void printDeckList(QPrinter *printer); void printDeckList(QPrinter *printer);
signals: signals:
void deckHashChanged(); void deckHashChanged();
public: public:
DeckListModel(QObject *parent = 0); DeckListModel(QObject *parent = 0);
~DeckListModel(); ~DeckListModel();
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const; QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) 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 index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const; QModelIndex parent(const QModelIndex &index) const;
Qt::ItemFlags flags(const QModelIndex &index) const; Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role); bool setData(const QModelIndex &index, const QVariant &value, int role);
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
QModelIndex addCard(const QString &cardName, const QString &zoneName); QModelIndex addCard(const QString &cardName, const QString &zoneName);
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
void cleanList(); void cleanList();
DeckLoader *getDeckList() const { return deckList; } DeckLoader *getDeckList() const { return deckList; }
void setDeckList(DeckLoader *_deck); void setDeckList(DeckLoader *_deck);
void pricesUpdated(InnerDecklistNode *node = 0); void pricesUpdated(InnerDecklistNode *node = 0);
private: private:
DeckLoader *deckList; DeckLoader *deckList;
InnerDecklistNode *root; InnerDecklistNode *root;
InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent); InnerDecklistNode *createNodeIfNeeded(const QString &name, InnerDecklistNode *parent);
QModelIndex nodeToIndex(AbstractDecklistNode *node) const; QModelIndex nodeToIndex(AbstractDecklistNode *node) const;
void emitRecursiveUpdates(const QModelIndex &index); void emitRecursiveUpdates(const QModelIndex &index);
void sortHelper(InnerDecklistNode *node, Qt::SortOrder order); void sortHelper(InnerDecklistNode *node, Qt::SortOrder order);
void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node); void printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node);
template<typename T> T getNode(const QModelIndex &index) const template<typename T> T getNode(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid())
return dynamic_cast<T>(root); return dynamic_cast<T>(root);
return dynamic_cast<T>(static_cast<AbstractDecklistNode *>(index.internalPointer())); return dynamic_cast<T>(static_cast<AbstractDecklistNode *>(index.internalPointer()));
} }
}; };
#endif #endif
...@@ -8,46 +8,46 @@ ...@@ -8,46 +8,46 @@
#include <QDesktopServices> #include <QDesktopServices>
DeckStatsInterface::DeckStatsInterface(QObject *parent) DeckStatsInterface::DeckStatsInterface(QObject *parent)
: QObject(parent) : QObject(parent)
{ {
manager = new QNetworkAccessManager(this); manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *)));
} }
void DeckStatsInterface::queryFinished(QNetworkReply *reply) void DeckStatsInterface::queryFinished(QNetworkReply *reply)
{ {
if (reply->error() != QNetworkReply::NoError) { if (reply->error() != QNetworkReply::NoError) {
QMessageBox::critical(0, tr("Error"), reply->errorString()); QMessageBox::critical(0, tr("Error"), reply->errorString());
reply->deleteLater(); reply->deleteLater();
deleteLater(); deleteLater();
return; return;
} }
QString data(reply->readAll()); QString data(reply->readAll());
reply->deleteLater(); reply->deleteLater();
QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\""); QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\"");
if (!rx.indexIn(data)) { if (!rx.indexIn(data)) {
QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed.")); QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed."));
deleteLater(); deleteLater();
return; return;
} }
QString deckUrl = rx.cap(1); QString deckUrl = rx.cap(1);
QDesktopServices::openUrl(deckUrl); QDesktopServices::openUrl(deckUrl);
deleteLater(); deleteLater();
} }
void DeckStatsInterface::analyzeDeck(DeckList *deck) void DeckStatsInterface::analyzeDeck(DeckList *deck)
{ {
QUrl params; QUrl params;
params.addQueryItem("deck", deck->writeToString_Plain()); params.addQueryItem("deck", deck->writeToString_Plain());
QByteArray data; QByteArray data;
data.append(params.encodedQuery()); data.append(params.encodedQuery());
QNetworkRequest request(QUrl("http://deckstats.net/index.php")); QNetworkRequest request(QUrl("http://deckstats.net/index.php"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
manager->post(request, data); manager->post(request, data);
} }
...@@ -8,14 +8,14 @@ class QNetworkReply; ...@@ -8,14 +8,14 @@ class QNetworkReply;
class DeckList; class DeckList;
class DeckStatsInterface : public QObject { class DeckStatsInterface : public QObject {
Q_OBJECT Q_OBJECT
private: private:
QNetworkAccessManager *manager; QNetworkAccessManager *manager;
private slots: private slots:
void queryFinished(QNetworkReply *reply); void queryFinished(QNetworkReply *reply);
public: public:
DeckStatsInterface(QObject *parent = 0); DeckStatsInterface(QObject *parent = 0);
void analyzeDeck(DeckList *deck); void analyzeDeck(DeckList *deck);
}; };
#endif #endif
...@@ -8,479 +8,479 @@ ...@@ -8,479 +8,479 @@
#include "main.h" #include "main.h"
DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag) DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag)
: AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0) : AbstractCardDragItem(_item, _hotSpot, parentDrag), currentZone(0)
{ {
} }
void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos) void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos)
{ {
QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos); QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos);
DeckViewCardContainer *cursorZone = 0; DeckViewCardContainer *cursorZone = 0;
for (int i = colliding.size() - 1; i >= 0; i--) for (int i = colliding.size() - 1; i >= 0; i--)
if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(colliding.at(i)))) if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(colliding.at(i))))
break; break;
if (!cursorZone) if (!cursorZone)
return; return;
currentZone = cursorZone; currentZone = cursorZone;
QPointF newPos = cursorScenePos; QPointF newPos = cursorScenePos;
if (newPos != pos()) { if (newPos != pos()) {
for (int i = 0; i < childDrags.size(); i++) for (int i = 0; i < childDrags.size(); i++)
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
setPos(newPos); setPos(newPos);
} }
} }
void DeckViewCardDragItem::handleDrop(DeckViewCardContainer *target) void DeckViewCardDragItem::handleDrop(DeckViewCardContainer *target)
{ {
DeckViewCard *card = static_cast<DeckViewCard *>(item); DeckViewCard *card = static_cast<DeckViewCard *>(item);
DeckViewCardContainer *start = static_cast<DeckViewCardContainer *>(item->parentItem()); DeckViewCardContainer *start = static_cast<DeckViewCardContainer *>(item->parentItem());
start->removeCard(card); start->removeCard(card);
target->addCard(card); target->addCard(card);
card->setParentItem(target); card->setParentItem(target);
} }
void DeckViewCardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void DeckViewCardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
setCursor(Qt::OpenHandCursor); setCursor(Qt::OpenHandCursor);
DeckViewScene *sc = static_cast<DeckViewScene *>(scene()); DeckViewScene *sc = static_cast<DeckViewScene *>(scene());
sc->removeItem(this); sc->removeItem(this);
if (currentZone) { if (currentZone) {
handleDrop(currentZone); handleDrop(currentZone);
for (int i = 0; i < childDrags.size(); i++) { for (int i = 0; i < childDrags.size(); i++) {
DeckViewCardDragItem *c = static_cast<DeckViewCardDragItem *>(childDrags[i]); DeckViewCardDragItem *c = static_cast<DeckViewCardDragItem *>(childDrags[i]);
c->handleDrop(currentZone); c->handleDrop(currentZone);
sc->removeItem(c); sc->removeItem(c);
} }
sc->updateContents(); sc->updateContents();
} }
event->accept(); event->accept();
} }
DeckViewCard::DeckViewCard(const QString &_name, const QString &_originZone, QGraphicsItem *parent) DeckViewCard::DeckViewCard(const QString &_name, const QString &_originZone, QGraphicsItem *parent)
: AbstractCardItem(_name, 0, -1, parent), originZone(_originZone), dragItem(0) : AbstractCardItem(_name, 0, -1, parent), originZone(_originZone), dragItem(0)
{ {
setAcceptsHoverEvents(true); setAcceptsHoverEvents(true);
} }
DeckViewCard::~DeckViewCard() DeckViewCard::~DeckViewCard()
{ {
delete dragItem; delete dragItem;
} }
void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{ {
AbstractCardItem::paint(painter, option, widget); AbstractCardItem::paint(painter, option, widget);
painter->save(); painter->save();
QPen pen;//(Qt::DotLine); QPen pen;//(Qt::DotLine);
pen.setWidth(3); pen.setWidth(3);
if (originZone == "main") if (originZone == "main")
pen.setColor(QColor(0, 255, 0)); pen.setColor(QColor(0, 255, 0));
else else
pen.setColor(QColor(255, 0, 0)); pen.setColor(QColor(255, 0, 0));
painter->setPen(pen); painter->setPen(pen);
painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3)); painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3));
painter->restore(); painter->restore();
} }
void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance())
return; return;
if (static_cast<DeckViewScene *>(scene())->getLocked()) if (static_cast<DeckViewScene *>(scene())->getLocked())
return; return;
delete dragItem; delete dragItem;
dragItem = new DeckViewCardDragItem(this, event->pos()); dragItem = new DeckViewCardDragItem(this, event->pos());
scene()->addItem(dragItem); scene()->addItem(dragItem);
dragItem->updatePosition(event->scenePos()); dragItem->updatePosition(event->scenePos());
dragItem->grabMouse(); dragItem->grabMouse();
QList<QGraphicsItem *> sel = scene()->selectedItems(); QList<QGraphicsItem *> sel = scene()->selectedItems();
int j = 0; int j = 0;
for (int i = 0; i < sel.size(); i++) { for (int i = 0; i < sel.size(); i++) {
DeckViewCard *c = static_cast<DeckViewCard *>(sel.at(i)); DeckViewCard *c = static_cast<DeckViewCard *>(sel.at(i));
if (c == this) if (c == this)
continue; continue;
++j; ++j;
QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0); QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0);
DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem); DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem);
drag->setPos(dragItem->pos() + childPos); drag->setPos(dragItem->pos() + childPos);
scene()->addItem(drag); scene()->addItem(drag);
} }
setCursor(Qt::OpenHandCursor); setCursor(Qt::OpenHandCursor);
} }
void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event) void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{ {
event->accept(); event->accept();
processHoverEvent(); processHoverEvent();
} }
DeckViewCardContainer::DeckViewCardContainer(const QString &_name) DeckViewCardContainer::DeckViewCardContainer(const QString &_name)
: QGraphicsItem(), name(_name), width(0), height(0) : QGraphicsItem(), name(_name), width(0), height(0)
{ {
QString bgPath = settingsCache->getTableBgPath(); QString bgPath = settingsCache->getTableBgPath();
if (!bgPath.isEmpty()) if (!bgPath.isEmpty())
bgPixmap.load(bgPath); bgPixmap.load(bgPath);
setCacheMode(DeviceCoordinateCache); setCacheMode(DeviceCoordinateCache);
} }
QRectF DeckViewCardContainer::boundingRect() const QRectF DeckViewCardContainer::boundingRect() const
{ {
return QRectF(0, 0, width, height); return QRectF(0, 0, width, height);
} }
void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
qreal totalTextWidth = getCardTypeTextWidth(); qreal totalTextWidth = getCardTypeTextWidth();
if (bgPixmap.isNull()) if (bgPixmap.isNull())
painter->fillRect(boundingRect(), QColor(0, 0, 100)); painter->fillRect(boundingRect(), QColor(0, 0, 100));
else else
painter->fillRect(boundingRect(), QBrush(bgPixmap)); painter->fillRect(boundingRect(), QBrush(bgPixmap));
painter->setPen(QColor(255, 255, 255, 100)); painter->setPen(QColor(255, 255, 255, 100));
painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY));
painter->setPen(QColor(Qt::white)); painter->setPen(QColor(Qt::white));
QFont f("Serif"); QFont f("Serif");
f.setStyleHint(QFont::Serif); f.setStyleHint(QFont::Serif);
f.setPixelSize(24); f.setPixelSize(24);
f.setWeight(QFont::Bold); f.setWeight(QFont::Bold);
painter->setFont(f); painter->setFont(f);
painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size())); painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size()));
f.setPixelSize(16); f.setPixelSize(16);
painter->setFont(f); painter->setFont(f);
QList<QString> cardTypeList = cardsByType.uniqueKeys(); QList<QString> cardTypeList = cardsByType.uniqueKeys();
qreal yUntilNow = separatorY + paddingY; qreal yUntilNow = separatorY + paddingY;
for (int i = 0; i < cardTypeList.size(); ++i) { for (int i = 0; i < cardTypeList.size(); ++i) {
if (i != 0) { if (i != 0) {
painter->setPen(QColor(255, 255, 255, 100)); painter->setPen(QColor(255, 255, 255, 100));
painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2)); painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2));
} }
qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first;
QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight); QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight);
yUntilNow += thisRowHeight + paddingY; yUntilNow += thisRowHeight + paddingY;
painter->setPen(Qt::white); painter->setPen(Qt::white);
painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]); painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]);
} }
} }
void DeckViewCardContainer::addCard(DeckViewCard *card) void DeckViewCardContainer::addCard(DeckViewCard *card)
{ {
cards.append(card); cards.append(card);
cardsByType.insert(card->getInfo()->getMainCardType(), card); cardsByType.insert(card->getInfo()->getMainCardType(), card);
} }
void DeckViewCardContainer::removeCard(DeckViewCard *card) void DeckViewCardContainer::removeCard(DeckViewCard *card)
{ {
cards.removeAt(cards.indexOf(card)); cards.removeAt(cards.indexOf(card));
cardsByType.remove(card->getInfo()->getMainCardType(), card); cardsByType.remove(card->getInfo()->getMainCardType(), card);
} }
QList<QPair<int, int> > DeckViewCardContainer::getRowsAndCols() const QList<QPair<int, int> > DeckViewCardContainer::getRowsAndCols() const
{ {
QList<QPair<int, int> > result; QList<QPair<int, int> > result;
QList<QString> cardTypeList = cardsByType.uniqueKeys(); QList<QString> cardTypeList = cardsByType.uniqueKeys();
for (int i = 0; i < cardTypeList.size(); ++i) for (int i = 0; i < cardTypeList.size(); ++i)
result.append(QPair<int, int>(1, cardsByType.count(cardTypeList[i]))); result.append(QPair<int, int>(1, cardsByType.count(cardTypeList[i])));
return result; return result;
} }
int DeckViewCardContainer::getCardTypeTextWidth() const int DeckViewCardContainer::getCardTypeTextWidth() const
{ {
QFont f("Serif"); QFont f("Serif");
f.setStyleHint(QFont::Serif); f.setStyleHint(QFont::Serif);
f.setPixelSize(16); f.setPixelSize(16);
f.setWeight(QFont::Bold); f.setWeight(QFont::Bold);
QFontMetrics fm(f); QFontMetrics fm(f);
int maxCardTypeWidth = 0; int maxCardTypeWidth = 0;
QMapIterator<QString, DeckViewCard *> i(cardsByType); QMapIterator<QString, DeckViewCard *> i(cardsByType);
while (i.hasNext()) { while (i.hasNext()) {
int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width(); int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width();
if (cardTypeWidth > maxCardTypeWidth) if (cardTypeWidth > maxCardTypeWidth)
maxCardTypeWidth = cardTypeWidth; maxCardTypeWidth = cardTypeWidth;
} }
return maxCardTypeWidth + 15; return maxCardTypeWidth + 15;
} }
QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int> > &rowsAndCols) const QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int> > &rowsAndCols) const
{ {
qreal totalHeight = 0; qreal totalHeight = 0;
qreal totalWidth = 0; qreal totalWidth = 0;
// Calculate space needed for cards // Calculate space needed for cards
for (int i = 0; i < rowsAndCols.size(); ++i) { for (int i = 0; i < rowsAndCols.size(); ++i) {
totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY; totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY;
if (CARD_WIDTH * rowsAndCols[i].second > totalWidth) if (CARD_WIDTH * rowsAndCols[i].second > totalWidth)
totalWidth = CARD_WIDTH * rowsAndCols[i].second; totalWidth = CARD_WIDTH * rowsAndCols[i].second;
} }
return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY); return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY);
} }
void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int> > &rowsAndCols) void DeckViewCardContainer::rearrangeItems(const QList<QPair<int, int> > &rowsAndCols)
{ {
currentRowsAndCols = rowsAndCols; currentRowsAndCols = rowsAndCols;
int totalCols = 0, totalRows = 0; int totalCols = 0, totalRows = 0;
qreal yUntilNow = separatorY + paddingY; qreal yUntilNow = separatorY + paddingY;
qreal x = (qreal) getCardTypeTextWidth(); qreal x = (qreal) getCardTypeTextWidth();
for (int i = 0; i < rowsAndCols.size(); ++i) { for (int i = 0; i < rowsAndCols.size(); ++i) {
const int tempRows = rowsAndCols[i].first; const int tempRows = rowsAndCols[i].first;
const int tempCols = rowsAndCols[i].second; const int tempCols = rowsAndCols[i].second;
totalRows += tempRows; totalRows += tempRows;
if (tempCols > totalCols) if (tempCols > totalCols)
totalCols = tempCols; totalCols = tempCols;
QList<QString> cardTypeList = cardsByType.uniqueKeys(); QList<QString> cardTypeList = cardsByType.uniqueKeys();
QList<DeckViewCard *> row = cardsByType.values(cardTypeList[i]); QList<DeckViewCard *> row = cardsByType.values(cardTypeList[i]);
for (int j = 0; j < row.size(); ++j) { for (int j = 0; j < row.size(); ++j) {
DeckViewCard *card = row[j]; DeckViewCard *card = row[j];
card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT); card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT);
} }
yUntilNow += tempRows * CARD_HEIGHT + paddingY; yUntilNow += tempRows * CARD_HEIGHT + paddingY;
} }
prepareGeometryChange(); prepareGeometryChange();
QSizeF bRect = calculateBoundingRect(rowsAndCols); QSizeF bRect = calculateBoundingRect(rowsAndCols);
width = bRect.width(); width = bRect.width();
height = bRect.height(); height = bRect.height();
} }
void DeckViewCardContainer::setWidth(qreal _width) void DeckViewCardContainer::setWidth(qreal _width)
{ {
prepareGeometryChange(); prepareGeometryChange();
width = _width; width = _width;
update(); update();
} }
DeckViewScene::DeckViewScene(QObject *parent) DeckViewScene::DeckViewScene(QObject *parent)
: QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0) : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0)
{ {
} }
DeckViewScene::~DeckViewScene() DeckViewScene::~DeckViewScene()
{ {
clearContents(); clearContents();
delete deck; delete deck;
} }
void DeckViewScene::clearContents() void DeckViewScene::clearContents()
{ {
QMapIterator<QString, DeckViewCardContainer *> i(cardContainers); QMapIterator<QString, DeckViewCardContainer *> i(cardContainers);
while (i.hasNext()) while (i.hasNext())
delete i.next().value(); delete i.next().value();
cardContainers.clear(); cardContainers.clear();
} }
void DeckViewScene::setDeck(const DeckList &_deck) void DeckViewScene::setDeck(const DeckList &_deck)
{ {
if (deck) if (deck)
delete deck; delete deck;
deck = new DeckList(_deck); deck = new DeckList(_deck);
rebuildTree(); rebuildTree();
applySideboardPlan(deck->getCurrentSideboardPlan()); applySideboardPlan(deck->getCurrentSideboardPlan());
rearrangeItems(); rearrangeItems();
} }
void DeckViewScene::rebuildTree() void DeckViewScene::rebuildTree()
{ {
clearContents(); clearContents();
if (!deck) if (!deck)
return; return;
InnerDecklistNode *listRoot = deck->getRoot(); InnerDecklistNode *listRoot = deck->getRoot();
for (int i = 0; i < listRoot->size(); i++) { for (int i = 0; i < listRoot->size(); i++) {
InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i)); InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0);
if (!container) { if (!container) {
container = new DeckViewCardContainer(currentZone->getName()); container = new DeckViewCardContainer(currentZone->getName());
cardContainers.insert(currentZone->getName(), container); cardContainers.insert(currentZone->getName(), container);
addItem(container); addItem(container);
} }
for (int j = 0; j < currentZone->size(); j++) { for (int j = 0; j < currentZone->size(); j++) {
DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j)); DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
if (!currentCard) if (!currentCard)
continue; continue;
for (int k = 0; k < currentCard->getNumber(); ++k) { for (int k = 0; k < currentCard->getNumber(); ++k) {
DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container); DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container);
container->addCard(newCard); container->addCard(newCard);
emit newCardAdded(newCard); emit newCardAdded(newCard);
} }
} }
} }
} }
void DeckViewScene::applySideboardPlan(const QList<MoveCard_ToZone> &plan) void DeckViewScene::applySideboardPlan(const QList<MoveCard_ToZone> &plan)
{ {
for (int i = 0; i < plan.size(); ++i) { for (int i = 0; i < plan.size(); ++i) {
const MoveCard_ToZone &m = plan[i]; const MoveCard_ToZone &m = plan[i];
DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone())); DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone()));
DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone())); DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone()));
if (!start || !target) if (!start || !target)
continue; continue;
DeckViewCard *card = 0; DeckViewCard *card = 0;
const QList<DeckViewCard *> &cardList = start->getCards(); const QList<DeckViewCard *> &cardList = start->getCards();
for (int j = 0; j < cardList.size(); ++j) for (int j = 0; j < cardList.size(); ++j)
if (cardList[j]->getName() == QString::fromStdString(m.card_name())) { if (cardList[j]->getName() == QString::fromStdString(m.card_name())) {
card = cardList[j]; card = cardList[j];
break; break;
} }
if (!card) if (!card)
continue; continue;
start->removeCard(card); start->removeCard(card);
target->addCard(card); target->addCard(card);
card->setParentItem(target); card->setParentItem(target);
} }
} }
void DeckViewScene::rearrangeItems() void DeckViewScene::rearrangeItems()
{ {
const int spacing = CARD_HEIGHT / 3; const int spacing = CARD_HEIGHT / 3;
QList<DeckViewCardContainer *> contList = cardContainers.values(); QList<DeckViewCardContainer *> contList = cardContainers.values();
// Initialize space requirements // Initialize space requirements
QList<QList<QPair<int, int> > > rowsAndColsList; QList<QList<QPair<int, int> > > rowsAndColsList;
QList<QList<int> > cardCountList; QList<QList<int> > cardCountList;
for (int i = 0; i < contList.size(); ++i) { for (int i = 0; i < contList.size(); ++i) {
QList<QPair<int, int> > rowsAndCols = contList[i]->getRowsAndCols(); QList<QPair<int, int> > rowsAndCols = contList[i]->getRowsAndCols();
rowsAndColsList.append(rowsAndCols); rowsAndColsList.append(rowsAndCols);
cardCountList.append(QList<int>()); cardCountList.append(QList<int>());
for (int j = 0; j < rowsAndCols.size(); ++j) for (int j = 0; j < rowsAndCols.size(); ++j)
cardCountList[i].append(rowsAndCols[j].second); cardCountList[i].append(rowsAndCols[j].second);
} }
qreal totalHeight, totalWidth; qreal totalHeight, totalWidth;
for (;;) { for (;;) {
// Calculate total size before this iteration // Calculate total size before this iteration
totalHeight = -spacing; totalHeight = -spacing;
totalWidth = 0; totalWidth = 0;
for (int i = 0; i < contList.size(); ++i) { for (int i = 0; i < contList.size(); ++i) {
QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]); QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]);
totalHeight += contSize.height() + spacing; totalHeight += contSize.height() + spacing;
if (contSize.width() > totalWidth) if (contSize.width() > totalWidth)
totalWidth = contSize.width(); totalWidth = contSize.width();
} }
// We're done when the aspect ratio shifts from too high to too low. // We're done when the aspect ratio shifts from too high to too low.
if (totalWidth / totalHeight <= optimalAspectRatio) if (totalWidth / totalHeight <= optimalAspectRatio)
break; break;
// Find category with highest column count // Find category with highest column count
int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0; int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0;
for (int i = 0; i < rowsAndColsList.size(); ++i) for (int i = 0; i < rowsAndColsList.size(); ++i)
for (int j = 0; j < rowsAndColsList[i].size(); ++j) for (int j = 0; j < rowsAndColsList[i].size(); ++j)
if (rowsAndColsList[i][j].second > maxCols) { if (rowsAndColsList[i][j].second > maxCols) {
maxIndex1 = i; maxIndex1 = i;
maxIndex2 = j; maxIndex2 = j;
maxCols = rowsAndColsList[i][j].second; maxCols = rowsAndColsList[i][j].second;
} }
// Add row to category // Add row to category
const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first; const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first;
const int maxCardCount = cardCountList[maxIndex1][maxIndex2]; const int maxCardCount = cardCountList[maxIndex1][maxIndex2];
rowsAndColsList[maxIndex1][maxIndex2] = QPair<int, int>(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1))); rowsAndColsList[maxIndex1][maxIndex2] = QPair<int, int>(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1)));
} }
totalHeight = -spacing; totalHeight = -spacing;
for (int i = 0; i < contList.size(); ++i) { for (int i = 0; i < contList.size(); ++i) {
DeckViewCardContainer *c = contList[i]; DeckViewCardContainer *c = contList[i];
c->rearrangeItems(rowsAndColsList[i]); c->rearrangeItems(rowsAndColsList[i]);
c->setPos(0, totalHeight + spacing); c->setPos(0, totalHeight + spacing);
totalHeight += c->boundingRect().height() + spacing; totalHeight += c->boundingRect().height() + spacing;
} }
totalWidth = totalHeight * optimalAspectRatio; totalWidth = totalHeight * optimalAspectRatio;
for (int i = 0; i < contList.size(); ++i) for (int i = 0; i < contList.size(); ++i)
contList[i]->setWidth(totalWidth); contList[i]->setWidth(totalWidth);
setSceneRect(QRectF(0, 0, totalWidth, totalHeight)); setSceneRect(QRectF(0, 0, totalWidth, totalHeight));
} }
void DeckViewScene::updateContents() void DeckViewScene::updateContents()
{ {
rearrangeItems(); rearrangeItems();
emit sideboardPlanChanged(); emit sideboardPlanChanged();
} }
QList<MoveCard_ToZone> DeckViewScene::getSideboardPlan() const QList<MoveCard_ToZone> DeckViewScene::getSideboardPlan() const
{ {
QList<MoveCard_ToZone> result; QList<MoveCard_ToZone> result;
QMapIterator<QString, DeckViewCardContainer *> containerIterator(cardContainers); QMapIterator<QString, DeckViewCardContainer *> containerIterator(cardContainers);
while (containerIterator.hasNext()) { while (containerIterator.hasNext()) {
DeckViewCardContainer *cont = containerIterator.next().value(); DeckViewCardContainer *cont = containerIterator.next().value();
const QList<DeckViewCard *> cardList = cont->getCards(); const QList<DeckViewCard *> cardList = cont->getCards();
for (int i = 0; i < cardList.size(); ++i) for (int i = 0; i < cardList.size(); ++i)
if (cardList[i]->getOriginZone() != cont->getName()) { if (cardList[i]->getOriginZone() != cont->getName()) {
MoveCard_ToZone m; MoveCard_ToZone m;
m.set_card_name(cardList[i]->getName().toStdString()); m.set_card_name(cardList[i]->getName().toStdString());
m.set_start_zone(cardList[i]->getOriginZone().toStdString()); m.set_start_zone(cardList[i]->getOriginZone().toStdString());
m.set_target_zone(cont->getName().toStdString()); m.set_target_zone(cont->getName().toStdString());
result.append(m); result.append(m);
} }
} }
return result; return result;
} }
void DeckViewScene::resetSideboardPlan() void DeckViewScene::resetSideboardPlan()
{ {
rebuildTree(); rebuildTree();
rearrangeItems(); rearrangeItems();
} }
DeckView::DeckView(QWidget *parent) DeckView::DeckView(QWidget *parent)
: QGraphicsView(parent) : QGraphicsView(parent)
{ {
deckViewScene = new DeckViewScene(this); deckViewScene = new DeckViewScene(this);
setBackgroundBrush(QBrush(QColor(0, 0, 0))); setBackgroundBrush(QBrush(QColor(0, 0, 0)));
setDragMode(RubberBandDrag); setDragMode(RubberBandDrag);
setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/); setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/);
setScene(deckViewScene); setScene(deckViewScene);
connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &)));
connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *)));
connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged())); connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged()));
} }
void DeckView::resizeEvent(QResizeEvent *event) void DeckView::resizeEvent(QResizeEvent *event)
{ {
QGraphicsView::resizeEvent(event); QGraphicsView::resizeEvent(event);
deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height()); deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height());
deckViewScene->rearrangeItems(); deckViewScene->rearrangeItems();
} }
void DeckView::updateSceneRect(const QRectF &rect) void DeckView::updateSceneRect(const QRectF &rect)
{ {
fitInView(rect, Qt::KeepAspectRatio); fitInView(rect, Qt::KeepAspectRatio);
} }
void DeckView::setDeck(const DeckList &_deck) void DeckView::setDeck(const DeckList &_deck)
{ {
deckViewScene->setDeck(_deck); deckViewScene->setDeck(_deck);
} }
void DeckView::resetSideboardPlan() void DeckView::resetSideboardPlan()
{ {
deckViewScene->resetSideboardPlan(); deckViewScene->resetSideboardPlan();
} }
...@@ -19,101 +19,101 @@ class MoveCardToZone; ...@@ -19,101 +19,101 @@ class MoveCardToZone;
class DeckViewCard : public AbstractCardItem { class DeckViewCard : public AbstractCardItem {
private: private:
QString originZone; QString originZone;
DeckViewCardDragItem *dragItem; DeckViewCardDragItem *dragItem;
public: public:
DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0); DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0);
~DeckViewCard(); ~DeckViewCard();
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
const QString &getOriginZone() const { return originZone; } const QString &getOriginZone() const { return originZone; }
protected: protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
}; };
class DeckViewCardDragItem : public AbstractCardDragItem { class DeckViewCardDragItem : public AbstractCardDragItem {
private: private:
DeckViewCardContainer *currentZone; DeckViewCardContainer *currentZone;
void handleDrop(DeckViewCardContainer *target); void handleDrop(DeckViewCardContainer *target);
public: public:
DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0);
void updatePosition(const QPointF &cursorScenePos); void updatePosition(const QPointF &cursorScenePos);
protected: protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
}; };
class DeckViewCardContainer : public QGraphicsItem { class DeckViewCardContainer : public QGraphicsItem {
private: private:
static const int separatorY = 20; static const int separatorY = 20;
static const int paddingY = 10; static const int paddingY = 10;
QString name; QString name;
QList<DeckViewCard *> cards; QList<DeckViewCard *> cards;
QMultiMap<QString, DeckViewCard *> cardsByType; QMultiMap<QString, DeckViewCard *> cardsByType;
QList<QPair<int, int> > currentRowsAndCols; QList<QPair<int, int> > currentRowsAndCols;
qreal width, height; qreal width, height;
QPixmap bgPixmap; QPixmap bgPixmap;
int getCardTypeTextWidth() const; int getCardTypeTextWidth() const;
public: public:
enum { Type = typeDeckViewCardContainer }; enum { Type = typeDeckViewCardContainer };
int type() const { return Type; } int type() const { return Type; }
DeckViewCardContainer(const QString &_name); DeckViewCardContainer(const QString &_name);
QRectF boundingRect() const; QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void addCard(DeckViewCard *card); void addCard(DeckViewCard *card);
void removeCard(DeckViewCard *card); void removeCard(DeckViewCard *card);
const QList<DeckViewCard *> &getCards() const { return cards; } const QList<DeckViewCard *> &getCards() const { return cards; }
const QString &getName() const { return name; } const QString &getName() const { return name; }
void setWidth(qreal _width); void setWidth(qreal _width);
QList<QPair<int, int> > getRowsAndCols() const; QList<QPair<int, int> > getRowsAndCols() const;
QSizeF calculateBoundingRect(const QList<QPair<int, int> > &rowsAndCols) const; QSizeF calculateBoundingRect(const QList<QPair<int, int> > &rowsAndCols) const;
void rearrangeItems(const QList<QPair<int, int> > &rowsAndCols); void rearrangeItems(const QList<QPair<int, int> > &rowsAndCols);
}; };
class DeckViewScene : public QGraphicsScene { class DeckViewScene : public QGraphicsScene {
Q_OBJECT Q_OBJECT
signals: signals:
void newCardAdded(AbstractCardItem *card); void newCardAdded(AbstractCardItem *card);
void sideboardPlanChanged(); void sideboardPlanChanged();
private: private:
bool locked; bool locked;
DeckList *deck; DeckList *deck;
QMap<QString, DeckViewCardContainer *> cardContainers; QMap<QString, DeckViewCardContainer *> cardContainers;
qreal optimalAspectRatio; qreal optimalAspectRatio;
void clearContents(); void clearContents();
void rebuildTree(); void rebuildTree();
void applySideboardPlan(const QList<MoveCard_ToZone> &plan); void applySideboardPlan(const QList<MoveCard_ToZone> &plan);
public: public:
DeckViewScene(QObject *parent = 0); DeckViewScene(QObject *parent = 0);
~DeckViewScene(); ~DeckViewScene();
void setLocked(bool _locked) { locked = _locked; } void setLocked(bool _locked) { locked = _locked; }
bool getLocked() const { return locked; } bool getLocked() const { return locked; }
void setDeck(const DeckList &_deck); void setDeck(const DeckList &_deck);
void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; } void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; }
void rearrangeItems(); void rearrangeItems();
void updateContents(); void updateContents();
QList<MoveCard_ToZone> getSideboardPlan() const; QList<MoveCard_ToZone> getSideboardPlan() const;
void resetSideboardPlan(); void resetSideboardPlan();
}; };
class DeckView : public QGraphicsView { class DeckView : public QGraphicsView {
Q_OBJECT Q_OBJECT
private: private:
DeckViewScene *deckViewScene; DeckViewScene *deckViewScene;
protected: protected:
void resizeEvent(QResizeEvent *event); void resizeEvent(QResizeEvent *event);
public slots: public slots:
void updateSceneRect(const QRectF &rect); void updateSceneRect(const QRectF &rect);
signals: signals:
void newCardAdded(AbstractCardItem *card); void newCardAdded(AbstractCardItem *card);
void sideboardPlanChanged(); void sideboardPlanChanged();
public: public:
DeckView(QWidget *parent = 0); DeckView(QWidget *parent = 0);
void setDeck(const DeckList &_deck); void setDeck(const DeckList &_deck);
void setLocked(bool _locked) { deckViewScene->setLocked(_locked); } void setLocked(bool _locked) { deckViewScene->setLocked(_locked); }
QList<MoveCard_ToZone> getSideboardPlan() const { return deckViewScene->getSideboardPlan(); } QList<MoveCard_ToZone> getSideboardPlan() const { return deckViewScene->getSideboardPlan(); }
void resetSideboardPlan(); void resetSideboardPlan();
}; };
#endif #endif
...@@ -10,86 +10,86 @@ ...@@ -10,86 +10,86 @@
#include "main.h" #include "main.h"
DlgCardSearch::DlgCardSearch(QWidget *parent) DlgCardSearch::DlgCardSearch(QWidget *parent)
: QDialog(parent) : QDialog(parent)
{ {
QLabel *cardNameLabel = new QLabel(tr("Card name:")); QLabel *cardNameLabel = new QLabel(tr("Card name:"));
cardNameEdit = new QLineEdit; cardNameEdit = new QLineEdit;
QLabel *cardTextLabel = new QLabel(tr("Card text:")); QLabel *cardTextLabel = new QLabel(tr("Card text:"));
cardTextEdit = new QLineEdit; cardTextEdit = new QLineEdit;
QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):")); QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):"));
const QStringList &cardTypes = db->getAllMainCardTypes(); const QStringList &cardTypes = db->getAllMainCardTypes();
QVBoxLayout *cardTypesLayout = new QVBoxLayout; QVBoxLayout *cardTypesLayout = new QVBoxLayout;
for (int i = 0; i < cardTypes.size(); ++i) { for (int i = 0; i < cardTypes.size(); ++i) {
QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]); QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]);
cardTypeCheckBox->setChecked(true); cardTypeCheckBox->setChecked(true);
cardTypeCheckBoxes.append(cardTypeCheckBox); cardTypeCheckBoxes.append(cardTypeCheckBox);
cardTypesLayout->addWidget(cardTypeCheckBox); cardTypesLayout->addWidget(cardTypeCheckBox);
} }
QLabel *cardColorsLabel = new QLabel(tr("Color (OR):")); QLabel *cardColorsLabel = new QLabel(tr("Color (OR):"));
const QStringList &cardColors = db->getAllColors(); const QStringList &cardColors = db->getAllColors();
QHBoxLayout *cardColorsLayout = new QHBoxLayout; QHBoxLayout *cardColorsLayout = new QHBoxLayout;
for (int i = 0; i < cardColors.size(); ++i) { for (int i = 0; i < cardColors.size(); ++i) {
QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]); QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]);
cardColorCheckBox->setChecked(true); cardColorCheckBox->setChecked(true);
cardColorCheckBoxes.append(cardColorCheckBox); cardColorCheckBoxes.append(cardColorCheckBox);
cardColorsLayout->addWidget(cardColorCheckBox); cardColorsLayout->addWidget(cardColorCheckBox);
} }
QPushButton *okButton = new QPushButton(tr("O&K")); QPushButton *okButton = new QPushButton(tr("O&K"));
okButton->setDefault(true); okButton->setDefault(true);
okButton->setAutoDefault(true); okButton->setAutoDefault(true);
QPushButton *cancelButton = new QPushButton(tr("&Cancel")); QPushButton *cancelButton = new QPushButton(tr("&Cancel"));
connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
QHBoxLayout *buttonHBox = new QHBoxLayout; QHBoxLayout *buttonHBox = new QHBoxLayout;
buttonHBox->addStretch(); buttonHBox->addStretch();
buttonHBox->addWidget(okButton); buttonHBox->addWidget(okButton);
buttonHBox->addWidget(cancelButton); buttonHBox->addWidget(cancelButton);
QGridLayout *optionsLayout = new QGridLayout; QGridLayout *optionsLayout = new QGridLayout;
optionsLayout->addWidget(cardNameLabel, 0, 0); optionsLayout->addWidget(cardNameLabel, 0, 0);
optionsLayout->addWidget(cardNameEdit, 0, 1); optionsLayout->addWidget(cardNameEdit, 0, 1);
optionsLayout->addWidget(cardTextLabel, 1, 0); optionsLayout->addWidget(cardTextLabel, 1, 0);
optionsLayout->addWidget(cardTextEdit, 1, 1); optionsLayout->addWidget(cardTextEdit, 1, 1);
optionsLayout->addWidget(cardTypesLabel, 2, 0); optionsLayout->addWidget(cardTypesLabel, 2, 0);
optionsLayout->addLayout(cardTypesLayout, 2, 1); optionsLayout->addLayout(cardTypesLayout, 2, 1);
optionsLayout->addWidget(cardColorsLabel, 3, 0); optionsLayout->addWidget(cardColorsLabel, 3, 0);
optionsLayout->addLayout(cardColorsLayout, 3, 1); optionsLayout->addLayout(cardColorsLayout, 3, 1);
QVBoxLayout *mainLayout = new QVBoxLayout; QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(optionsLayout); mainLayout->addLayout(optionsLayout);
mainLayout->addLayout(buttonHBox); mainLayout->addLayout(buttonHBox);
setLayout(mainLayout); setLayout(mainLayout);
setWindowTitle(tr("Card search")); setWindowTitle(tr("Card search"));
} }
QString DlgCardSearch::getCardName() const QString DlgCardSearch::getCardName() const
{ {
return cardNameEdit->text(); return cardNameEdit->text();
} }
QString DlgCardSearch::getCardText() const QString DlgCardSearch::getCardText() const
{ {
return cardTextEdit->text(); return cardTextEdit->text();
} }
QSet<QString> DlgCardSearch::getCardTypes() const QSet<QString> DlgCardSearch::getCardTypes() const
{ {
QStringList result; QStringList result;
for (int i = 0; i < cardTypeCheckBoxes.size(); ++i) for (int i = 0; i < cardTypeCheckBoxes.size(); ++i)
if (cardTypeCheckBoxes[i]->isChecked()) if (cardTypeCheckBoxes[i]->isChecked())
result.append(cardTypeCheckBoxes[i]->text()); result.append(cardTypeCheckBoxes[i]->text());
return QSet<QString>::fromList(result); return QSet<QString>::fromList(result);
} }
QSet<QString> DlgCardSearch::getCardColors() const QSet<QString> DlgCardSearch::getCardColors() const
{ {
QStringList result; QStringList result;
for (int i = 0; i < cardColorCheckBoxes.size(); ++i) for (int i = 0; i < cardColorCheckBoxes.size(); ++i)
if (cardColorCheckBoxes[i]->isChecked()) if (cardColorCheckBoxes[i]->isChecked())
result.append(cardColorCheckBoxes[i]->text()); result.append(cardColorCheckBoxes[i]->text());
return QSet<QString>::fromList(result); return QSet<QString>::fromList(result);
} }
...@@ -9,16 +9,16 @@ class QLineEdit; ...@@ -9,16 +9,16 @@ class QLineEdit;
class QCheckBox; class QCheckBox;
class DlgCardSearch : public QDialog { class DlgCardSearch : public QDialog {
Q_OBJECT Q_OBJECT
private: private:
QLineEdit *cardNameEdit, *cardTextEdit; QLineEdit *cardNameEdit, *cardTextEdit;
QList<QCheckBox *> cardTypeCheckBoxes, cardColorCheckBoxes; QList<QCheckBox *> cardTypeCheckBoxes, cardColorCheckBoxes;
public: public:
DlgCardSearch(QWidget *parent = 0); DlgCardSearch(QWidget *parent = 0);
QString getCardName() const; QString getCardName() const;
QString getCardText() const; QString getCardText() const;
QSet<QString> getCardTypes() const; QSet<QString> getCardTypes() const;
QSet<QString> getCardColors() const; QSet<QString> getCardColors() const;
}; };
#endif #endif
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment