diff --git a/TODO.md b/TODO.md index c4285db3..0dc0d849 100644 --- a/TODO.md +++ b/TODO.md @@ -28,7 +28,6 @@ Note that "improve" and "write" always also means: "document and comment" * Rename the picture filenames to something more meaningful. * Create an index, lists of tables/figures/... - ## Storage * Find a better place for sets.xml than doc. @@ -41,24 +40,6 @@ Note that "improve" and "write" always also means: "document and comment" * Document everything!1!! * Coding guidelines -##Fix compile warnings -* (CMAKE_VERBOSE_MAKEFILE, compile with clang++), this could indicate missing program functionality: - -``` -cockatrice/src/abstractclient.cpp:72:12: warning: enumeration value 'SessionEvent_SessionEventType_SERVER_COMPLETE_LIST' not handled in switch [-Wswitch] - switch ((SessionEvent::SessionEventType) getPbExtension(event)) { -``` - -``` -cockatrice/Cockatrice.VanNostrand/cockatrice/src/player.cpp:1725:12: warning: 4 enumeration values not handled in switch: 'cmMoveToTopLibrary', 'cmMoveToBottomLibrary', 'cmMoveToGraveyard'... [-Wswitch] - switch (static_cast(a->data().toInt())) { -``` - -``` -cockatrice/src/cardzone.cpp:127:11: warning: enumeration values 'CaseTopCardsOfZone', 'CaseRevealZone', and 'CaseShuffleZone' not handled in switch [-Wswitch] - switch (gc) { -``` - ##Else * Update SFMT library (http://www.math.sci.hiroshima-u.ac.jp/~m-mat@math.sci.hiroshima-u.ac.jp/MT/SFMT/) in common/sfmt and adapt common/rng_sfmt.cpp diff --git a/cockatrice/src/abstractcarddragitem.cpp b/cockatrice/src/abstractcarddragitem.cpp index ac640046..14724db3 100644 --- a/cockatrice/src/abstractcarddragitem.cpp +++ b/cockatrice/src/abstractcarddragitem.cpp @@ -5,47 +5,47 @@ #include AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag) - : QGraphicsItem(), item(_item), hotSpot(_hotSpot) + : QGraphicsItem(), item(_item), hotSpot(_hotSpot) { - if (parentDrag) { - parentDrag->addChildDrag(this); - setZValue(2000000007 + hotSpot.x() * 1000000 + hotSpot.y() * 1000 + 1000); - } else { - if ((hotSpot.x() < 0) || (hotSpot.y() < 0)) { - qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); - hotSpot = QPointF(); - } else if ((hotSpot.x() > CARD_WIDTH) || (hotSpot.y() > CARD_HEIGHT)) { - qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); - hotSpot = QPointF(CARD_WIDTH, CARD_HEIGHT); - } - setCursor(Qt::ClosedHandCursor); - setZValue(2000000007); - } - if (item->getTapped()) - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + if (parentDrag) { + parentDrag->addChildDrag(this); + setZValue(2000000007 + hotSpot.x() * 1000000 + hotSpot.y() * 1000 + 1000); + } else { + if ((hotSpot.x() < 0) || (hotSpot.y() < 0)) { + qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); + hotSpot = QPointF(); + } else if ((hotSpot.x() > CARD_WIDTH) || (hotSpot.y() > CARD_HEIGHT)) { + qDebug() << "CardDragItem: coordinate overflow: x =" << hotSpot.x() << ", y =" << hotSpot.y(); + hotSpot = QPointF(CARD_WIDTH, CARD_HEIGHT); + } + setCursor(Qt::ClosedHandCursor); + setZValue(2000000007); + } + if (item->getTapped()) + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); - setCacheMode(DeviceCoordinateCache); + setCacheMode(DeviceCoordinateCache); } AbstractCardDragItem::~AbstractCardDragItem() { - qDebug("CardDragItem destructor"); - for (int i = 0; i < childDrags.size(); i++) - delete childDrags[i]; + qDebug("CardDragItem destructor"); + for (int i = 0; i < childDrags.size(); i++) + delete childDrags[i]; } void AbstractCardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - item->paint(painter, option, widget); + item->paint(painter, option, widget); } void AbstractCardDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - event->accept(); - updatePosition(event->scenePos()); + event->accept(); + updatePosition(event->scenePos()); } void AbstractCardDragItem::addChildDrag(AbstractCardDragItem *child) { - childDrags << child; + childDrags << child; } diff --git a/cockatrice/src/abstractcarddragitem.h b/cockatrice/src/abstractcarddragitem.h index 047c4f55..e574f6c2 100644 --- a/cockatrice/src/abstractcarddragitem.h +++ b/cockatrice/src/abstractcarddragitem.h @@ -8,24 +8,24 @@ class CardZone; class CardInfo; class AbstractCardDragItem : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - AbstractCardItem *item; - QPointF hotSpot; - QList childDrags; + AbstractCardItem *item; + QPointF hotSpot; + QList childDrags; public: - enum { Type = typeCardDrag }; - int type() const { return Type; } - AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); - ~AbstractCardDragItem(); - QRectF boundingRect() const { return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - AbstractCardItem *getItem() const { return item; } - QPointF getHotSpot() const { return hotSpot; } - void addChildDrag(AbstractCardDragItem *child); - virtual void updatePosition(const QPointF &cursorScenePos) = 0; + enum { Type = typeCardDrag }; + int type() const { return Type; } + AbstractCardDragItem(AbstractCardItem *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); + ~AbstractCardDragItem(); + QRectF boundingRect() const { return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + AbstractCardItem *getItem() const { return item; } + QPointF getHotSpot() const { return hotSpot; } + void addChildDrag(AbstractCardDragItem *child); + virtual void updatePosition(const QPointF &cursorScenePos) = 0; protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); }; #endif diff --git a/cockatrice/src/abstractcarditem.cpp b/cockatrice/src/abstractcarditem.cpp index 724a21fe..7b624572 100644 --- a/cockatrice/src/abstractcarditem.cpp +++ b/cockatrice/src/abstractcarditem.cpp @@ -12,245 +12,245 @@ #include AbstractCardItem::AbstractCardItem(const QString &_name, Player *_owner, int _id, QGraphicsItem *parent) - : ArrowTarget(_owner, parent), infoWidget(0), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), isHovered(false), realZValue(0) + : ArrowTarget(_owner, parent), infoWidget(0), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), isHovered(false), realZValue(0) { - setCursor(Qt::OpenHandCursor); - setFlag(ItemIsSelectable); - setCacheMode(DeviceCoordinateCache); - - connect(db, SIGNAL(cardListChanged()), this, SLOT(cardInfoUpdated())); - connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate())); - cardInfoUpdated(); + setCursor(Qt::OpenHandCursor); + setFlag(ItemIsSelectable); + setCacheMode(DeviceCoordinateCache); + + connect(db, SIGNAL(cardListChanged()), this, SLOT(cardInfoUpdated())); + connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate())); + cardInfoUpdated(); } AbstractCardItem::~AbstractCardItem() { - emit deleteCardInfoPopup(name); + emit deleteCardInfoPopup(name); } QRectF AbstractCardItem::boundingRect() const { - return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); + return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } void AbstractCardItem::pixmapUpdated() { - update(); - emit sigPixmapUpdated(); + update(); + emit sigPixmapUpdated(); } void AbstractCardItem::cardInfoUpdated() { - info = db->getCard(name); - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); + info = db->getCard(name); + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); } void AbstractCardItem::setRealZValue(qreal _zValue) { - realZValue = _zValue; - setZValue(_zValue); + realZValue = _zValue; + setZValue(_zValue); } QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const { - return QSizeF( - painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(), - painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length() - ); + return QSizeF( + painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(), + painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length() + ); } void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle) { - QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); - - painter->resetTransform(); - - QTransform pixmapTransform; - pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2); - pixmapTransform.rotate(angle); - pixmapTransform.translate(-translatedSize.width() / 2, -translatedSize.height() / 2); - painter->setTransform(pixmapTransform); + QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); + + painter->resetTransform(); + + QTransform pixmapTransform; + pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2); + pixmapTransform.rotate(angle); + pixmapTransform.translate(-translatedSize.width() / 2, -translatedSize.height() / 2); + painter->setTransform(pixmapTransform); - QFont f; - int fontSize = round(translatedSize.height() / 8); - if (fontSize < 9) - fontSize = 9; - if (fontSize > 10) - fontSize = 10; - f.setPixelSize(fontSize); + QFont f; + int fontSize = round(translatedSize.height() / 8); + if (fontSize < 9) + fontSize = 9; + if (fontSize > 10) + fontSize = 10; + f.setPixelSize(fontSize); - painter->setFont(f); + painter->setFont(f); } void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle) { - qreal scaleFactor = translatedSize.width() / boundingRect().width(); - - CardInfo *imageSource = facedown ? db->getCard() : info; - QPixmap *translatedPixmap = imageSource->getPixmap(translatedSize.toSize()); - painter->save(); - QColor bgColor = Qt::transparent; - if (translatedPixmap) { - painter->save(); - transformPainter(painter, translatedSize, angle); - painter->drawPixmap(QPointF(0, 0), *translatedPixmap); - painter->restore(); - } else { - QString colorStr; - if (!color.isEmpty()) - colorStr = color; - else if (info->getColors().size() > 1) - colorStr = "m"; - else if (!info->getColors().isEmpty()) - colorStr = info->getColors().first().toLower(); - - if (colorStr == "b") - bgColor = QColor(0, 0, 0); - else if (colorStr == "u") - bgColor = QColor(0, 140, 180); - else if (colorStr == "w") - bgColor = QColor(255, 250, 140); - else if (colorStr == "r") - bgColor = QColor(230, 0, 0); - else if (colorStr == "g") - bgColor = QColor(0, 160, 0); - else if (colorStr == "m") - bgColor = QColor(250, 190, 30); - else - bgColor = QColor(230, 230, 230); - } - painter->setBrush(bgColor); - QPen pen(Qt::black); - pen.setWidth(2); - painter->setPen(pen); - painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 2)); - - if (!translatedPixmap || settingsCache->getDisplayCardNames() || facedown) { - painter->save(); - transformPainter(painter, translatedSize, angle); - painter->setPen(Qt::white); - painter->setBackground(Qt::black); - painter->setBackgroundMode(Qt::OpaqueMode); - QString nameStr; - if (facedown) - nameStr = "# " + QString::number(id); - else - nameStr = name; - painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr); - painter->restore(); - } - - painter->restore(); + qreal scaleFactor = translatedSize.width() / boundingRect().width(); + + CardInfo *imageSource = facedown ? db->getCard() : info; + QPixmap *translatedPixmap = imageSource->getPixmap(translatedSize.toSize()); + painter->save(); + QColor bgColor = Qt::transparent; + if (translatedPixmap) { + painter->save(); + transformPainter(painter, translatedSize, angle); + painter->drawPixmap(QPointF(0, 0), *translatedPixmap); + painter->restore(); + } else { + QString colorStr; + if (!color.isEmpty()) + colorStr = color; + else if (info->getColors().size() > 1) + colorStr = "m"; + else if (!info->getColors().isEmpty()) + colorStr = info->getColors().first().toLower(); + + if (colorStr == "b") + bgColor = QColor(0, 0, 0); + else if (colorStr == "u") + bgColor = QColor(0, 140, 180); + else if (colorStr == "w") + bgColor = QColor(255, 250, 140); + else if (colorStr == "r") + bgColor = QColor(230, 0, 0); + else if (colorStr == "g") + bgColor = QColor(0, 160, 0); + else if (colorStr == "m") + bgColor = QColor(250, 190, 30); + else + bgColor = QColor(230, 230, 230); + } + painter->setBrush(bgColor); + QPen pen(Qt::black); + pen.setWidth(2); + painter->setPen(pen); + painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 2)); + + if (!translatedPixmap || settingsCache->getDisplayCardNames() || facedown) { + painter->save(); + transformPainter(painter, translatedSize, angle); + painter->setPen(Qt::white); + painter->setBackground(Qt::black); + painter->setBackgroundMode(Qt::OpaqueMode); + QString nameStr; + if (facedown) + nameStr = "# " + QString::number(id); + else + nameStr = name; + painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr); + painter->restore(); + } + + painter->restore(); } void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - painter->save(); + painter->save(); - QSizeF translatedSize = getTranslatedSize(painter); - paintPicture(painter, translatedSize, tapAngle); - - painter->save(); - painter->setRenderHint(QPainter::Antialiasing, false); - transformPainter(painter, translatedSize, tapAngle); - if (isSelected()) { - painter->setPen(Qt::red); - painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); - } else if (isHovered) { - painter->setPen(Qt::yellow); - painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); - } - painter->restore(); + QSizeF translatedSize = getTranslatedSize(painter); + paintPicture(painter, translatedSize, tapAngle); + + painter->save(); + painter->setRenderHint(QPainter::Antialiasing, false); + transformPainter(painter, translatedSize, tapAngle); + if (isSelected()) { + painter->setPen(Qt::red); + painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); + } else if (isHovered) { + painter->setPen(Qt::yellow); + painter->drawRect(QRectF(0.5, 0.5, translatedSize.width() - 1, translatedSize.height() - 1)); + } + painter->restore(); - painter->restore(); + painter->restore(); } void AbstractCardItem::setName(const QString &_name) { - if (name == _name) - return; - - emit deleteCardInfoPopup(name); - disconnect(info, 0, this, 0); - name = _name; - info = db->getCard(name); - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); - update(); + if (name == _name) + return; + + emit deleteCardInfoPopup(name); + disconnect(info, 0, this, 0); + name = _name; + info = db->getCard(name); + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated())); + update(); } void AbstractCardItem::setHovered(bool _hovered) { - if (isHovered == _hovered) - return; - - if (_hovered) - processHoverEvent(); - isHovered = _hovered; - setZValue(_hovered ? 2000000004 : realZValue); - update(); + if (isHovered == _hovered) + return; + + if (_hovered) + processHoverEvent(); + isHovered = _hovered; + setZValue(_hovered ? 2000000004 : realZValue); + update(); } void AbstractCardItem::setColor(const QString &_color) { - color = _color; - update(); + color = _color; + update(); } void AbstractCardItem::setTapped(bool _tapped, bool canAnimate) { - if (tapped == _tapped) - return; - - tapped = _tapped; - if (settingsCache->getTapAnimation() && canAnimate) - static_cast(scene())->registerAnimationItem(this); - else { - tapAngle = tapped ? 90 : 0; - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); - update(); - } + if (tapped == _tapped) + return; + + tapped = _tapped; + if (settingsCache->getTapAnimation() && canAnimate) + static_cast(scene())->registerAnimationItem(this); + else { + tapAngle = tapped ? 90 : 0; + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + update(); + } } void AbstractCardItem::setFaceDown(bool _facedown) { - facedown = _facedown; - update(); - emit updateCardMenu(this); + facedown = _facedown; + update(); + emit updateCardMenu(this); } void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (!isSelected()) { - scene()->clearSelection(); - setSelected(true); - } - if (event->button() == Qt::LeftButton) - setCursor(Qt::ClosedHandCursor); - else if (event->button() == Qt::MidButton) - emit showCardInfoPopup(event->screenPos(), name); - event->accept(); + if (!isSelected()) { + scene()->clearSelection(); + setSelected(true); + } + if (event->button() == Qt::LeftButton) + setCursor(Qt::ClosedHandCursor); + else if (event->button() == Qt::MidButton) + emit showCardInfoPopup(event->screenPos(), name); + event->accept(); } void AbstractCardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::MidButton) - emit deleteCardInfoPopup(name); - - // This function ensures the parent function doesn't mess around with our selection. - event->accept(); + if (event->button() == Qt::MidButton) + emit deleteCardInfoPopup(name); + + // This function ensures the parent function doesn't mess around with our selection. + event->accept(); } void AbstractCardItem::processHoverEvent() { - emit hovered(this); + emit hovered(this); } QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { - if (change == ItemSelectedHasChanged) { - update(); - return value; - } else - return QGraphicsItem::itemChange(change, value); + if (change == ItemSelectedHasChanged) { + update(); + return value; + } else + return QGraphicsItem::itemChange(change, value); } diff --git a/cockatrice/src/abstractcarditem.h b/cockatrice/src/abstractcarditem.h index 9a11fad1..7f68ddcd 100644 --- a/cockatrice/src/abstractcarditem.h +++ b/cockatrice/src/abstractcarditem.h @@ -12,59 +12,59 @@ const int CARD_WIDTH = 72; const int CARD_HEIGHT = 102; class AbstractCardItem : public ArrowTarget { - Q_OBJECT + Q_OBJECT protected: - CardInfo *info; - CardInfoWidget *infoWidget; - int id; - QString name; - bool tapped; - bool facedown; - int tapAngle; - QString color; + CardInfo *info; + CardInfoWidget *infoWidget; + int id; + QString name; + bool tapped; + bool facedown; + int tapAngle; + QString color; private: - bool isHovered; - qreal realZValue; + bool isHovered; + qreal realZValue; private slots: - void pixmapUpdated(); - void cardInfoUpdated(); - void callUpdate() { update(); } + void pixmapUpdated(); + void cardInfoUpdated(); + void callUpdate() { update(); } signals: - void hovered(AbstractCardItem *card); - void showCardInfoPopup(QPoint pos, QString cardName); - void deleteCardInfoPopup(QString cardName); - void updateCardMenu(AbstractCardItem *card); - void sigPixmapUpdated(); + void hovered(AbstractCardItem *card); + void showCardInfoPopup(QPoint pos, QString cardName); + void deleteCardInfoPopup(QString cardName); + void updateCardMenu(AbstractCardItem *card); + void sigPixmapUpdated(); public: - enum { Type = typeCard }; - int type() const { return Type; } - AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0); - ~AbstractCardItem(); - QRectF boundingRect() const; - QSizeF getTranslatedSize(QPainter *painter) const; - void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - CardInfo *getInfo() const { return info; } - int getId() const { return id; } - void setId(int _id) { id = _id; } - QString getName() const { return name; } - void setName(const QString &_name = QString()); - qreal getRealZValue() const { return realZValue; } - void setRealZValue(qreal _zValue); - void setHovered(bool _hovered); - QString getColor() const { return color; } - void setColor(const QString &_color); - bool getTapped() const { return tapped; } - void setTapped(bool _tapped, bool canAnimate = false); - bool getFaceDown() const { return facedown; } - void setFaceDown(bool _facedown); - void processHoverEvent(); - void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); } + enum { Type = typeCard }; + int type() const { return Type; } + AbstractCardItem(const QString &_name = QString(), Player *_owner = 0, int _id = -1, QGraphicsItem *parent = 0); + ~AbstractCardItem(); + QRectF boundingRect() const; + QSizeF getTranslatedSize(QPainter *painter) const; + void paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + CardInfo *getInfo() const { return info; } + int getId() const { return id; } + void setId(int _id) { id = _id; } + QString getName() const { return name; } + void setName(const QString &_name = QString()); + qreal getRealZValue() const { return realZValue; } + void setRealZValue(qreal _zValue); + void setHovered(bool _hovered); + QString getColor() const { return color; } + void setColor(const QString &_color); + bool getTapped() const { return tapped; } + void setTapped(bool _tapped, bool canAnimate = false); + bool getFaceDown() const { return facedown; } + void setFaceDown(bool _facedown); + void processHoverEvent(); + void deleteCardInfoPopup() { emit deleteCardInfoPopup(name); } protected: - void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); + void transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); }; #endif diff --git a/cockatrice/src/abstractclient.cpp b/cockatrice/src/abstractclient.cpp index de823716..f2e8915b 100644 --- a/cockatrice/src/abstractclient.cpp +++ b/cockatrice/src/abstractclient.cpp @@ -20,31 +20,31 @@ #include "client_metatypes.h" AbstractClient::AbstractClient(QObject *parent) - : QObject(parent), nextCmdId(0), status(StatusDisconnected) + : QObject(parent), nextCmdId(0), status(StatusDisconnected) { - qRegisterMetaType("QVariant"); - qRegisterMetaType("CommandContainer"); - qRegisterMetaType("Response"); - qRegisterMetaType("Response::ResponseCode"); - qRegisterMetaType("ClientStatus"); - qRegisterMetaType("RoomEvent"); - qRegisterMetaType("GameEventContainer"); - qRegisterMetaType("Event_ServerIdentification"); - qRegisterMetaType("Event_ConnectionClosed"); - qRegisterMetaType("Event_ServerShutdown"); - qRegisterMetaType("Event_AddToList"); - qRegisterMetaType("Event_RemoveFromList"); - qRegisterMetaType("Event_UserJoined"); - qRegisterMetaType("Event_UserLeft"); - qRegisterMetaType("Event_ServerMessage"); - qRegisterMetaType("Event_ListRooms"); - qRegisterMetaType("Event_GameJoined"); - qRegisterMetaType("Event_UserMessage"); - qRegisterMetaType("ServerInfo_User"); - qRegisterMetaType >("QList"); - qRegisterMetaType("Event_ReplayAdded"); - - connect(this, SIGNAL(sigQueuePendingCommand(PendingCommand *)), this, SLOT(queuePendingCommand(PendingCommand *))); + qRegisterMetaType("QVariant"); + qRegisterMetaType("CommandContainer"); + qRegisterMetaType("Response"); + qRegisterMetaType("Response::ResponseCode"); + qRegisterMetaType("ClientStatus"); + qRegisterMetaType("RoomEvent"); + qRegisterMetaType("GameEventContainer"); + qRegisterMetaType("Event_ServerIdentification"); + qRegisterMetaType("Event_ConnectionClosed"); + qRegisterMetaType("Event_ServerShutdown"); + qRegisterMetaType("Event_AddToList"); + qRegisterMetaType("Event_RemoveFromList"); + qRegisterMetaType("Event_UserJoined"); + qRegisterMetaType("Event_UserLeft"); + qRegisterMetaType("Event_ServerMessage"); + qRegisterMetaType("Event_ListRooms"); + qRegisterMetaType("Event_GameJoined"); + qRegisterMetaType("Event_UserMessage"); + qRegisterMetaType("ServerInfo_User"); + qRegisterMetaType >("QList"); + qRegisterMetaType("Event_ReplayAdded"); + + connect(this, SIGNAL(sigQueuePendingCommand(PendingCommand *)), this, SLOT(queuePendingCommand(PendingCommand *))); } AbstractClient::~AbstractClient() @@ -53,109 +53,110 @@ AbstractClient::~AbstractClient() void AbstractClient::processProtocolItem(const ServerMessage &item) { - switch (item.message_type()) { - case ServerMessage::RESPONSE: { - const Response &response = item.response(); - const int cmdId = response.cmd_id(); - - PendingCommand *pend = pendingCommands.value(cmdId, 0); - if (!pend) - return; - pendingCommands.remove(cmdId); - - pend->processResponse(response); - pend->deleteLater(); - break; - } - case ServerMessage::SESSION_EVENT: { - const SessionEvent &event = item.session_event(); - switch ((SessionEvent::SessionEventType) getPbExtension(event)) { - case SessionEvent::SERVER_IDENTIFICATION: emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext)); break; - case SessionEvent::SERVER_MESSAGE: emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext)); break; - case SessionEvent::SERVER_SHUTDOWN: emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext)); break; - case SessionEvent::CONNECTION_CLOSED: emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext)); break; - case SessionEvent::USER_MESSAGE: emit userMessageEventReceived(event.GetExtension(Event_UserMessage::ext)); break; - case SessionEvent::LIST_ROOMS: emit listRoomsEventReceived(event.GetExtension(Event_ListRooms::ext)); break; - case SessionEvent::ADD_TO_LIST: emit addToListEventReceived(event.GetExtension(Event_AddToList::ext)); break; - case SessionEvent::REMOVE_FROM_LIST: emit removeFromListEventReceived(event.GetExtension(Event_RemoveFromList::ext)); break; - case SessionEvent::USER_JOINED: emit userJoinedEventReceived(event.GetExtension(Event_UserJoined::ext)); break; - case SessionEvent::USER_LEFT: emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext)); break; - case SessionEvent::GAME_JOINED: emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext)); break; - case SessionEvent::REPLAY_ADDED: emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext)); break; - } - break; - } - case ServerMessage::GAME_EVENT_CONTAINER: { - emit gameEventContainerReceived(item.game_event_container()); - break; - } - case ServerMessage::ROOM_EVENT: { - emit roomEventReceived(item.room_event()); - break; - } - } + switch (item.message_type()) { + case ServerMessage::RESPONSE: { + const Response &response = item.response(); + const int cmdId = response.cmd_id(); + + PendingCommand *pend = pendingCommands.value(cmdId, 0); + if (!pend) + return; + pendingCommands.remove(cmdId); + + pend->processResponse(response); + pend->deleteLater(); + break; + } + case ServerMessage::SESSION_EVENT: { + const SessionEvent &event = item.session_event(); + switch ((SessionEvent::SessionEventType) getPbExtension(event)) { + case SessionEvent::SERVER_IDENTIFICATION: emit serverIdentificationEventReceived(event.GetExtension(Event_ServerIdentification::ext)); break; + case SessionEvent::SERVER_MESSAGE: emit serverMessageEventReceived(event.GetExtension(Event_ServerMessage::ext)); break; + case SessionEvent::SERVER_SHUTDOWN: emit serverShutdownEventReceived(event.GetExtension(Event_ServerShutdown::ext)); break; + case SessionEvent::CONNECTION_CLOSED: emit connectionClosedEventReceived(event.GetExtension(Event_ConnectionClosed::ext)); break; + case SessionEvent::USER_MESSAGE: emit userMessageEventReceived(event.GetExtension(Event_UserMessage::ext)); break; + case SessionEvent::LIST_ROOMS: emit listRoomsEventReceived(event.GetExtension(Event_ListRooms::ext)); break; + case SessionEvent::ADD_TO_LIST: emit addToListEventReceived(event.GetExtension(Event_AddToList::ext)); break; + case SessionEvent::REMOVE_FROM_LIST: emit removeFromListEventReceived(event.GetExtension(Event_RemoveFromList::ext)); break; + case SessionEvent::USER_JOINED: emit userJoinedEventReceived(event.GetExtension(Event_UserJoined::ext)); break; + case SessionEvent::USER_LEFT: emit userLeftEventReceived(event.GetExtension(Event_UserLeft::ext)); break; + case SessionEvent::GAME_JOINED: emit gameJoinedEventReceived(event.GetExtension(Event_GameJoined::ext)); break; + case SessionEvent::REPLAY_ADDED: emit replayAddedEventReceived(event.GetExtension(Event_ReplayAdded::ext)); break; + default: break; + } + break; + } + case ServerMessage::GAME_EVENT_CONTAINER: { + emit gameEventContainerReceived(item.game_event_container()); + break; + } + case ServerMessage::ROOM_EVENT: { + emit roomEventReceived(item.room_event()); + break; + } + } } void AbstractClient::setStatus(const ClientStatus _status) { - QMutexLocker locker(&clientMutex); - if (_status != status) { - status = _status; - emit statusChanged(_status); - } + QMutexLocker locker(&clientMutex); + if (_status != status) { + status = _status; + emit statusChanged(_status); + } } void AbstractClient::sendCommand(const CommandContainer &cont) { - sendCommand(new PendingCommand(cont)); + sendCommand(new PendingCommand(cont)); } void AbstractClient::sendCommand(PendingCommand *pend) { - pend->moveToThread(thread()); - emit sigQueuePendingCommand(pend); + pend->moveToThread(thread()); + emit sigQueuePendingCommand(pend); } void AbstractClient::queuePendingCommand(PendingCommand *pend) { - // This function is always called from the client thread via signal/slot. - const int cmdId = getNewCmdId(); - pend->getCommandContainer().set_cmd_id(cmdId); - - pendingCommands.insert(cmdId, pend); - - sendCommandContainer(pend->getCommandContainer()); + // This function is always called from the client thread via signal/slot. + const int cmdId = getNewCmdId(); + pend->getCommandContainer().set_cmd_id(cmdId); + + pendingCommands.insert(cmdId, pend); + + sendCommandContainer(pend->getCommandContainer()); } PendingCommand *AbstractClient::prepareSessionCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - SessionCommand *c = cont.add_session_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + SessionCommand *c = cont.add_session_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *AbstractClient::prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId) { - CommandContainer cont; - RoomCommand *c = cont.add_room_command(); - cont.set_room_id(roomId); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + RoomCommand *c = cont.add_room_command(); + cont.set_room_id(roomId); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *AbstractClient::prepareModeratorCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - ModeratorCommand *c = cont.add_moderator_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + ModeratorCommand *c = cont.add_moderator_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *AbstractClient::prepareAdminCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - AdminCommand *c = cont.add_admin_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + AdminCommand *c = cont.add_admin_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } diff --git a/cockatrice/src/abstractclient.h b/cockatrice/src/abstractclient.h index 507c3fdd..130c85b5 100644 --- a/cockatrice/src/abstractclient.h +++ b/cockatrice/src/abstractclient.h @@ -26,67 +26,67 @@ class Event_ServerShutdown; class Event_ReplayAdded; enum ClientStatus { - StatusDisconnected, - StatusDisconnecting, - StatusConnecting, - StatusAwaitingWelcome, - StatusLoggingIn, - StatusLoggedIn, + StatusDisconnected, + StatusDisconnecting, + StatusConnecting, + StatusAwaitingWelcome, + StatusLoggingIn, + StatusLoggedIn, }; class AbstractClient : public QObject { - Q_OBJECT + Q_OBJECT signals: - void statusChanged(ClientStatus _status); - - // Room events - void roomEventReceived(const RoomEvent &event); - // Game events - void gameEventContainerReceived(const GameEventContainer &event); - // Session events - void serverIdentificationEventReceived(const Event_ServerIdentification &event); - void connectionClosedEventReceived(const Event_ConnectionClosed &event); - void serverShutdownEventReceived(const Event_ServerShutdown &event); - void addToListEventReceived(const Event_AddToList &event); - void removeFromListEventReceived(const Event_RemoveFromList &event); - void userJoinedEventReceived(const Event_UserJoined &event); - void userLeftEventReceived(const Event_UserLeft &event); - void serverMessageEventReceived(const Event_ServerMessage &event); - void listRoomsEventReceived(const Event_ListRooms &event); - void gameJoinedEventReceived(const Event_GameJoined &event); - void userMessageEventReceived(const Event_UserMessage &event); - void userInfoChanged(const ServerInfo_User &userInfo); - void buddyListReceived(const QList &buddyList); - void ignoreListReceived(const QList &ignoreList); - void replayAddedEventReceived(const Event_ReplayAdded &event); - - void sigQueuePendingCommand(PendingCommand *pend); + void statusChanged(ClientStatus _status); + + // Room events + void roomEventReceived(const RoomEvent &event); + // Game events + void gameEventContainerReceived(const GameEventContainer &event); + // Session events + void serverIdentificationEventReceived(const Event_ServerIdentification &event); + void connectionClosedEventReceived(const Event_ConnectionClosed &event); + void serverShutdownEventReceived(const Event_ServerShutdown &event); + void addToListEventReceived(const Event_AddToList &event); + void removeFromListEventReceived(const Event_RemoveFromList &event); + void userJoinedEventReceived(const Event_UserJoined &event); + void userLeftEventReceived(const Event_UserLeft &event); + void serverMessageEventReceived(const Event_ServerMessage &event); + void listRoomsEventReceived(const Event_ListRooms &event); + void gameJoinedEventReceived(const Event_GameJoined &event); + void userMessageEventReceived(const Event_UserMessage &event); + void userInfoChanged(const ServerInfo_User &userInfo); + void buddyListReceived(const QList &buddyList); + void ignoreListReceived(const QList &ignoreList); + void replayAddedEventReceived(const Event_ReplayAdded &event); + + void sigQueuePendingCommand(PendingCommand *pend); private: - int nextCmdId; - mutable QMutex clientMutex; - ClientStatus status; + int nextCmdId; + mutable QMutex clientMutex; + ClientStatus status; private slots: - void queuePendingCommand(PendingCommand *pend); + void queuePendingCommand(PendingCommand *pend); protected slots: - void processProtocolItem(const ServerMessage &item); + void processProtocolItem(const ServerMessage &item); protected: - QMap pendingCommands; - QString userName, password; - void setStatus(ClientStatus _status); - int getNewCmdId() { return nextCmdId++; } - virtual void sendCommandContainer(const CommandContainer &cont) = 0; + QMap pendingCommands; + QString userName, password; + void setStatus(ClientStatus _status); + int getNewCmdId() { return nextCmdId++; } + virtual void sendCommandContainer(const CommandContainer &cont) = 0; public: - AbstractClient(QObject *parent = 0); - ~AbstractClient(); - - ClientStatus getStatus() const { QMutexLocker locker(&clientMutex); return status; } - void sendCommand(const CommandContainer &cont); - void sendCommand(PendingCommand *pend); - - static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd); - static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId); - static PendingCommand *prepareModeratorCommand(const ::google::protobuf::Message &cmd); - static PendingCommand *prepareAdminCommand(const ::google::protobuf::Message &cmd); + AbstractClient(QObject *parent = 0); + ~AbstractClient(); + + ClientStatus getStatus() const { QMutexLocker locker(&clientMutex); return status; } + void sendCommand(const CommandContainer &cont); + void sendCommand(PendingCommand *pend); + + static PendingCommand *prepareSessionCommand(const ::google::protobuf::Message &cmd); + static PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd, int roomId); + static PendingCommand *prepareModeratorCommand(const ::google::protobuf::Message &cmd); + static PendingCommand *prepareAdminCommand(const ::google::protobuf::Message &cmd); }; #endif diff --git a/cockatrice/src/abstractcounter.cpp b/cockatrice/src/abstractcounter.cpp index 42e506fd..73fc9466 100644 --- a/cockatrice/src/abstractcounter.cpp +++ b/cockatrice/src/abstractcounter.cpp @@ -9,137 +9,137 @@ #include "pb/command_set_counter.pb.h" AbstractCounter::AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent) - : QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea) + : QGraphicsItem(parent), player(_player), id(_id), name(_name), value(_value), hovered(false), aDec(0), aInc(0), dialogSemaphore(false), deleteAfterDialog(false), shownInCounterArea(_shownInCounterArea) { - setAcceptsHoverEvents(true); - - if (player->getLocal()) { - menu = new QMenu(name); - aSet = new QAction(this); - connect(aSet, SIGNAL(triggered()), this, SLOT(setCounter())); - menu->addAction(aSet); - menu->addSeparator(); - for (int i = -10; i <= 10; ++i) - if (i == 0) - menu->addSeparator(); - else { - QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this); - if (i == -1) - aDec = aIncrement; - else if (i == 1) - aInc = aIncrement; - aIncrement->setData(i); - connect(aIncrement, SIGNAL(triggered()), this, SLOT(incrementCounter())); - menu->addAction(aIncrement); - } - } else - menu = 0; - - retranslateUi(); + setAcceptsHoverEvents(true); + + if (player->getLocal()) { + menu = new QMenu(name); + aSet = new QAction(this); + connect(aSet, SIGNAL(triggered()), this, SLOT(setCounter())); + menu->addAction(aSet); + menu->addSeparator(); + for (int i = -10; i <= 10; ++i) + if (i == 0) + menu->addSeparator(); + else { + QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this); + if (i == -1) + aDec = aIncrement; + else if (i == 1) + aInc = aIncrement; + aIncrement->setData(i); + connect(aIncrement, SIGNAL(triggered()), this, SLOT(incrementCounter())); + menu->addAction(aIncrement); + } + } else + menu = 0; + + retranslateUi(); } AbstractCounter::~AbstractCounter() { - delete menu; + delete menu; } void AbstractCounter::delCounter() { - if (dialogSemaphore) - deleteAfterDialog = true; - else - deleteLater(); + if (dialogSemaphore) + deleteAfterDialog = true; + else + deleteLater(); } void AbstractCounter::retranslateUi() { - if (menu) { - aSet->setText(tr("&Set counter...")); - } + if (menu) { + aSet->setText(tr("&Set counter...")); + } } void AbstractCounter::setShortcutsActive() { - if (name == "life") { - aSet->setShortcut(tr("Ctrl+L")); - aDec->setShortcut(tr("F11")); - aInc->setShortcut(tr("F12")); - } + if (name == "life") { + aSet->setShortcut(tr("Ctrl+L")); + aDec->setShortcut(tr("F11")); + aInc->setShortcut(tr("F12")); + } } void AbstractCounter::setShortcutsInactive() { - if (name == "life") { - aSet->setShortcut(QKeySequence()); - aDec->setShortcut(QKeySequence()); - aInc->setShortcut(QKeySequence()); - } + if (name == "life") { + aSet->setShortcut(QKeySequence()); + aDec->setShortcut(QKeySequence()); + aInc->setShortcut(QKeySequence()); + } } void AbstractCounter::setValue(int _value) { - value = _value; - update(); + value = _value; + update(); } void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - Command_IncCounter cmd; - cmd.set_counter_id(id); - cmd.set_delta(1); - player->sendGameCommand(cmd); - event->accept(); - } else if (event->button() == Qt::RightButton) { - Command_IncCounter cmd; - cmd.set_counter_id(id); - cmd.set_delta(-1); - player->sendGameCommand(cmd); - event->accept(); - } else if (event->button() == Qt::MidButton) { - if (menu) - menu->exec(event->screenPos()); - event->accept(); - } else - event->ignore(); + if (event->button() == Qt::LeftButton) { + Command_IncCounter cmd; + cmd.set_counter_id(id); + cmd.set_delta(1); + player->sendGameCommand(cmd); + event->accept(); + } else if (event->button() == Qt::RightButton) { + Command_IncCounter cmd; + cmd.set_counter_id(id); + cmd.set_delta(-1); + player->sendGameCommand(cmd); + event->accept(); + } else if (event->button() == Qt::MidButton) { + if (menu) + menu->exec(event->screenPos()); + event->accept(); + } else + event->ignore(); } void AbstractCounter::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/) { - hovered = true; - update(); + hovered = true; + update(); } void AbstractCounter::hoverLeaveEvent(QGraphicsSceneHoverEvent * /*event*/) { - hovered = false; - update(); + hovered = false; + update(); } void AbstractCounter::incrementCounter() { - const int delta = static_cast(sender())->data().toInt(); - Command_IncCounter cmd; - cmd.set_counter_id(id); - cmd.set_delta(delta); - player->sendGameCommand(cmd); + const int delta = static_cast(sender())->data().toInt(); + Command_IncCounter cmd; + cmd.set_counter_id(id); + cmd.set_delta(delta); + player->sendGameCommand(cmd); } void AbstractCounter::setCounter() { - bool ok; - dialogSemaphore = true; - int newValue = QInputDialog::getInteger(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok); - if (deleteAfterDialog) { - deleteLater(); - return; - } - dialogSemaphore = false; - if (!ok) - return; - - Command_SetCounter cmd; - cmd.set_counter_id(id); - cmd.set_value(newValue); - player->sendGameCommand(cmd); + bool ok; + dialogSemaphore = true; + int newValue = QInputDialog::getInteger(0, tr("Set counter"), tr("New value for counter '%1':").arg(name), value, -2000000000, 2000000000, 1, &ok); + if (deleteAfterDialog) { + deleteLater(); + return; + } + dialogSemaphore = false; + if (!ok) + return; + + Command_SetCounter cmd; + cmd.set_counter_id(id); + cmd.set_value(newValue); + player->sendGameCommand(cmd); } diff --git a/cockatrice/src/abstractcounter.h b/cockatrice/src/abstractcounter.h index 6a4a4188..713c11c5 100644 --- a/cockatrice/src/abstractcounter.h +++ b/cockatrice/src/abstractcounter.h @@ -8,41 +8,41 @@ class QMenu; class QAction; class AbstractCounter : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - Player *player; - int id; - QString name; - int value; - bool hovered; - - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); + Player *player; + int id; + QString name; + int value; + bool hovered; + + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); private: - QAction *aSet, *aDec, *aInc; - QMenu *menu; - bool dialogSemaphore, deleteAfterDialog; - bool shownInCounterArea; + QAction *aSet, *aDec, *aInc; + QMenu *menu; + bool dialogSemaphore, deleteAfterDialog; + bool shownInCounterArea; private slots: - void incrementCounter(); - void setCounter(); + void incrementCounter(); + void setCounter(); public: - AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent = 0); - ~AbstractCounter(); - - QMenu *getMenu() const { return menu; } - void retranslateUi(); - - int getId() const { return id; } - QString getName() const { return name; } - bool getShownInCounterArea() const { return shownInCounterArea; } - int getValue() const { return value; } - void setValue(int _value); - void delCounter(); - - void setShortcutsActive(); - void setShortcutsInactive(); + AbstractCounter(Player *_player, int _id, const QString &_name, bool _shownInCounterArea, int _value, QGraphicsItem *parent = 0); + ~AbstractCounter(); + + QMenu *getMenu() const { return menu; } + void retranslateUi(); + + int getId() const { return id; } + QString getName() const { return name; } + bool getShownInCounterArea() const { return shownInCounterArea; } + int getValue() const { return value; } + void setValue(int _value); + void delCounter(); + + void setShortcutsActive(); + void setShortcutsInactive(); }; #endif diff --git a/cockatrice/src/abstractgraphicsitem.cpp b/cockatrice/src/abstractgraphicsitem.cpp index 47b21bbc..c0cc330c 100644 --- a/cockatrice/src/abstractgraphicsitem.cpp +++ b/cockatrice/src/abstractgraphicsitem.cpp @@ -3,48 +3,48 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int fontSize, const QColor &color, int position, int count, QPainter *painter) { - painter->save(); + painter->save(); - QString numStr = QString::number(number); - QFont font("Serif"); - font.setPixelSize(fontSize); - font.setWeight(QFont::Bold); - - QFontMetrics fm(font); - double w = fm.width(numStr) * 1.3; - double h = fm.height() * 1.3; - if (w < h) - w = h; + QString numStr = QString::number(number); + QFont font("Serif"); + font.setPixelSize(fontSize); + font.setWeight(QFont::Bold); + + QFontMetrics fm(font); + double w = fm.width(numStr) * 1.3; + double h = fm.height() * 1.3; + if (w < h) + w = h; - painter->setPen(QColor(255, 255, 255, 0)); - QRadialGradient grad(QPointF(0.5, 0.5), 0.5); - grad.setCoordinateMode(QGradient::ObjectBoundingMode); - QColor color1(color), color2(color); - color1.setAlpha(255); - color2.setAlpha(0); - grad.setColorAt(0, color1); - grad.setColorAt(0.8, color1); - grad.setColorAt(1, color2); - painter->setBrush(QBrush(grad)); - - QRectF textRect; - if (position == -1) - textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); - else { - qreal xOffset = 10; - qreal yOffset = 20; - qreal spacing = 2; - if (position < 2) - textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset, w, h); - else - textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset + (spacing + h) * (position / 2), w, h); - } - - painter->drawEllipse(textRect); + painter->setPen(QColor(255, 255, 255, 0)); + QRadialGradient grad(QPointF(0.5, 0.5), 0.5); + grad.setCoordinateMode(QGradient::ObjectBoundingMode); + QColor color1(color), color2(color); + color1.setAlpha(255); + color2.setAlpha(0); + grad.setColorAt(0, color1); + grad.setColorAt(0.8, color1); + grad.setColorAt(1, color2); + painter->setBrush(QBrush(grad)); + + QRectF textRect; + if (position == -1) + textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); + else { + qreal xOffset = 10; + qreal yOffset = 20; + qreal spacing = 2; + if (position < 2) + textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset, w, h); + else + textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), yOffset + (spacing + h) * (position / 2), w, h); + } + + painter->drawEllipse(textRect); - painter->setPen(Qt::black); - painter->setFont(font); - painter->drawText(textRect, Qt::AlignCenter, numStr); + painter->setPen(Qt::black); + painter->setFont(font); + painter->drawText(textRect, Qt::AlignCenter, numStr); - painter->restore(); + painter->restore(); } diff --git a/cockatrice/src/abstractgraphicsitem.h b/cockatrice/src/abstractgraphicsitem.h index 2bb094d3..83cbf0db 100644 --- a/cockatrice/src/abstractgraphicsitem.h +++ b/cockatrice/src/abstractgraphicsitem.h @@ -4,20 +4,20 @@ #include enum GraphicsItemType { - typeCard = QGraphicsItem::UserType + 1, - typeCardDrag = QGraphicsItem::UserType + 2, - typeZone = QGraphicsItem::UserType + 3, - typePlayerTarget = QGraphicsItem::UserType + 4, - typeDeckViewCardContainer = QGraphicsItem::UserType + 5, - typeOther = QGraphicsItem::UserType + 6 + typeCard = QGraphicsItem::UserType + 1, + typeCardDrag = QGraphicsItem::UserType + 2, + typeZone = QGraphicsItem::UserType + 3, + typePlayerTarget = QGraphicsItem::UserType + 4, + typeDeckViewCardContainer = QGraphicsItem::UserType + 5, + typeOther = QGraphicsItem::UserType + 6 }; class AbstractGraphicsItem : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter); + void paintNumberEllipse(int number, int radius, const QColor &color, int position, int count, QPainter *painter); public: - AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent) { } + AbstractGraphicsItem(QGraphicsItem *parent = 0) : QObject(), QGraphicsItem(parent) { } }; #endif diff --git a/cockatrice/src/arrowitem.cpp b/cockatrice/src/arrowitem.cpp index 037645d5..a27b451a 100644 --- a/cockatrice/src/arrowitem.cpp +++ b/cockatrice/src/arrowitem.cpp @@ -17,127 +17,127 @@ ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &_color) : QGraphicsItem(), player(_player), id(_id), startItem(_startItem), targetItem(_targetItem), color(_color), fullColor(true) { - qDebug() << "ArrowItem constructor: startItem=" << static_cast(startItem); - setZValue(2000000005); - - if (startItem) - startItem->addArrowFrom(this); - if (targetItem) - targetItem->addArrowTo(this); - - if (startItem && targetItem) - updatePath(); + qDebug() << "ArrowItem constructor: startItem=" << static_cast(startItem); + setZValue(2000000005); + + if (startItem) + startItem->addArrowFrom(this); + if (targetItem) + targetItem->addArrowTo(this); + + if (startItem && targetItem) + updatePath(); } ArrowItem::~ArrowItem() { - qDebug() << "ArrowItem destructor"; + qDebug() << "ArrowItem destructor"; } void ArrowItem::delArrow() { - if (startItem) { - startItem->removeArrowFrom(this); - startItem = 0; - } - - if (targetItem) { - targetItem->setBeingPointedAt(false); - targetItem->removeArrowTo(this); - targetItem = 0; - } - - player->removeArrow(this); - deleteLater(); + if (startItem) { + startItem->removeArrowFrom(this); + startItem = 0; + } + + if (targetItem) { + targetItem->setBeingPointedAt(false); + targetItem->removeArrowTo(this); + targetItem = 0; + } + + player->removeArrow(this); + deleteLater(); } void ArrowItem::updatePath() { - if (!targetItem) - return; - - QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2)); - updatePath(endPoint); + if (!targetItem) + return; + + QPointF endPoint = targetItem->mapToScene(QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2)); + updatePath(endPoint); } void ArrowItem::updatePath(const QPointF &endPoint) { - const double arrowWidth = 15.0; - const double headWidth = 40.0; - const double headLength = headWidth / sqrt(2); - const double phi = 15; - - if (!startItem) - return; - - QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2)); - QLineF line(startPoint, endPoint); - qreal lineLength = line.length(); - - prepareGeometryChange(); - if (lineLength < 30) - path = QPainterPath(); - else { - QPointF c(lineLength / 2, tan(phi * M_PI / 180) * lineLength); - - QPainterPath centerLine; - centerLine.moveTo(0, 0); - centerLine.quadTo(c, QPointF(lineLength, 0)); - - double percentage = 1 - headLength / lineLength; - QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage); - QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001)); - qreal alpha = testLine.angle() - 90; - QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); - QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); - QPointF point1 = endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); - QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); - - path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); - path.quadTo(c, endPoint1); - path.lineTo(point1); - path.lineTo(QPointF(lineLength, 0)); - path.lineTo(point2); - path.lineTo(endPoint2); - path.quadTo(c, arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); - path.lineTo(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); - } - - setPos(startPoint); - setTransform(QTransform().rotate(-line.angle())); + const double arrowWidth = 15.0; + const double headWidth = 40.0; + const double headLength = headWidth / sqrt(2); + const double phi = 15; + + if (!startItem) + return; + + QPointF startPoint = startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2)); + QLineF line(startPoint, endPoint); + qreal lineLength = line.length(); + + prepareGeometryChange(); + if (lineLength < 30) + path = QPainterPath(); + else { + QPointF c(lineLength / 2, tan(phi * M_PI / 180) * lineLength); + + QPainterPath centerLine; + centerLine.moveTo(0, 0); + centerLine.quadTo(c, QPointF(lineLength, 0)); + + double percentage = 1 - headLength / lineLength; + QPointF arrowBodyEndPoint = centerLine.pointAtPercent(percentage); + QLineF testLine(arrowBodyEndPoint, centerLine.pointAtPercent(percentage + 0.001)); + qreal alpha = testLine.angle() - 90; + QPointF endPoint1 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); + QPointF endPoint2 = arrowBodyEndPoint + arrowWidth / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); + QPointF point1 = endPoint1 + (headWidth - arrowWidth) / 2 * QPointF(cos(alpha * M_PI / 180), -sin(alpha * M_PI / 180)); + QPointF point2 = endPoint2 + (headWidth - arrowWidth) / 2 * QPointF(-cos(alpha * M_PI / 180), sin(alpha * M_PI / 180)); + + path = QPainterPath(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); + path.quadTo(c, endPoint1); + path.lineTo(point1); + path.lineTo(QPointF(lineLength, 0)); + path.lineTo(point2); + path.lineTo(endPoint2); + path.quadTo(c, arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); + path.lineTo(-arrowWidth / 2 * QPointF(cos((phi - 90) * M_PI / 180), sin((phi - 90) * M_PI / 180))); + } + + setPos(startPoint); + setTransform(QTransform().rotate(-line.angle())); } void ArrowItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QColor paintColor(color); - if (fullColor) - paintColor.setAlpha(200); - else - paintColor.setAlpha(150); - painter->setBrush(paintColor); - painter->drawPath(path); + QColor paintColor(color); + if (fullColor) + paintColor.setAlpha(200); + else + paintColor.setAlpha(150); + painter->setBrush(paintColor); + painter->drawPath(path); } void ArrowItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (!player->getLocal()) { - event->ignore(); - return; - } - - QList colliding = scene()->items(event->scenePos()); - for (int i = 0; i < colliding.size(); ++i) - if (qgraphicsitem_cast(colliding[i])) { - event->ignore(); - return; - } - - event->accept(); - if (event->button() == Qt::RightButton) { - Command_DeleteArrow cmd; - cmd.set_arrow_id(id); - player->sendGameCommand(cmd); - } + if (!player->getLocal()) { + event->ignore(); + return; + } + + QList colliding = scene()->items(event->scenePos()); + for (int i = 0; i < colliding.size(); ++i) + if (qgraphicsitem_cast(colliding[i])) { + event->ignore(); + return; + } + + event->accept(); + if (event->button() == Qt::RightButton) { + Command_DeleteArrow cmd; + cmd.set_arrow_id(id); + player->sendGameCommand(cmd); + } } ArrowDragItem::ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color) @@ -147,85 +147,85 @@ ArrowDragItem::ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QCol void ArrowDragItem::addChildArrow(ArrowDragItem *childArrow) { - childArrows.append(childArrow); + childArrows.append(childArrow); } void ArrowDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - // This ensures that if a mouse move event happens after a call to delArrow(), - // the event will be discarded as it would create some stray pointers. - if (!startItem) - return; - - QPointF endPos = event->scenePos(); - - QList colliding = scene()->items(endPos); - ArrowTarget *cursorItem = 0; - qreal cursorItemZ = -1; - for (int i = colliding.size() - 1; i >= 0; i--) - if (qgraphicsitem_cast(colliding.at(i)) || qgraphicsitem_cast(colliding.at(i))) - if (colliding.at(i)->zValue() > cursorItemZ) { - cursorItem = static_cast(colliding.at(i)); - cursorItemZ = cursorItem->zValue(); - } - if ((cursorItem != targetItem) && targetItem) { - targetItem->setBeingPointedAt(false); - targetItem->removeArrowTo(this); - } + // This ensures that if a mouse move event happens after a call to delArrow(), + // the event will be discarded as it would create some stray pointers. + if (!startItem) + return; + + QPointF endPos = event->scenePos(); + + QList colliding = scene()->items(endPos); + ArrowTarget *cursorItem = 0; + qreal cursorItemZ = -1; + for (int i = colliding.size() - 1; i >= 0; i--) + if (qgraphicsitem_cast(colliding.at(i)) || qgraphicsitem_cast(colliding.at(i))) + if (colliding.at(i)->zValue() > cursorItemZ) { + cursorItem = static_cast(colliding.at(i)); + cursorItemZ = cursorItem->zValue(); + } + if ((cursorItem != targetItem) && targetItem) { + targetItem->setBeingPointedAt(false); + targetItem->removeArrowTo(this); + } if (!cursorItem) { - fullColor = false; - targetItem = 0; - updatePath(endPos); - } else { - if (cursorItem != targetItem) { - fullColor = true; - if (cursorItem != startItem) { - cursorItem->setBeingPointedAt(true); - cursorItem->addArrowTo(this); - } - targetItem = cursorItem; - } - updatePath(); - } - update(); - - for (int i = 0; i < childArrows.size(); ++i) - childArrows[i]->mouseMoveEvent(event); + fullColor = false; + targetItem = 0; + updatePath(endPos); + } else { + if (cursorItem != targetItem) { + fullColor = true; + if (cursorItem != startItem) { + cursorItem->setBeingPointedAt(true); + cursorItem->addArrowTo(this); + } + targetItem = cursorItem; + } + updatePath(); + } + update(); + + for (int i = 0; i < childArrows.size(); ++i) + childArrows[i]->mouseMoveEvent(event); } void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (!startItem) - return; - - if (targetItem && (targetItem != startItem)) { - CardZone *startZone = static_cast(startItem)->getZone(); - // For now, we can safely assume that the start item is always a card. - // The target item can be a player as well. - CardItem *startCard = qgraphicsitem_cast(startItem); - CardItem *targetCard = qgraphicsitem_cast(targetItem); + if (!startItem) + return; + + if (targetItem && (targetItem != startItem)) { + CardZone *startZone = static_cast(startItem)->getZone(); + // For now, we can safely assume that the start item is always a card. + // The target item can be a player as well. + CardItem *startCard = qgraphicsitem_cast(startItem); + CardItem *targetCard = qgraphicsitem_cast(targetItem); - Command_CreateArrow cmd; - cmd.mutable_arrow_color()->CopyFrom(convertQColorToColor(color)); - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_start_card_id(startCard->getId()); + Command_CreateArrow cmd; + cmd.mutable_arrow_color()->CopyFrom(convertQColorToColor(color)); + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_start_card_id(startCard->getId()); - if (targetCard) { - CardZone *targetZone = targetCard->getZone(); - cmd.set_target_player_id(targetZone->getPlayer()->getId()); - cmd.set_target_zone(targetZone->getName().toStdString()); - cmd.set_target_card_id(targetCard->getId()); - } else { - PlayerTarget *targetPlayer = qgraphicsitem_cast(targetItem); - cmd.set_target_player_id(targetPlayer->getOwner()->getId()); - } - player->sendGameCommand(cmd); - } - delArrow(); + if (targetCard) { + CardZone *targetZone = targetCard->getZone(); + cmd.set_target_player_id(targetZone->getPlayer()->getId()); + cmd.set_target_zone(targetZone->getName().toStdString()); + cmd.set_target_card_id(targetCard->getId()); + } else { + PlayerTarget *targetPlayer = qgraphicsitem_cast(targetItem); + cmd.set_target_player_id(targetPlayer->getOwner()->getId()); + } + player->sendGameCommand(cmd); + } + delArrow(); - for (int i = 0; i < childArrows.size(); ++i) - childArrows[i]->mouseReleaseEvent(event); + for (int i = 0; i < childArrows.size(); ++i) + childArrows[i]->mouseReleaseEvent(event); } ArrowAttachItem::ArrowAttachItem(ArrowTarget *_startItem) @@ -235,57 +235,57 @@ ArrowAttachItem::ArrowAttachItem(ArrowTarget *_startItem) void ArrowAttachItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (!startItem) - return; + if (!startItem) + return; - QPointF endPos = event->scenePos(); - - QList colliding = scene()->items(endPos); + QPointF endPos = event->scenePos(); + + QList colliding = scene()->items(endPos); ArrowTarget *cursorItem = 0; - qreal cursorItemZ = -1; + qreal cursorItemZ = -1; for (int i = colliding.size() - 1; i >= 0; i--) if (qgraphicsitem_cast(colliding.at(i))) - if (colliding.at(i)->zValue() > cursorItemZ) { - cursorItem = static_cast(colliding.at(i)); - cursorItemZ = cursorItem->zValue(); - } - - if ((cursorItem != targetItem) && targetItem) - targetItem->setBeingPointedAt(false); + if (colliding.at(i)->zValue() > cursorItemZ) { + cursorItem = static_cast(colliding.at(i)); + cursorItemZ = cursorItem->zValue(); + } + + if ((cursorItem != targetItem) && targetItem) + targetItem->setBeingPointedAt(false); if (!cursorItem) { - fullColor = false; - targetItem = 0; - updatePath(endPos); - } else { - fullColor = true; - if (cursorItem != startItem) - cursorItem->setBeingPointedAt(true); - targetItem = cursorItem; - updatePath(); - } - update(); + fullColor = false; + targetItem = 0; + updatePath(endPos); + } else { + fullColor = true; + if (cursorItem != startItem) + cursorItem->setBeingPointedAt(true); + targetItem = cursorItem; + updatePath(); + } + update(); } void ArrowAttachItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * /*event*/) { - if (!startItem) - return; + if (!startItem) + return; - if (targetItem && (targetItem != startItem)) { - CardItem *startCard = qgraphicsitem_cast(startItem); - CardZone *startZone = startCard->getZone(); - CardItem *targetCard = qgraphicsitem_cast(targetItem); - CardZone *targetZone = targetCard->getZone(); - - Command_AttachCard cmd; - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_card_id(startCard->getId()); - cmd.set_target_player_id(targetZone->getPlayer()->getId()); - cmd.set_target_zone(targetZone->getName().toStdString()); - cmd.set_target_card_id(targetCard->getId()); + if (targetItem && (targetItem != startItem)) { + CardItem *startCard = qgraphicsitem_cast(startItem); + CardZone *startZone = startCard->getZone(); + CardItem *targetCard = qgraphicsitem_cast(targetItem); + CardZone *targetZone = targetCard->getZone(); + + Command_AttachCard cmd; + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_card_id(startCard->getId()); + cmd.set_target_player_id(targetZone->getPlayer()->getId()); + cmd.set_target_zone(targetZone->getName().toStdString()); + cmd.set_target_card_id(targetCard->getId()); - player->sendGameCommand(cmd); - } - - delArrow(); + player->sendGameCommand(cmd); + } + + delArrow(); } diff --git a/cockatrice/src/arrowitem.h b/cockatrice/src/arrowitem.h index f97c83e7..67517404 100644 --- a/cockatrice/src/arrowitem.h +++ b/cockatrice/src/arrowitem.h @@ -10,54 +10,54 @@ class Player; class ArrowTarget; class ArrowItem : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT private: - QPainterPath path; - QMenu *menu; + QPainterPath path; + QMenu *menu; protected: - Player *player; - int id; - ArrowTarget *startItem, *targetItem; - QColor color; - bool fullColor; - void mousePressEvent(QGraphicsSceneMouseEvent *event); + Player *player; + int id; + ArrowTarget *startItem, *targetItem; + QColor color; + bool fullColor; + void mousePressEvent(QGraphicsSceneMouseEvent *event); public: - ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color); - ~ArrowItem(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QRectF boundingRect() const { return path.boundingRect(); } - QPainterPath shape() const { return path; } - void updatePath(); - void updatePath(const QPointF &endPoint); - - int getId() const { return id; } - Player *getPlayer() const { return player; } - void setStartItem(ArrowTarget *_item) { startItem = _item; } - void setTargetItem(ArrowTarget *_item) { targetItem = _item; } - ArrowTarget *getStartItem() const { return startItem; } - ArrowTarget *getTargetItem() const { return targetItem; } - void delArrow(); + ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTarget *_targetItem, const QColor &color); + ~ArrowItem(); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QRectF boundingRect() const { return path.boundingRect(); } + QPainterPath shape() const { return path; } + void updatePath(); + void updatePath(const QPointF &endPoint); + + int getId() const { return id; } + Player *getPlayer() const { return player; } + void setStartItem(ArrowTarget *_item) { startItem = _item; } + void setTargetItem(ArrowTarget *_item) { targetItem = _item; } + ArrowTarget *getStartItem() const { return startItem; } + ArrowTarget *getTargetItem() const { return targetItem; } + void delArrow(); }; class ArrowDragItem : public ArrowItem { - Q_OBJECT + Q_OBJECT private: - QList childArrows; + QList childArrows; public: - ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color); - void addChildArrow(ArrowDragItem *childArrow); + ArrowDragItem(Player *_owner, ArrowTarget *_startItem, const QColor &_color); + void addChildArrow(ArrowDragItem *childArrow); protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; class ArrowAttachItem : public ArrowItem { - Q_OBJECT + Q_OBJECT public: - ArrowAttachItem(ArrowTarget *_startItem); + ArrowAttachItem(ArrowTarget *_startItem); protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; #endif // ARROWITEM_H diff --git a/cockatrice/src/arrowtarget.cpp b/cockatrice/src/arrowtarget.cpp index 1740eb95..f20405a5 100644 --- a/cockatrice/src/arrowtarget.cpp +++ b/cockatrice/src/arrowtarget.cpp @@ -3,24 +3,24 @@ #include "player.h" ArrowTarget::ArrowTarget(Player *_owner, QGraphicsItem *parent) - : AbstractGraphicsItem(parent), owner(_owner), beingPointedAt(false) + : AbstractGraphicsItem(parent), owner(_owner), beingPointedAt(false) { } ArrowTarget::~ArrowTarget() { - for (int i = 0; i < arrowsFrom.size(); ++i) { - arrowsFrom[i]->setStartItem(0); - arrowsFrom[i]->delArrow(); - } - for (int i = 0; i < arrowsTo.size(); ++i) { - arrowsTo[i]->setTargetItem(0); - arrowsTo[i]->delArrow(); - } + for (int i = 0; i < arrowsFrom.size(); ++i) { + arrowsFrom[i]->setStartItem(0); + arrowsFrom[i]->delArrow(); + } + for (int i = 0; i < arrowsTo.size(); ++i) { + arrowsTo[i]->setTargetItem(0); + arrowsTo[i]->delArrow(); + } } void ArrowTarget::setBeingPointedAt(bool _beingPointedAt) { - beingPointedAt = _beingPointedAt; - update(); + beingPointedAt = _beingPointedAt; + update(); } diff --git a/cockatrice/src/arrowtarget.h b/cockatrice/src/arrowtarget.h index ce3ca55c..31fcf157 100644 --- a/cockatrice/src/arrowtarget.h +++ b/cockatrice/src/arrowtarget.h @@ -8,28 +8,28 @@ class Player; class ArrowItem; class ArrowTarget : public AbstractGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - Player *owner; + Player *owner; private: - bool beingPointedAt; - QList arrowsFrom, arrowsTo; + bool beingPointedAt; + QList arrowsFrom, arrowsTo; public: - ArrowTarget(Player *_owner, QGraphicsItem *parent = 0); - ~ArrowTarget(); - - Player *getOwner() const { return owner; } - - void setBeingPointedAt(bool _beingPointedAt); - bool getBeingPointedAt() const { return beingPointedAt; } - - const QList &getArrowsFrom() const { return arrowsFrom; } - void addArrowFrom(ArrowItem *arrow) { arrowsFrom.append(arrow); } - void removeArrowFrom(ArrowItem *arrow) { arrowsFrom.removeAt(arrowsFrom.indexOf(arrow)); } - - const QList &getArrowsTo() const { return arrowsTo; } - void addArrowTo(ArrowItem *arrow) { arrowsTo.append(arrow); } - void removeArrowTo(ArrowItem *arrow) { arrowsTo.removeAt(arrowsTo.indexOf(arrow)); } + ArrowTarget(Player *_owner, QGraphicsItem *parent = 0); + ~ArrowTarget(); + + Player *getOwner() const { return owner; } + + void setBeingPointedAt(bool _beingPointedAt); + bool getBeingPointedAt() const { return beingPointedAt; } + + const QList &getArrowsFrom() const { return arrowsFrom; } + void addArrowFrom(ArrowItem *arrow) { arrowsFrom.append(arrow); } + void removeArrowFrom(ArrowItem *arrow) { arrowsFrom.removeAt(arrowsFrom.indexOf(arrow)); } + + const QList &getArrowsTo() const { return arrowsTo; } + void addArrowTo(ArrowItem *arrow) { arrowsTo.append(arrow); } + void removeArrowTo(ArrowItem *arrow) { arrowsTo.removeAt(arrowsTo.indexOf(arrow)); } }; #endif diff --git a/cockatrice/src/carddatabase.cpp b/cockatrice/src/carddatabase.cpp index 8a0280a9..e5c60e52 100644 --- a/cockatrice/src/carddatabase.cpp +++ b/cockatrice/src/carddatabase.cpp @@ -17,782 +17,782 @@ const int CardDatabase::versionNeeded = 2; CardSet::CardSet(const QString &_shortName, const QString &_longName) - : shortName(_shortName), longName(_longName) + : shortName(_shortName), longName(_longName) { - updateSortKey(); + updateSortKey(); } QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardSet *set) { - xml.writeStartElement("set"); - xml.writeTextElement("name", set->getShortName()); - xml.writeTextElement("longname", set->getLongName()); - xml.writeEndElement(); + xml.writeStartElement("set"); + xml.writeTextElement("name", set->getShortName()); + xml.writeTextElement("longname", set->getLongName()); + xml.writeEndElement(); - return xml; + return xml; } void CardSet::setSortKey(unsigned int _sortKey) { - sortKey = _sortKey; + sortKey = _sortKey; - QSettings settings; - settings.beginGroup("sets"); - settings.beginGroup(shortName); - settings.setValue("sortkey", sortKey); + QSettings settings; + settings.beginGroup("sets"); + settings.beginGroup(shortName); + settings.setValue("sortkey", sortKey); } void CardSet::updateSortKey() { - QSettings settings; - settings.beginGroup("sets"); - settings.beginGroup(shortName); - sortKey = settings.value("sortkey", 0).toInt(); + QSettings settings; + settings.beginGroup("sets"); + settings.beginGroup(shortName); + sortKey = settings.value("sortkey", 0).toInt(); } class SetList::CompareFunctor { public: - inline bool operator()(CardSet *a, CardSet *b) const - { - return a->getSortKey() < b->getSortKey(); - } + inline bool operator()(CardSet *a, CardSet *b) const + { + return a->getSortKey() < b->getSortKey(); + } }; void SetList::sortByKey() { - qSort(begin(), end(), CompareFunctor()); + qSort(begin(), end(), CompareFunctor()); } PictureToLoad::PictureToLoad(CardInfo *_card, bool _stripped, bool _hq) - : card(_card), stripped(_stripped), setIndex(0), hq(_hq) + : card(_card), stripped(_stripped), setIndex(0), hq(_hq) { - if (card) { - sortedSets = card->getSets(); - sortedSets.sortByKey(); - } + if (card) { + sortedSets = card->getSets(); + sortedSets.sortByKey(); + } } bool PictureToLoad::nextSet() { - if (setIndex == sortedSets.size() - 1) - return false; - ++setIndex; - return true; + if (setIndex == sortedSets.size() - 1) + return false; + ++setIndex; + return true; } PictureLoader::PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent) - : QObject(parent), _picsPath(__picsPath), picDownload(_picDownload), downloadRunning(false), loadQueueRunning(false) + : QObject(parent), _picsPath(__picsPath), picDownload(_picDownload), downloadRunning(false), loadQueueRunning(false) { - connect(this, SIGNAL(startLoadQueue()), this, SLOT(processLoadQueue()), Qt::QueuedConnection); - - networkManager = new QNetworkAccessManager(this); - connect(networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(picDownloadFinished(QNetworkReply *))); + connect(this, SIGNAL(startLoadQueue()), this, SLOT(processLoadQueue()), Qt::QueuedConnection); + + networkManager = new QNetworkAccessManager(this); + connect(networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(picDownloadFinished(QNetworkReply *))); } PictureLoader::~PictureLoader() { - // This does not work with the destroyed() signal as this destructor is called after the main event loop is done. - thread()->quit(); + // This does not work with the destroyed() signal as this destructor is called after the main event loop is done. + thread()->quit(); } void PictureLoader::processLoadQueue() { - if (loadQueueRunning) - return; - - loadQueueRunning = true; - forever { - mutex.lock(); - if (loadQueue.isEmpty()) { - mutex.unlock(); - loadQueueRunning = false; - return; - } - PictureToLoad ptl = loadQueue.takeFirst(); - mutex.unlock(); - QString correctedName = ptl.getCard()->getCorrectedName(); - QString picsPath = _picsPath; - QString setName = ptl.getSetName(); - - QImage image; - if (!image.load(QString("%1/%2/%3.full.jpg").arg(picsPath).arg(setName).arg(correctedName))) - if (!image.load(QString("%1/%2/%3%4.full.jpg").arg(picsPath).arg(setName).arg(correctedName).arg(1))) - if (!image.load(QString("%1/%2/%3/%4.full.jpg").arg(picsPath).arg("downloadedPics").arg(setName).arg(correctedName))) { - if (picDownload) { - cardsToDownload.append(ptl); - if (!downloadRunning) - startNextPicDownload(); - } else { - if (ptl.nextSet()) - loadQueue.prepend(ptl); - else - emit imageLoaded(ptl.getCard(), QImage()); - } - continue; - } - - emit imageLoaded(ptl.getCard(), image); - } + if (loadQueueRunning) + return; + + loadQueueRunning = true; + forever { + mutex.lock(); + if (loadQueue.isEmpty()) { + mutex.unlock(); + loadQueueRunning = false; + return; + } + PictureToLoad ptl = loadQueue.takeFirst(); + mutex.unlock(); + QString correctedName = ptl.getCard()->getCorrectedName(); + QString picsPath = _picsPath; + QString setName = ptl.getSetName(); + + QImage image; + if (!image.load(QString("%1/%2/%3.full.jpg").arg(picsPath).arg(setName).arg(correctedName))) + if (!image.load(QString("%1/%2/%3%4.full.jpg").arg(picsPath).arg(setName).arg(correctedName).arg(1))) + if (!image.load(QString("%1/%2/%3/%4.full.jpg").arg(picsPath).arg("downloadedPics").arg(setName).arg(correctedName))) { + if (picDownload) { + cardsToDownload.append(ptl); + if (!downloadRunning) + startNextPicDownload(); + } else { + if (ptl.nextSet()) + loadQueue.prepend(ptl); + else + emit imageLoaded(ptl.getCard(), QImage()); + } + continue; + } + + emit imageLoaded(ptl.getCard(), image); + } } void PictureLoader::startNextPicDownload() { - if (cardsToDownload.isEmpty()) { - cardBeingDownloaded = 0; - downloadRunning = false; - return; - } - - downloadRunning = true; - - cardBeingDownloaded = cardsToDownload.takeFirst(); - QString picUrl; - if (cardBeingDownloaded.getStripped()) - picUrl = cardBeingDownloaded.getCard()->getPicURLSt(cardBeingDownloaded.getSetName()); - else if (cardBeingDownloaded.getHq()) { - picUrl = cardBeingDownloaded.getCard()->getPicURLHq(cardBeingDownloaded.getSetName()); - if (picUrl.isEmpty()) { - picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); - cardBeingDownloaded.setHq(false); - } - } else - picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); - QUrl url(picUrl); - - QNetworkRequest req(url); - qDebug() << "starting picture download:" << req.url(); - networkManager->get(req); + if (cardsToDownload.isEmpty()) { + cardBeingDownloaded = 0; + downloadRunning = false; + return; + } + + downloadRunning = true; + + cardBeingDownloaded = cardsToDownload.takeFirst(); + QString picUrl; + if (cardBeingDownloaded.getStripped()) + picUrl = cardBeingDownloaded.getCard()->getPicURLSt(cardBeingDownloaded.getSetName()); + else if (cardBeingDownloaded.getHq()) { + picUrl = cardBeingDownloaded.getCard()->getPicURLHq(cardBeingDownloaded.getSetName()); + if (picUrl.isEmpty()) { + picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); + cardBeingDownloaded.setHq(false); + } + } else + picUrl = cardBeingDownloaded.getCard()->getPicURL(cardBeingDownloaded.getSetName()); + QUrl url(picUrl); + + QNetworkRequest req(url); + qDebug() << "starting picture download:" << req.url(); + networkManager->get(req); } void PictureLoader::picDownloadFinished(QNetworkReply *reply) { - QString picsPath = _picsPath; - const QByteArray &picData = reply->readAll(); - QImage testImage; - if (testImage.loadFromData(picData)) { - if (!QDir(QString(picsPath + "/downloadedPics/")).exists()) { - QDir dir(picsPath); - if (!dir.exists()) - return; - dir.mkdir("downloadedPics"); - } - if (!QDir(QString(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName())).exists()) { - QDir dir(QString(picsPath + "/downloadedPics")); - dir.mkdir(cardBeingDownloaded.getSetName()); - } - - QString suffix; - if (!cardBeingDownloaded.getStripped()) - suffix = ".full"; - - QFile newPic(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName() + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + suffix + ".jpg"); - if (!newPic.open(QIODevice::WriteOnly)) - return; - newPic.write(picData); - newPic.close(); - - emit imageLoaded(cardBeingDownloaded.getCard(), testImage); - } else if (cardBeingDownloaded.getHq()) { - qDebug() << "HQ: received invalid picture. URL:" << reply->request().url(); - cardBeingDownloaded.setHq(false); - cardsToDownload.prepend(cardBeingDownloaded); - } else { - qDebug() << "LQ: received invalid picture. URL:" << reply->request().url(); - if (cardBeingDownloaded.nextSet()) { - cardBeingDownloaded.setHq(true); - mutex.lock(); - loadQueue.prepend(cardBeingDownloaded); - mutex.unlock(); - emit startLoadQueue(); - } else - emit imageLoaded(cardBeingDownloaded.getCard(), QImage()); - } - - reply->deleteLater(); - startNextPicDownload(); + QString picsPath = _picsPath; + const QByteArray &picData = reply->readAll(); + QImage testImage; + if (testImage.loadFromData(picData)) { + if (!QDir(QString(picsPath + "/downloadedPics/")).exists()) { + QDir dir(picsPath); + if (!dir.exists()) + return; + dir.mkdir("downloadedPics"); + } + if (!QDir(QString(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName())).exists()) { + QDir dir(QString(picsPath + "/downloadedPics")); + dir.mkdir(cardBeingDownloaded.getSetName()); + } + + QString suffix; + if (!cardBeingDownloaded.getStripped()) + suffix = ".full"; + + QFile newPic(picsPath + "/downloadedPics/" + cardBeingDownloaded.getSetName() + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + suffix + ".jpg"); + if (!newPic.open(QIODevice::WriteOnly)) + return; + newPic.write(picData); + newPic.close(); + + emit imageLoaded(cardBeingDownloaded.getCard(), testImage); + } else if (cardBeingDownloaded.getHq()) { + qDebug() << "HQ: received invalid picture. URL:" << reply->request().url(); + cardBeingDownloaded.setHq(false); + cardsToDownload.prepend(cardBeingDownloaded); + } else { + qDebug() << "LQ: received invalid picture. URL:" << reply->request().url(); + if (cardBeingDownloaded.nextSet()) { + cardBeingDownloaded.setHq(true); + mutex.lock(); + loadQueue.prepend(cardBeingDownloaded); + mutex.unlock(); + emit startLoadQueue(); + } else + emit imageLoaded(cardBeingDownloaded.getCard(), QImage()); + } + + reply->deleteLater(); + startNextPicDownload(); } void PictureLoader::loadImage(CardInfo *card, bool stripped) { - QMutexLocker locker(&mutex); - - loadQueue.append(PictureToLoad(card, stripped)); - emit startLoadQueue(); + QMutexLocker locker(&mutex); + + loadQueue.append(PictureToLoad(card, stripped)); + emit startLoadQueue(); } void PictureLoader::setPicsPath(const QString &path) { - QMutexLocker locker(&mutex); - _picsPath = path; + QMutexLocker locker(&mutex); + _picsPath = path; } void PictureLoader::setPicDownload(bool _picDownload) { - QMutexLocker locker(&mutex); - picDownload = _picDownload; + QMutexLocker locker(&mutex); + picDownload = _picDownload; } CardInfo::CardInfo(CardDatabase *_db, - const QString &_name, - bool _isToken, - const QString &_manacost, - const QString &_cardtype, - const QString &_powtough, - const QString &_text, - const QStringList &_colors, - int _loyalty, - bool _cipt, - int _tableRow, - const SetList &_sets, - const QMap &_picURLs, - const QMap &_picURLsHq, - const QMap &_picURLsSt) - : db(_db), - name(_name), - isToken(_isToken), - sets(_sets), - manacost(_manacost), - cardtype(_cardtype), - powtough(_powtough), - text(_text), - colors(_colors), - loyalty(_loyalty), - picURLs(_picURLs), - picURLsHq(_picURLsHq), - picURLsSt(_picURLsSt), - cipt(_cipt), - tableRow(_tableRow), - pixmap(NULL) + const QString &_name, + bool _isToken, + const QString &_manacost, + const QString &_cardtype, + const QString &_powtough, + const QString &_text, + const QStringList &_colors, + int _loyalty, + bool _cipt, + int _tableRow, + const SetList &_sets, + const QMap &_picURLs, + const QMap &_picURLsHq, + const QMap &_picURLsSt) + : db(_db), + name(_name), + isToken(_isToken), + sets(_sets), + manacost(_manacost), + cardtype(_cardtype), + powtough(_powtough), + text(_text), + colors(_colors), + loyalty(_loyalty), + picURLs(_picURLs), + picURLsHq(_picURLsHq), + picURLsSt(_picURLsSt), + cipt(_cipt), + tableRow(_tableRow), + pixmap(NULL) { - for (int i = 0; i < sets.size(); i++) - sets[i]->append(this); + for (int i = 0; i < sets.size(); i++) + sets[i]->append(this); } CardInfo::~CardInfo() { - clearPixmapCache(); + clearPixmapCache(); } QString CardInfo::getMainCardType() const { - QString result = getCardType(); - /* - Legendary Artifact Creature - Golem - Instant // Instant - */ + QString result = getCardType(); + /* + Legendary Artifact Creature - Golem + Instant // Instant + */ - int pos; - if ((pos = result.indexOf('-')) != -1) - result.remove(pos, result.length()); - if ((pos = result.indexOf("//")) != -1) - result.remove(pos, result.length()); - result = result.simplified(); - /* - Legendary Artifact Creature - Instant - */ + int pos; + if ((pos = result.indexOf('-')) != -1) + result.remove(pos, result.length()); + if ((pos = result.indexOf("//")) != -1) + result.remove(pos, result.length()); + result = result.simplified(); + /* + Legendary Artifact Creature + Instant + */ - if ((pos = result.lastIndexOf(' ')) != -1) - result = result.mid(pos + 1); - /* - Creature - Instant - */ + if ((pos = result.lastIndexOf(' ')) != -1) + result = result.mid(pos + 1); + /* + Creature + Instant + */ - return result; + return result; } QString CardInfo::getCorrectedName() const { - QString result = name; - // Fire // Ice, Circle of Protection: Red, "Ach! Hans, Run!", Who/What/When/Where/Why, Question Elemental? - return result.remove(" // ").remove(':').remove('"').remove('?').replace('/', ' '); + QString result = name; + // Fire // Ice, Circle of Protection: Red, "Ach! Hans, Run!", Who/What/When/Where/Why, Question Elemental? + return result.remove(" // ").remove(':').remove('"').remove('?').replace('/', ' '); } void CardInfo::addToSet(CardSet *set) { - set->append(this); - sets << set; + set->append(this); + sets << set; } QString CardInfo::getPicURL() const { - SetList sortedSets = sets; - sortedSets.sortByKey(); - return picURLs.value(sortedSets.first()->getShortName()); + SetList sortedSets = sets; + sortedSets.sortByKey(); + return picURLs.value(sortedSets.first()->getShortName()); } QPixmap *CardInfo::loadPixmap() { - if (pixmap) - return pixmap; - pixmap = new QPixmap(); - - if (getName().isEmpty()) { - pixmap->load(settingsCache->getCardBackPicturePath()); - return pixmap; - } - db->loadImage(this); - return pixmap; + if (pixmap) + return pixmap; + pixmap = new QPixmap(); + + if (getName().isEmpty()) { + pixmap->load(settingsCache->getCardBackPicturePath()); + return pixmap; + } + db->loadImage(this); + return pixmap; } void CardInfo::imageLoaded(const QImage &image) { - if (!image.isNull()) { - *pixmap = QPixmap::fromImage(image); - emit pixmapUpdated(); - } + if (!image.isNull()) { + *pixmap = QPixmap::fromImage(image); + emit pixmapUpdated(); + } } QPixmap *CardInfo::getPixmap(QSize size) { - QPixmap *cachedPixmap = scaledPixmapCache.value(size.width()); - if (cachedPixmap) - return cachedPixmap; - QPixmap *bigPixmap = loadPixmap(); - QPixmap *result; - if (bigPixmap->isNull()) { - if (!getName().isEmpty()) - return 0; - else { - result = new QPixmap(size); - result->fill(Qt::transparent); - QSvgRenderer svg(QString(":/back.svg")); - QPainter painter(result); - svg.render(&painter, QRectF(0, 0, size.width(), size.height())); - } - } else - result = new QPixmap(bigPixmap->scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - scaledPixmapCache.insert(size.width(), result); - return result; + QPixmap *cachedPixmap = scaledPixmapCache.value(size.width()); + if (cachedPixmap) + return cachedPixmap; + QPixmap *bigPixmap = loadPixmap(); + QPixmap *result; + if (bigPixmap->isNull()) { + if (!getName().isEmpty()) + return 0; + else { + result = new QPixmap(size); + result->fill(Qt::transparent); + QSvgRenderer svg(QString(":/back.svg")); + QPainter painter(result); + svg.render(&painter, QRectF(0, 0, size.width(), size.height())); + } + } else + result = new QPixmap(bigPixmap->scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + scaledPixmapCache.insert(size.width(), result); + return result; } void CardInfo::clearPixmapCache() { - if (pixmap) { - qDebug() << "Deleting pixmap for" << name; - delete pixmap; - pixmap = 0; - QMapIterator i(scaledPixmapCache); - while (i.hasNext()) { - i.next(); - qDebug() << " Deleting cached pixmap for width" << i.key(); - delete i.value(); - } - scaledPixmapCache.clear(); - } + if (pixmap) { + qDebug() << "Deleting pixmap for" << name; + delete pixmap; + pixmap = 0; + QMapIterator i(scaledPixmapCache); + while (i.hasNext()) { + i.next(); + qDebug() << " Deleting cached pixmap for width" << i.key(); + delete i.value(); + } + scaledPixmapCache.clear(); + } } void CardInfo::clearPixmapCacheMiss() { - if (!pixmap) - return; - if (pixmap->isNull()) - clearPixmapCache(); + if (!pixmap) + return; + if (pixmap->isNull()) + clearPixmapCache(); } void CardInfo::updatePixmapCache() { - qDebug() << "Updating pixmap cache for" << name; - clearPixmapCache(); - loadPixmap(); - - emit pixmapUpdated(); + qDebug() << "Updating pixmap cache for" << name; + clearPixmapCache(); + loadPixmap(); + + emit pixmapUpdated(); } QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfo *info) { - xml.writeStartElement("card"); - xml.writeTextElement("name", info->getName()); + xml.writeStartElement("card"); + xml.writeTextElement("name", info->getName()); - const SetList &sets = info->getSets(); - for (int i = 0; i < sets.size(); i++) { - xml.writeStartElement("set"); - xml.writeAttribute("picURL", info->getPicURL(sets[i]->getShortName())); - xml.writeAttribute("picURLHq", info->getPicURLHq(sets[i]->getShortName())); - xml.writeAttribute("picURLSt", info->getPicURLSt(sets[i]->getShortName())); - xml.writeCharacters(sets[i]->getShortName()); - xml.writeEndElement(); - } - const QStringList &colors = info->getColors(); - for (int i = 0; i < colors.size(); i++) - xml.writeTextElement("color", colors[i]); + const SetList &sets = info->getSets(); + for (int i = 0; i < sets.size(); i++) { + xml.writeStartElement("set"); + xml.writeAttribute("picURL", info->getPicURL(sets[i]->getShortName())); + xml.writeAttribute("picURLHq", info->getPicURLHq(sets[i]->getShortName())); + xml.writeAttribute("picURLSt", info->getPicURLSt(sets[i]->getShortName())); + xml.writeCharacters(sets[i]->getShortName()); + xml.writeEndElement(); + } + const QStringList &colors = info->getColors(); + for (int i = 0; i < colors.size(); i++) + xml.writeTextElement("color", colors[i]); - xml.writeTextElement("manacost", info->getManaCost()); - xml.writeTextElement("type", info->getCardType()); - if (!info->getPowTough().isEmpty()) - xml.writeTextElement("pt", info->getPowTough()); - xml.writeTextElement("tablerow", QString::number(info->getTableRow())); - xml.writeTextElement("text", info->getText()); - if (info->getMainCardType() == "Planeswalker") - xml.writeTextElement("loyalty", QString::number(info->getLoyalty())); - if (info->getCipt()) - xml.writeTextElement("cipt", "1"); - if (info->getIsToken()) - xml.writeTextElement("token", "1"); - xml.writeEndElement(); // card + xml.writeTextElement("manacost", info->getManaCost()); + xml.writeTextElement("type", info->getCardType()); + if (!info->getPowTough().isEmpty()) + xml.writeTextElement("pt", info->getPowTough()); + xml.writeTextElement("tablerow", QString::number(info->getTableRow())); + xml.writeTextElement("text", info->getText()); + if (info->getMainCardType() == "Planeswalker") + xml.writeTextElement("loyalty", QString::number(info->getLoyalty())); + if (info->getCipt()) + xml.writeTextElement("cipt", "1"); + if (info->getIsToken()) + xml.writeTextElement("token", "1"); + xml.writeEndElement(); // card - return xml; + return xml; } CardDatabase::CardDatabase(QObject *parent) - : QObject(parent), loadSuccess(false), noCard(0) + : QObject(parent), loadSuccess(false), noCard(0) { - connect(settingsCache, SIGNAL(picsPathChanged()), this, SLOT(picsPathChanged())); - connect(settingsCache, SIGNAL(cardDatabasePathChanged()), this, SLOT(loadCardDatabase())); - connect(settingsCache, SIGNAL(tokenDatabasePathChanged()), this, SLOT(loadTokenDatabase())); - connect(settingsCache, SIGNAL(picDownloadChanged()), this, SLOT(picDownloadChanged())); - - loadCardDatabase(); - loadTokenDatabase(); - - pictureLoaderThread = new QThread; - pictureLoader = new PictureLoader(settingsCache->getPicsPath(), settingsCache->getPicDownload()); - pictureLoader->moveToThread(pictureLoaderThread); - connect(pictureLoader, SIGNAL(imageLoaded(CardInfo *, const QImage &)), this, SLOT(imageLoaded(CardInfo *, const QImage &))); - pictureLoaderThread->start(QThread::LowPriority); + connect(settingsCache, SIGNAL(picsPathChanged()), this, SLOT(picsPathChanged())); + connect(settingsCache, SIGNAL(cardDatabasePathChanged()), this, SLOT(loadCardDatabase())); + connect(settingsCache, SIGNAL(tokenDatabasePathChanged()), this, SLOT(loadTokenDatabase())); + connect(settingsCache, SIGNAL(picDownloadChanged()), this, SLOT(picDownloadChanged())); + + loadCardDatabase(); + loadTokenDatabase(); + + pictureLoaderThread = new QThread; + pictureLoader = new PictureLoader(settingsCache->getPicsPath(), settingsCache->getPicDownload()); + pictureLoader->moveToThread(pictureLoaderThread); + connect(pictureLoader, SIGNAL(imageLoaded(CardInfo *, const QImage &)), this, SLOT(imageLoaded(CardInfo *, const QImage &))); + pictureLoaderThread->start(QThread::LowPriority); - noCard = new CardInfo(this); - noCard->loadPixmap(); // cache pixmap for card back - connect(settingsCache, SIGNAL(cardBackPicturePathChanged()), noCard, SLOT(updatePixmapCache())); + noCard = new CardInfo(this); + noCard->loadPixmap(); // cache pixmap for card back + connect(settingsCache, SIGNAL(cardBackPicturePathChanged()), noCard, SLOT(updatePixmapCache())); } CardDatabase::~CardDatabase() { - clear(); - delete noCard; - - pictureLoader->deleteLater(); - pictureLoaderThread->wait(); - delete pictureLoaderThread; + clear(); + delete noCard; + + pictureLoader->deleteLater(); + pictureLoaderThread->wait(); + delete pictureLoaderThread; } void CardDatabase::clear() { - QHashIterator setIt(setHash); - while (setIt.hasNext()) { - setIt.next(); - delete setIt.value(); - } - setHash.clear(); - - QHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - delete i.value(); - } - cardHash.clear(); + QHashIterator setIt(setHash); + while (setIt.hasNext()) { + setIt.next(); + delete setIt.value(); + } + setHash.clear(); + + QHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + delete i.value(); + } + cardHash.clear(); } void CardDatabase::addCard(CardInfo *card) { - cardHash.insert(card->getName(), card); - emit cardAdded(card); + cardHash.insert(card->getName(), card); + emit cardAdded(card); } void CardDatabase::removeCard(CardInfo *card) { - cardHash.remove(card->getName()); - emit cardRemoved(card); + cardHash.remove(card->getName()); + emit cardRemoved(card); } CardInfo *CardDatabase::getCard(const QString &cardName, bool createIfNotFound) { - if (cardName.isEmpty()) - return noCard; - else if (cardHash.contains(cardName)) - return cardHash.value(cardName); - else if (createIfNotFound) { - CardInfo *newCard = new CardInfo(this, cardName, true); - newCard->addToSet(getSet("TK")); - cardHash.insert(cardName, newCard); - return newCard; - } else - return 0; + if (cardName.isEmpty()) + return noCard; + else if (cardHash.contains(cardName)) + return cardHash.value(cardName); + else if (createIfNotFound) { + CardInfo *newCard = new CardInfo(this, cardName, true); + newCard->addToSet(getSet("TK")); + cardHash.insert(cardName, newCard); + return newCard; + } else + return 0; } CardSet *CardDatabase::getSet(const QString &setName) { - if (setHash.contains(setName)) - return setHash.value(setName); - else { - CardSet *newSet = new CardSet(setName); - setHash.insert(setName, newSet); - return newSet; - } + if (setHash.contains(setName)) + return setHash.value(setName); + else { + CardSet *newSet = new CardSet(setName); + setHash.insert(setName, newSet); + return newSet; + } } SetList CardDatabase::getSetList() const { - SetList result; - QHashIterator i(setHash); - while (i.hasNext()) { - i.next(); - result << i.value(); - } - return result; + SetList result; + QHashIterator i(setHash); + while (i.hasNext()) { + i.next(); + result << i.value(); + } + return result; } void CardDatabase::clearPixmapCache() { - QHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - i.value()->clearPixmapCache(); - } - if (noCard) - noCard->clearPixmapCache(); + QHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + i.value()->clearPixmapCache(); + } + if (noCard) + noCard->clearPixmapCache(); } void CardDatabase::loadSetsFromXml(QXmlStreamReader &xml) { - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "set") { - QString shortName, longName; - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "name") - shortName = xml.readElementText(); - else if (xml.name() == "longname") - longName = xml.readElementText(); - } - setHash.insert(shortName, new CardSet(shortName, longName)); - } - } + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "set") { + QString shortName, longName; + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "name") + shortName = xml.readElementText(); + else if (xml.name() == "longname") + longName = xml.readElementText(); + } + setHash.insert(shortName, new CardSet(shortName, longName)); + } + } } void CardDatabase::loadCardsFromXml(QXmlStreamReader &xml) { - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "card") { - QString name, manacost, type, pt, text; - QStringList colors; - QMap picURLs, picURLsHq, picURLsSt; - SetList sets; - int tableRow = 0; - int loyalty = 0; - bool cipt = false; - bool isToken = false; - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "name") - name = xml.readElementText(); - else if (xml.name() == "manacost") - manacost = xml.readElementText(); - else if (xml.name() == "type") - type = xml.readElementText(); - else if (xml.name() == "pt") - pt = xml.readElementText(); - else if (xml.name() == "text") - text = xml.readElementText(); - else if (xml.name() == "set") { - QString picURL = xml.attributes().value("picURL").toString(); - QString picURLHq = xml.attributes().value("picURLHq").toString(); - QString picURLSt = xml.attributes().value("picURLSt").toString(); - QString setName = xml.readElementText(); - sets.append(getSet(setName)); - picURLs.insert(setName, picURL); - picURLsHq.insert(setName, picURLHq); - picURLsSt.insert(setName, picURLSt); - } else if (xml.name() == "color") - colors << xml.readElementText(); - else if (xml.name() == "tablerow") - tableRow = xml.readElementText().toInt(); - else if (xml.name() == "cipt") - cipt = (xml.readElementText() == "1"); - else if (xml.name() == "loyalty") - loyalty = xml.readElementText().toInt(); - else if (xml.name() == "token") - isToken = xml.readElementText().toInt(); - } - cardHash.insert(name, new CardInfo(this, name, isToken, manacost, type, pt, text, colors, loyalty, cipt, tableRow, sets, picURLs, picURLsHq, picURLsSt)); - } - } + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "card") { + QString name, manacost, type, pt, text; + QStringList colors; + QMap picURLs, picURLsHq, picURLsSt; + SetList sets; + int tableRow = 0; + int loyalty = 0; + bool cipt = false; + bool isToken = false; + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "name") + name = xml.readElementText(); + else if (xml.name() == "manacost") + manacost = xml.readElementText(); + else if (xml.name() == "type") + type = xml.readElementText(); + else if (xml.name() == "pt") + pt = xml.readElementText(); + else if (xml.name() == "text") + text = xml.readElementText(); + else if (xml.name() == "set") { + QString picURL = xml.attributes().value("picURL").toString(); + QString picURLHq = xml.attributes().value("picURLHq").toString(); + QString picURLSt = xml.attributes().value("picURLSt").toString(); + QString setName = xml.readElementText(); + sets.append(getSet(setName)); + picURLs.insert(setName, picURL); + picURLsHq.insert(setName, picURLHq); + picURLsSt.insert(setName, picURLSt); + } else if (xml.name() == "color") + colors << xml.readElementText(); + else if (xml.name() == "tablerow") + tableRow = xml.readElementText().toInt(); + else if (xml.name() == "cipt") + cipt = (xml.readElementText() == "1"); + else if (xml.name() == "loyalty") + loyalty = xml.readElementText().toInt(); + else if (xml.name() == "token") + isToken = xml.readElementText().toInt(); + } + cardHash.insert(name, new CardInfo(this, name, isToken, manacost, type, pt, text, colors, loyalty, cipt, tableRow, sets, picURLs, picURLsHq, picURLsSt)); + } + } } bool CardDatabase::loadFromFile(const QString &fileName, bool tokens) { - QFile file(fileName); - file.open(QIODevice::ReadOnly); - if (!file.isOpen()) - return false; - - if (tokens) { - QMutableHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - if (i.value()->getIsToken()) { - delete i.value(); - i.remove(); - } - } - } else { - QHashIterator setIt(setHash); - while (setIt.hasNext()) { - setIt.next(); - delete setIt.value(); - } - setHash.clear(); - - QMutableHashIterator i(cardHash); - while (i.hasNext()) { - i.next(); - if (!i.value()->getIsToken()) { - delete i.value(); - i.remove(); - } - } - cardHash.clear(); - } + QFile file(fileName); + file.open(QIODevice::ReadOnly); + if (!file.isOpen()) + return false; + + if (tokens) { + QMutableHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + if (i.value()->getIsToken()) { + delete i.value(); + i.remove(); + } + } + } else { + QHashIterator setIt(setHash); + while (setIt.hasNext()) { + setIt.next(); + delete setIt.value(); + } + setHash.clear(); + + QMutableHashIterator i(cardHash); + while (i.hasNext()) { + i.next(); + if (!i.value()->getIsToken()) { + delete i.value(); + i.remove(); + } + } + cardHash.clear(); + } - QXmlStreamReader xml(&file); - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::StartElement) { - if (xml.name() != "cockatrice_carddatabase") - return false; - if (xml.attributes().value("version").toString().toInt() < versionNeeded) - return false; - while (!xml.atEnd()) { - if (xml.readNext() == QXmlStreamReader::EndElement) - break; - if (xml.name() == "sets") - loadSetsFromXml(xml); - else if (xml.name() == "cards") - loadCardsFromXml(xml); - } - } - } - qDebug() << cardHash.size() << "cards in" << setHash.size() << "sets loaded"; - return !cardHash.isEmpty(); + QXmlStreamReader xml(&file); + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::StartElement) { + if (xml.name() != "cockatrice_carddatabase") + return false; + if (xml.attributes().value("version").toString().toInt() < versionNeeded) + return false; + while (!xml.atEnd()) { + if (xml.readNext() == QXmlStreamReader::EndElement) + break; + if (xml.name() == "sets") + loadSetsFromXml(xml); + else if (xml.name() == "cards") + loadCardsFromXml(xml); + } + } + } + qDebug() << cardHash.size() << "cards in" << setHash.size() << "sets loaded"; + return !cardHash.isEmpty(); } bool CardDatabase::saveToFile(const QString &fileName, bool tokens) { - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) - return false; - QXmlStreamWriter xml(&file); + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly)) + return false; + QXmlStreamWriter xml(&file); - xml.setAutoFormatting(true); - xml.writeStartDocument(); - xml.writeStartElement("cockatrice_carddatabase"); - xml.writeAttribute("version", QString::number(versionNeeded)); + xml.setAutoFormatting(true); + xml.writeStartDocument(); + xml.writeStartElement("cockatrice_carddatabase"); + xml.writeAttribute("version", QString::number(versionNeeded)); - if (!tokens) { - xml.writeStartElement("sets"); - QHashIterator setIterator(setHash); - while (setIterator.hasNext()) - xml << setIterator.next().value(); - xml.writeEndElement(); // sets - } + if (!tokens) { + xml.writeStartElement("sets"); + QHashIterator setIterator(setHash); + while (setIterator.hasNext()) + xml << setIterator.next().value(); + xml.writeEndElement(); // sets + } - xml.writeStartElement("cards"); - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) { - CardInfo *card = cardIterator.next().value(); - if (card->getIsToken() == tokens) - xml << card; - } - xml.writeEndElement(); // cards + xml.writeStartElement("cards"); + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) { + CardInfo *card = cardIterator.next().value(); + if (card->getIsToken() == tokens) + xml << card; + } + xml.writeEndElement(); // cards - xml.writeEndElement(); // cockatrice_carddatabase - xml.writeEndDocument(); + xml.writeEndElement(); // cockatrice_carddatabase + xml.writeEndDocument(); - return true; + return true; } void CardDatabase::picDownloadChanged() { - pictureLoader->setPicDownload(settingsCache->getPicDownload()); - if (settingsCache->getPicDownload()) { - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) - cardIterator.next().value()->clearPixmapCacheMiss(); - } + pictureLoader->setPicDownload(settingsCache->getPicDownload()); + if (settingsCache->getPicDownload()) { + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) + cardIterator.next().value()->clearPixmapCacheMiss(); + } } bool CardDatabase::loadCardDatabase(const QString &path, bool tokens) { - bool tempLoadSuccess = false; - if (!path.isEmpty()) - tempLoadSuccess = loadFromFile(path, tokens); - - if (tempLoadSuccess) { - SetList allSets; - QHashIterator setsIterator(setHash); - while (setsIterator.hasNext()) - allSets.append(setsIterator.next().value()); - allSets.sortByKey(); - for (int i = 0; i < allSets.size(); ++i) - allSets[i]->setSortKey(i); - - emit cardListChanged(); - } - - if (!tokens) - loadSuccess = tempLoadSuccess; - - return tempLoadSuccess; + bool tempLoadSuccess = false; + if (!path.isEmpty()) + tempLoadSuccess = loadFromFile(path, tokens); + + if (tempLoadSuccess) { + SetList allSets; + QHashIterator setsIterator(setHash); + while (setsIterator.hasNext()) + allSets.append(setsIterator.next().value()); + allSets.sortByKey(); + for (int i = 0; i < allSets.size(); ++i) + allSets[i]->setSortKey(i); + + emit cardListChanged(); + } + + if (!tokens) + loadSuccess = tempLoadSuccess; + + return tempLoadSuccess; } void CardDatabase::loadCardDatabase() { - loadCardDatabase(settingsCache->getCardDatabasePath(), false); + loadCardDatabase(settingsCache->getCardDatabasePath(), false); } void CardDatabase::loadTokenDatabase() { - loadCardDatabase(settingsCache->getTokenDatabasePath(), true); + loadCardDatabase(settingsCache->getTokenDatabasePath(), true); } QStringList CardDatabase::getAllColors() const { - QSet colors; - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) { - const QStringList &cardColors = cardIterator.next().value()->getColors(); - if (cardColors.isEmpty()) - colors.insert("X"); - else - for (int i = 0; i < cardColors.size(); ++i) - colors.insert(cardColors[i]); - } - return colors.toList(); + QSet colors; + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) { + const QStringList &cardColors = cardIterator.next().value()->getColors(); + if (cardColors.isEmpty()) + colors.insert("X"); + else + for (int i = 0; i < cardColors.size(); ++i) + colors.insert(cardColors[i]); + } + return colors.toList(); } QStringList CardDatabase::getAllMainCardTypes() const { - QSet types; - QHashIterator cardIterator(cardHash); - while (cardIterator.hasNext()) - types.insert(cardIterator.next().value()->getMainCardType()); - return types.toList(); + QSet types; + QHashIterator cardIterator(cardHash); + while (cardIterator.hasNext()) + types.insert(cardIterator.next().value()->getMainCardType()); + return types.toList(); } void CardDatabase::cacheCardPixmaps(const QStringList &cardNames) { - for (int i = 0; i < cardNames.size(); ++i) - getCard(cardNames[i])->loadPixmap(); + for (int i = 0; i < cardNames.size(); ++i) + getCard(cardNames[i])->loadPixmap(); } void CardDatabase::loadImage(CardInfo *card) { - pictureLoader->loadImage(card, false); + pictureLoader->loadImage(card, false); } void CardDatabase::imageLoaded(CardInfo *card, QImage image) { - card->imageLoaded(image); + card->imageLoaded(image); } void CardDatabase::picsPathChanged() { - pictureLoader->setPicsPath(settingsCache->getPicsPath()); - clearPixmapCache(); + pictureLoader->setPicsPath(settingsCache->getPicsPath()); + clearPixmapCache(); } diff --git a/cockatrice/src/carddatabase.h b/cockatrice/src/carddatabase.h index 1f87d276..9d3f33f3 100644 --- a/cockatrice/src/carddatabase.h +++ b/cockatrice/src/carddatabase.h @@ -22,191 +22,191 @@ typedef QMap QStringMap; class CardSet : public QList { private: - QString shortName, longName; - unsigned int sortKey; + QString shortName, longName; + unsigned int sortKey; public: - CardSet(const QString &_shortName = QString(), const QString &_longName = QString()); - QString getShortName() const { return shortName; } - QString getLongName() const { return longName; } - int getSortKey() const { return sortKey; } - void setSortKey(unsigned int _sortKey); - void updateSortKey(); + CardSet(const QString &_shortName = QString(), const QString &_longName = QString()); + QString getShortName() const { return shortName; } + QString getLongName() const { return longName; } + int getSortKey() const { return sortKey; } + void setSortKey(unsigned int _sortKey); + void updateSortKey(); }; class SetList : public QList { private: - class CompareFunctor; + class CompareFunctor; public: - void sortByKey(); + void sortByKey(); }; class PictureToLoad { private: - CardInfo *card; - bool stripped; - SetList sortedSets; - int setIndex; - bool hq; + CardInfo *card; + bool stripped; + SetList sortedSets; + int setIndex; + bool hq; public: - PictureToLoad(CardInfo *_card = 0, bool _stripped = false, bool _hq = true); - CardInfo *getCard() const { return card; } - bool getStripped() const { return stripped; } - QString getSetName() const { return sortedSets[setIndex]->getShortName(); } - bool nextSet(); - - bool getHq() const { return hq; } - void setHq(bool _hq) { hq = _hq; } - + PictureToLoad(CardInfo *_card = 0, bool _stripped = false, bool _hq = true); + CardInfo *getCard() const { return card; } + bool getStripped() const { return stripped; } + QString getSetName() const { return sortedSets[setIndex]->getShortName(); } + bool nextSet(); + + bool getHq() const { return hq; } + void setHq(bool _hq) { hq = _hq; } + }; class PictureLoader : public QObject { - Q_OBJECT + Q_OBJECT private: - QString _picsPath; - QList loadQueue; - QMutex mutex; - QNetworkAccessManager *networkManager; - QList cardsToDownload; - PictureToLoad cardBeingDownloaded; - bool picDownload, downloadRunning, loadQueueRunning; - void startNextPicDownload(); + QString _picsPath; + QList loadQueue; + QMutex mutex; + QNetworkAccessManager *networkManager; + QList cardsToDownload; + PictureToLoad cardBeingDownloaded; + bool picDownload, downloadRunning, loadQueueRunning; + void startNextPicDownload(); public: - PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent = 0); - ~PictureLoader(); - void setPicsPath(const QString &path); - void setPicDownload(bool _picDownload); - void loadImage(CardInfo *card, bool stripped); + PictureLoader(const QString &__picsPath, bool _picDownload, QObject *parent = 0); + ~PictureLoader(); + void setPicsPath(const QString &path); + void setPicDownload(bool _picDownload); + void loadImage(CardInfo *card, bool stripped); private slots: - void picDownloadFinished(QNetworkReply *reply); + void picDownloadFinished(QNetworkReply *reply); public slots: - void processLoadQueue(); + void processLoadQueue(); signals: - void startLoadQueue(); - void imageLoaded(CardInfo *card, const QImage &image); + void startLoadQueue(); + void imageLoaded(CardInfo *card, const QImage &image); }; class CardInfo : public QObject { - Q_OBJECT + Q_OBJECT private: - CardDatabase *db; + CardDatabase *db; - QString name; - bool isToken; - SetList sets; - QString manacost; - QString cardtype; - QString powtough; - QString text; - QStringList colors; - int loyalty; - QMap picURLs, picURLsHq, picURLsSt; - bool cipt; - int tableRow; - QPixmap *pixmap; - QMap scaledPixmapCache; + QString name; + bool isToken; + SetList sets; + QString manacost; + QString cardtype; + QString powtough; + QString text; + QStringList colors; + int loyalty; + QMap picURLs, picURLsHq, picURLsSt; + bool cipt; + int tableRow; + QPixmap *pixmap; + QMap scaledPixmapCache; public: - CardInfo(CardDatabase *_db, - const QString &_name = QString(), - bool _isToken = false, - const QString &_manacost = QString(), - const QString &_cardtype = QString(), - const QString &_powtough = QString(), - const QString &_text = QString(), - const QStringList &_colors = QStringList(), - int _loyalty = 0, - bool _cipt = false, - int _tableRow = 0, - const SetList &_sets = SetList(), - const QStringMap &_picURLs = QStringMap(), - const QStringMap &_picURLsHq = QStringMap(), - const QStringMap &_picURLsSt = QStringMap()); - ~CardInfo(); - const QString &getName() const { return name; } - bool getIsToken() const { return isToken; } - const SetList &getSets() const { return sets; } - const QString &getManaCost() const { return manacost; } - const QString &getCardType() const { return cardtype; } - const QString &getPowTough() const { return powtough; } - const QString &getText() const { return text; } - const int &getLoyalty() const { return loyalty; } - bool getCipt() const { return cipt; } - void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); } - void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); } - void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); } - void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); } - void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); } - const QStringList &getColors() const { return colors; } - QString getPicURL(const QString &set) const { return picURLs.value(set); } - QString getPicURLHq(const QString &set) const { return picURLsHq.value(set); } - QString getPicURLSt(const QString &set) const { return picURLsSt.value(set); } - QString getPicURL() const; - const QMap &getPicURLs() const { return picURLs; } - QString getMainCardType() const; - QString getCorrectedName() const; - int getTableRow() const { return tableRow; } - void setTableRow(int _tableRow) { tableRow = _tableRow; } - void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); } - void setPicURL(const QString &_set, const QString &_picURL) { picURLs.insert(_set, _picURL); } - void setPicURLHq(const QString &_set, const QString &_picURL) { picURLsHq.insert(_set, _picURL); } - void setPicURLSt(const QString &_set, const QString &_picURL) { picURLsSt.insert(_set, _picURL); } - void addToSet(CardSet *set); - QPixmap *loadPixmap(); - QPixmap *getPixmap(QSize size); - void clearPixmapCache(); - void clearPixmapCacheMiss(); - void imageLoaded(const QImage &image); + CardInfo(CardDatabase *_db, + const QString &_name = QString(), + bool _isToken = false, + const QString &_manacost = QString(), + const QString &_cardtype = QString(), + const QString &_powtough = QString(), + const QString &_text = QString(), + const QStringList &_colors = QStringList(), + int _loyalty = 0, + bool _cipt = false, + int _tableRow = 0, + const SetList &_sets = SetList(), + const QStringMap &_picURLs = QStringMap(), + const QStringMap &_picURLsHq = QStringMap(), + const QStringMap &_picURLsSt = QStringMap()); + ~CardInfo(); + const QString &getName() const { return name; } + bool getIsToken() const { return isToken; } + const SetList &getSets() const { return sets; } + const QString &getManaCost() const { return manacost; } + const QString &getCardType() const { return cardtype; } + const QString &getPowTough() const { return powtough; } + const QString &getText() const { return text; } + const int &getLoyalty() const { return loyalty; } + bool getCipt() const { return cipt; } + void setManaCost(const QString &_manaCost) { manacost = _manaCost; emit cardInfoChanged(this); } + void setCardType(const QString &_cardType) { cardtype = _cardType; emit cardInfoChanged(this); } + void setPowTough(const QString &_powTough) { powtough = _powTough; emit cardInfoChanged(this); } + void setText(const QString &_text) { text = _text; emit cardInfoChanged(this); } + void setColors(const QStringList &_colors) { colors = _colors; emit cardInfoChanged(this); } + const QStringList &getColors() const { return colors; } + QString getPicURL(const QString &set) const { return picURLs.value(set); } + QString getPicURLHq(const QString &set) const { return picURLsHq.value(set); } + QString getPicURLSt(const QString &set) const { return picURLsSt.value(set); } + QString getPicURL() const; + const QMap &getPicURLs() const { return picURLs; } + QString getMainCardType() const; + QString getCorrectedName() const; + int getTableRow() const { return tableRow; } + void setTableRow(int _tableRow) { tableRow = _tableRow; } + void setLoyalty(int _loyalty) { loyalty = _loyalty; emit cardInfoChanged(this); } + void setPicURL(const QString &_set, const QString &_picURL) { picURLs.insert(_set, _picURL); } + void setPicURLHq(const QString &_set, const QString &_picURL) { picURLsHq.insert(_set, _picURL); } + void setPicURLSt(const QString &_set, const QString &_picURL) { picURLsSt.insert(_set, _picURL); } + void addToSet(CardSet *set); + QPixmap *loadPixmap(); + QPixmap *getPixmap(QSize size); + void clearPixmapCache(); + void clearPixmapCacheMiss(); + void imageLoaded(const QImage &image); public slots: - void updatePixmapCache(); + void updatePixmapCache(); signals: - void pixmapUpdated(); - void cardInfoChanged(CardInfo *card); + void pixmapUpdated(); + void cardInfoChanged(CardInfo *card); }; class CardDatabase : public QObject { - Q_OBJECT + Q_OBJECT protected: - QHash cardHash; - QHash setHash; - bool loadSuccess; - CardInfo *noCard; - - QThread *pictureLoaderThread; - PictureLoader *pictureLoader; + QHash cardHash; + QHash setHash; + bool loadSuccess; + CardInfo *noCard; + + QThread *pictureLoaderThread; + PictureLoader *pictureLoader; private: - static const int versionNeeded; - void loadCardsFromXml(QXmlStreamReader &xml); - void loadSetsFromXml(QXmlStreamReader &xml); + static const int versionNeeded; + void loadCardsFromXml(QXmlStreamReader &xml); + void loadSetsFromXml(QXmlStreamReader &xml); public: - CardDatabase(QObject *parent = 0); - ~CardDatabase(); - void clear(); - void addCard(CardInfo *card); - void removeCard(CardInfo *card); - CardInfo *getCard(const QString &cardName = QString(), bool createIfNotFound = true); - CardSet *getSet(const QString &setName); - QList getCardList() const { return cardHash.values(); } - SetList getSetList() const; - bool loadFromFile(const QString &fileName, bool tokens = false); - bool saveToFile(const QString &fileName, bool tokens = false); - QStringList getAllColors() const; - QStringList getAllMainCardTypes() const; - bool getLoadSuccess() const { return loadSuccess; } - void cacheCardPixmaps(const QStringList &cardNames); - void loadImage(CardInfo *card); + CardDatabase(QObject *parent = 0); + ~CardDatabase(); + void clear(); + void addCard(CardInfo *card); + void removeCard(CardInfo *card); + CardInfo *getCard(const QString &cardName = QString(), bool createIfNotFound = true); + CardSet *getSet(const QString &setName); + QList getCardList() const { return cardHash.values(); } + SetList getSetList() const; + bool loadFromFile(const QString &fileName, bool tokens = false); + bool saveToFile(const QString &fileName, bool tokens = false); + QStringList getAllColors() const; + QStringList getAllMainCardTypes() const; + bool getLoadSuccess() const { return loadSuccess; } + void cacheCardPixmaps(const QStringList &cardNames); + void loadImage(CardInfo *card); public slots: - void clearPixmapCache(); - bool loadCardDatabase(const QString &path, bool tokens = false); + void clearPixmapCache(); + bool loadCardDatabase(const QString &path, bool tokens = false); private slots: - void imageLoaded(CardInfo *card, QImage image); - void picDownloadChanged(); - void picsPathChanged(); - - void loadCardDatabase(); - void loadTokenDatabase(); + void imageLoaded(CardInfo *card, QImage image); + void picDownloadChanged(); + void picsPathChanged(); + + void loadCardDatabase(); + void loadTokenDatabase(); signals: - void cardListChanged(); - void cardAdded(CardInfo *card); - void cardRemoved(CardInfo *card); + void cardListChanged(); + void cardAdded(CardInfo *card); + void cardRemoved(CardInfo *card); }; #endif diff --git a/cockatrice/src/carddatabasemodel.cpp b/cockatrice/src/carddatabasemodel.cpp index 0abdf70a..e62664be 100644 --- a/cockatrice/src/carddatabasemodel.cpp +++ b/cockatrice/src/carddatabasemodel.cpp @@ -118,7 +118,6 @@ CardDatabaseDisplayModel::CardDatabaseDisplayModel(QObject *parent) bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { CardInfo const *info = static_cast(sourceModel())->getCard(sourceRow); - if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken())) return false; diff --git a/cockatrice/src/carddragitem.cpp b/cockatrice/src/carddragitem.cpp index 8df7790b..0ddb9109 100644 --- a/cockatrice/src/carddragitem.cpp +++ b/cockatrice/src/carddragitem.cpp @@ -9,82 +9,82 @@ #include CardDragItem::CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag) - : AbstractCardDragItem(_item, _hotSpot, parentDrag), id(_id), faceDown(_faceDown), occupied(false), currentZone(0) + : AbstractCardDragItem(_item, _hotSpot, parentDrag), id(_id), faceDown(_faceDown), occupied(false), currentZone(0) { } void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - AbstractCardDragItem::paint(painter, option, widget); - - if (occupied) - painter->fillRect(boundingRect(), QColor(200, 0, 0, 100)); + AbstractCardDragItem::paint(painter, option, widget); + + if (occupied) + painter->fillRect(boundingRect(), QColor(200, 0, 0, 100)); } void CardDragItem::updatePosition(const QPointF &cursorScenePos) { - QList colliding = scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, static_cast(scene())->getViewTransform()); + QList colliding = scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, static_cast(scene())->getViewTransform()); - CardZone *cardZone = 0; - ZoneViewZone *zoneViewZone = 0; - for (int i = colliding.size() - 1; i >= 0; i--) { - CardZone *temp = qgraphicsitem_cast(colliding.at(i)); - if (!cardZone) - cardZone = temp; - if (!zoneViewZone) - zoneViewZone = qobject_cast(temp); - } - CardZone *cursorZone = 0; - if (zoneViewZone) - cursorZone = zoneViewZone; - else if (cardZone) - cursorZone = cardZone; - if (!cursorZone) - return; - currentZone = cursorZone; - - QPointF zonePos = currentZone->scenePos(); - QPointF cursorPosInZone = cursorScenePos - zonePos; - QPointF cardTopLeft = cursorPosInZone - hotSpot; - QPointF closestGridPoint = cursorZone->closestGridPoint(cardTopLeft); - QPointF newPos = zonePos + closestGridPoint; - - if (newPos != pos()) { - for (int i = 0; i < childDrags.size(); i++) - childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); - setPos(newPos); - - bool newOccupied = false; - TableZone *table = qobject_cast(cursorZone); - if (table) - if (table->getCardFromCoords(closestGridPoint)) - newOccupied = true; - if (newOccupied != occupied) { - occupied = newOccupied; - update(); - } - } + CardZone *cardZone = 0; + ZoneViewZone *zoneViewZone = 0; + for (int i = colliding.size() - 1; i >= 0; i--) { + CardZone *temp = qgraphicsitem_cast(colliding.at(i)); + if (!cardZone) + cardZone = temp; + if (!zoneViewZone) + zoneViewZone = qobject_cast(temp); + } + CardZone *cursorZone = 0; + if (zoneViewZone) + cursorZone = zoneViewZone; + else if (cardZone) + cursorZone = cardZone; + if (!cursorZone) + return; + currentZone = cursorZone; + + QPointF zonePos = currentZone->scenePos(); + QPointF cursorPosInZone = cursorScenePos - zonePos; + QPointF cardTopLeft = cursorPosInZone - hotSpot; + QPointF closestGridPoint = cursorZone->closestGridPoint(cardTopLeft); + QPointF newPos = zonePos + closestGridPoint; + + if (newPos != pos()) { + for (int i = 0; i < childDrags.size(); i++) + childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); + setPos(newPos); + + bool newOccupied = false; + TableZone *table = qobject_cast(cursorZone); + if (table) + if (table->getCardFromCoords(closestGridPoint)) + newOccupied = true; + if (newOccupied != occupied) { + occupied = newOccupied; + update(); + } + } } void CardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - setCursor(Qt::OpenHandCursor); - QGraphicsScene *sc = scene(); - QPointF sp = pos(); - sc->removeItem(this); + setCursor(Qt::OpenHandCursor); + QGraphicsScene *sc = scene(); + QPointF sp = pos(); + sc->removeItem(this); - QList dragItemList; - CardZone *startZone = static_cast(item)->getZone(); - if (currentZone && !(static_cast(item)->getAttachedTo() && (startZone == currentZone))) { - dragItemList.append(this); - for (int i = 0; i < childDrags.size(); i++) { - CardDragItem *c = static_cast(childDrags[i]); - if (!(static_cast(c->item)->getAttachedTo() && (startZone == currentZone)) && !c->occupied) - dragItemList.append(c); - sc->removeItem(c); - } - } - currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint()); + QList dragItemList; + CardZone *startZone = static_cast(item)->getZone(); + if (currentZone && !(static_cast(item)->getAttachedTo() && (startZone == currentZone))) { + dragItemList.append(this); + for (int i = 0; i < childDrags.size(); i++) { + CardDragItem *c = static_cast(childDrags[i]); + if (!(static_cast(c->item)->getAttachedTo() && (startZone == currentZone)) && !c->occupied) + dragItemList.append(c); + sc->removeItem(c); + } + } + currentZone->handleDropEvent(dragItemList, startZone, (sp - currentZone->scenePos()).toPoint()); - event->accept(); + event->accept(); } diff --git a/cockatrice/src/carddragitem.h b/cockatrice/src/carddragitem.h index eec2f487..ea81998f 100644 --- a/cockatrice/src/carddragitem.h +++ b/cockatrice/src/carddragitem.h @@ -6,20 +6,20 @@ class CardItem; class CardDragItem : public AbstractCardDragItem { - Q_OBJECT + Q_OBJECT private: - int id; - bool faceDown; - bool occupied; - CardZone *currentZone; + int id; + bool faceDown; + bool occupied; + CardZone *currentZone; public: - CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag = 0); - int getId() const { return id; } - bool getFaceDown() const { return faceDown; } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void updatePosition(const QPointF &cursorScenePos); + CardDragItem(CardItem *_item, int _id, const QPointF &_hotSpot, bool _faceDown, AbstractCardDragItem *parentDrag = 0); + int getId() const { return id; } + bool getFaceDown() const { return faceDown; } + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void updatePosition(const QPointF &cursorScenePos); protected: - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; #endif diff --git a/cockatrice/src/cardinfowidget.cpp b/cockatrice/src/cardinfowidget.cpp index e0ad1b7e..6b5e995a 100644 --- a/cockatrice/src/cardinfowidget.cpp +++ b/cockatrice/src/cardinfowidget.cpp @@ -12,209 +12,209 @@ #include "settingscache.h" CardInfoWidget::CardInfoWidget(ResizeMode _mode, const QString &cardName, QWidget *parent, Qt::WindowFlags flags) - : QFrame(parent, flags) - , pixmapWidth(0) - , aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH) - , minimized(settingsCache->getCardInfoMinimized()) // Initialize the cardinfo view status from cache. - , mode(_mode) - , info(0) + : QFrame(parent, flags) + , pixmapWidth(0) + , aspectRatio((qreal) CARD_HEIGHT / (qreal) CARD_WIDTH) + , minimized(settingsCache->getCardInfoMinimized()) // Initialize the cardinfo view status from cache. + , mode(_mode) + , info(0) { - if (mode == ModeGameTab) { - // Create indexed list of status views for card. - const QStringList cardInfoStatus = QStringList() << tr("Show card only") << tr("Show text only") << tr("Show full info"); - - // Create droplist for cardinfo view selection, and set right current index. - dropList = new QComboBox(); - dropList->addItems(cardInfoStatus); - dropList->setCurrentIndex(minimized); - connect(dropList, SIGNAL(currentIndexChanged(int)), this, SLOT(minimizeClicked(int))); - } + if (mode == ModeGameTab) { + // Create indexed list of status views for card. + const QStringList cardInfoStatus = QStringList() << tr("Show card only") << tr("Show text only") << tr("Show full info"); + + // Create droplist for cardinfo view selection, and set right current index. + dropList = new QComboBox(); + dropList->addItems(cardInfoStatus); + dropList->setCurrentIndex(minimized); + connect(dropList, SIGNAL(currentIndexChanged(int)), this, SLOT(minimizeClicked(int))); + } - cardPicture = new QLabel; - cardPicture->setAlignment(Qt::AlignCenter); + cardPicture = new QLabel; + cardPicture->setAlignment(Qt::AlignCenter); - nameLabel1 = new QLabel; - nameLabel2 = new QLabel; - nameLabel2->setWordWrap(true); - manacostLabel1 = new QLabel; - manacostLabel2 = new QLabel; - manacostLabel2->setWordWrap(true); - cardtypeLabel1 = new QLabel; - cardtypeLabel2 = new QLabel; - cardtypeLabel2->setWordWrap(true); - powtoughLabel1 = new QLabel; - powtoughLabel2 = new QLabel; - loyaltyLabel1 = new QLabel; - loyaltyLabel2 = new QLabel; + nameLabel1 = new QLabel; + nameLabel2 = new QLabel; + nameLabel2->setWordWrap(true); + manacostLabel1 = new QLabel; + manacostLabel2 = new QLabel; + manacostLabel2->setWordWrap(true); + cardtypeLabel1 = new QLabel; + cardtypeLabel2 = new QLabel; + cardtypeLabel2->setWordWrap(true); + powtoughLabel1 = new QLabel; + powtoughLabel2 = new QLabel; + loyaltyLabel1 = new QLabel; + loyaltyLabel2 = new QLabel; - textLabel = new QTextEdit(); - textLabel->setReadOnly(true); + textLabel = new QTextEdit(); + textLabel->setReadOnly(true); - QGridLayout *grid = new QGridLayout(this); - int row = 0; - if (mode == ModeGameTab) - grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight); - grid->addWidget(cardPicture, row++, 0, 1, 2); - grid->addWidget(nameLabel1, row, 0); - grid->addWidget(nameLabel2, row++, 1); - grid->addWidget(manacostLabel1, row, 0); - grid->addWidget(manacostLabel2, row++, 1); - grid->addWidget(cardtypeLabel1, row, 0); - grid->addWidget(cardtypeLabel2, row++, 1); - grid->addWidget(powtoughLabel1, row, 0); - grid->addWidget(powtoughLabel2, row++, 1); - grid->addWidget(loyaltyLabel1, row, 0); - grid->addWidget(loyaltyLabel2, row++, 1); - grid->addWidget(textLabel, row, 0, -1, 2); - grid->setRowStretch(row, 1); - grid->setColumnStretch(1, 1); + QGridLayout *grid = new QGridLayout(this); + int row = 0; + if (mode == ModeGameTab) + grid->addWidget(dropList, row++, 1, 1, 1, Qt::AlignRight); + grid->addWidget(cardPicture, row++, 0, 1, 2); + grid->addWidget(nameLabel1, row, 0); + grid->addWidget(nameLabel2, row++, 1); + grid->addWidget(manacostLabel1, row, 0); + grid->addWidget(manacostLabel2, row++, 1); + grid->addWidget(cardtypeLabel1, row, 0); + grid->addWidget(cardtypeLabel2, row++, 1); + grid->addWidget(powtoughLabel1, row, 0); + grid->addWidget(powtoughLabel2, row++, 1); + grid->addWidget(loyaltyLabel1, row, 0); + grid->addWidget(loyaltyLabel2, row++, 1); + grid->addWidget(textLabel, row, 0, -1, 2); + grid->setRowStretch(row, 1); + grid->setColumnStretch(1, 1); - retranslateUi(); - setFrameStyle(QFrame::Panel | QFrame::Raised); - if (mode == ModeGameTab) { - textLabel->setMinimumHeight(100); - setFixedWidth(sizeHint().width()); - } else if (mode == ModePopUp) { - QDesktopWidget desktopWidget; - pixmapWidth = desktopWidget.screenGeometry().height() / 3 / aspectRatio; - setFixedWidth(pixmapWidth + 150); - } else - setFixedWidth(250); - - setCard(db->getCard(cardName)); - setMinimized(settingsCache->getCardInfoMinimized()); + retranslateUi(); + setFrameStyle(QFrame::Panel | QFrame::Raised); + if (mode == ModeGameTab) { + textLabel->setMinimumHeight(100); + setFixedWidth(sizeHint().width()); + } else if (mode == ModePopUp) { + QDesktopWidget desktopWidget; + pixmapWidth = desktopWidget.screenGeometry().height() / 3 / aspectRatio; + setFixedWidth(pixmapWidth + 150); + } else + setFixedWidth(250); + + setCard(db->getCard(cardName)); + setMinimized(settingsCache->getCardInfoMinimized()); } void CardInfoWidget::minimizeClicked(int newMinimized) { - // Set new status, and store it in the settings cache. - setMinimized(newMinimized); - settingsCache->setCardInfoMinimized(newMinimized); + // Set new status, and store it in the settings cache. + setMinimized(newMinimized); + settingsCache->setCardInfoMinimized(newMinimized); } bool CardInfoWidget::shouldShowPowTough() { -// return (!info->getPowTough().isEmpty() && (minimized != 0)); - return (minimized != 0); +// return (!info->getPowTough().isEmpty() && (minimized != 0)); + return (minimized != 0); } bool CardInfoWidget::shouldShowLoyalty() { -// return ((info->getLoyalty() > 0) && (minimized != 0)); - return (minimized != 0); +// return ((info->getLoyalty() > 0) && (minimized != 0)); + return (minimized != 0); } void CardInfoWidget::setMinimized(int _minimized) { - minimized = _minimized; + minimized = _minimized; - // Toggle oracle fields according to selected view. - bool showAll = ((minimized == 1) || (minimized == 2)); - bool showPowTough = info ? (showAll && shouldShowPowTough()) : true; - bool showLoyalty = info ? (showAll && shouldShowLoyalty()) : true; - if (mode == ModeGameTab) { - nameLabel1->setVisible(showAll); - nameLabel2->setVisible(showAll); - manacostLabel1->setVisible(showAll); - manacostLabel2->setVisible(showAll); - cardtypeLabel1->setVisible(showAll); - cardtypeLabel2->setVisible(showAll); - powtoughLabel1->setVisible(showPowTough); - powtoughLabel2->setVisible(showPowTough); - loyaltyLabel1->setVisible(showLoyalty); - loyaltyLabel2->setVisible(showLoyalty); - textLabel->setVisible(showAll); - } + // Toggle oracle fields according to selected view. + bool showAll = ((minimized == 1) || (minimized == 2)); + bool showPowTough = info ? (showAll && shouldShowPowTough()) : true; + bool showLoyalty = info ? (showAll && shouldShowLoyalty()) : true; + if (mode == ModeGameTab) { + nameLabel1->setVisible(showAll); + nameLabel2->setVisible(showAll); + manacostLabel1->setVisible(showAll); + manacostLabel2->setVisible(showAll); + cardtypeLabel1->setVisible(showAll); + cardtypeLabel2->setVisible(showAll); + powtoughLabel1->setVisible(showPowTough); + powtoughLabel2->setVisible(showPowTough); + loyaltyLabel1->setVisible(showLoyalty); + loyaltyLabel2->setVisible(showLoyalty); + textLabel->setVisible(showAll); + } - cardPicture->hide(); - cardHeightOffset = minimumSizeHint().height() + 10; - - // Set the picture to be shown only at "card only" (0) and "full info" (2) - if (mode == ModeGameTab) { - cardPicture->setVisible((minimized == 0) || (minimized == 2)); + cardPicture->hide(); + cardHeightOffset = minimumSizeHint().height() + 10; + + // Set the picture to be shown only at "card only" (0) and "full info" (2) + if (mode == ModeGameTab) { + cardPicture->setVisible((minimized == 0) || (minimized == 2)); - if (minimized == 0) - setMaximumHeight(cardHeightOffset + width() * aspectRatio); - else - setMaximumHeight(1000000); - } else - cardPicture->show(); - resize(width(), sizeHint().height()); + if (minimized == 0) + setMaximumHeight(cardHeightOffset + width() * aspectRatio); + else + setMaximumHeight(1000000); + } else + cardPicture->show(); + resize(width(), sizeHint().height()); } void CardInfoWidget::setCard(CardInfo *card) { - if (info) - disconnect(info, 0, this, 0); - info = card; - connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); - connect(info, SIGNAL(destroyed()), this, SLOT(clear())); + if (info) + disconnect(info, 0, this, 0); + info = card; + connect(info, SIGNAL(pixmapUpdated()), this, SLOT(updatePixmap())); + connect(info, SIGNAL(destroyed()), this, SLOT(clear())); - updatePixmap(); - nameLabel2->setText(card->getName()); - manacostLabel2->setText(card->getManaCost()); - cardtypeLabel2->setText(card->getCardType()); - powtoughLabel2->setText(card->getPowTough()); - loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); - textLabel->setText(card->getText()); + updatePixmap(); + nameLabel2->setText(card->getName()); + manacostLabel2->setText(card->getManaCost()); + cardtypeLabel2->setText(card->getCardType()); + powtoughLabel2->setText(card->getPowTough()); + loyaltyLabel2->setText(card->getLoyalty() > 0 ? QString::number(card->getLoyalty()) : QString()); + textLabel->setText(card->getText()); - powtoughLabel1->setVisible(shouldShowPowTough()); - powtoughLabel2->setVisible(shouldShowPowTough()); - loyaltyLabel1->setVisible(shouldShowLoyalty()); - loyaltyLabel2->setVisible(shouldShowLoyalty()); + powtoughLabel1->setVisible(shouldShowPowTough()); + powtoughLabel2->setVisible(shouldShowPowTough()); + loyaltyLabel1->setVisible(shouldShowLoyalty()); + loyaltyLabel2->setVisible(shouldShowLoyalty()); } void CardInfoWidget::setCard(const QString &cardName) { - setCard(db->getCard(cardName)); + setCard(db->getCard(cardName)); } void CardInfoWidget::setCard(AbstractCardItem *card) { - setCard(card->getInfo()); + setCard(card->getInfo()); } void CardInfoWidget::clear() { - setCard(db->getCard()); + setCard(db->getCard()); } void CardInfoWidget::updatePixmap() { - if (pixmapWidth == 0) - return; - - QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); - if (resizedPixmap) - cardPicture->setPixmap(*resizedPixmap); - else - cardPicture->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); + if (pixmapWidth == 0) + return; + + QPixmap *resizedPixmap = info->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)); + if (resizedPixmap) + cardPicture->setPixmap(*resizedPixmap); + else + cardPicture->setPixmap(*(db->getCard()->getPixmap(QSize(pixmapWidth, pixmapWidth * aspectRatio)))); } void CardInfoWidget::retranslateUi() { - nameLabel1->setText(tr("Name:")); - manacostLabel1->setText(tr("Mana cost:")); - cardtypeLabel1->setText(tr("Card type:")); - powtoughLabel1->setText(tr("P / T:")); - loyaltyLabel1->setText(tr("Loyalty:")); + nameLabel1->setText(tr("Name:")); + manacostLabel1->setText(tr("Mana cost:")); + cardtypeLabel1->setText(tr("Card type:")); + powtoughLabel1->setText(tr("P / T:")); + loyaltyLabel1->setText(tr("Loyalty:")); } void CardInfoWidget::resizeEvent(QResizeEvent * /*event*/) { - if (mode == ModePopUp) - return; - if ((minimized == 1) && (mode == ModeGameTab)) { - pixmapWidth = 0; - return; - } - qreal newPixmapWidth = qMax((qreal) 100.0, qMin((qreal) cardPicture->width(), (qreal) ((height() - cardHeightOffset) / aspectRatio))); - if (newPixmapWidth != pixmapWidth) { - pixmapWidth = newPixmapWidth; - updatePixmap(); - } + if (mode == ModePopUp) + return; + if ((minimized == 1) && (mode == ModeGameTab)) { + pixmapWidth = 0; + return; + } + qreal newPixmapWidth = qMax((qreal) 100.0, qMin((qreal) cardPicture->width(), (qreal) ((height() - cardHeightOffset) / aspectRatio))); + if (newPixmapWidth != pixmapWidth) { + pixmapWidth = newPixmapWidth; + updatePixmap(); + } } QString CardInfoWidget::getCardName() const { - return nameLabel2->text(); + return nameLabel2->text(); } diff --git a/cockatrice/src/cardinfowidget.h b/cockatrice/src/cardinfowidget.h index f04395b3..ecfd6eca 100644 --- a/cockatrice/src/cardinfowidget.h +++ b/cockatrice/src/cardinfowidget.h @@ -14,51 +14,51 @@ class QResizeEvent; class QMouseEvent; class CardInfoWidget : public QFrame { - Q_OBJECT + Q_OBJECT public: - enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp }; + enum ResizeMode { ModeDeckEditor, ModeGameTab, ModePopUp }; private: - int pixmapWidth; - qreal cardHeightOffset; - qreal aspectRatio; - // XXX: Why isn't this an eunm? - int minimized; // 0 - card, 1 - oracle only, 2 - full - ResizeMode mode; + int pixmapWidth; + qreal cardHeightOffset; + qreal aspectRatio; + // XXX: Why isn't this an eunm? + int minimized; // 0 - card, 1 - oracle only, 2 - full + ResizeMode mode; - QComboBox *dropList; - QLabel *cardPicture; - QLabel *nameLabel1, *nameLabel2; - QLabel *manacostLabel1, *manacostLabel2; - QLabel *cardtypeLabel1, *cardtypeLabel2; - QLabel *powtoughLabel1, *powtoughLabel2; - QLabel *loyaltyLabel1, *loyaltyLabel2; - QTextEdit *textLabel; + QComboBox *dropList; + QLabel *cardPicture; + QLabel *nameLabel1, *nameLabel2; + QLabel *manacostLabel1, *manacostLabel2; + QLabel *cardtypeLabel1, *cardtypeLabel2; + QLabel *powtoughLabel1, *powtoughLabel2; + QLabel *loyaltyLabel1, *loyaltyLabel2; + QTextEdit *textLabel; - bool shouldShowPowTough(); - bool shouldShowLoyalty(); + bool shouldShowPowTough(); + bool shouldShowLoyalty(); - CardInfo *info; - void setMinimized(int _minimized); + CardInfo *info; + void setMinimized(int _minimized); public: - CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0); - void retranslateUi(); - QString getCardName() const; + CardInfoWidget(ResizeMode _mode, const QString &cardName = QString(), QWidget *parent = 0, Qt::WindowFlags f = 0); + void retranslateUi(); + QString getCardName() const; public slots: - void setCard(CardInfo *card); - void setCard(const QString &cardName); - void setCard(AbstractCardItem *card); + void setCard(CardInfo *card); + void setCard(const QString &cardName); + void setCard(AbstractCardItem *card); private slots: - void clear(); - void updatePixmap(); - void minimizeClicked(int newMinimized); + void clear(); + void updatePixmap(); + void minimizeClicked(int newMinimized); protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); }; #endif diff --git a/cockatrice/src/carditem.cpp b/cockatrice/src/carditem.cpp index a6696198..a6b582ad 100644 --- a/cockatrice/src/carditem.cpp +++ b/cockatrice/src/carditem.cpp @@ -18,374 +18,374 @@ #include "pb/serverinfo_card.pb.h" 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); - - cardMenu = new QMenu; - ptMenu = new QMenu; - moveMenu = new QMenu; - - retranslateUi(); - emit updateCardMenu(this); + owner->addCard(this); + + cardMenu = new QMenu; + ptMenu = new QMenu; + moveMenu = new QMenu; + + retranslateUi(); + emit updateCardMenu(this); } CardItem::~CardItem() { - prepareDelete(); - - if (scene()) - static_cast(scene())->unregisterAnimationItem(this); - - delete cardMenu; - delete ptMenu; - delete moveMenu; - - deleteDragItem(); + prepareDelete(); + + if (scene()) + static_cast(scene())->unregisterAnimationItem(this); + + delete cardMenu; + delete ptMenu; + delete moveMenu; + + deleteDragItem(); } void CardItem::prepareDelete() { - if (owner) { - if (owner->getCardMenu() == cardMenu) { - owner->setCardMenu(0); - owner->getGame()->setActiveCard(0); - } - owner = 0; - } - - while (!attachedCards.isEmpty()) { - attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards() - attachedCards.first()->setAttachedTo(0); - } - - if (attachedTo) { - attachedTo->removeAttachedCard(this); - attachedTo = 0; - } + if (owner) { + if (owner->getCardMenu() == cardMenu) { + owner->setCardMenu(0); + owner->getGame()->setActiveCard(0); + } + owner = 0; + } + + while (!attachedCards.isEmpty()) { + attachedCards.first()->setZone(0); // so that it won't try to call reorganizeCards() + attachedCards.first()->setAttachedTo(0); + } + + if (attachedTo) { + attachedTo->removeAttachedCard(this); + attachedTo = 0; + } } void CardItem::deleteLater() { - prepareDelete(); - AbstractCardItem::deleteLater(); + prepareDelete(); + AbstractCardItem::deleteLater(); } void CardItem::setZone(CardZone *_zone) { - zone = _zone; - emit updateCardMenu(this); + zone = _zone; + emit updateCardMenu(this); } void CardItem::retranslateUi() { - moveMenu->setTitle(tr("&Move to")); - ptMenu->setTitle(tr("&Power / toughness")); + moveMenu->setTitle(tr("&Move to")); + ptMenu->setTitle(tr("&Power / toughness")); } void CardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - painter->save(); - AbstractCardItem::paint(painter, option, widget); - - int i = 0; - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) { - counterIterator.next(); - QColor color; - color.setHsv(counterIterator.key() * 60, 150, 255); - - paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter); - ++i; - } - - QSizeF translatedSize = getTranslatedSize(painter); - qreal scaleFactor = translatedSize.width() / boundingRect().width(); - - if (!pt.isEmpty()) { - painter->save(); - - transformPainter(painter, translatedSize, tapAngle); - painter->setBackground(Qt::black); - painter->setBackgroundMode(Qt::OpaqueMode); - 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->restore(); - } - if (!annotation.isEmpty()) { - painter->save(); + painter->save(); + AbstractCardItem::paint(painter, option, widget); + + int i = 0; + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) { + counterIterator.next(); + QColor color; + color.setHsv(counterIterator.key() * 60, 150, 255); + + paintNumberEllipse(counterIterator.value(), 14, color, i, counters.size(), painter); + ++i; + } + + QSizeF translatedSize = getTranslatedSize(painter); + qreal scaleFactor = translatedSize.width() / boundingRect().width(); + + if (!pt.isEmpty()) { + painter->save(); + + transformPainter(painter, translatedSize, tapAngle); + painter->setBackground(Qt::black); + painter->setBackgroundMode(Qt::OpaqueMode); + 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->restore(); + } + if (!annotation.isEmpty()) { + painter->save(); - transformPainter(painter, translatedSize, tapAngle); - painter->setBackground(Qt::black); - painter->setBackgroundMode(Qt::OpaqueMode); - 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->restore(); - } - if (getBeingPointedAt()) - painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); - painter->restore(); + transformPainter(painter, translatedSize, tapAngle); + painter->setBackground(Qt::black); + painter->setBackgroundMode(Qt::OpaqueMode); + 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->restore(); + } + if (getBeingPointedAt()) + painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); + painter->restore(); } void CardItem::setAttacking(bool _attacking) { - attacking = _attacking; - update(); + attacking = _attacking; + update(); } void CardItem::setCounter(int _id, int _value) { - if (_value) - counters.insert(_id, _value); - else - counters.remove(_id); - update(); + if (_value) + counters.insert(_id, _value); + else + counters.remove(_id); + update(); } void CardItem::setAnnotation(const QString &_annotation) { - annotation = _annotation; - update(); + annotation = _annotation; + update(); } void CardItem::setDoesntUntap(bool _doesntUntap) { - doesntUntap = _doesntUntap; + doesntUntap = _doesntUntap; } void CardItem::setPT(const QString &_pt) { - pt = _pt; - update(); + pt = _pt; + update(); } void CardItem::setAttachedTo(CardItem *_attachedTo) { - if (attachedTo) - attachedTo->removeAttachedCard(this); - - gridPoint.setX(-1); - attachedTo = _attachedTo; - if (attachedTo) { - setParentItem(attachedTo->getZone()); - attachedTo->addAttachedCard(this); - if (zone != attachedTo->getZone()) - attachedTo->getZone()->reorganizeCards(); - } else - setParentItem(zone); + if (attachedTo) + attachedTo->removeAttachedCard(this); + + gridPoint.setX(-1); + attachedTo = _attachedTo; + if (attachedTo) { + setParentItem(attachedTo->getZone()); + attachedTo->addAttachedCard(this); + if (zone != attachedTo->getZone()) + attachedTo->getZone()->reorganizeCards(); + } else + setParentItem(zone); - if (zone) - zone->reorganizeCards(); - - emit updateCardMenu(this); + if (zone) + zone->reorganizeCards(); + + emit updateCardMenu(this); } void CardItem::resetState() { - attacking = false; - facedown = false; - counters.clear(); - pt.clear(); - annotation.clear(); - attachedTo = 0; - attachedCards.clear(); - setTapped(false, false); - setDoesntUntap(false); - if (scene()) - static_cast(scene())->unregisterAnimationItem(this); - update(); + attacking = false; + facedown = false; + counters.clear(); + pt.clear(); + annotation.clear(); + attachedTo = 0; + attachedCards.clear(); + setTapped(false, false); + setDoesntUntap(false); + if (scene()) + static_cast(scene())->unregisterAnimationItem(this); + update(); } void CardItem::processCardInfo(const ServerInfo_Card &info) { - counters.clear(); - const int counterListSize = info.counter_list_size(); - for (int i = 0; i < counterListSize; ++i) { - const ServerInfo_CardCounter &counterInfo = info.counter_list(i); - counters.insert(counterInfo.id(), counterInfo.value()); - } - - setId(info.id()); - setName(QString::fromStdString(info.name())); - setAttacking(info.attacking()); - setFaceDown(info.face_down()); - setPT(QString::fromStdString(info.pt())); - setAnnotation(QString::fromStdString(info.annotation())); - setColor(QString::fromStdString(info.color())); - setTapped(info.tapped()); - setDestroyOnZoneChange(info.destroy_on_zone_change()); - setDoesntUntap(info.doesnt_untap()); + counters.clear(); + const int counterListSize = info.counter_list_size(); + for (int i = 0; i < counterListSize; ++i) { + const ServerInfo_CardCounter &counterInfo = info.counter_list(i); + counters.insert(counterInfo.id(), counterInfo.value()); + } + + setId(info.id()); + setName(QString::fromStdString(info.name())); + setAttacking(info.attacking()); + setFaceDown(info.face_down()); + setPT(QString::fromStdString(info.pt())); + setAnnotation(QString::fromStdString(info.annotation())); + setColor(QString::fromStdString(info.color())); + setTapped(info.tapped()); + setDestroyOnZoneChange(info.destroy_on_zone_change()); + setDoesntUntap(info.doesnt_untap()); } CardDragItem *CardItem::createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown) { - deleteDragItem(); - dragItem = new CardDragItem(this, _id, _pos, faceDown); - dragItem->setVisible(false); - scene()->addItem(dragItem); - dragItem->updatePosition(_scenePos); - dragItem->setVisible(true); + deleteDragItem(); + dragItem = new CardDragItem(this, _id, _pos, faceDown); + dragItem->setVisible(false); + scene()->addItem(dragItem); + dragItem->updatePosition(_scenePos); + dragItem->setVisible(true); - return dragItem; + return dragItem; } void CardItem::deleteDragItem() { - dragItem->deleteLater(); - dragItem = NULL; + dragItem->deleteLater(); + dragItem = NULL; } void CardItem::drawArrow(const QColor &arrowColor) { - if (static_cast(owner->parent())->getSpectator()) - return; - - Player *arrowOwner = static_cast(owner->parent())->getActiveLocalPlayer(); - ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor); - scene()->addItem(arrow); - arrow->grabMouse(); - - QListIterator itemIterator(scene()->selectedItems()); - while (itemIterator.hasNext()) { - CardItem *c = qgraphicsitem_cast(itemIterator.next()); - if (!c || (c == this)) - continue; - if (c->getZone() != zone) - continue; - - ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor); - scene()->addItem(childArrow); - arrow->addChildArrow(childArrow); - } + if (static_cast(owner->parent())->getSpectator()) + return; + + Player *arrowOwner = static_cast(owner->parent())->getActiveLocalPlayer(); + ArrowDragItem *arrow = new ArrowDragItem(arrowOwner, this, arrowColor); + scene()->addItem(arrow); + arrow->grabMouse(); + + QListIterator itemIterator(scene()->selectedItems()); + while (itemIterator.hasNext()) { + CardItem *c = qgraphicsitem_cast(itemIterator.next()); + if (!c || (c == this)) + continue; + if (c->getZone() != zone) + continue; + + ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, c, arrowColor); + scene()->addItem(childArrow); + arrow->addChildArrow(childArrow); + } } void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (event->buttons().testFlag(Qt::RightButton)) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance()) - return; - - QColor arrowColor = Qt::red; - if (event->modifiers().testFlag(Qt::ControlModifier)) - arrowColor = Qt::yellow; - else if (event->modifiers().testFlag(Qt::AltModifier)) - arrowColor = Qt::blue; - else if (event->modifiers().testFlag(Qt::ShiftModifier)) - arrowColor = Qt::green; - - drawArrow(arrowColor); - } else if (event->buttons().testFlag(Qt::LeftButton)) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) - return; - if (zone->getIsView()) { - const ZoneViewZone *const view = static_cast(zone); - if (view->getRevealZone() && !view->getWriteableRevealZone()) - return; - } else if (!owner->getLocal()) - return; - - bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier); - - createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown); - dragItem->grabMouse(); - - QList sel = scene()->selectedItems(); - int j = 0; - for (int i = 0; i < sel.size(); i++) { - CardItem *c = (CardItem *) sel.at(i); - if ((c == this) || (c->getZone() != zone)) - continue; - ++j; - QPointF childPos; - if (zone->getHasCardAttr()) - childPos = c->pos() - pos(); - else - childPos = QPointF(j * CARD_WIDTH / 2, 0); - CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem); - drag->setPos(dragItem->pos() + childPos); - scene()->addItem(drag); - } - } - setCursor(Qt::OpenHandCursor); + if (event->buttons().testFlag(Qt::RightButton)) { + if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + return; + + QColor arrowColor = Qt::red; + if (event->modifiers().testFlag(Qt::ControlModifier)) + arrowColor = Qt::yellow; + else if (event->modifiers().testFlag(Qt::AltModifier)) + arrowColor = Qt::blue; + else if (event->modifiers().testFlag(Qt::ShiftModifier)) + arrowColor = Qt::green; + + drawArrow(arrowColor); + } else if (event->buttons().testFlag(Qt::LeftButton)) { + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + return; + if (zone->getIsView()) { + const ZoneViewZone *const view = static_cast(zone); + if (view->getRevealZone() && !view->getWriteableRevealZone()) + return; + } else if (!owner->getLocal()) + return; + + bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier); + + createDragItem(id, event->pos(), event->scenePos(), facedown || forceFaceDown); + dragItem->grabMouse(); + + QList sel = scene()->selectedItems(); + int j = 0; + for (int i = 0; i < sel.size(); i++) { + CardItem *c = (CardItem *) sel.at(i); + if ((c == this) || (c->getZone() != zone)) + continue; + ++j; + QPointF childPos; + if (zone->getHasCardAttr()) + childPos = c->pos() - pos(); + else + childPos = QPointF(j * CARD_WIDTH / 2, 0); + CardDragItem *drag = new CardDragItem(c, c->getId(), childPos, c->getFaceDown() || forceFaceDown, dragItem); + drag->setPos(dragItem->pos() + childPos); + scene()->addItem(drag); + } + } + setCursor(Qt::OpenHandCursor); } void CardItem::playCard(bool faceDown) { - // Do nothing if the card belongs to another player - if (!owner->getLocal()) - return; + // Do nothing if the card belongs to another player + if (!owner->getLocal()) + return; - TableZone *tz = qobject_cast(zone); - if (tz) - tz->toggleTapped(); - else - zone->getPlayer()->playCard(this, faceDown, info->getCipt()); + TableZone *tz = qobject_cast(zone); + if (tz) + tz->toggleTapped(); + else + zone->getPlayer()->playCard(this, faceDown, info->getCipt()); } void CardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::RightButton) { - if (cardMenu) - if (!cardMenu->isEmpty()) - cardMenu->exec(event->screenPos()); - } else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) { - - bool hideCard = false; - if (zone->getIsView()) { - ZoneViewZone *view = static_cast(zone); - if (view->getRevealZone() && !view->getWriteableRevealZone()) - hideCard = true; - } - if (hideCard) - zone->removeCard(this); - else - playCard(event->modifiers().testFlag(Qt::ShiftModifier)); - } + if (event->button() == Qt::RightButton) { + if (cardMenu) + if (!cardMenu->isEmpty()) + cardMenu->exec(event->screenPos()); + } else if ((event->button() == Qt::LeftButton) && !settingsCache->getDoubleClickToPlay()) { + + bool hideCard = false; + if (zone->getIsView()) { + ZoneViewZone *view = static_cast(zone); + if (view->getRevealZone() && !view->getWriteableRevealZone()) + hideCard = true; + } + if (hideCard) + zone->removeCard(this); + else + playCard(event->modifiers().testFlag(Qt::ShiftModifier)); + } - setCursor(Qt::OpenHandCursor); - AbstractCardItem::mouseReleaseEvent(event); + setCursor(Qt::OpenHandCursor); + AbstractCardItem::mouseReleaseEvent(event); } void CardItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { - if (settingsCache->getDoubleClickToPlay()) { - if (revealedCard) - zone->removeCard(this); - else - playCard(event->modifiers().testFlag(Qt::ShiftModifier)); - } - event->accept(); + if (settingsCache->getDoubleClickToPlay()) { + if (revealedCard) + zone->removeCard(this); + else + playCard(event->modifiers().testFlag(Qt::ShiftModifier)); + } + event->accept(); } bool CardItem::animationEvent() { - int delta = 18; - if (!tapped) - delta *= -1; - - tapAngle += delta; - - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); - setHovered(false); - update(); + int delta = 18; + if (!tapped) + delta *= -1; + + tapAngle += delta; + + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + setHovered(false); + update(); - if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0))) - return false; - return true; + if ((tapped && (tapAngle >= 90)) || (!tapped && (tapAngle <= 0))) + return false; + return true; } QVariant CardItem::itemChange(GraphicsItemChange change, const QVariant &value) { - if ((change == ItemSelectedHasChanged) && owner) { - if (value == true) { - owner->setCardMenu(cardMenu); - owner->getGame()->setActiveCard(this); - } else if (owner->getCardMenu() == cardMenu) { - owner->setCardMenu(0); - owner->getGame()->setActiveCard(0); - } - } - return QGraphicsItem::itemChange(change, value); + if ((change == ItemSelectedHasChanged) && owner) { + if (value == true) { + owner->setCardMenu(cardMenu); + owner->getGame()->setActiveCard(this); + } else if (owner->getCardMenu() == cardMenu) { + owner->setCardMenu(0); + owner->getGame()->setActiveCard(0); + } + } + return QGraphicsItem::itemChange(change, value); } diff --git a/cockatrice/src/carditem.h b/cockatrice/src/carditem.h index 99473f3c..9952550d 100644 --- a/cockatrice/src/carditem.h +++ b/cockatrice/src/carditem.h @@ -14,75 +14,75 @@ class QColor; const int MAX_COUNTERS_ON_CARD = 999; class CardItem : public AbstractCardItem { - Q_OBJECT + Q_OBJECT private: - CardZone *zone; - bool revealedCard; - bool attacking; - QMap counters; - QString annotation; - QString pt; - bool destroyOnZoneChange; - bool doesntUntap; - QPoint gridPoint; - CardDragItem *dragItem; - CardItem *attachedTo; - QList attachedCards; - - QMenu *cardMenu, *ptMenu, *moveMenu; + CardZone *zone; + bool revealedCard; + bool attacking; + QMap counters; + QString annotation; + QString pt; + bool destroyOnZoneChange; + bool doesntUntap; + QPoint gridPoint; + CardDragItem *dragItem; + CardItem *attachedTo; + QList attachedCards; + + QMenu *cardMenu, *ptMenu, *moveMenu; - void prepareDelete(); + void prepareDelete(); public slots: - void deleteLater(); + void deleteLater(); public: - enum { Type = typeCard }; - int type() const { return Type; } - CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0); - ~CardItem(); - void retranslateUi(); - CardZone *getZone() const { return zone; } - void setZone(CardZone *_zone); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QPoint getGridPoint() const { return gridPoint; } - void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; } - QPoint getGridPos() const { return gridPoint; } - Player *getOwner() const { return owner; } - void setOwner(Player *_owner) { owner = _owner; } - bool getRevealedCard() const { return revealedCard; } - bool getAttacking() const { return attacking; } - void setAttacking(bool _attacking); - const QMap &getCounters() const { return counters; } - void setCounter(int _id, int _value); - QString getAnnotation() const { return annotation; } - void setAnnotation(const QString &_annotation); - bool getDoesntUntap() const { return doesntUntap; } - void setDoesntUntap(bool _doesntUntap); - QString getPT() const { return pt; } - void setPT(const QString &_pt); - bool getDestroyOnZoneChange() const { return destroyOnZoneChange; } - void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; } - CardItem *getAttachedTo() const { return attachedTo; } - void setAttachedTo(CardItem *_attachedTo); - void addAttachedCard(CardItem *card) { attachedCards.append(card); } - void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); } - const QList &getAttachedCards() const { return attachedCards; } - void resetState(); - void processCardInfo(const ServerInfo_Card &info); + enum { Type = typeCard }; + int type() const { return Type; } + CardItem(Player *_owner, const QString &_name = QString(), int _cardid = -1, bool revealedCard = false, QGraphicsItem *parent = 0); + ~CardItem(); + void retranslateUi(); + CardZone *getZone() const { return zone; } + void setZone(CardZone *_zone); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QPoint getGridPoint() const { return gridPoint; } + void setGridPoint(const QPoint &_gridPoint) { gridPoint = _gridPoint; } + QPoint getGridPos() const { return gridPoint; } + Player *getOwner() const { return owner; } + void setOwner(Player *_owner) { owner = _owner; } + bool getRevealedCard() const { return revealedCard; } + bool getAttacking() const { return attacking; } + void setAttacking(bool _attacking); + const QMap &getCounters() const { return counters; } + void setCounter(int _id, int _value); + QString getAnnotation() const { return annotation; } + void setAnnotation(const QString &_annotation); + bool getDoesntUntap() const { return doesntUntap; } + void setDoesntUntap(bool _doesntUntap); + QString getPT() const { return pt; } + void setPT(const QString &_pt); + bool getDestroyOnZoneChange() const { return destroyOnZoneChange; } + void setDestroyOnZoneChange(bool _destroy) { destroyOnZoneChange = _destroy; } + CardItem *getAttachedTo() const { return attachedTo; } + void setAttachedTo(CardItem *_attachedTo); + void addAttachedCard(CardItem *card) { attachedCards.append(card); } + void removeAttachedCard(CardItem *card) { attachedCards.removeAt(attachedCards.indexOf(card)); } + const QList &getAttachedCards() const { return attachedCards; } + void resetState(); + void processCardInfo(const ServerInfo_Card &info); - QMenu *getCardMenu() const { return cardMenu; } - QMenu *getPTMenu() const { return ptMenu; } - QMenu *getMoveMenu() const { return moveMenu; } - - bool animationEvent(); - CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown); - void deleteDragItem(); - void drawArrow(const QColor &arrowColor); - void playCard(bool faceDown); + QMenu *getCardMenu() const { return cardMenu; } + QMenu *getPTMenu() const { return ptMenu; } + QMenu *getMoveMenu() const { return moveMenu; } + + bool animationEvent(); + CardDragItem *createDragItem(int _id, const QPointF &_pos, const QPointF &_scenePos, bool faceDown); + void deleteDragItem(); + void drawArrow(const QColor &arrowColor); + void playCard(bool faceDown); protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - QVariant itemChange(GraphicsItemChange change, const QVariant &value); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + QVariant itemChange(GraphicsItemChange change, const QVariant &value); }; #endif diff --git a/cockatrice/src/cardlist.cpp b/cockatrice/src/cardlist.cpp index e4d809ef..34466265 100644 --- a/cockatrice/src/cardlist.cpp +++ b/cockatrice/src/cardlist.cpp @@ -3,57 +3,57 @@ #include "carddatabase.h" CardList::CardList(bool _contentsKnown) - : QList(), contentsKnown(_contentsKnown) + : QList(), contentsKnown(_contentsKnown) { } CardItem *CardList::findCard(const int id, const bool remove, int *position) { - if (!contentsKnown) { - if (empty()) - return 0; - CardItem *temp = at(0); - if (remove) - removeAt(0); - if (position) - *position = id; - return temp; - } else - for (int i = 0; i < size(); i++) { - CardItem *temp = at(i); - if (temp->getId() == id) { - if (remove) - removeAt(i); - if (position) - *position = i; - return temp; - } - } - return 0; + if (!contentsKnown) { + if (empty()) + return 0; + CardItem *temp = at(0); + if (remove) + removeAt(0); + if (position) + *position = id; + return temp; + } else + for (int i = 0; i < size(); i++) { + CardItem *temp = at(i); + if (temp->getId() == id) { + if (remove) + removeAt(i); + if (position) + *position = i; + return temp; + } + } + return 0; } class CardList::compareFunctor { private: - int flags; + int flags; public: - compareFunctor(int _flags) : flags(_flags) - { - } - inline bool operator()(CardItem *a, CardItem *b) const - { - if (flags & SortByType) { - QString t1 = a->getInfo()->getMainCardType(); - QString t2 = b->getInfo()->getMainCardType(); - if ((t1 == t2) && (flags & SortByName)) - return a->getName() < b->getName(); - return t1 < t2; - } else - return a->getName() < b->getName(); - } + compareFunctor(int _flags) : flags(_flags) + { + } + inline bool operator()(CardItem *a, CardItem *b) const + { + if (flags & SortByType) { + QString t1 = a->getInfo()->getMainCardType(); + QString t2 = b->getInfo()->getMainCardType(); + if ((t1 == t2) && (flags & SortByName)) + return a->getName() < b->getName(); + return t1 < t2; + } else + return a->getName() < b->getName(); + } }; void CardList::sort(int flags) { - compareFunctor cf(flags); - qSort(begin(), end(), cf); + compareFunctor cf(flags); + qSort(begin(), end(), cf); } diff --git a/cockatrice/src/cardlist.h b/cockatrice/src/cardlist.h index 101973af..d148ca6d 100644 --- a/cockatrice/src/cardlist.h +++ b/cockatrice/src/cardlist.h @@ -7,15 +7,15 @@ class CardItem; class CardList : public QList { private: - class compareFunctor; + class compareFunctor; protected: - bool contentsKnown; + bool contentsKnown; public: - enum SortFlags { SortByName = 1, SortByType = 2 }; - CardList(bool _contentsKnown); - CardItem *findCard(const int id, const bool remove, int *position = NULL); - bool getContentsKnown() const { return contentsKnown; } - void sort(int flags = SortByName); + enum SortFlags { SortByName = 1, SortByType = 2 }; + CardList(bool _contentsKnown); + CardItem *findCard(const int id, const bool remove, int *position = NULL); + bool getContentsKnown() const { return contentsKnown; } + void sort(int flags = SortByName); }; #endif diff --git a/cockatrice/src/cardzone.cpp b/cockatrice/src/cardzone.cpp index a5fa3e18..f09cac1f 100644 --- a/cockatrice/src/cardzone.cpp +++ b/cockatrice/src/cardzone.cpp @@ -10,256 +10,257 @@ #include "pb/serverinfo_user.pb.h" CardZone::CardZone(Player *_p, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent, bool _isView) - : AbstractGraphicsItem(parent), player(_p), name(_name), cards(_contentsKnown), view(NULL), menu(NULL), doubleClickAction(0), hasCardAttr(_hasCardAttr), isShufflable(_isShufflable), isView(_isView) + : AbstractGraphicsItem(parent), player(_p), name(_name), cards(_contentsKnown), view(NULL), menu(NULL), doubleClickAction(0), hasCardAttr(_hasCardAttr), isShufflable(_isShufflable), isView(_isView) { - if (!isView) - player->addZone(this); + if (!isView) + player->addZone(this); } CardZone::~CardZone() { - qDebug() << "CardZone destructor: " << name; - delete view; - clearContents(); + qDebug() << "CardZone destructor: " << name; + delete view; + clearContents(); } void CardZone::retranslateUi() { - for (int i = 0; i < cards.size(); ++i) - cards[i]->retranslateUi(); + for (int i = 0; i < cards.size(); ++i) + cards[i]->retranslateUi(); } void CardZone::clearContents() { - for (int i = 0; i < cards.size(); i++) { - // If an incorrectly implemented server doesn't return attached cards to whom they belong before dropping a player, - // we have to return them to avoid a crash. - const QList &attachedCards = cards[i]->getAttachedCards(); - for (int j = 0; j < attachedCards.size(); ++j) - attachedCards[j]->setParentItem(attachedCards[j]->getZone()); - - player->deleteCard(cards.at(i)); - } - cards.clear(); - emit cardCountChanged(); + for (int i = 0; i < cards.size(); i++) { + // If an incorrectly implemented server doesn't return attached cards to whom they belong before dropping a player, + // we have to return them to avoid a crash. + const QList &attachedCards = cards[i]->getAttachedCards(); + for (int j = 0; j < attachedCards.size(); ++j) + attachedCards[j]->setParentItem(attachedCards[j]->getZone()); + + player->deleteCard(cards.at(i)); + } + cards.clear(); + emit cardCountChanged(); } QString CardZone::getTranslatedName(bool hisOwn, GrammaticalCase gc) const { - QString ownerName = player->getName(); - bool female = player->getUserInfo()->gender() == ServerInfo_User::Female; - if (name == "hand") - return female - ? (hisOwn - ? tr("her hand", "nominative, female owner") - : tr("%1's hand", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his hand", "nominative, male owner") - : tr("%1's hand", "nominative, male owner").arg(ownerName) - ); - else if (name == "deck") - switch (gc) { - case CaseLookAtZone: - return female - ? (hisOwn - ? tr("her library", "look at zone, female owner") - : tr("%1's library", "look at zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "look at zone, male owner") - : tr("%1's library", "look at zone, male owner").arg(ownerName) - ); - case CaseTopCardsOfZone: - return female - ? (hisOwn - ? tr("of her library", "top cards of zone, female owner") - : tr("of %1's library", "top cards of zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("of his library", "top cards of zone, male owner") - : tr("of %1's library", "top cards of zone, male owner").arg(ownerName) - ); - case CaseRevealZone: - return female - ? (hisOwn - ? tr("her library", "reveal zone, female owner") - : tr("%1's library", "reveal zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "reveal zone, male owner") - : tr("%1's library", "reveal zone, male owner").arg(ownerName) - ); - case CaseShuffleZone: - return female - ? (hisOwn - ? tr("her library", "shuffle, female owner") - : tr("%1's library", "shuffle, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "shuffle, male owner") - : tr("%1's library", "shuffle, male owner").arg(ownerName) - ); - default: - return female - ? (hisOwn - ? tr("her library", "nominative, female owner") - : tr("%1's library", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his library", "nominative, male owner") - : tr("%1's library", "nominative, male owner").arg(ownerName) - ); - } - else if (name == "grave") - return female - ? (hisOwn - ? tr("her graveyard", "nominative, female owner") - : tr("%1's graveyard", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his graveyard", "nominative, male owner") - : tr("%1's graveyard", "nominative, male owner").arg(ownerName) - ); - else if (name == "rfg") - return female - ? (hisOwn - ? tr("her exile", "nominative, female owner") - : tr("%1's exile", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his exile", "nominative, male owner") - : tr("%1's exile", "nominative, male owner").arg(ownerName) - ); - else if (name == "sb") - switch (gc) { - case CaseLookAtZone: - return female - ? (hisOwn - ? tr("her sideboard", "look at zone, female owner") - : tr("%1's sideboard", "look at zone, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his sideboard", "look at zone, male owner") - : tr("%1's sideboard", "look at zone, male owner").arg(ownerName) - ); - case CaseNominative: - return female - ? (hisOwn - ? tr("her sideboard", "nominative, female owner") - : tr("%1's sideboard", "nominative, female owner").arg(ownerName) - ) : (hisOwn - ? tr("his sideboard", "nominative, male owner") - : tr("%1's sideboard", "nominative, male owner").arg(ownerName) - ); - } - return QString(); + QString ownerName = player->getName(); + bool female = player->getUserInfo()->gender() == ServerInfo_User::Female; + if (name == "hand") + return female + ? (hisOwn + ? tr("her hand", "nominative, female owner") + : tr("%1's hand", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his hand", "nominative, male owner") + : tr("%1's hand", "nominative, male owner").arg(ownerName) + ); + else if (name == "deck") + switch (gc) { + case CaseLookAtZone: + return female + ? (hisOwn + ? tr("her library", "look at zone, female owner") + : tr("%1's library", "look at zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "look at zone, male owner") + : tr("%1's library", "look at zone, male owner").arg(ownerName) + ); + case CaseTopCardsOfZone: + return female + ? (hisOwn + ? tr("of her library", "top cards of zone, female owner") + : tr("of %1's library", "top cards of zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("of his library", "top cards of zone, male owner") + : tr("of %1's library", "top cards of zone, male owner").arg(ownerName) + ); + case CaseRevealZone: + return female + ? (hisOwn + ? tr("her library", "reveal zone, female owner") + : tr("%1's library", "reveal zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "reveal zone, male owner") + : tr("%1's library", "reveal zone, male owner").arg(ownerName) + ); + case CaseShuffleZone: + return female + ? (hisOwn + ? tr("her library", "shuffle, female owner") + : tr("%1's library", "shuffle, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "shuffle, male owner") + : tr("%1's library", "shuffle, male owner").arg(ownerName) + ); + default: + return female + ? (hisOwn + ? tr("her library", "nominative, female owner") + : tr("%1's library", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his library", "nominative, male owner") + : tr("%1's library", "nominative, male owner").arg(ownerName) + ); + } + else if (name == "grave") + return female + ? (hisOwn + ? tr("her graveyard", "nominative, female owner") + : tr("%1's graveyard", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his graveyard", "nominative, male owner") + : tr("%1's graveyard", "nominative, male owner").arg(ownerName) + ); + else if (name == "rfg") + return female + ? (hisOwn + ? tr("her exile", "nominative, female owner") + : tr("%1's exile", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his exile", "nominative, male owner") + : tr("%1's exile", "nominative, male owner").arg(ownerName) + ); + else if (name == "sb") + switch (gc) { + case CaseLookAtZone: + return female + ? (hisOwn + ? tr("her sideboard", "look at zone, female owner") + : tr("%1's sideboard", "look at zone, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his sideboard", "look at zone, male owner") + : tr("%1's sideboard", "look at zone, male owner").arg(ownerName) + ); + case CaseNominative: + return female + ? (hisOwn + ? tr("her sideboard", "nominative, female owner") + : tr("%1's sideboard", "nominative, female owner").arg(ownerName) + ) : (hisOwn + ? tr("his sideboard", "nominative, male owner") + : tr("%1's sideboard", "nominative, male owner").arg(ownerName) + ); + default: break; + } + return QString(); } void CardZone::mouseDoubleClickEvent(QGraphicsSceneMouseEvent */*event*/) { - if (doubleClickAction) - doubleClickAction->trigger(); + if (doubleClickAction) + doubleClickAction->trigger(); } bool CardZone::showContextMenu(const QPoint &screenPos) { - if (menu) { - menu->exec(screenPos); - return true; - } - return false; + if (menu) { + menu->exec(screenPos); + return true; + } + return false; } void CardZone::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::RightButton) { - if (showContextMenu(event->screenPos())) - event->accept(); - else - event->ignore(); - } else - event->ignore(); + if (event->button() == Qt::RightButton) { + if (showContextMenu(event->screenPos())) + event->accept(); + else + event->ignore(); + } else + event->ignore(); } void CardZone::addCard(CardItem *card, bool reorganize, int x, int y) { - if (view) - if ((x <= view->getCards().size()) || (view->getNumberCards() == -1)) - view->addCard(new CardItem(player, card->getName(), card->getId()), reorganize, x, y); + if (view) + if ((x <= view->getCards().size()) || (view->getNumberCards() == -1)) + view->addCard(new CardItem(player, card->getName(), card->getId()), reorganize, x, y); - card->setZone(this); - addCardImpl(card, x, y); + card->setZone(this); + addCardImpl(card, x, y); - if (reorganize) - reorganizeCards(); - - emit cardCountChanged(); + if (reorganize) + reorganizeCards(); + + emit cardCountChanged(); } CardItem *CardZone::getCard(int cardId, const QString &cardName) { - CardItem *c = cards.findCard(cardId, false); - if (!c) { - qDebug() << "CardZone::getCard: card id=" << cardId << "not found"; - return 0; - } - // If the card's id is -1, this zone is invisible, - // so we need to give the card an id and a name as it comes out. - // It can be assumed that in an invisible zone, all cards are equal. - if ((c->getId() == -1) || (c->getName().isEmpty())) { - c->setId(cardId); - c->setName(cardName); - } - return c; + CardItem *c = cards.findCard(cardId, false); + if (!c) { + qDebug() << "CardZone::getCard: card id=" << cardId << "not found"; + return 0; + } + // If the card's id is -1, this zone is invisible, + // so we need to give the card an id and a name as it comes out. + // It can be assumed that in an invisible zone, all cards are equal. + if ((c->getId() == -1) || (c->getName().isEmpty())) { + c->setId(cardId); + c->setName(cardName); + } + return c; } CardItem *CardZone::takeCard(int position, int cardId, bool /*canResize*/) { - if (position == -1) { - // position == -1 means either that the zone is indexed by card id - // or that it doesn't matter which card you take. - for (int i = 0; i < cards.size(); ++i) - if (cards[i]->getId() == cardId) { - position = i; - break; - } - if (position == -1) - position = 0; - } - if (position >= cards.size()) - return 0; + if (position == -1) { + // position == -1 means either that the zone is indexed by card id + // or that it doesn't matter which card you take. + for (int i = 0; i < cards.size(); ++i) + if (cards[i]->getId() == cardId) { + position = i; + break; + } + if (position == -1) + position = 0; + } + if (position >= cards.size()) + return 0; - CardItem *c = cards.takeAt(position); + CardItem *c = cards.takeAt(position); - if (view) - view->removeCard(position); + if (view) + view->removeCard(position); - c->setId(cardId); + c->setId(cardId); - reorganizeCards(); - emit cardCountChanged(); - return c; + reorganizeCards(); + emit cardCountChanged(); + return c; } void CardZone::removeCard(CardItem *card) { - cards.removeAt(cards.indexOf(card)); - reorganizeCards(); - emit cardCountChanged(); - player->deleteCard(card); + cards.removeAt(cards.indexOf(card)); + reorganizeCards(); + emit cardCountChanged(); + player->deleteCard(card); } void CardZone::moveAllToZone() { - QList data = static_cast(sender())->data().toList(); - QString targetZone = data[0].toString(); - int targetX = data[1].toInt(); - - Command_MoveCard cmd; - cmd.set_start_zone(getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(targetZone.toStdString()); - cmd.set_x(targetX); - - for (int i = 0; i < cards.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(cards[i]->getId()); - - player->sendGameCommand(cmd); + QList data = static_cast(sender())->data().toList(); + QString targetZone = data[0].toString(); + int targetX = data[1].toInt(); + + Command_MoveCard cmd; + cmd.set_start_zone(getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(targetZone.toStdString()); + cmd.set_x(targetX); + + for (int i = 0; i < cards.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(cards[i]->getId()); + + player->sendGameCommand(cmd); } QPointF CardZone::closestGridPoint(const QPointF &point) { - return point; + return point; } diff --git a/cockatrice/src/cardzone.h b/cockatrice/src/cardzone.h index 0da4d251..adaf0141 100644 --- a/cockatrice/src/cardzone.h +++ b/cockatrice/src/cardzone.h @@ -14,56 +14,56 @@ class QPainter; class CardDragItem; class CardZone : public AbstractGraphicsItem { - Q_OBJECT + Q_OBJECT protected: - Player *player; - QString name; - CardList cards; - ZoneViewZone *view; - QMenu *menu; - QAction *doubleClickAction; - bool hasCardAttr; - bool isShufflable; - bool isView; - bool alwaysRevealTopCard; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - virtual void addCardImpl(CardItem *card, int x, int y) = 0; + Player *player; + QString name; + CardList cards; + ZoneViewZone *view; + QMenu *menu; + QAction *doubleClickAction; + bool hasCardAttr; + bool isShufflable; + bool isView; + bool alwaysRevealTopCard; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + virtual void addCardImpl(CardItem *card, int x, int y) = 0; signals: - void cardCountChanged(); + void cardCountChanged(); public slots: - void moveAllToZone(); - bool showContextMenu(const QPoint &screenPos); + void moveAllToZone(); + bool showContextMenu(const QPoint &screenPos); public: - enum { Type = typeZone }; - int type() const { return Type; } - virtual void handleDropEvent(const QList &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(); - void retranslateUi(); - void clearContents(); - bool getHasCardAttr() const { return hasCardAttr; } - bool getIsShufflable() const { return isShufflable; } - QMenu *getMenu() const { return menu; } - void setMenu(QMenu *_menu, QAction *_doubleClickAction = 0) { menu = _menu; doubleClickAction = _doubleClickAction; } - QString getName() const { return name; } - QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const; - Player *getPlayer() const { return player; } - bool contentsKnown() const { return cards.getContentsKnown(); } - const CardList &getCards() const { return cards; } - void addCard(CardItem *card, bool reorganize, int x, int y = -1); - // getCard() finds a card by id. - 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. - virtual CardItem *takeCard(int position, int cardId, bool canResize = true); - void removeCard(CardItem *card); - ZoneViewZone *getView() const { return view; } - void setView(ZoneViewZone *_view) { view = _view; } - virtual void reorganizeCards() = 0; - virtual QPointF closestGridPoint(const QPointF &point); - bool getIsView() const { return isView; } - bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; } - void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; } + enum { Type = typeZone }; + int type() const { return Type; } + virtual void handleDropEvent(const QList &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(); + void retranslateUi(); + void clearContents(); + bool getHasCardAttr() const { return hasCardAttr; } + bool getIsShufflable() const { return isShufflable; } + QMenu *getMenu() const { return menu; } + void setMenu(QMenu *_menu, QAction *_doubleClickAction = 0) { menu = _menu; doubleClickAction = _doubleClickAction; } + QString getName() const { return name; } + QString getTranslatedName(bool hisOwn, GrammaticalCase gc) const; + Player *getPlayer() const { return player; } + bool contentsKnown() const { return cards.getContentsKnown(); } + const CardList &getCards() const { return cards; } + void addCard(CardItem *card, bool reorganize, int x, int y = -1); + // getCard() finds a card by id. + 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. + virtual CardItem *takeCard(int position, int cardId, bool canResize = true); + void removeCard(CardItem *card); + ZoneViewZone *getView() const { return view; } + void setView(ZoneViewZone *_view) { view = _view; } + virtual void reorganizeCards() = 0; + virtual QPointF closestGridPoint(const QPointF &point); + bool getIsView() const { return isView; } + bool getAlwaysRevealTopCard() const { return alwaysRevealTopCard; } + void setAlwaysRevealTopCard(bool _alwaysRevealTopCard) { alwaysRevealTopCard = _alwaysRevealTopCard; } }; #endif diff --git a/cockatrice/src/chatview.cpp b/cockatrice/src/chatview.cpp index 376a6fd1..ae157647 100644 --- a/cockatrice/src/chatview.cpp +++ b/cockatrice/src/chatview.cpp @@ -10,256 +10,256 @@ #include "pixmapgenerator.h" 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; }"); - userContextMenu = new UserContextMenu(tabSupervisor, this, game); - connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - - viewport()->setCursor(Qt::IBeamCursor); - setReadOnly(true); - setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); - setOpenLinks(false); - connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &))); + document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }"); + userContextMenu = new UserContextMenu(tabSupervisor, this, game); + connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + + viewport()->setCursor(Qt::IBeamCursor); + setReadOnly(true); + setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); + setOpenLinks(false); + connect(this, SIGNAL(anchorClicked(const QUrl &)), this, SLOT(openLink(const QUrl &))); } void ChatView::retranslateUi() { - userContextMenu->retranslateUi(); + userContextMenu->retranslateUi(); } QTextCursor ChatView::prepareBlock(bool same) { - lastSender.clear(); - - QTextCursor cursor(document()->lastBlock()); - cursor.movePosition(QTextCursor::End); - if (!same) { - QTextBlockFormat blockFormat; - if ((evenNumber = !evenNumber)) - blockFormat.setBackground(palette().alternateBase()); - blockFormat.setBottomMargin(2); - cursor.insertBlock(blockFormat); - } else - cursor.insertHtml("
"); - - return cursor; + lastSender.clear(); + + QTextCursor cursor(document()->lastBlock()); + cursor.movePosition(QTextCursor::End); + if (!same) { + QTextBlockFormat blockFormat; + if ((evenNumber = !evenNumber)) + blockFormat.setBackground(palette().alternateBase()); + blockFormat.setBottomMargin(2); + cursor.insertBlock(blockFormat); + } else + cursor.insertHtml("
"); + + return cursor; } void ChatView::appendHtml(const QString &html) { - bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); - prepareBlock().insertHtml(html); - if (atBottom) - verticalScrollBar()->setValue(verticalScrollBar()->maximum()); + bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); + prepareBlock().insertHtml(html); + if (atBottom) + verticalScrollBar()->setValue(verticalScrollBar()->maximum()); } void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName) { - QTextCharFormat oldFormat = cursor.charFormat(); - QTextCharFormat anchorFormat = oldFormat; - anchorFormat.setForeground(Qt::blue); - anchorFormat.setAnchor(true); - anchorFormat.setAnchorHref("card://" + cardName); - - cursor.setCharFormat(anchorFormat); - cursor.insertText(cardName); - cursor.setCharFormat(oldFormat); + QTextCharFormat oldFormat = cursor.charFormat(); + QTextCharFormat anchorFormat = oldFormat; + anchorFormat.setForeground(Qt::blue); + anchorFormat.setAnchor(true); + anchorFormat.setAnchorHref("card://" + cardName); + + cursor.setCharFormat(anchorFormat); + cursor.insertText(cardName); + cursor.setCharFormat(oldFormat); } void ChatView::appendUrlTag(QTextCursor &cursor, QString url) { - if (!url.contains("://")) - url.prepend("http://"); - - QTextCharFormat oldFormat = cursor.charFormat(); - QTextCharFormat anchorFormat = oldFormat; - anchorFormat.setForeground(Qt::blue); - anchorFormat.setAnchor(true); - anchorFormat.setAnchorHref(url); - - cursor.setCharFormat(anchorFormat); - cursor.insertText(url); - cursor.setCharFormat(oldFormat); + if (!url.contains("://")) + url.prepend("http://"); + + QTextCharFormat oldFormat = cursor.charFormat(); + QTextCharFormat anchorFormat = oldFormat; + anchorFormat.setForeground(Qt::blue); + anchorFormat.setAnchor(true); + anchorFormat.setAnchorHref(url); + + cursor.setCharFormat(anchorFormat); + cursor.insertText(url); + cursor.setCharFormat(oldFormat); } void ChatView::appendMessage(QString message, QString sender, UserLevelFlags userLevel, bool playerBold) { - bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); - bool sameSender = (sender == lastSender) && !lastSender.isEmpty(); - QTextCursor cursor = prepareBlock(sameSender); - lastSender = sender; - - if (showTimestamps && !sameSender) { - QTextCharFormat timeFormat; - timeFormat.setForeground(Qt::black); - cursor.setCharFormat(timeFormat); - cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] ")); - } - - QTextCharFormat senderFormat; - if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) { - senderFormat.setFontWeight(QFont::Bold); - senderFormat.setForeground(Qt::red); - } else { - senderFormat.setForeground(Qt::blue); - if (playerBold) - senderFormat.setFontWeight(QFont::Bold); - } - senderFormat.setAnchor(true); - senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender); - if (!sameSender) { - if (!sender.isEmpty()) { - const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize(); - cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel)); - cursor.insertText(" "); - } - cursor.setCharFormat(senderFormat); - if (!sender.isEmpty()) - sender.append(": "); - cursor.insertText(sender); - } else - cursor.insertText(" "); - - QTextCharFormat messageFormat; - if (sender.isEmpty()) - messageFormat.setForeground(Qt::darkGreen); - cursor.setCharFormat(messageFormat); - - int from = 0, index = 0; - while ((index = message.indexOf('[', from)) != -1) { - cursor.insertText(message.left(index)); - message = message.mid(index); - if (message.isEmpty()) - break; + bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); + bool sameSender = (sender == lastSender) && !lastSender.isEmpty(); + QTextCursor cursor = prepareBlock(sameSender); + lastSender = sender; + + if (showTimestamps && !sameSender) { + QTextCharFormat timeFormat; + timeFormat.setForeground(Qt::black); + cursor.setCharFormat(timeFormat); + cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] ")); + } + + QTextCharFormat senderFormat; + if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) { + senderFormat.setFontWeight(QFont::Bold); + senderFormat.setForeground(Qt::red); + } else { + senderFormat.setForeground(Qt::blue); + if (playerBold) + senderFormat.setFontWeight(QFont::Bold); + } + senderFormat.setAnchor(true); + senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender); + if (!sameSender) { + if (!sender.isEmpty()) { + const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize(); + cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel)); + cursor.insertText(" "); + } + cursor.setCharFormat(senderFormat); + if (!sender.isEmpty()) + sender.append(": "); + cursor.insertText(sender); + } else + cursor.insertText(" "); + + QTextCharFormat messageFormat; + if (sender.isEmpty()) + messageFormat.setForeground(Qt::darkGreen); + cursor.setCharFormat(messageFormat); + + int from = 0, index = 0; + while ((index = message.indexOf('[', from)) != -1) { + cursor.insertText(message.left(index)); + message = message.mid(index); + if (message.isEmpty()) + break; - if (message.startsWith("[card]")) { - message = message.mid(6); - int closeTagIndex = message.indexOf("[/card]"); - QString cardName = message.left(closeTagIndex); - if (closeTagIndex == -1) - message.clear(); - else - message = message.mid(closeTagIndex + 7); - - appendCardTag(cursor, cardName); - } else if (message.startsWith("[[")) { - message = message.mid(2); - int closeTagIndex = message.indexOf("]]"); - QString cardName = message.left(closeTagIndex); - if (closeTagIndex == -1) - message.clear(); - else - message = message.mid(closeTagIndex + 2); - - appendCardTag(cursor, cardName); - } else if (message.startsWith("[url]")) { - message = message.mid(5); - int closeTagIndex = message.indexOf("[/url]"); - QString url = message.left(closeTagIndex); - if (closeTagIndex == -1) - message.clear(); - else - message = message.mid(closeTagIndex + 6); - - appendUrlTag(cursor, url); - } else - from = 1; - } - if (!message.isEmpty()) - cursor.insertText(message); - - if (atBottom) - verticalScrollBar()->setValue(verticalScrollBar()->maximum()); + if (message.startsWith("[card]")) { + message = message.mid(6); + int closeTagIndex = message.indexOf("[/card]"); + QString cardName = message.left(closeTagIndex); + if (closeTagIndex == -1) + message.clear(); + else + message = message.mid(closeTagIndex + 7); + + appendCardTag(cursor, cardName); + } else if (message.startsWith("[[")) { + message = message.mid(2); + int closeTagIndex = message.indexOf("]]"); + QString cardName = message.left(closeTagIndex); + if (closeTagIndex == -1) + message.clear(); + else + message = message.mid(closeTagIndex + 2); + + appendCardTag(cursor, cardName); + } else if (message.startsWith("[url]")) { + message = message.mid(5); + int closeTagIndex = message.indexOf("[/url]"); + QString url = message.left(closeTagIndex); + if (closeTagIndex == -1) + message.clear(); + else + message = message.mid(closeTagIndex + 6); + + appendUrlTag(cursor, url); + } else + from = 1; + } + if (!message.isEmpty()) + cursor.insertText(message); + + if (atBottom) + verticalScrollBar()->setValue(verticalScrollBar()->maximum()); } void ChatView::enterEvent(QEvent * /*event*/) { - setMouseTracking(true); + setMouseTracking(true); } void ChatView::leaveEvent(QEvent * /*event*/) { - setMouseTracking(false); + setMouseTracking(false); } QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const { - QTextCursor cursor(cursorForPosition(pos)); - QTextBlock block(cursor.block()); - QTextBlock::iterator it; - for (it = block.begin(); !(it.atEnd()); ++it) { - QTextFragment frag = it.fragment(); - if (frag.contains(cursor.position())) - return frag; - } - return QTextFragment(); + QTextCursor cursor(cursorForPosition(pos)); + QTextBlock block(cursor.block()); + QTextBlock::iterator it; + for (it = block.begin(); !(it.atEnd()); ++it) { + QTextFragment frag = it.fragment(); + if (frag.contains(cursor.position())) + return frag; + } + return QTextFragment(); } void ChatView::mouseMoveEvent(QMouseEvent *event) { - QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref(); - if (!anchorHref.isEmpty()) { - const int delimiterIndex = anchorHref.indexOf("://"); - if (delimiterIndex != -1) { - const QString scheme = anchorHref.left(delimiterIndex); - hoveredContent = anchorHref.mid(delimiterIndex + 3); - if (scheme == "card") { - hoveredItemType = HoveredCard; - emit cardNameHovered(hoveredContent); - } else if (scheme == "user") - hoveredItemType = HoveredUser; - else - hoveredItemType = HoveredUrl; - viewport()->setCursor(Qt::PointingHandCursor); - } else { - hoveredItemType = HoveredNothing; - viewport()->setCursor(Qt::IBeamCursor); - } - } else { - hoveredItemType = HoveredNothing; - viewport()->setCursor(Qt::IBeamCursor); - } - - QTextBrowser::mouseMoveEvent(event); + QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref(); + if (!anchorHref.isEmpty()) { + const int delimiterIndex = anchorHref.indexOf("://"); + if (delimiterIndex != -1) { + const QString scheme = anchorHref.left(delimiterIndex); + hoveredContent = anchorHref.mid(delimiterIndex + 3); + if (scheme == "card") { + hoveredItemType = HoveredCard; + emit cardNameHovered(hoveredContent); + } else if (scheme == "user") + hoveredItemType = HoveredUser; + else + hoveredItemType = HoveredUrl; + viewport()->setCursor(Qt::PointingHandCursor); + } else { + hoveredItemType = HoveredNothing; + viewport()->setCursor(Qt::IBeamCursor); + } + } else { + hoveredItemType = HoveredNothing; + viewport()->setCursor(Qt::IBeamCursor); + } + + QTextBrowser::mouseMoveEvent(event); } void ChatView::mousePressEvent(QMouseEvent *event) { - switch (hoveredItemType) { - case HoveredCard: { - if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) - emit showCardInfoPopup(event->globalPos(), hoveredContent); - break; - } - case HoveredUser: { - if (event->button() == Qt::RightButton) { - const int delimiterIndex = hoveredContent.indexOf("_"); - UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt()); - const QString userName = hoveredContent.mid(delimiterIndex + 1); - - userContextMenu->showContextMenu(event->globalPos(), userName, userLevel); - } - break; - } - default: { - QTextBrowser::mousePressEvent(event); - } - } + switch (hoveredItemType) { + case HoveredCard: { + if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) + emit showCardInfoPopup(event->globalPos(), hoveredContent); + break; + } + case HoveredUser: { + if (event->button() == Qt::RightButton) { + const int delimiterIndex = hoveredContent.indexOf("_"); + UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt()); + const QString userName = hoveredContent.mid(delimiterIndex + 1); + + userContextMenu->showContextMenu(event->globalPos(), userName, userLevel); + } + break; + } + default: { + QTextBrowser::mousePressEvent(event); + } + } } void ChatView::mouseReleaseEvent(QMouseEvent *event) { - if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) - emit deleteCardInfoPopup(QString("_")); - - QTextBrowser::mouseReleaseEvent(event); + if ((event->button() == Qt::MidButton) || (event->button() == Qt::LeftButton)) + emit deleteCardInfoPopup(QString("_")); + + QTextBrowser::mouseReleaseEvent(event); } void ChatView::openLink(const QUrl &link) { - if ((link.scheme() == "card") || (link.scheme() == "user")) - return; - - QDesktopServices::openUrl(link); + if ((link.scheme() == "card") || (link.scheme() == "user")) + return; + + QDesktopServices::openUrl(link); } diff --git a/cockatrice/src/chatview.h b/cockatrice/src/chatview.h index d5c35d38..1e8a2022 100644 --- a/cockatrice/src/chatview.h +++ b/cockatrice/src/chatview.h @@ -14,40 +14,40 @@ class TabSupervisor; class TabGame; class ChatView : public QTextBrowser { - Q_OBJECT + Q_OBJECT protected: - const TabSupervisor * const tabSupervisor; - TabGame * const game; + const TabSupervisor * const tabSupervisor; + TabGame * const game; private: - enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser }; - UserContextMenu *userContextMenu; - QString lastSender; - bool evenNumber; - bool showTimestamps; - HoveredItemType hoveredItemType; - QString hoveredContent; - QTextFragment getFragmentUnderMouse(const QPoint &pos) const; - QTextCursor prepareBlock(bool same = false); - void appendCardTag(QTextCursor &cursor, const QString &cardName); - void appendUrlTag(QTextCursor &cursor, QString url); + enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser }; + UserContextMenu *userContextMenu; + QString lastSender; + bool evenNumber; + bool showTimestamps; + HoveredItemType hoveredItemType; + QString hoveredContent; + QTextFragment getFragmentUnderMouse(const QPoint &pos) const; + QTextCursor prepareBlock(bool same = false); + void appendCardTag(QTextCursor &cursor, const QString &cardName); + void appendUrlTag(QTextCursor &cursor, QString url); private slots: - void openLink(const QUrl &link); + void openLink(const QUrl &link); public: - ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0); - void retranslateUi(); - void appendHtml(const QString &html); - void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false); + ChatView(const TabSupervisor *_tabSupervisor, TabGame *_game, bool _showTimestamps, QWidget *parent = 0); + void retranslateUi(); + void appendHtml(const QString &html); + void appendMessage(QString message, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), bool playerBold = false); protected: - void enterEvent(QEvent *event); - void leaveEvent(QEvent *event); - void mouseMoveEvent(QMouseEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); signals: - void openMessageDialog(const QString &userName, bool focus); - void cardNameHovered(QString cardName); - void showCardInfoPopup(QPoint pos, QString cardName); - void deleteCardInfoPopup(QString cardName); + void openMessageDialog(const QString &userName, bool focus); + void cardNameHovered(QString cardName); + void showCardInfoPopup(QPoint pos, QString cardName); + void deleteCardInfoPopup(QString cardName); }; #endif diff --git a/cockatrice/src/counter_general.cpp b/cockatrice/src/counter_general.cpp index 6ded4732..edc44519 100644 --- a/cockatrice/src/counter_general.cpp +++ b/cockatrice/src/counter_general.cpp @@ -3,34 +3,34 @@ #include 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 { - 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*/) { - QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); - int translatedHeight = mapRect.size().height(); - qreal scaleFactor = translatedHeight / boundingRect().height(); - QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); - - painter->save(); - painter->resetTransform(); - painter->drawPixmap(QPoint(0, 0), pixmap); + QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); + int translatedHeight = mapRect.size().height(); + qreal scaleFactor = translatedHeight / boundingRect().height(); + QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); + + painter->save(); + painter->resetTransform(); + painter->drawPixmap(QPoint(0, 0), pixmap); - if (value) { - QFont f("Serif"); - f.setPixelSize(qMax((int) (radius * scaleFactor), 10)); - f.setWeight(QFont::Bold); - painter->setPen(Qt::black); - painter->setFont(f); - painter->drawText(mapRect, Qt::AlignCenter, QString::number(value)); - } - painter->restore(); + if (value) { + QFont f("Serif"); + f.setPixelSize(qMax((int) (radius * scaleFactor), 10)); + f.setWeight(QFont::Bold); + painter->setPen(Qt::black); + painter->setFont(f); + painter->drawText(mapRect, Qt::AlignCenter, QString::number(value)); + } + painter->restore(); } diff --git a/cockatrice/src/counter_general.h b/cockatrice/src/counter_general.h index d815f3c4..2808b654 100644 --- a/cockatrice/src/counter_general.h +++ b/cockatrice/src/counter_general.h @@ -4,14 +4,14 @@ #include "abstractcounter.h" class GeneralCounter : public AbstractCounter { - Q_OBJECT + Q_OBJECT private: - QColor color; - int radius; + QColor color; + int radius; public: - GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + GeneralCounter(Player *_player, int _id, const QString &_name, const QColor &_color, int _radius, int _value, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; #endif diff --git a/cockatrice/src/deck_loader.cpp b/cockatrice/src/deck_loader.cpp index b0e34d80..6a907ed7 100644 --- a/cockatrice/src/deck_loader.cpp +++ b/cockatrice/src/deck_loader.cpp @@ -4,98 +4,96 @@ #include "decklist.h" const QStringList DeckLoader::fileNameFilters = QStringList() - << QObject::tr("Cockatrice decks (*.cod)") - << QObject::tr("Plain text decks (*.dec *.mwDeck)") - << QObject::tr("All files (*.*)"); + << QObject::tr("Common deck formats (*.cod *.dec *.mwDeck)") + << QObject::tr("All files (*.*)"); DeckLoader::DeckLoader() - : DeckList(), - lastFileName(QString()), - lastFileFormat(CockatriceFormat), - lastRemoteDeckId(-1) + : DeckList(), + lastFileName(QString()), + lastFileFormat(CockatriceFormat), + lastRemoteDeckId(-1) { } DeckLoader::DeckLoader(const QString &nativeString) - : DeckList(nativeString), - lastFileName(QString()), - lastFileFormat(CockatriceFormat), - lastRemoteDeckId(-1) + : DeckList(nativeString), + lastFileName(QString()), + lastFileFormat(CockatriceFormat), + lastRemoteDeckId(-1) { } DeckLoader::DeckLoader(const DeckList &other) - : DeckList(other), - lastFileName(QString()), - lastFileFormat(CockatriceFormat), - lastRemoteDeckId(-1) + : DeckList(other), + lastFileName(QString()), + lastFileFormat(CockatriceFormat), + lastRemoteDeckId(-1) { } DeckLoader::DeckLoader(const DeckLoader &other) - : DeckList(other), - lastFileName(other.lastFileName), - lastFileFormat(other.lastFileFormat), - lastRemoteDeckId(other.lastRemoteDeckId) + : DeckList(other), + lastFileName(other.lastFileName), + lastFileFormat(other.lastFileFormat), + lastRemoteDeckId(other.lastRemoteDeckId) { } bool DeckLoader::loadFromFile(const QString &fileName, FileFormat fmt) { - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return false; - - bool result = false; - switch (fmt) { - case PlainTextFormat: result = loadFromFile_Plain(&file); break; - case CockatriceFormat: result = loadFromFile_Native(&file); break; - } - if (result) { - lastFileName = fileName; - lastFileFormat = fmt; - - emit deckLoaded(); - } - return result; + QFile file(fileName); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return false; + + bool result = false; + switch (fmt) { + case PlainTextFormat: result = loadFromFile_Plain(&file); break; + case CockatriceFormat: result = loadFromFile_Native(&file); break; + } + if (result) { + lastFileName = fileName; + lastFileFormat = fmt; + + emit deckLoaded(); + } + return result; } bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) { - bool result = loadFromString_Native(nativeString); - if (result) { - lastFileName = QString(); - lastFileFormat = CockatriceFormat; - lastRemoteDeckId = remoteDeckId; - - emit deckLoaded(); - } - return result; + bool result = loadFromString_Native(nativeString); + if (result) { + lastFileName = QString(); + lastFileFormat = CockatriceFormat; + lastRemoteDeckId = remoteDeckId; + + emit deckLoaded(); + } + return result; } bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) { - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) - return false; + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) + return false; - bool result = false; - switch (fmt) { - case PlainTextFormat: result = saveToFile_Plain(&file); break; - case CockatriceFormat: result = saveToFile_Native(&file); break; - } - if (result) { - lastFileName = fileName; - lastFileFormat = fmt; - } - return result; + bool result = false; + switch (fmt) { + case PlainTextFormat: result = saveToFile_Plain(&file); break; + case CockatriceFormat: result = saveToFile_Native(&file); break; + } + if (result) { + lastFileName = fileName; + lastFileFormat = fmt; + } + return result; } -DeckLoader::FileFormat DeckLoader::getFormatFromNameFilter(const QString &selectedNameFilter) +DeckLoader::FileFormat DeckLoader::getFormatFromName(const QString &fileName) { - switch (fileNameFilters.indexOf(selectedNameFilter)) { - case 0: return CockatriceFormat; - case 1: return PlainTextFormat; - } - return PlainTextFormat; + if (fileName.endsWith(".cod", Qt::CaseInsensitive)) { + return CockatriceFormat; + } + return PlainTextFormat; } diff --git a/cockatrice/src/deck_loader.h b/cockatrice/src/deck_loader.h index 53f9e583..70c481d1 100644 --- a/cockatrice/src/deck_loader.h +++ b/cockatrice/src/deck_loader.h @@ -4,30 +4,30 @@ #include "decklist.h" class DeckLoader : public DeckList { - Q_OBJECT + Q_OBJECT signals: - void deckLoaded(); + void deckLoaded(); public: - enum FileFormat { PlainTextFormat, CockatriceFormat }; - static const QStringList fileNameFilters; + enum FileFormat { PlainTextFormat, CockatriceFormat }; + static const QStringList fileNameFilters; private: - QString lastFileName; - FileFormat lastFileFormat; - int lastRemoteDeckId; + QString lastFileName; + FileFormat lastFileFormat; + int lastRemoteDeckId; public: - DeckLoader(); - DeckLoader(const QString &nativeString); - DeckLoader(const DeckList &other); - DeckLoader(const DeckLoader &other); - const QString &getLastFileName() const { return lastFileName; } - FileFormat getLastFileFormat() const { return lastFileFormat; } - int getLastRemoteDeckId() const { return lastRemoteDeckId; } - - static FileFormat getFormatFromNameFilter(const QString &selectedNameFilter); - - bool loadFromFile(const QString &fileName, FileFormat fmt); - bool loadFromRemote(const QString &nativeString, int remoteDeckId); - bool saveToFile(const QString &fileName, FileFormat fmt); + DeckLoader(); + DeckLoader(const QString &nativeString); + DeckLoader(const DeckList &other); + DeckLoader(const DeckLoader &other); + const QString &getLastFileName() const { return lastFileName; } + FileFormat getLastFileFormat() const { return lastFileFormat; } + int getLastRemoteDeckId() const { return lastRemoteDeckId; } + + static FileFormat getFormatFromName(const QString &fileName); + + bool loadFromFile(const QString &fileName, FileFormat fmt); + bool loadFromRemote(const QString &nativeString, int remoteDeckId); + bool saveToFile(const QString &fileName, FileFormat fmt); }; #endif diff --git a/cockatrice/src/decklistmodel.h b/cockatrice/src/decklistmodel.h index 3ef47642..e2a85c56 100644 --- a/cockatrice/src/decklistmodel.h +++ b/cockatrice/src/decklistmodel.h @@ -45,7 +45,6 @@ public: Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role); bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - QModelIndex findCard(const QString &cardName, const QString &zoneName) const; QModelIndex addCard(const QString &cardName, const QString &zoneName); void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); diff --git a/cockatrice/src/deckstats_interface.cpp b/cockatrice/src/deckstats_interface.cpp index 65cb101c..eae4caae 100644 --- a/cockatrice/src/deckstats_interface.cpp +++ b/cockatrice/src/deckstats_interface.cpp @@ -8,46 +8,46 @@ #include DeckStatsInterface::DeckStatsInterface(QObject *parent) - : QObject(parent) + : QObject(parent) { - manager = new QNetworkAccessManager(this); - connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); + manager = new QNetworkAccessManager(this); + connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(queryFinished(QNetworkReply *))); } void DeckStatsInterface::queryFinished(QNetworkReply *reply) { - if (reply->error() != QNetworkReply::NoError) { - QMessageBox::critical(0, tr("Error"), reply->errorString()); - reply->deleteLater(); - deleteLater(); - return; - } - - QString data(reply->readAll()); - reply->deleteLater(); - - QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\""); - if (!rx.indexIn(data)) { - QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed.")); - deleteLater(); - return; - } - - QString deckUrl = rx.cap(1); - QDesktopServices::openUrl(deckUrl); - - deleteLater(); + if (reply->error() != QNetworkReply::NoError) { + QMessageBox::critical(0, tr("Error"), reply->errorString()); + reply->deleteLater(); + deleteLater(); + return; + } + + QString data(reply->readAll()); + reply->deleteLater(); + + QRegExp rx("id=\"deckstats_deck_url\" value=\"([^\"]+)\""); + if (!rx.indexIn(data)) { + QMessageBox::critical(0, tr("Error"), tr("The reply from the server could not be parsed.")); + deleteLater(); + return; + } + + QString deckUrl = rx.cap(1); + QDesktopServices::openUrl(deckUrl); + + deleteLater(); } void DeckStatsInterface::analyzeDeck(DeckList *deck) { - QUrl params; - params.addQueryItem("deck", deck->writeToString_Plain()); - QByteArray data; - data.append(params.encodedQuery()); - - QNetworkRequest request(QUrl("http://deckstats.net/index.php")); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - - manager->post(request, data); + QUrl params; + params.addQueryItem("deck", deck->writeToString_Plain()); + QByteArray data; + data.append(params.encodedQuery()); + + QNetworkRequest request(QUrl("http://deckstats.net/index.php")); + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + + manager->post(request, data); } diff --git a/cockatrice/src/deckstats_interface.h b/cockatrice/src/deckstats_interface.h index 89361b2d..e8454dd5 100644 --- a/cockatrice/src/deckstats_interface.h +++ b/cockatrice/src/deckstats_interface.h @@ -8,14 +8,14 @@ class QNetworkReply; class DeckList; class DeckStatsInterface : public QObject { - Q_OBJECT + Q_OBJECT private: - QNetworkAccessManager *manager; + QNetworkAccessManager *manager; private slots: - void queryFinished(QNetworkReply *reply); + void queryFinished(QNetworkReply *reply); public: - DeckStatsInterface(QObject *parent = 0); - void analyzeDeck(DeckList *deck); + DeckStatsInterface(QObject *parent = 0); + void analyzeDeck(DeckList *deck); }; #endif diff --git a/cockatrice/src/deckview.cpp b/cockatrice/src/deckview.cpp index a073cf2d..1746c58b 100644 --- a/cockatrice/src/deckview.cpp +++ b/cockatrice/src/deckview.cpp @@ -8,479 +8,479 @@ #include "main.h" 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) { - QList colliding = scene()->items(cursorScenePos); + QList colliding = scene()->items(cursorScenePos); - DeckViewCardContainer *cursorZone = 0; - for (int i = colliding.size() - 1; i >= 0; i--) - if ((cursorZone = qgraphicsitem_cast(colliding.at(i)))) - break; - if (!cursorZone) - return; - currentZone = cursorZone; - - QPointF newPos = cursorScenePos; - if (newPos != pos()) { - for (int i = 0; i < childDrags.size(); i++) - childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); - setPos(newPos); - } + DeckViewCardContainer *cursorZone = 0; + for (int i = colliding.size() - 1; i >= 0; i--) + if ((cursorZone = qgraphicsitem_cast(colliding.at(i)))) + break; + if (!cursorZone) + return; + currentZone = cursorZone; + + QPointF newPos = cursorScenePos; + if (newPos != pos()) { + for (int i = 0; i < childDrags.size(); i++) + childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); + setPos(newPos); + } } void DeckViewCardDragItem::handleDrop(DeckViewCardContainer *target) { - DeckViewCard *card = static_cast(item); - DeckViewCardContainer *start = static_cast(item->parentItem()); - start->removeCard(card); - target->addCard(card); - card->setParentItem(target); + DeckViewCard *card = static_cast(item); + DeckViewCardContainer *start = static_cast(item->parentItem()); + start->removeCard(card); + target->addCard(card); + card->setParentItem(target); } void DeckViewCardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - setCursor(Qt::OpenHandCursor); - DeckViewScene *sc = static_cast(scene()); - sc->removeItem(this); + setCursor(Qt::OpenHandCursor); + DeckViewScene *sc = static_cast(scene()); + sc->removeItem(this); - if (currentZone) { - handleDrop(currentZone); - for (int i = 0; i < childDrags.size(); i++) { - DeckViewCardDragItem *c = static_cast(childDrags[i]); - c->handleDrop(currentZone); - sc->removeItem(c); - } - - sc->updateContents(); - } - - event->accept(); + if (currentZone) { + handleDrop(currentZone); + for (int i = 0; i < childDrags.size(); i++) { + DeckViewCardDragItem *c = static_cast(childDrags[i]); + c->handleDrop(currentZone); + sc->removeItem(c); + } + + sc->updateContents(); + } + + event->accept(); } 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() { - delete dragItem; + delete dragItem; } void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - AbstractCardItem::paint(painter, option, widget); - - painter->save(); - QPen pen;//(Qt::DotLine); - pen.setWidth(3); - if (originZone == "main") - pen.setColor(QColor(0, 255, 0)); - else - pen.setColor(QColor(255, 0, 0)); - painter->setPen(pen); - painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3)); - painter->restore(); + AbstractCardItem::paint(painter, option, widget); + + painter->save(); + QPen pen;//(Qt::DotLine); + pen.setWidth(3); + if (originZone == "main") + pen.setColor(QColor(0, 255, 0)); + else + pen.setColor(QColor(255, 0, 0)); + painter->setPen(pen); + painter->drawRect(QRectF(1.5, 1.5, CARD_WIDTH - 3, CARD_HEIGHT - 3)); + painter->restore(); } void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) - return; - - if (static_cast(scene())->getLocked()) - return; - - delete dragItem; - dragItem = new DeckViewCardDragItem(this, event->pos()); - scene()->addItem(dragItem); - dragItem->updatePosition(event->scenePos()); - dragItem->grabMouse(); - - QList sel = scene()->selectedItems(); - int j = 0; - for (int i = 0; i < sel.size(); i++) { - DeckViewCard *c = static_cast(sel.at(i)); - if (c == this) - continue; - ++j; - QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0); - DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem); - drag->setPos(dragItem->pos() + childPos); - scene()->addItem(drag); - } - setCursor(Qt::OpenHandCursor); + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < 2 * QApplication::startDragDistance()) + return; + + if (static_cast(scene())->getLocked()) + return; + + delete dragItem; + dragItem = new DeckViewCardDragItem(this, event->pos()); + scene()->addItem(dragItem); + dragItem->updatePosition(event->scenePos()); + dragItem->grabMouse(); + + QList sel = scene()->selectedItems(); + int j = 0; + for (int i = 0; i < sel.size(); i++) { + DeckViewCard *c = static_cast(sel.at(i)); + if (c == this) + continue; + ++j; + QPointF childPos = QPointF(j * CARD_WIDTH / 2, 0); + DeckViewCardDragItem *drag = new DeckViewCardDragItem(c, childPos, dragItem); + drag->setPos(dragItem->pos() + childPos); + scene()->addItem(drag); + } + setCursor(Qt::OpenHandCursor); } void DeckViewCard::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - event->accept(); - processHoverEvent(); + event->accept(); + processHoverEvent(); } DeckViewCardContainer::DeckViewCardContainer(const QString &_name) - : QGraphicsItem(), name(_name), width(0), height(0) + : QGraphicsItem(), name(_name), width(0), height(0) { - QString bgPath = settingsCache->getTableBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); + QString bgPath = settingsCache->getTableBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); - setCacheMode(DeviceCoordinateCache); + setCacheMode(DeviceCoordinateCache); } 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*/) { - qreal totalTextWidth = getCardTypeTextWidth(); - - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), QColor(0, 0, 100)); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); - painter->setPen(QColor(255, 255, 255, 100)); - painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); - - painter->setPen(QColor(Qt::white)); - QFont f("Serif"); - f.setStyleHint(QFont::Serif); - f.setPixelSize(24); - f.setWeight(QFont::Bold); - painter->setFont(f); - painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size())); - - f.setPixelSize(16); - painter->setFont(f); - QList cardTypeList = cardsByType.uniqueKeys(); - qreal yUntilNow = separatorY + paddingY; - for (int i = 0; i < cardTypeList.size(); ++i) { - if (i != 0) { - painter->setPen(QColor(255, 255, 255, 100)); - painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2)); - } - qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; - QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight); - yUntilNow += thisRowHeight + paddingY; - - painter->setPen(Qt::white); - painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]); - } + qreal totalTextWidth = getCardTypeTextWidth(); + + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), QColor(0, 0, 100)); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); + painter->setPen(QColor(255, 255, 255, 100)); + painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); + + painter->setPen(QColor(Qt::white)); + QFont f("Serif"); + f.setStyleHint(QFont::Serif); + f.setPixelSize(24); + f.setWeight(QFont::Bold); + painter->setFont(f); + painter->drawText(10, 0, width - 20, separatorY, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, InnerDecklistNode::visibleNameFromName(name) + QString(": %1").arg(cards.size())); + + f.setPixelSize(16); + painter->setFont(f); + QList cardTypeList = cardsByType.uniqueKeys(); + qreal yUntilNow = separatorY + paddingY; + for (int i = 0; i < cardTypeList.size(); ++i) { + if (i != 0) { + painter->setPen(QColor(255, 255, 255, 100)); + painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2)); + } + qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; + QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight); + yUntilNow += thisRowHeight + paddingY; + + painter->setPen(Qt::white); + painter->drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextSingleLine, cardTypeList[i]); + } } void DeckViewCardContainer::addCard(DeckViewCard *card) { - cards.append(card); - cardsByType.insert(card->getInfo()->getMainCardType(), card); + cards.append(card); + cardsByType.insert(card->getInfo()->getMainCardType(), card); } void DeckViewCardContainer::removeCard(DeckViewCard *card) { - cards.removeAt(cards.indexOf(card)); - cardsByType.remove(card->getInfo()->getMainCardType(), card); + cards.removeAt(cards.indexOf(card)); + cardsByType.remove(card->getInfo()->getMainCardType(), card); } QList > DeckViewCardContainer::getRowsAndCols() const { - QList > result; - QList cardTypeList = cardsByType.uniqueKeys(); - for (int i = 0; i < cardTypeList.size(); ++i) - result.append(QPair(1, cardsByType.count(cardTypeList[i]))); - return result; + QList > result; + QList cardTypeList = cardsByType.uniqueKeys(); + for (int i = 0; i < cardTypeList.size(); ++i) + result.append(QPair(1, cardsByType.count(cardTypeList[i]))); + return result; } int DeckViewCardContainer::getCardTypeTextWidth() const { - QFont f("Serif"); - f.setStyleHint(QFont::Serif); - f.setPixelSize(16); - f.setWeight(QFont::Bold); - QFontMetrics fm(f); - - int maxCardTypeWidth = 0; - QMapIterator i(cardsByType); - while (i.hasNext()) { - int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width(); - if (cardTypeWidth > maxCardTypeWidth) - maxCardTypeWidth = cardTypeWidth; - } - - return maxCardTypeWidth + 15; + QFont f("Serif"); + f.setStyleHint(QFont::Serif); + f.setPixelSize(16); + f.setWeight(QFont::Bold); + QFontMetrics fm(f); + + int maxCardTypeWidth = 0; + QMapIterator i(cardsByType); + while (i.hasNext()) { + int cardTypeWidth = fm.size(Qt::TextSingleLine, i.next().key()).width(); + if (cardTypeWidth > maxCardTypeWidth) + maxCardTypeWidth = cardTypeWidth; + } + + return maxCardTypeWidth + 15; } QSizeF DeckViewCardContainer::calculateBoundingRect(const QList > &rowsAndCols) const { - qreal totalHeight = 0; - qreal totalWidth = 0; - - // Calculate space needed for cards - for (int i = 0; i < rowsAndCols.size(); ++i) { - totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY; - if (CARD_WIDTH * rowsAndCols[i].second > totalWidth) - totalWidth = CARD_WIDTH * rowsAndCols[i].second; - } - - return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY); + qreal totalHeight = 0; + qreal totalWidth = 0; + + // Calculate space needed for cards + for (int i = 0; i < rowsAndCols.size(); ++i) { + totalHeight += CARD_HEIGHT * rowsAndCols[i].first + paddingY; + if (CARD_WIDTH * rowsAndCols[i].second > totalWidth) + totalWidth = CARD_WIDTH * rowsAndCols[i].second; + } + + return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY); } void DeckViewCardContainer::rearrangeItems(const QList > &rowsAndCols) { - currentRowsAndCols = rowsAndCols; - - int totalCols = 0, totalRows = 0; - qreal yUntilNow = separatorY + paddingY; - qreal x = (qreal) getCardTypeTextWidth(); - for (int i = 0; i < rowsAndCols.size(); ++i) { - const int tempRows = rowsAndCols[i].first; - const int tempCols = rowsAndCols[i].second; - totalRows += tempRows; - if (tempCols > totalCols) - totalCols = tempCols; - - QList cardTypeList = cardsByType.uniqueKeys(); - QList row = cardsByType.values(cardTypeList[i]); - for (int j = 0; j < row.size(); ++j) { - DeckViewCard *card = row[j]; - card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT); - } - yUntilNow += tempRows * CARD_HEIGHT + paddingY; - } - - prepareGeometryChange(); - QSizeF bRect = calculateBoundingRect(rowsAndCols); - width = bRect.width(); - height = bRect.height(); + currentRowsAndCols = rowsAndCols; + + int totalCols = 0, totalRows = 0; + qreal yUntilNow = separatorY + paddingY; + qreal x = (qreal) getCardTypeTextWidth(); + for (int i = 0; i < rowsAndCols.size(); ++i) { + const int tempRows = rowsAndCols[i].first; + const int tempCols = rowsAndCols[i].second; + totalRows += tempRows; + if (tempCols > totalCols) + totalCols = tempCols; + + QList cardTypeList = cardsByType.uniqueKeys(); + QList row = cardsByType.values(cardTypeList[i]); + for (int j = 0; j < row.size(); ++j) { + DeckViewCard *card = row[j]; + card->setPos(x + (j % tempCols) * CARD_WIDTH, yUntilNow + (j / tempCols) * CARD_HEIGHT); + } + yUntilNow += tempRows * CARD_HEIGHT + paddingY; + } + + prepareGeometryChange(); + QSizeF bRect = calculateBoundingRect(rowsAndCols); + width = bRect.width(); + height = bRect.height(); } void DeckViewCardContainer::setWidth(qreal _width) { - prepareGeometryChange(); - width = _width; - update(); + prepareGeometryChange(); + width = _width; + update(); } DeckViewScene::DeckViewScene(QObject *parent) - : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0) + : QGraphicsScene(parent), locked(true), deck(0), optimalAspectRatio(1.0) { } DeckViewScene::~DeckViewScene() { - clearContents(); - delete deck; + clearContents(); + delete deck; } void DeckViewScene::clearContents() { - QMapIterator i(cardContainers); - while (i.hasNext()) - delete i.next().value(); - cardContainers.clear(); + QMapIterator i(cardContainers); + while (i.hasNext()) + delete i.next().value(); + cardContainers.clear(); } void DeckViewScene::setDeck(const DeckList &_deck) { - if (deck) - delete deck; - - deck = new DeckList(_deck); - rebuildTree(); - applySideboardPlan(deck->getCurrentSideboardPlan()); - rearrangeItems(); + if (deck) + delete deck; + + deck = new DeckList(_deck); + rebuildTree(); + applySideboardPlan(deck->getCurrentSideboardPlan()); + rearrangeItems(); } void DeckViewScene::rebuildTree() { - clearContents(); - - if (!deck) - return; - - InnerDecklistNode *listRoot = deck->getRoot(); - for (int i = 0; i < listRoot->size(); i++) { - InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); - - DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); - if (!container) { - container = new DeckViewCardContainer(currentZone->getName()); - cardContainers.insert(currentZone->getName(), container); - addItem(container); - } - - for (int j = 0; j < currentZone->size(); j++) { - DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); - if (!currentCard) - continue; + clearContents(); + + if (!deck) + return; + + InnerDecklistNode *listRoot = deck->getRoot(); + for (int i = 0; i < listRoot->size(); i++) { + InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); + + DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); + if (!container) { + container = new DeckViewCardContainer(currentZone->getName()); + cardContainers.insert(currentZone->getName(), container); + addItem(container); + } + + for (int j = 0; j < currentZone->size(); j++) { + DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); + if (!currentCard) + continue; - for (int k = 0; k < currentCard->getNumber(); ++k) { - DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container); - container->addCard(newCard); - emit newCardAdded(newCard); - } - } - } + for (int k = 0; k < currentCard->getNumber(); ++k) { + DeckViewCard *newCard = new DeckViewCard(currentCard->getName(), currentZone->getName(), container); + container->addCard(newCard); + emit newCardAdded(newCard); + } + } + } } void DeckViewScene::applySideboardPlan(const QList &plan) { - for (int i = 0; i < plan.size(); ++i) { - const MoveCard_ToZone &m = plan[i]; - DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone())); - DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone())); - if (!start || !target) - continue; - - DeckViewCard *card = 0; - const QList &cardList = start->getCards(); - for (int j = 0; j < cardList.size(); ++j) - if (cardList[j]->getName() == QString::fromStdString(m.card_name())) { - card = cardList[j]; - break; - } - if (!card) - continue; - - start->removeCard(card); - target->addCard(card); - card->setParentItem(target); - } + for (int i = 0; i < plan.size(); ++i) { + const MoveCard_ToZone &m = plan[i]; + DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone())); + DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone())); + if (!start || !target) + continue; + + DeckViewCard *card = 0; + const QList &cardList = start->getCards(); + for (int j = 0; j < cardList.size(); ++j) + if (cardList[j]->getName() == QString::fromStdString(m.card_name())) { + card = cardList[j]; + break; + } + if (!card) + continue; + + start->removeCard(card); + target->addCard(card); + card->setParentItem(target); + } } void DeckViewScene::rearrangeItems() { - const int spacing = CARD_HEIGHT / 3; - QList contList = cardContainers.values(); - - // Initialize space requirements - QList > > rowsAndColsList; - QList > cardCountList; - for (int i = 0; i < contList.size(); ++i) { - QList > rowsAndCols = contList[i]->getRowsAndCols(); - rowsAndColsList.append(rowsAndCols); - - cardCountList.append(QList()); - for (int j = 0; j < rowsAndCols.size(); ++j) - cardCountList[i].append(rowsAndCols[j].second); - } - - qreal totalHeight, totalWidth; - for (;;) { - // Calculate total size before this iteration - totalHeight = -spacing; - totalWidth = 0; - for (int i = 0; i < contList.size(); ++i) { - QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]); - totalHeight += contSize.height() + spacing; - if (contSize.width() > totalWidth) - totalWidth = contSize.width(); - } - - // We're done when the aspect ratio shifts from too high to too low. - if (totalWidth / totalHeight <= optimalAspectRatio) - break; - - // Find category with highest column count - int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0; - for (int i = 0; i < rowsAndColsList.size(); ++i) - for (int j = 0; j < rowsAndColsList[i].size(); ++j) - if (rowsAndColsList[i][j].second > maxCols) { - maxIndex1 = i; - maxIndex2 = j; - maxCols = rowsAndColsList[i][j].second; - } - - // Add row to category - const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first; - const int maxCardCount = cardCountList[maxIndex1][maxIndex2]; - rowsAndColsList[maxIndex1][maxIndex2] = QPair(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1))); - } - - totalHeight = -spacing; - for (int i = 0; i < contList.size(); ++i) { - DeckViewCardContainer *c = contList[i]; - c->rearrangeItems(rowsAndColsList[i]); - c->setPos(0, totalHeight + spacing); - totalHeight += c->boundingRect().height() + spacing; - } - - totalWidth = totalHeight * optimalAspectRatio; - for (int i = 0; i < contList.size(); ++i) - contList[i]->setWidth(totalWidth); - - setSceneRect(QRectF(0, 0, totalWidth, totalHeight)); + const int spacing = CARD_HEIGHT / 3; + QList contList = cardContainers.values(); + + // Initialize space requirements + QList > > rowsAndColsList; + QList > cardCountList; + for (int i = 0; i < contList.size(); ++i) { + QList > rowsAndCols = contList[i]->getRowsAndCols(); + rowsAndColsList.append(rowsAndCols); + + cardCountList.append(QList()); + for (int j = 0; j < rowsAndCols.size(); ++j) + cardCountList[i].append(rowsAndCols[j].second); + } + + qreal totalHeight, totalWidth; + for (;;) { + // Calculate total size before this iteration + totalHeight = -spacing; + totalWidth = 0; + for (int i = 0; i < contList.size(); ++i) { + QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]); + totalHeight += contSize.height() + spacing; + if (contSize.width() > totalWidth) + totalWidth = contSize.width(); + } + + // We're done when the aspect ratio shifts from too high to too low. + if (totalWidth / totalHeight <= optimalAspectRatio) + break; + + // Find category with highest column count + int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0; + for (int i = 0; i < rowsAndColsList.size(); ++i) + for (int j = 0; j < rowsAndColsList[i].size(); ++j) + if (rowsAndColsList[i][j].second > maxCols) { + maxIndex1 = i; + maxIndex2 = j; + maxCols = rowsAndColsList[i][j].second; + } + + // Add row to category + const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first; + const int maxCardCount = cardCountList[maxIndex1][maxIndex2]; + rowsAndColsList[maxIndex1][maxIndex2] = QPair(maxRows + 1, (int) ceil((qreal) maxCardCount / (qreal) (maxRows + 1))); + } + + totalHeight = -spacing; + for (int i = 0; i < contList.size(); ++i) { + DeckViewCardContainer *c = contList[i]; + c->rearrangeItems(rowsAndColsList[i]); + c->setPos(0, totalHeight + spacing); + totalHeight += c->boundingRect().height() + spacing; + } + + totalWidth = totalHeight * optimalAspectRatio; + for (int i = 0; i < contList.size(); ++i) + contList[i]->setWidth(totalWidth); + + setSceneRect(QRectF(0, 0, totalWidth, totalHeight)); } void DeckViewScene::updateContents() { - rearrangeItems(); - emit sideboardPlanChanged(); + rearrangeItems(); + emit sideboardPlanChanged(); } QList DeckViewScene::getSideboardPlan() const { - QList result; - QMapIterator containerIterator(cardContainers); - while (containerIterator.hasNext()) { - DeckViewCardContainer *cont = containerIterator.next().value(); - const QList cardList = cont->getCards(); - for (int i = 0; i < cardList.size(); ++i) - if (cardList[i]->getOriginZone() != cont->getName()) { - MoveCard_ToZone m; - m.set_card_name(cardList[i]->getName().toStdString()); - m.set_start_zone(cardList[i]->getOriginZone().toStdString()); - m.set_target_zone(cont->getName().toStdString()); - result.append(m); - } - } - return result; + QList result; + QMapIterator containerIterator(cardContainers); + while (containerIterator.hasNext()) { + DeckViewCardContainer *cont = containerIterator.next().value(); + const QList cardList = cont->getCards(); + for (int i = 0; i < cardList.size(); ++i) + if (cardList[i]->getOriginZone() != cont->getName()) { + MoveCard_ToZone m; + m.set_card_name(cardList[i]->getName().toStdString()); + m.set_start_zone(cardList[i]->getOriginZone().toStdString()); + m.set_target_zone(cont->getName().toStdString()); + result.append(m); + } + } + return result; } void DeckViewScene::resetSideboardPlan() { - rebuildTree(); - rearrangeItems(); + rebuildTree(); + rearrangeItems(); } DeckView::DeckView(QWidget *parent) - : QGraphicsView(parent) + : QGraphicsView(parent) { - deckViewScene = new DeckViewScene(this); - - setBackgroundBrush(QBrush(QColor(0, 0, 0))); - setDragMode(RubberBandDrag); - setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/); - setScene(deckViewScene); + deckViewScene = new DeckViewScene(this); + + setBackgroundBrush(QBrush(QColor(0, 0, 0))); + setDragMode(RubberBandDrag); + setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing/* | QPainter::SmoothPixmapTransform*/); + setScene(deckViewScene); - connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); - connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); - connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged())); + connect(deckViewScene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); + connect(deckViewScene, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); + connect(deckViewScene, SIGNAL(sideboardPlanChanged()), this, SIGNAL(sideboardPlanChanged())); } void DeckView::resizeEvent(QResizeEvent *event) { - QGraphicsView::resizeEvent(event); - deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height()); - deckViewScene->rearrangeItems(); + QGraphicsView::resizeEvent(event); + deckViewScene->setOptimalAspectRatio((qreal) width() / (qreal) height()); + deckViewScene->rearrangeItems(); } void DeckView::updateSceneRect(const QRectF &rect) { - fitInView(rect, Qt::KeepAspectRatio); + fitInView(rect, Qt::KeepAspectRatio); } void DeckView::setDeck(const DeckList &_deck) { - deckViewScene->setDeck(_deck); + deckViewScene->setDeck(_deck); } void DeckView::resetSideboardPlan() { - deckViewScene->resetSideboardPlan(); + deckViewScene->resetSideboardPlan(); } diff --git a/cockatrice/src/deckview.h b/cockatrice/src/deckview.h index a7aeb2f1..059afa2a 100644 --- a/cockatrice/src/deckview.h +++ b/cockatrice/src/deckview.h @@ -19,101 +19,101 @@ class MoveCardToZone; class DeckViewCard : public AbstractCardItem { private: - QString originZone; - DeckViewCardDragItem *dragItem; + QString originZone; + DeckViewCardDragItem *dragItem; public: - DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0); - ~DeckViewCard(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - const QString &getOriginZone() const { return originZone; } + DeckViewCard(const QString &_name = QString(), const QString &_originZone = QString(), QGraphicsItem *parent = 0); + ~DeckViewCard(); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + const QString &getOriginZone() const { return originZone; } protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); }; class DeckViewCardDragItem : public AbstractCardDragItem { private: - DeckViewCardContainer *currentZone; - void handleDrop(DeckViewCardContainer *target); + DeckViewCardContainer *currentZone; + void handleDrop(DeckViewCardContainer *target); public: - DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); - void updatePosition(const QPointF &cursorScenePos); + DeckViewCardDragItem(DeckViewCard *_item, const QPointF &_hotSpot, AbstractCardDragItem *parentDrag = 0); + void updatePosition(const QPointF &cursorScenePos); protected: - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); }; class DeckViewCardContainer : public QGraphicsItem { private: - static const int separatorY = 20; - static const int paddingY = 10; - - QString name; - QList cards; - QMultiMap cardsByType; - QList > currentRowsAndCols; - qreal width, height; - QPixmap bgPixmap; - int getCardTypeTextWidth() const; + static const int separatorY = 20; + static const int paddingY = 10; + + QString name; + QList cards; + QMultiMap cardsByType; + QList > currentRowsAndCols; + qreal width, height; + QPixmap bgPixmap; + int getCardTypeTextWidth() const; public: - enum { Type = typeDeckViewCardContainer }; - int type() const { return Type; } - DeckViewCardContainer(const QString &_name); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void addCard(DeckViewCard *card); - void removeCard(DeckViewCard *card); - const QList &getCards() const { return cards; } - const QString &getName() const { return name; } - void setWidth(qreal _width); + enum { Type = typeDeckViewCardContainer }; + int type() const { return Type; } + DeckViewCardContainer(const QString &_name); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void addCard(DeckViewCard *card); + void removeCard(DeckViewCard *card); + const QList &getCards() const { return cards; } + const QString &getName() const { return name; } + void setWidth(qreal _width); - QList > getRowsAndCols() const; - QSizeF calculateBoundingRect(const QList > &rowsAndCols) const; - void rearrangeItems(const QList > &rowsAndCols); + QList > getRowsAndCols() const; + QSizeF calculateBoundingRect(const QList > &rowsAndCols) const; + void rearrangeItems(const QList > &rowsAndCols); }; class DeckViewScene : public QGraphicsScene { - Q_OBJECT + Q_OBJECT signals: - void newCardAdded(AbstractCardItem *card); - void sideboardPlanChanged(); + void newCardAdded(AbstractCardItem *card); + void sideboardPlanChanged(); private: - bool locked; - DeckList *deck; - QMap cardContainers; - qreal optimalAspectRatio; - void clearContents(); - void rebuildTree(); - void applySideboardPlan(const QList &plan); + bool locked; + DeckList *deck; + QMap cardContainers; + qreal optimalAspectRatio; + void clearContents(); + void rebuildTree(); + void applySideboardPlan(const QList &plan); public: - DeckViewScene(QObject *parent = 0); - ~DeckViewScene(); - void setLocked(bool _locked) { locked = _locked; } - bool getLocked() const { return locked; } - void setDeck(const DeckList &_deck); - void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; } - void rearrangeItems(); - void updateContents(); - QList getSideboardPlan() const; - void resetSideboardPlan(); + DeckViewScene(QObject *parent = 0); + ~DeckViewScene(); + void setLocked(bool _locked) { locked = _locked; } + bool getLocked() const { return locked; } + void setDeck(const DeckList &_deck); + void setOptimalAspectRatio(qreal _optimalAspectRatio) { optimalAspectRatio = _optimalAspectRatio; } + void rearrangeItems(); + void updateContents(); + QList getSideboardPlan() const; + void resetSideboardPlan(); }; class DeckView : public QGraphicsView { - Q_OBJECT + Q_OBJECT private: - DeckViewScene *deckViewScene; + DeckViewScene *deckViewScene; protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); public slots: - void updateSceneRect(const QRectF &rect); + void updateSceneRect(const QRectF &rect); signals: - void newCardAdded(AbstractCardItem *card); - void sideboardPlanChanged(); + void newCardAdded(AbstractCardItem *card); + void sideboardPlanChanged(); public: - DeckView(QWidget *parent = 0); - void setDeck(const DeckList &_deck); - void setLocked(bool _locked) { deckViewScene->setLocked(_locked); } - QList getSideboardPlan() const { return deckViewScene->getSideboardPlan(); } - void resetSideboardPlan(); + DeckView(QWidget *parent = 0); + void setDeck(const DeckList &_deck); + void setLocked(bool _locked) { deckViewScene->setLocked(_locked); } + QList getSideboardPlan() const { return deckViewScene->getSideboardPlan(); } + void resetSideboardPlan(); }; #endif diff --git a/cockatrice/src/dlg_cardsearch.cpp b/cockatrice/src/dlg_cardsearch.cpp index 55d9419c..e73e11a2 100644 --- a/cockatrice/src/dlg_cardsearch.cpp +++ b/cockatrice/src/dlg_cardsearch.cpp @@ -10,86 +10,86 @@ #include "main.h" DlgCardSearch::DlgCardSearch(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - QLabel *cardNameLabel = new QLabel(tr("Card name:")); - cardNameEdit = new QLineEdit; - - QLabel *cardTextLabel = new QLabel(tr("Card text:")); - cardTextEdit = new QLineEdit; - - QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):")); - const QStringList &cardTypes = db->getAllMainCardTypes(); - QVBoxLayout *cardTypesLayout = new QVBoxLayout; - for (int i = 0; i < cardTypes.size(); ++i) { - QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]); - cardTypeCheckBox->setChecked(true); - cardTypeCheckBoxes.append(cardTypeCheckBox); - cardTypesLayout->addWidget(cardTypeCheckBox); - } - - QLabel *cardColorsLabel = new QLabel(tr("Color (OR):")); - const QStringList &cardColors = db->getAllColors(); - QHBoxLayout *cardColorsLayout = new QHBoxLayout; - for (int i = 0; i < cardColors.size(); ++i) { - QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]); - cardColorCheckBox->setChecked(true); - cardColorCheckBoxes.append(cardColorCheckBox); - cardColorsLayout->addWidget(cardColorCheckBox); - } - - QPushButton *okButton = new QPushButton(tr("O&K")); - okButton->setDefault(true); - okButton->setAutoDefault(true); - QPushButton *cancelButton = new QPushButton(tr("&Cancel")); - connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); - QHBoxLayout *buttonHBox = new QHBoxLayout; - buttonHBox->addStretch(); - buttonHBox->addWidget(okButton); - buttonHBox->addWidget(cancelButton); - - QGridLayout *optionsLayout = new QGridLayout; - optionsLayout->addWidget(cardNameLabel, 0, 0); - optionsLayout->addWidget(cardNameEdit, 0, 1); - optionsLayout->addWidget(cardTextLabel, 1, 0); - optionsLayout->addWidget(cardTextEdit, 1, 1); - optionsLayout->addWidget(cardTypesLabel, 2, 0); - optionsLayout->addLayout(cardTypesLayout, 2, 1); - optionsLayout->addWidget(cardColorsLabel, 3, 0); - optionsLayout->addLayout(cardColorsLayout, 3, 1); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(optionsLayout); - mainLayout->addLayout(buttonHBox); - setLayout(mainLayout); - setWindowTitle(tr("Card search")); + QLabel *cardNameLabel = new QLabel(tr("Card name:")); + cardNameEdit = new QLineEdit; + + QLabel *cardTextLabel = new QLabel(tr("Card text:")); + cardTextEdit = new QLineEdit; + + QLabel *cardTypesLabel = new QLabel(tr("Card type (OR):")); + const QStringList &cardTypes = db->getAllMainCardTypes(); + QVBoxLayout *cardTypesLayout = new QVBoxLayout; + for (int i = 0; i < cardTypes.size(); ++i) { + QCheckBox *cardTypeCheckBox = new QCheckBox(cardTypes[i]); + cardTypeCheckBox->setChecked(true); + cardTypeCheckBoxes.append(cardTypeCheckBox); + cardTypesLayout->addWidget(cardTypeCheckBox); + } + + QLabel *cardColorsLabel = new QLabel(tr("Color (OR):")); + const QStringList &cardColors = db->getAllColors(); + QHBoxLayout *cardColorsLayout = new QHBoxLayout; + for (int i = 0; i < cardColors.size(); ++i) { + QCheckBox *cardColorCheckBox = new QCheckBox(cardColors[i]); + cardColorCheckBox->setChecked(true); + cardColorCheckBoxes.append(cardColorCheckBox); + cardColorsLayout->addWidget(cardColorCheckBox); + } + + QPushButton *okButton = new QPushButton(tr("O&K")); + okButton->setDefault(true); + okButton->setAutoDefault(true); + QPushButton *cancelButton = new QPushButton(tr("&Cancel")); + connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); + connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + QHBoxLayout *buttonHBox = new QHBoxLayout; + buttonHBox->addStretch(); + buttonHBox->addWidget(okButton); + buttonHBox->addWidget(cancelButton); + + QGridLayout *optionsLayout = new QGridLayout; + optionsLayout->addWidget(cardNameLabel, 0, 0); + optionsLayout->addWidget(cardNameEdit, 0, 1); + optionsLayout->addWidget(cardTextLabel, 1, 0); + optionsLayout->addWidget(cardTextEdit, 1, 1); + optionsLayout->addWidget(cardTypesLabel, 2, 0); + optionsLayout->addLayout(cardTypesLayout, 2, 1); + optionsLayout->addWidget(cardColorsLabel, 3, 0); + optionsLayout->addLayout(cardColorsLayout, 3, 1); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(optionsLayout); + mainLayout->addLayout(buttonHBox); + setLayout(mainLayout); + setWindowTitle(tr("Card search")); } QString DlgCardSearch::getCardName() const { - return cardNameEdit->text(); + return cardNameEdit->text(); } QString DlgCardSearch::getCardText() const { - return cardTextEdit->text(); + return cardTextEdit->text(); } QSet DlgCardSearch::getCardTypes() const { - QStringList result; - for (int i = 0; i < cardTypeCheckBoxes.size(); ++i) - if (cardTypeCheckBoxes[i]->isChecked()) - result.append(cardTypeCheckBoxes[i]->text()); - return QSet::fromList(result); + QStringList result; + for (int i = 0; i < cardTypeCheckBoxes.size(); ++i) + if (cardTypeCheckBoxes[i]->isChecked()) + result.append(cardTypeCheckBoxes[i]->text()); + return QSet::fromList(result); } QSet DlgCardSearch::getCardColors() const { - QStringList result; - for (int i = 0; i < cardColorCheckBoxes.size(); ++i) - if (cardColorCheckBoxes[i]->isChecked()) - result.append(cardColorCheckBoxes[i]->text()); - return QSet::fromList(result); + QStringList result; + for (int i = 0; i < cardColorCheckBoxes.size(); ++i) + if (cardColorCheckBoxes[i]->isChecked()) + result.append(cardColorCheckBoxes[i]->text()); + return QSet::fromList(result); } diff --git a/cockatrice/src/dlg_cardsearch.h b/cockatrice/src/dlg_cardsearch.h index 4c2ccccf..0736085f 100644 --- a/cockatrice/src/dlg_cardsearch.h +++ b/cockatrice/src/dlg_cardsearch.h @@ -9,16 +9,16 @@ class QLineEdit; class QCheckBox; class DlgCardSearch : public QDialog { - Q_OBJECT + Q_OBJECT private: - QLineEdit *cardNameEdit, *cardTextEdit; - QList cardTypeCheckBoxes, cardColorCheckBoxes; + QLineEdit *cardNameEdit, *cardTextEdit; + QList cardTypeCheckBoxes, cardColorCheckBoxes; public: - DlgCardSearch(QWidget *parent = 0); - QString getCardName() const; - QString getCardText() const; - QSet getCardTypes() const; - QSet getCardColors() const; + DlgCardSearch(QWidget *parent = 0); + QString getCardName() const; + QString getCardText() const; + QSet getCardTypes() const; + QSet getCardColors() const; }; #endif diff --git a/cockatrice/src/dlg_connect.cpp b/cockatrice/src/dlg_connect.cpp index b645b1eb..d1955d14 100644 --- a/cockatrice/src/dlg_connect.cpp +++ b/cockatrice/src/dlg_connect.cpp @@ -7,66 +7,66 @@ #include "dlg_connect.h" DlgConnect::DlgConnect(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - QSettings settings; - settings.beginGroup("server"); + QSettings settings; + settings.beginGroup("server"); - hostLabel = new QLabel(tr("&Host:")); - hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString()); - hostLabel->setBuddy(hostEdit); + hostLabel = new QLabel(tr("&Host:")); + hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString()); + hostLabel->setBuddy(hostEdit); - portLabel = new QLabel(tr("&Port:")); - portEdit = new QLineEdit(settings.value("port", "4747").toString()); - portLabel->setBuddy(portEdit); + portLabel = new QLabel(tr("&Port:")); + portEdit = new QLineEdit(settings.value("port", "4747").toString()); + portLabel->setBuddy(portEdit); - playernameLabel = new QLabel(tr("Player &name:")); - playernameEdit = new QLineEdit(settings.value("playername", "Player").toString()); - playernameLabel->setBuddy(playernameEdit); + playernameLabel = new QLabel(tr("Player &name:")); + playernameEdit = new QLineEdit(settings.value("playername", "Player").toString()); + playernameLabel->setBuddy(playernameEdit); - passwordLabel = new QLabel(tr("P&assword:")); - passwordEdit = new QLineEdit(settings.value("password").toString()); - passwordLabel->setBuddy(passwordEdit); - passwordEdit->setEchoMode(QLineEdit::Password); - - savePasswordCheckBox = new QCheckBox(tr("&Save password")); - savePasswordCheckBox->setChecked(settings.value("save_password", 1).toInt()); + passwordLabel = new QLabel(tr("P&assword:")); + passwordEdit = new QLineEdit(settings.value("password").toString()); + passwordLabel->setBuddy(passwordEdit); + passwordEdit->setEchoMode(QLineEdit::Password); + + savePasswordCheckBox = new QCheckBox(tr("&Save password")); + savePasswordCheckBox->setChecked(settings.value("save_password", 1).toInt()); - QGridLayout *grid = new QGridLayout; - grid->addWidget(hostLabel, 0, 0); - grid->addWidget(hostEdit, 0, 1); - grid->addWidget(portLabel, 1, 0); - grid->addWidget(portEdit, 1, 1); - grid->addWidget(playernameLabel, 2, 0); - grid->addWidget(playernameEdit, 2, 1); - grid->addWidget(passwordLabel, 3, 0); - grid->addWidget(passwordEdit, 3, 1); - grid->addWidget(savePasswordCheckBox, 4, 0, 1, 2); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(grid); - mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + QGridLayout *grid = new QGridLayout; + grid->addWidget(hostLabel, 0, 0); + grid->addWidget(hostEdit, 0, 1); + grid->addWidget(portLabel, 1, 0); + grid->addWidget(portEdit, 1, 1); + grid->addWidget(playernameLabel, 2, 0); + grid->addWidget(playernameEdit, 2, 1); + grid->addWidget(passwordLabel, 3, 0); + grid->addWidget(passwordEdit, 3, 1); + grid->addWidget(savePasswordCheckBox, 4, 0, 1, 2); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(grid); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); - setWindowTitle(tr("Connect to server")); - setFixedHeight(sizeHint().height()); - setMinimumWidth(300); + setWindowTitle(tr("Connect to server")); + setFixedHeight(sizeHint().height()); + setMinimumWidth(300); } void DlgConnect::actOk() { - QSettings settings; - settings.beginGroup("server"); - settings.setValue("hostname", hostEdit->text()); - settings.setValue("port", portEdit->text()); - settings.setValue("playername", playernameEdit->text()); - settings.setValue("password", savePasswordCheckBox->isChecked() ? passwordEdit->text() : QString()); - settings.setValue("save_password", savePasswordCheckBox->isChecked() ? 1 : 0); - settings.endGroup(); + QSettings settings; + settings.beginGroup("server"); + settings.setValue("hostname", hostEdit->text()); + settings.setValue("port", portEdit->text()); + settings.setValue("playername", playernameEdit->text()); + settings.setValue("password", savePasswordCheckBox->isChecked() ? passwordEdit->text() : QString()); + settings.setValue("save_password", savePasswordCheckBox->isChecked() ? 1 : 0); + settings.endGroup(); - accept(); + accept(); } diff --git a/cockatrice/src/dlg_connect.h b/cockatrice/src/dlg_connect.h index 9a292c34..87fe4ed9 100644 --- a/cockatrice/src/dlg_connect.h +++ b/cockatrice/src/dlg_connect.h @@ -9,19 +9,19 @@ class QPushButton; class QCheckBox; class DlgConnect : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgConnect(QWidget *parent = 0); - QString getHost() const { return hostEdit->text(); } - int getPort() const { return portEdit->text().toInt(); } - QString getPlayerName() const { return playernameEdit->text(); } - QString getPassword() const { return passwordEdit->text(); } + DlgConnect(QWidget *parent = 0); + QString getHost() const { return hostEdit->text(); } + int getPort() const { return portEdit->text().toInt(); } + QString getPlayerName() const { return playernameEdit->text(); } + QString getPassword() const { return passwordEdit->text(); } private slots: - void actOk(); + void actOk(); private: - QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel; - QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit; - QCheckBox *savePasswordCheckBox; + QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel; + QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit; + QCheckBox *savePasswordCheckBox; }; #endif diff --git a/cockatrice/src/dlg_create_token.cpp b/cockatrice/src/dlg_create_token.cpp index 21d2eeac..942fdda6 100644 --- a/cockatrice/src/dlg_create_token.cpp +++ b/cockatrice/src/dlg_create_token.cpp @@ -16,160 +16,160 @@ #include "main.h" DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent) - : QDialog(parent), predefinedTokens(_predefinedTokens) + : QDialog(parent), predefinedTokens(_predefinedTokens) { - nameLabel = new QLabel(tr("&Name:")); - nameEdit = new QLineEdit(tr("Token")); - nameEdit->selectAll(); - nameLabel->setBuddy(nameEdit); + nameLabel = new QLabel(tr("&Name:")); + nameEdit = new QLineEdit(tr("Token")); + nameEdit->selectAll(); + nameLabel->setBuddy(nameEdit); - colorLabel = new QLabel(tr("C&olor:")); - colorEdit = new QComboBox; - colorEdit->addItem(tr("white"), "w"); - colorEdit->addItem(tr("blue"), "u"); - colorEdit->addItem(tr("black"), "b"); - colorEdit->addItem(tr("red"), "r"); - colorEdit->addItem(tr("green"), "g"); - colorEdit->addItem(tr("multicolor"), "m"); - colorEdit->addItem(tr("colorless"), QString()); - colorLabel->setBuddy(colorEdit); + colorLabel = new QLabel(tr("C&olor:")); + colorEdit = new QComboBox; + colorEdit->addItem(tr("white"), "w"); + colorEdit->addItem(tr("blue"), "u"); + colorEdit->addItem(tr("black"), "b"); + colorEdit->addItem(tr("red"), "r"); + colorEdit->addItem(tr("green"), "g"); + colorEdit->addItem(tr("multicolor"), "m"); + colorEdit->addItem(tr("colorless"), QString()); + colorLabel->setBuddy(colorEdit); - ptLabel = new QLabel(tr("&P/T:")); - ptEdit = new QLineEdit; - ptLabel->setBuddy(ptEdit); + ptLabel = new QLabel(tr("&P/T:")); + ptEdit = new QLineEdit; + ptLabel->setBuddy(ptEdit); - annotationLabel = new QLabel(tr("&Annotation:")); - annotationEdit = new QLineEdit; - annotationLabel->setBuddy(annotationEdit); - - destroyCheckBox = new QCheckBox(tr("&Destroy token when it leaves the table")); - destroyCheckBox->setChecked(true); + annotationLabel = new QLabel(tr("&Annotation:")); + annotationEdit = new QLineEdit; + annotationLabel->setBuddy(annotationEdit); + + destroyCheckBox = new QCheckBox(tr("&Destroy token when it leaves the table")); + destroyCheckBox->setChecked(true); - QGridLayout *grid = new QGridLayout; - grid->addWidget(nameLabel, 0, 0); - grid->addWidget(nameEdit, 0, 1); - grid->addWidget(colorLabel, 1, 0); - grid->addWidget(colorEdit, 1, 1); - grid->addWidget(ptLabel, 2, 0); - grid->addWidget(ptEdit, 2, 1); - grid->addWidget(annotationLabel, 3, 0); - grid->addWidget(annotationEdit, 3, 1); - grid->addWidget(destroyCheckBox, 4, 0, 1, 2); - - QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); - tokenDataGroupBox->setLayout(grid); - - cardDatabaseModel = new CardDatabaseModel(db, this); - cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); - cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); - cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); - - chooseTokenFromAllRadioButton = new QRadioButton(tr("Show &all tokens")); - connect(chooseTokenFromAllRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromAll(bool))); - chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck")); - connect(chooseTokenFromDeckRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromDeck(bool))); - QTreeView *chooseTokenView = new QTreeView; - chooseTokenView->setModel(cardDatabaseDisplayModel); - chooseTokenView->setUniformRowHeights(true); - chooseTokenView->setRootIsDecorated(false); - chooseTokenView->setAlternatingRowColors(true); - chooseTokenView->setSortingEnabled(true); - chooseTokenView->sortByColumn(0, Qt::AscendingOrder); - chooseTokenView->resizeColumnToContents(0); - chooseTokenView->header()->setStretchLastSection(false); - chooseTokenView->header()->hideSection(1); - chooseTokenView->header()->hideSection(2); - chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); - chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); - connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); - - if (predefinedTokens.isEmpty()) - chooseTokenFromAllRadioButton->setChecked(true); - else { - chooseTokenFromDeckRadioButton->setChecked(true); - cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); - } - - QVBoxLayout *tokenChooseLayout = new QVBoxLayout; - tokenChooseLayout->addWidget(chooseTokenFromAllRadioButton); - tokenChooseLayout->addWidget(chooseTokenFromDeckRadioButton); - tokenChooseLayout->addWidget(chooseTokenView); - - QGroupBox *tokenChooseGroupBox = new QGroupBox(tr("Choose token from list")); - tokenChooseGroupBox->setLayout(tokenChooseLayout); - - QVBoxLayout *leftVBox = new QVBoxLayout; - leftVBox->addWidget(tokenDataGroupBox); - leftVBox->addStretch(); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addLayout(leftVBox); - hbox->addWidget(tokenChooseGroupBox); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hbox); - mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + QGridLayout *grid = new QGridLayout; + grid->addWidget(nameLabel, 0, 0); + grid->addWidget(nameEdit, 0, 1); + grid->addWidget(colorLabel, 1, 0); + grid->addWidget(colorEdit, 1, 1); + grid->addWidget(ptLabel, 2, 0); + grid->addWidget(ptEdit, 2, 1); + grid->addWidget(annotationLabel, 3, 0); + grid->addWidget(annotationEdit, 3, 1); + grid->addWidget(destroyCheckBox, 4, 0, 1, 2); + + QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); + tokenDataGroupBox->setLayout(grid); + + cardDatabaseModel = new CardDatabaseModel(db, this); + cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); + cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); + cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); + + chooseTokenFromAllRadioButton = new QRadioButton(tr("Show &all tokens")); + connect(chooseTokenFromAllRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromAll(bool))); + chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck")); + connect(chooseTokenFromDeckRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromDeck(bool))); + QTreeView *chooseTokenView = new QTreeView; + chooseTokenView->setModel(cardDatabaseDisplayModel); + chooseTokenView->setUniformRowHeights(true); + chooseTokenView->setRootIsDecorated(false); + chooseTokenView->setAlternatingRowColors(true); + chooseTokenView->setSortingEnabled(true); + chooseTokenView->sortByColumn(0, Qt::AscendingOrder); + chooseTokenView->resizeColumnToContents(0); + chooseTokenView->header()->setStretchLastSection(false); + chooseTokenView->header()->hideSection(1); + chooseTokenView->header()->hideSection(2); + chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); + chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); + connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); + + if (predefinedTokens.isEmpty()) + chooseTokenFromAllRadioButton->setChecked(true); + else { + chooseTokenFromDeckRadioButton->setChecked(true); + cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); + } + + QVBoxLayout *tokenChooseLayout = new QVBoxLayout; + tokenChooseLayout->addWidget(chooseTokenFromAllRadioButton); + tokenChooseLayout->addWidget(chooseTokenFromDeckRadioButton); + tokenChooseLayout->addWidget(chooseTokenView); + + QGroupBox *tokenChooseGroupBox = new QGroupBox(tr("Choose token from list")); + tokenChooseGroupBox->setLayout(tokenChooseLayout); + + QVBoxLayout *leftVBox = new QVBoxLayout; + leftVBox->addWidget(tokenDataGroupBox); + leftVBox->addStretch(); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addLayout(leftVBox); + hbox->addWidget(tokenChooseGroupBox); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hbox); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); - setWindowTitle(tr("Create token")); - setFixedHeight(sizeHint().height()); - setMinimumWidth(300); + setWindowTitle(tr("Create token")); + setFixedHeight(sizeHint().height()); + setMinimumWidth(300); } void DlgCreateToken::tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex & /*previous*/) { - const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); - const CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : db->getCard(); - - nameEdit->setText(cardInfo->getName()); - const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); - colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); - ptEdit->setText(cardInfo->getPowTough()); - annotationEdit->setText(cardInfo->getText()); + const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); + const CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : db->getCard(); + + nameEdit->setText(cardInfo->getName()); + const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); + colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); + ptEdit->setText(cardInfo->getPowTough()); + annotationEdit->setText(cardInfo->getText()); } void DlgCreateToken::actChooseTokenFromAll(bool checked) { - if (checked) - cardDatabaseDisplayModel->setCardNameSet(QSet()); + if (checked) + cardDatabaseDisplayModel->setCardNameSet(QSet()); } void DlgCreateToken::actChooseTokenFromDeck(bool checked) { - if (checked) - cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); + if (checked) + cardDatabaseDisplayModel->setCardNameSet(QSet::fromList(predefinedTokens)); } void DlgCreateToken::actOk() { - accept(); + accept(); } QString DlgCreateToken::getName() const { - return nameEdit->text(); + return nameEdit->text(); } QString DlgCreateToken::getColor() const { - return colorEdit->itemData(colorEdit->currentIndex()).toString(); + return colorEdit->itemData(colorEdit->currentIndex()).toString(); } QString DlgCreateToken::getPT() const { - return ptEdit->text(); + return ptEdit->text(); } QString DlgCreateToken::getAnnotation() const { - return annotationEdit->text(); + return annotationEdit->text(); } bool DlgCreateToken::getDestroy() const { - return destroyCheckBox->isChecked(); + return destroyCheckBox->isChecked(); } diff --git a/cockatrice/src/dlg_create_token.h b/cockatrice/src/dlg_create_token.h index 2bc371fe..45d7c2c5 100644 --- a/cockatrice/src/dlg_create_token.h +++ b/cockatrice/src/dlg_create_token.h @@ -15,28 +15,28 @@ class CardDatabaseModel; class CardDatabaseDisplayModel; class DlgCreateToken : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0); - QString getName() const; - QString getColor() const; - QString getPT() const; - QString getAnnotation() const; - bool getDestroy() const; + DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent = 0); + QString getName() const; + QString getColor() const; + QString getPT() const; + QString getAnnotation() const; + bool getDestroy() const; private slots: - void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); - void actChooseTokenFromAll(bool checked); - void actChooseTokenFromDeck(bool checked); - void actOk(); + void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); + void actChooseTokenFromAll(bool checked); + void actChooseTokenFromDeck(bool checked); + void actOk(); private: - CardDatabaseModel *cardDatabaseModel; - CardDatabaseDisplayModel *cardDatabaseDisplayModel; - QStringList predefinedTokens; - QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; - QComboBox *colorEdit; - QLineEdit *nameEdit, *ptEdit, *annotationEdit; - QCheckBox *destroyCheckBox; - QRadioButton *chooseTokenFromAllRadioButton, *chooseTokenFromDeckRadioButton; + CardDatabaseModel *cardDatabaseModel; + CardDatabaseDisplayModel *cardDatabaseDisplayModel; + QStringList predefinedTokens; + QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; + QComboBox *colorEdit; + QLineEdit *nameEdit, *ptEdit, *annotationEdit; + QCheckBox *destroyCheckBox; + QRadioButton *chooseTokenFromAllRadioButton, *chooseTokenFromDeckRadioButton; }; #endif diff --git a/cockatrice/src/dlg_creategame.cpp b/cockatrice/src/dlg_creategame.cpp index 6dd88901..fc62df7d 100644 --- a/cockatrice/src/dlg_creategame.cpp +++ b/cockatrice/src/dlg_creategame.cpp @@ -20,180 +20,180 @@ void DlgCreateGame::sharedCtor() { - descriptionLabel = new QLabel(tr("&Description:")); - descriptionEdit = new QLineEdit; - descriptionLabel->setBuddy(descriptionEdit); - descriptionEdit->setMaxLength(60); + descriptionLabel = new QLabel(tr("&Description:")); + descriptionEdit = new QLineEdit; + descriptionLabel->setBuddy(descriptionEdit); + descriptionEdit->setMaxLength(60); - maxPlayersLabel = new QLabel(tr("P&layers:")); - maxPlayersEdit = new QSpinBox(); - maxPlayersEdit->setMinimum(1); - maxPlayersEdit->setMaximum(100); - maxPlayersEdit->setValue(2); - maxPlayersLabel->setBuddy(maxPlayersEdit); - - QGridLayout *generalGrid = new QGridLayout; - generalGrid->addWidget(descriptionLabel, 0, 0); - generalGrid->addWidget(descriptionEdit, 0, 1); - generalGrid->addWidget(maxPlayersLabel, 1, 0); - generalGrid->addWidget(maxPlayersEdit, 1, 1); - - QVBoxLayout *gameTypeLayout = new QVBoxLayout; - QMapIterator gameTypeIterator(gameTypes); - while (gameTypeIterator.hasNext()) { - gameTypeIterator.next(); - QCheckBox *gameTypeCheckBox = new QCheckBox(gameTypeIterator.value()); - gameTypeLayout->addWidget(gameTypeCheckBox); - gameTypeCheckBoxes.insert(gameTypeIterator.key(), gameTypeCheckBox); - } - QGroupBox *gameTypeGroupBox = new QGroupBox(tr("Game type")); - gameTypeGroupBox->setLayout(gameTypeLayout); - - passwordLabel = new QLabel(tr("&Password:")); - passwordEdit = new QLineEdit; - passwordLabel->setBuddy(passwordEdit); + maxPlayersLabel = new QLabel(tr("P&layers:")); + maxPlayersEdit = new QSpinBox(); + maxPlayersEdit->setMinimum(1); + maxPlayersEdit->setMaximum(100); + maxPlayersEdit->setValue(2); + maxPlayersLabel->setBuddy(maxPlayersEdit); + + QGridLayout *generalGrid = new QGridLayout; + generalGrid->addWidget(descriptionLabel, 0, 0); + generalGrid->addWidget(descriptionEdit, 0, 1); + generalGrid->addWidget(maxPlayersLabel, 1, 0); + generalGrid->addWidget(maxPlayersEdit, 1, 1); + + QVBoxLayout *gameTypeLayout = new QVBoxLayout; + QMapIterator gameTypeIterator(gameTypes); + while (gameTypeIterator.hasNext()) { + gameTypeIterator.next(); + QCheckBox *gameTypeCheckBox = new QCheckBox(gameTypeIterator.value()); + gameTypeLayout->addWidget(gameTypeCheckBox); + gameTypeCheckBoxes.insert(gameTypeIterator.key(), gameTypeCheckBox); + } + QGroupBox *gameTypeGroupBox = new QGroupBox(tr("Game type")); + gameTypeGroupBox->setLayout(gameTypeLayout); + + passwordLabel = new QLabel(tr("&Password:")); + passwordEdit = new QLineEdit; + passwordLabel->setBuddy(passwordEdit); - onlyBuddiesCheckBox = new QCheckBox(tr("Only &buddies can join")); - onlyRegisteredCheckBox = new QCheckBox(tr("Only ®istered users can join")); - if (room && room->getUserInfo()->user_level() & ServerInfo_User::IsRegistered) - onlyRegisteredCheckBox->setChecked(true); - - QGridLayout *joinRestrictionsLayout = new QGridLayout; - joinRestrictionsLayout->addWidget(passwordLabel, 0, 0); - joinRestrictionsLayout->addWidget(passwordEdit, 0, 1); - joinRestrictionsLayout->addWidget(onlyBuddiesCheckBox, 1, 0, 1, 2); - joinRestrictionsLayout->addWidget(onlyRegisteredCheckBox, 2, 0, 1, 2); - - QGroupBox *joinRestrictionsGroupBox = new QGroupBox(tr("Joining restrictions")); - joinRestrictionsGroupBox->setLayout(joinRestrictionsLayout); - - spectatorsAllowedCheckBox = new QCheckBox(tr("&Spectators allowed")); - spectatorsAllowedCheckBox->setChecked(true); - connect(spectatorsAllowedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(spectatorsAllowedChanged(int))); - spectatorsNeedPasswordCheckBox = new QCheckBox(tr("Spectators &need a password to join")); - spectatorsCanTalkCheckBox = new QCheckBox(tr("Spectators can &chat")); - spectatorsSeeEverythingCheckBox = new QCheckBox(tr("Spectators see &everything")); - QVBoxLayout *spectatorsLayout = new QVBoxLayout; - spectatorsLayout->addWidget(spectatorsAllowedCheckBox); - spectatorsLayout->addWidget(spectatorsNeedPasswordCheckBox); - spectatorsLayout->addWidget(spectatorsCanTalkCheckBox); - spectatorsLayout->addWidget(spectatorsSeeEverythingCheckBox); - spectatorsGroupBox = new QGroupBox(tr("Spectators")); - spectatorsGroupBox->setLayout(spectatorsLayout); + onlyBuddiesCheckBox = new QCheckBox(tr("Only &buddies can join")); + onlyRegisteredCheckBox = new QCheckBox(tr("Only ®istered users can join")); + if (room && room->getUserInfo()->user_level() & ServerInfo_User::IsRegistered) + onlyRegisteredCheckBox->setChecked(true); + + QGridLayout *joinRestrictionsLayout = new QGridLayout; + joinRestrictionsLayout->addWidget(passwordLabel, 0, 0); + joinRestrictionsLayout->addWidget(passwordEdit, 0, 1); + joinRestrictionsLayout->addWidget(onlyBuddiesCheckBox, 1, 0, 1, 2); + joinRestrictionsLayout->addWidget(onlyRegisteredCheckBox, 2, 0, 1, 2); + + QGroupBox *joinRestrictionsGroupBox = new QGroupBox(tr("Joining restrictions")); + joinRestrictionsGroupBox->setLayout(joinRestrictionsLayout); + + spectatorsAllowedCheckBox = new QCheckBox(tr("&Spectators allowed")); + spectatorsAllowedCheckBox->setChecked(true); + connect(spectatorsAllowedCheckBox, SIGNAL(stateChanged(int)), this, SLOT(spectatorsAllowedChanged(int))); + spectatorsNeedPasswordCheckBox = new QCheckBox(tr("Spectators &need a password to join")); + spectatorsCanTalkCheckBox = new QCheckBox(tr("Spectators can &chat")); + spectatorsSeeEverythingCheckBox = new QCheckBox(tr("Spectators see &everything")); + QVBoxLayout *spectatorsLayout = new QVBoxLayout; + spectatorsLayout->addWidget(spectatorsAllowedCheckBox); + spectatorsLayout->addWidget(spectatorsNeedPasswordCheckBox); + spectatorsLayout->addWidget(spectatorsCanTalkCheckBox); + spectatorsLayout->addWidget(spectatorsSeeEverythingCheckBox); + spectatorsGroupBox = new QGroupBox(tr("Spectators")); + spectatorsGroupBox->setLayout(spectatorsLayout); - QGridLayout *grid = new QGridLayout; - grid->addLayout(generalGrid, 0, 0); - grid->addWidget(spectatorsGroupBox, 1, 0); - grid->addWidget(joinRestrictionsGroupBox, 0, 1); - grid->addWidget(gameTypeGroupBox, 1, 1); + QGridLayout *grid = new QGridLayout; + grid->addLayout(generalGrid, 0, 0); + grid->addWidget(spectatorsGroupBox, 1, 0); + grid->addWidget(joinRestrictionsGroupBox, 0, 1); + grid->addWidget(gameTypeGroupBox, 1, 1); - buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(grid); - mainLayout->addWidget(buttonBox); + buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(grid); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + setLayout(mainLayout); - setFixedHeight(sizeHint().height()); + setFixedHeight(sizeHint().height()); } DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent) - : QDialog(parent), room(_room), gameTypes(_gameTypes) + : QDialog(parent), room(_room), gameTypes(_gameTypes) { - sharedCtor(); - - buttonBox->addButton(QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); - - setWindowTitle(tr("Create game")); + sharedCtor(); + + buttonBox->addButton(QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); + + setWindowTitle(tr("Create game")); } DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap &_gameTypes, QWidget *parent) - : QDialog(parent), room(0), gameTypes(_gameTypes) + : QDialog(parent), room(0), gameTypes(_gameTypes) { - sharedCtor(); - - descriptionEdit->setEnabled(false); - maxPlayersEdit->setEnabled(false); - passwordEdit->setEnabled(false); - onlyBuddiesCheckBox->setEnabled(false); - onlyRegisteredCheckBox->setEnabled(false); - spectatorsAllowedCheckBox->setEnabled(false); - spectatorsNeedPasswordCheckBox->setEnabled(false); - spectatorsCanTalkCheckBox->setEnabled(false); - spectatorsSeeEverythingCheckBox->setEnabled(false); - - descriptionEdit->setText(QString::fromStdString(gameInfo.description())); - maxPlayersEdit->setValue(gameInfo.max_players()); - onlyBuddiesCheckBox->setChecked(gameInfo.only_buddies()); - onlyRegisteredCheckBox->setChecked(gameInfo.only_registered()); - spectatorsAllowedCheckBox->setChecked(gameInfo.spectators_allowed()); - spectatorsNeedPasswordCheckBox->setChecked(gameInfo.spectators_need_password()); - spectatorsCanTalkCheckBox->setChecked(gameInfo.spectators_can_chat()); - spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient()); - - QSet types; - for (int i = 0; i < gameInfo.game_types_size(); ++i) - types.insert(gameInfo.game_types(i)); - - QMapIterator gameTypeIterator(gameTypes); - while (gameTypeIterator.hasNext()) { - gameTypeIterator.next(); - - QCheckBox *gameTypeCheckBox = gameTypeCheckBoxes.value(gameTypeIterator.key()); - gameTypeCheckBox->setEnabled(false); - gameTypeCheckBox->setChecked(types.contains(gameTypeIterator.key())); - } - - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - - setWindowTitle(tr("Game information")); + sharedCtor(); + + descriptionEdit->setEnabled(false); + maxPlayersEdit->setEnabled(false); + passwordEdit->setEnabled(false); + onlyBuddiesCheckBox->setEnabled(false); + onlyRegisteredCheckBox->setEnabled(false); + spectatorsAllowedCheckBox->setEnabled(false); + spectatorsNeedPasswordCheckBox->setEnabled(false); + spectatorsCanTalkCheckBox->setEnabled(false); + spectatorsSeeEverythingCheckBox->setEnabled(false); + + descriptionEdit->setText(QString::fromStdString(gameInfo.description())); + maxPlayersEdit->setValue(gameInfo.max_players()); + onlyBuddiesCheckBox->setChecked(gameInfo.only_buddies()); + onlyRegisteredCheckBox->setChecked(gameInfo.only_registered()); + spectatorsAllowedCheckBox->setChecked(gameInfo.spectators_allowed()); + spectatorsNeedPasswordCheckBox->setChecked(gameInfo.spectators_need_password()); + spectatorsCanTalkCheckBox->setChecked(gameInfo.spectators_can_chat()); + spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient()); + + QSet types; + for (int i = 0; i < gameInfo.game_types_size(); ++i) + types.insert(gameInfo.game_types(i)); + + QMapIterator gameTypeIterator(gameTypes); + while (gameTypeIterator.hasNext()) { + gameTypeIterator.next(); + + QCheckBox *gameTypeCheckBox = gameTypeCheckBoxes.value(gameTypeIterator.key()); + gameTypeCheckBox->setEnabled(false); + gameTypeCheckBox->setChecked(types.contains(gameTypeIterator.key())); + } + + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + + setWindowTitle(tr("Game information")); } void DlgCreateGame::actOK() { - Command_CreateGame cmd; - cmd.set_description(descriptionEdit->text().toStdString()); - cmd.set_password(passwordEdit->text().toStdString()); - cmd.set_max_players(maxPlayersEdit->value()); - cmd.set_only_buddies(onlyBuddiesCheckBox->isChecked()); - cmd.set_only_registered(onlyRegisteredCheckBox->isChecked()); - cmd.set_spectators_allowed(spectatorsAllowedCheckBox->isChecked()); - cmd.set_spectators_need_password(spectatorsNeedPasswordCheckBox->isChecked()); - cmd.set_spectators_can_talk(spectatorsCanTalkCheckBox->isChecked()); - cmd.set_spectators_see_everything(spectatorsSeeEverythingCheckBox->isChecked()); - - QMapIterator gameTypeCheckBoxIterator(gameTypeCheckBoxes); - while (gameTypeCheckBoxIterator.hasNext()) { - gameTypeCheckBoxIterator.next(); - if (gameTypeCheckBoxIterator.value()->isChecked()) - cmd.add_game_type_ids(gameTypeCheckBoxIterator.key()); - } - - PendingCommand *pend = room->prepareRoomCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); - room->sendRoomCommand(pend); - - buttonBox->setEnabled(false); + Command_CreateGame cmd; + cmd.set_description(descriptionEdit->text().toStdString()); + cmd.set_password(passwordEdit->text().toStdString()); + cmd.set_max_players(maxPlayersEdit->value()); + cmd.set_only_buddies(onlyBuddiesCheckBox->isChecked()); + cmd.set_only_registered(onlyRegisteredCheckBox->isChecked()); + cmd.set_spectators_allowed(spectatorsAllowedCheckBox->isChecked()); + cmd.set_spectators_need_password(spectatorsNeedPasswordCheckBox->isChecked()); + cmd.set_spectators_can_talk(spectatorsCanTalkCheckBox->isChecked()); + cmd.set_spectators_see_everything(spectatorsSeeEverythingCheckBox->isChecked()); + + QMapIterator gameTypeCheckBoxIterator(gameTypeCheckBoxes); + while (gameTypeCheckBoxIterator.hasNext()) { + gameTypeCheckBoxIterator.next(); + if (gameTypeCheckBoxIterator.value()->isChecked()) + cmd.add_game_type_ids(gameTypeCheckBoxIterator.key()); + } + + PendingCommand *pend = room->prepareRoomCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); + room->sendRoomCommand(pend); + + buttonBox->setEnabled(false); } void DlgCreateGame::checkResponse(const Response &response) { - buttonBox->setEnabled(true); + buttonBox->setEnabled(true); - if (response.response_code() == Response::RespOk) - accept(); - else { - QMessageBox::critical(this, tr("Error"), tr("Server error.")); - return; - } + if (response.response_code() == Response::RespOk) + accept(); + else { + QMessageBox::critical(this, tr("Error"), tr("Server error.")); + return; + } } void DlgCreateGame::spectatorsAllowedChanged(int state) { - spectatorsNeedPasswordCheckBox->setEnabled(state); - spectatorsCanTalkCheckBox->setEnabled(state); - spectatorsSeeEverythingCheckBox->setEnabled(state); + spectatorsNeedPasswordCheckBox->setEnabled(state); + spectatorsCanTalkCheckBox->setEnabled(state); + spectatorsSeeEverythingCheckBox->setEnabled(state); } diff --git a/cockatrice/src/dlg_creategame.h b/cockatrice/src/dlg_creategame.h index b6ee2046..032bfc6f 100644 --- a/cockatrice/src/dlg_creategame.h +++ b/cockatrice/src/dlg_creategame.h @@ -17,28 +17,28 @@ class Response; class ServerInfo_Game; class DlgCreateGame : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent = 0); - DlgCreateGame(const ServerInfo_Game &game, const QMap &_gameTypes, QWidget *parent = 0); + DlgCreateGame(TabRoom *_room, const QMap &_gameTypes, QWidget *parent = 0); + DlgCreateGame(const ServerInfo_Game &game, const QMap &_gameTypes, QWidget *parent = 0); private slots: - void actOK(); - void checkResponse(const Response &response); - void spectatorsAllowedChanged(int state); + void actOK(); + void checkResponse(const Response &response); + void spectatorsAllowedChanged(int state); private: - TabRoom *room; - QMap gameTypes; - QMap gameTypeCheckBoxes; + TabRoom *room; + QMap gameTypes; + QMap gameTypeCheckBoxes; - QGroupBox *spectatorsGroupBox; - QLabel *descriptionLabel, *passwordLabel, *maxPlayersLabel; - QLineEdit *descriptionEdit, *passwordEdit; - QSpinBox *maxPlayersEdit; - QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox; - QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox; - QDialogButtonBox *buttonBox; - - void sharedCtor(); + QGroupBox *spectatorsGroupBox; + QLabel *descriptionLabel, *passwordLabel, *maxPlayersLabel; + QLineEdit *descriptionEdit, *passwordEdit; + QSpinBox *maxPlayersEdit; + QCheckBox *onlyBuddiesCheckBox, *onlyRegisteredCheckBox; + QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox, *spectatorsSeeEverythingCheckBox; + QDialogButtonBox *buttonBox; + + void sharedCtor(); }; #endif diff --git a/cockatrice/src/dlg_edit_tokens.cpp b/cockatrice/src/dlg_edit_tokens.cpp index 4e41d578..038b1a4a 100644 --- a/cockatrice/src/dlg_edit_tokens.cpp +++ b/cockatrice/src/dlg_edit_tokens.cpp @@ -16,160 +16,160 @@ #include DlgEditTokens::DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent) - : QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel) + : QDialog(parent), currentCard(0), cardDatabaseModel(_cardDatabaseModel) { - nameLabel = new QLabel(tr("&Name:")); - nameEdit = new QLineEdit; - nameEdit->setEnabled(false); - nameLabel->setBuddy(nameEdit); - - colorLabel = new QLabel(tr("C&olor:")); - colorEdit = new QComboBox; - colorEdit->addItem(tr("white"), "w"); - colorEdit->addItem(tr("blue"), "u"); - colorEdit->addItem(tr("black"), "b"); - colorEdit->addItem(tr("red"), "r"); - colorEdit->addItem(tr("green"), "g"); - colorEdit->addItem(tr("multicolor"), "m"); - colorEdit->addItem(tr("colorless"), QString()); - colorLabel->setBuddy(colorEdit); - connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int))); - - ptLabel = new QLabel(tr("&P/T:")); - ptEdit = new QLineEdit; - ptLabel->setBuddy(ptEdit); - connect(ptEdit, SIGNAL(textChanged(QString)), this, SLOT(ptChanged(QString))); - - annotationLabel = new QLabel(tr("&Annotation:")); - annotationEdit = new QLineEdit; - annotationLabel->setBuddy(annotationEdit); - connect(annotationEdit, SIGNAL(textChanged(QString)), this, SLOT(annotationChanged(QString))); - - QGridLayout *grid = new QGridLayout; - grid->addWidget(nameLabel, 0, 0); - grid->addWidget(nameEdit, 0, 1); - grid->addWidget(colorLabel, 1, 0); - grid->addWidget(colorEdit, 1, 1); - grid->addWidget(ptLabel, 2, 0); - grid->addWidget(ptEdit, 2, 1); - grid->addWidget(annotationLabel, 3, 0); - grid->addWidget(annotationEdit, 3, 1); - - QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); - tokenDataGroupBox->setLayout(grid); - - cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); - cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); - cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); - - chooseTokenView = new QTreeView; - chooseTokenView->setModel(cardDatabaseDisplayModel); - chooseTokenView->setUniformRowHeights(true); - chooseTokenView->setRootIsDecorated(false); - chooseTokenView->setAlternatingRowColors(true); - chooseTokenView->setSortingEnabled(true); - chooseTokenView->sortByColumn(0, Qt::AscendingOrder); - chooseTokenView->resizeColumnToContents(0); - chooseTokenView->header()->setStretchLastSection(false); - chooseTokenView->header()->hideSection(1); - chooseTokenView->header()->hideSection(2); - chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); - chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); - connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); - - QAction *aAddToken = new QAction(tr("Add token"), this); - aAddToken->setIcon(QIcon(":/resources/increment.svg")); - connect(aAddToken, SIGNAL(triggered()), this, SLOT(actAddToken())); - QAction *aRemoveToken = new QAction(tr("Remove token"), this); - aRemoveToken->setIcon(QIcon(":/resources/decrement.svg")); - connect(aRemoveToken, SIGNAL(triggered()), this, SLOT(actRemoveToken())); - - QToolBar *databaseToolBar = new QToolBar; - databaseToolBar->addAction(aAddToken); - databaseToolBar->addAction(aRemoveToken); - - QVBoxLayout *leftVBox = new QVBoxLayout; - leftVBox->addWidget(chooseTokenView); - leftVBox->addWidget(databaseToolBar); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addLayout(leftVBox); - hbox->addWidget(tokenDataGroupBox); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hbox); - mainLayout->addWidget(buttonBox); + nameLabel = new QLabel(tr("&Name:")); + nameEdit = new QLineEdit; + nameEdit->setEnabled(false); + nameLabel->setBuddy(nameEdit); + + colorLabel = new QLabel(tr("C&olor:")); + colorEdit = new QComboBox; + colorEdit->addItem(tr("white"), "w"); + colorEdit->addItem(tr("blue"), "u"); + colorEdit->addItem(tr("black"), "b"); + colorEdit->addItem(tr("red"), "r"); + colorEdit->addItem(tr("green"), "g"); + colorEdit->addItem(tr("multicolor"), "m"); + colorEdit->addItem(tr("colorless"), QString()); + colorLabel->setBuddy(colorEdit); + connect(colorEdit, SIGNAL(currentIndexChanged(int)), this, SLOT(colorChanged(int))); + + ptLabel = new QLabel(tr("&P/T:")); + ptEdit = new QLineEdit; + ptLabel->setBuddy(ptEdit); + connect(ptEdit, SIGNAL(textChanged(QString)), this, SLOT(ptChanged(QString))); + + annotationLabel = new QLabel(tr("&Annotation:")); + annotationEdit = new QLineEdit; + annotationLabel->setBuddy(annotationEdit); + connect(annotationEdit, SIGNAL(textChanged(QString)), this, SLOT(annotationChanged(QString))); + + QGridLayout *grid = new QGridLayout; + grid->addWidget(nameLabel, 0, 0); + grid->addWidget(nameEdit, 0, 1); + grid->addWidget(colorLabel, 1, 0); + grid->addWidget(colorEdit, 1, 1); + grid->addWidget(ptLabel, 2, 0); + grid->addWidget(ptEdit, 2, 1); + grid->addWidget(annotationLabel, 3, 0); + grid->addWidget(annotationEdit, 3, 1); + + QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data")); + tokenDataGroupBox->setLayout(grid); + + cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this); + cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel); + cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue); + + chooseTokenView = new QTreeView; + chooseTokenView->setModel(cardDatabaseDisplayModel); + chooseTokenView->setUniformRowHeights(true); + chooseTokenView->setRootIsDecorated(false); + chooseTokenView->setAlternatingRowColors(true); + chooseTokenView->setSortingEnabled(true); + chooseTokenView->sortByColumn(0, Qt::AscendingOrder); + chooseTokenView->resizeColumnToContents(0); + chooseTokenView->header()->setStretchLastSection(false); + chooseTokenView->header()->hideSection(1); + chooseTokenView->header()->hideSection(2); + chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents); + chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents); + connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex))); + + QAction *aAddToken = new QAction(tr("Add token"), this); + aAddToken->setIcon(QIcon(":/resources/increment.svg")); + connect(aAddToken, SIGNAL(triggered()), this, SLOT(actAddToken())); + QAction *aRemoveToken = new QAction(tr("Remove token"), this); + aRemoveToken->setIcon(QIcon(":/resources/decrement.svg")); + connect(aRemoveToken, SIGNAL(triggered()), this, SLOT(actRemoveToken())); + + QToolBar *databaseToolBar = new QToolBar; + databaseToolBar->addAction(aAddToken); + databaseToolBar->addAction(aRemoveToken); + + QVBoxLayout *leftVBox = new QVBoxLayout; + leftVBox->addWidget(chooseTokenView); + leftVBox->addWidget(databaseToolBar); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addLayout(leftVBox); + hbox->addWidget(tokenDataGroupBox); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hbox); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); - setWindowTitle(tr("Edit tokens")); + setLayout(mainLayout); + setWindowTitle(tr("Edit tokens")); } void DlgEditTokens::tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous) { - const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); - CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard(); - if (!cardInfo->getName().isEmpty()) - currentCard = cardInfo; - else - currentCard = 0; - - nameEdit->setText(cardInfo->getName()); - const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); - colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); - ptEdit->setText(cardInfo->getPowTough()); - annotationEdit->setText(cardInfo->getText()); + const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current); + CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard(); + if (!cardInfo->getName().isEmpty()) + currentCard = cardInfo; + else + currentCard = 0; + + nameEdit->setText(cardInfo->getName()); + const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first()); + colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); + ptEdit->setText(cardInfo->getPowTough()); + annotationEdit->setText(cardInfo->getText()); } void DlgEditTokens::actAddToken() { - QString name; - bool askAgain; - do { - name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:")); - if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) { - QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.")); - askAgain = true; - } else - askAgain = false; - } while (askAgain); - - if (name.isEmpty()) - return; - - CardInfo *card = new CardInfo(cardDatabaseModel->getDatabase(), name, true); - card->addToSet(cardDatabaseModel->getDatabase()->getSet("TK")); - card->setCardType("Token"); - cardDatabaseModel->getDatabase()->addCard(card); + QString name; + bool askAgain; + do { + name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:")); + if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) { + QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token.")); + askAgain = true; + } else + askAgain = false; + } while (askAgain); + + if (name.isEmpty()) + return; + + CardInfo *card = new CardInfo(cardDatabaseModel->getDatabase(), name, true); + card->addToSet(cardDatabaseModel->getDatabase()->getSet("TK")); + card->setCardType("Token"); + cardDatabaseModel->getDatabase()->addCard(card); } void DlgEditTokens::actRemoveToken() { - if (currentCard) { - CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() - currentCard = 0; - cardDatabaseModel->getDatabase()->removeCard(cardToRemove); - delete cardToRemove; - } + if (currentCard) { + CardInfo *cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() + currentCard = 0; + cardDatabaseModel->getDatabase()->removeCard(cardToRemove); + delete cardToRemove; + } } void DlgEditTokens::colorChanged(int colorIndex) { - if (currentCard) - currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString()); + if (currentCard) + currentCard->setColors(QStringList() << colorEdit->itemData(colorIndex).toString()); } void DlgEditTokens::ptChanged(const QString &_pt) { - if (currentCard) - currentCard->setPowTough(_pt); + if (currentCard) + currentCard->setPowTough(_pt); } void DlgEditTokens::annotationChanged(const QString &_annotation) { - if (currentCard) - currentCard->setText(_annotation); + if (currentCard) + currentCard->setText(_annotation); } diff --git a/cockatrice/src/dlg_edit_tokens.h b/cockatrice/src/dlg_edit_tokens.h index ac36512e..61d941ff 100644 --- a/cockatrice/src/dlg_edit_tokens.h +++ b/cockatrice/src/dlg_edit_tokens.h @@ -13,26 +13,26 @@ class QTreeView; class CardInfo; class DlgEditTokens : public QDialog { - Q_OBJECT + Q_OBJECT private slots: - void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); - void colorChanged(int _colorIndex); - void ptChanged(const QString &_pt); - void annotationChanged(const QString &_annotation); - - void actAddToken(); - void actRemoveToken(); + void tokenSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); + void colorChanged(int _colorIndex); + void ptChanged(const QString &_pt); + void annotationChanged(const QString &_annotation); + + void actAddToken(); + void actRemoveToken(); private: - CardInfo *currentCard; - CardDatabaseModel *cardDatabaseModel; - CardDatabaseDisplayModel *cardDatabaseDisplayModel; - QStringList predefinedTokens; - QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; - QComboBox *colorEdit; - QLineEdit *nameEdit, *ptEdit, *annotationEdit; - QTreeView *chooseTokenView; + CardInfo *currentCard; + CardDatabaseModel *cardDatabaseModel; + CardDatabaseDisplayModel *cardDatabaseDisplayModel; + QStringList predefinedTokens; + QLabel *nameLabel, *colorLabel, *ptLabel, *annotationLabel; + QComboBox *colorEdit; + QLineEdit *nameEdit, *ptEdit, *annotationEdit; + QTreeView *chooseTokenView; public: - DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0); + DlgEditTokens(CardDatabaseModel *_cardDatabaseModel, QWidget *parent = 0); }; #endif diff --git a/cockatrice/src/dlg_filter_games.cpp b/cockatrice/src/dlg_filter_games.cpp index 721a3d20..5e402294 100644 --- a/cockatrice/src/dlg_filter_games.cpp +++ b/cockatrice/src/dlg_filter_games.cpp @@ -11,162 +11,162 @@ #include DlgFilterGames::DlgFilterGames(const QMap &allGameTypes, QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - unavailableGamesVisibleCheckBox = new QCheckBox(tr("Show &unavailable games")); - passwordProtectedGamesVisibleCheckBox = new QCheckBox(tr("Show &password protected games")); - - QLabel *gameNameFilterLabel = new QLabel(tr("Game &description:")); - gameNameFilterEdit = new QLineEdit; - gameNameFilterLabel->setBuddy(gameNameFilterEdit); - - QLabel *creatorNameFilterLabel = new QLabel(tr("&Creator name:")); - creatorNameFilterEdit = new QLineEdit; - creatorNameFilterLabel->setBuddy(creatorNameFilterEdit); - - QVBoxLayout *gameTypeFilterLayout = new QVBoxLayout; - QMapIterator gameTypesIterator(allGameTypes); - while (gameTypesIterator.hasNext()) { - gameTypesIterator.next(); - QCheckBox *temp = new QCheckBox(gameTypesIterator.value()); - gameTypeFilterCheckBoxes.insert(gameTypesIterator.key(), temp); - gameTypeFilterLayout->addWidget(temp); - } - QGroupBox *gameTypeFilterGroupBox; - if (!allGameTypes.isEmpty()) { - gameTypeFilterGroupBox = new QGroupBox(tr("&Game types")); - gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout); - } else - gameTypeFilterGroupBox = 0; - - QLabel *maxPlayersFilterMinLabel = new QLabel(tr("at &least:")); - maxPlayersFilterMinSpinBox = new QSpinBox; - maxPlayersFilterMinSpinBox->setMinimum(1); - maxPlayersFilterMinSpinBox->setMaximum(99); - maxPlayersFilterMinSpinBox->setValue(1); - maxPlayersFilterMinLabel->setBuddy(maxPlayersFilterMinSpinBox); - - QLabel *maxPlayersFilterMaxLabel = new QLabel(tr("at &most:")); - maxPlayersFilterMaxSpinBox = new QSpinBox; - maxPlayersFilterMaxSpinBox->setMinimum(1); - maxPlayersFilterMaxSpinBox->setMaximum(99); - maxPlayersFilterMaxSpinBox->setValue(99); - maxPlayersFilterMaxLabel->setBuddy(maxPlayersFilterMaxSpinBox); - - QGridLayout *maxPlayersFilterLayout = new QGridLayout; - maxPlayersFilterLayout->addWidget(maxPlayersFilterMinLabel, 0, 0); - maxPlayersFilterLayout->addWidget(maxPlayersFilterMinSpinBox, 0, 1); - maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxLabel, 1, 0); - maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxSpinBox, 1, 1); - - QGroupBox *maxPlayersGroupBox = new QGroupBox(tr("Maximum player count")); - maxPlayersGroupBox->setLayout(maxPlayersFilterLayout); - - QGridLayout *leftGrid = new QGridLayout; - leftGrid->addWidget(gameNameFilterLabel, 0, 0); - leftGrid->addWidget(gameNameFilterEdit, 0, 1); - leftGrid->addWidget(creatorNameFilterLabel, 1, 0); - leftGrid->addWidget(creatorNameFilterEdit, 1, 1); - leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2); - leftGrid->addWidget(unavailableGamesVisibleCheckBox, 3, 0, 1, 2); - leftGrid->addWidget(passwordProtectedGamesVisibleCheckBox, 4, 0, 1, 2); - - QVBoxLayout *leftColumn = new QVBoxLayout; - leftColumn->addLayout(leftGrid); - leftColumn->addStretch(); - - QVBoxLayout *rightColumn = new QVBoxLayout; - rightColumn->addWidget(gameTypeFilterGroupBox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addLayout(leftColumn); - hbox->addLayout(rightColumn); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hbox); - mainLayout->addWidget(buttonBox); - - setLayout(mainLayout); - setWindowTitle(tr("Filter games")); + unavailableGamesVisibleCheckBox = new QCheckBox(tr("Show &unavailable games")); + passwordProtectedGamesVisibleCheckBox = new QCheckBox(tr("Show &password protected games")); + + QLabel *gameNameFilterLabel = new QLabel(tr("Game &description:")); + gameNameFilterEdit = new QLineEdit; + gameNameFilterLabel->setBuddy(gameNameFilterEdit); + + QLabel *creatorNameFilterLabel = new QLabel(tr("&Creator name:")); + creatorNameFilterEdit = new QLineEdit; + creatorNameFilterLabel->setBuddy(creatorNameFilterEdit); + + QVBoxLayout *gameTypeFilterLayout = new QVBoxLayout; + QMapIterator gameTypesIterator(allGameTypes); + while (gameTypesIterator.hasNext()) { + gameTypesIterator.next(); + QCheckBox *temp = new QCheckBox(gameTypesIterator.value()); + gameTypeFilterCheckBoxes.insert(gameTypesIterator.key(), temp); + gameTypeFilterLayout->addWidget(temp); + } + QGroupBox *gameTypeFilterGroupBox; + if (!allGameTypes.isEmpty()) { + gameTypeFilterGroupBox = new QGroupBox(tr("&Game types")); + gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout); + } else + gameTypeFilterGroupBox = 0; + + QLabel *maxPlayersFilterMinLabel = new QLabel(tr("at &least:")); + maxPlayersFilterMinSpinBox = new QSpinBox; + maxPlayersFilterMinSpinBox->setMinimum(1); + maxPlayersFilterMinSpinBox->setMaximum(99); + maxPlayersFilterMinSpinBox->setValue(1); + maxPlayersFilterMinLabel->setBuddy(maxPlayersFilterMinSpinBox); + + QLabel *maxPlayersFilterMaxLabel = new QLabel(tr("at &most:")); + maxPlayersFilterMaxSpinBox = new QSpinBox; + maxPlayersFilterMaxSpinBox->setMinimum(1); + maxPlayersFilterMaxSpinBox->setMaximum(99); + maxPlayersFilterMaxSpinBox->setValue(99); + maxPlayersFilterMaxLabel->setBuddy(maxPlayersFilterMaxSpinBox); + + QGridLayout *maxPlayersFilterLayout = new QGridLayout; + maxPlayersFilterLayout->addWidget(maxPlayersFilterMinLabel, 0, 0); + maxPlayersFilterLayout->addWidget(maxPlayersFilterMinSpinBox, 0, 1); + maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxLabel, 1, 0); + maxPlayersFilterLayout->addWidget(maxPlayersFilterMaxSpinBox, 1, 1); + + QGroupBox *maxPlayersGroupBox = new QGroupBox(tr("Maximum player count")); + maxPlayersGroupBox->setLayout(maxPlayersFilterLayout); + + QGridLayout *leftGrid = new QGridLayout; + leftGrid->addWidget(gameNameFilterLabel, 0, 0); + leftGrid->addWidget(gameNameFilterEdit, 0, 1); + leftGrid->addWidget(creatorNameFilterLabel, 1, 0); + leftGrid->addWidget(creatorNameFilterEdit, 1, 1); + leftGrid->addWidget(maxPlayersGroupBox, 2, 0, 1, 2); + leftGrid->addWidget(unavailableGamesVisibleCheckBox, 3, 0, 1, 2); + leftGrid->addWidget(passwordProtectedGamesVisibleCheckBox, 4, 0, 1, 2); + + QVBoxLayout *leftColumn = new QVBoxLayout; + leftColumn->addLayout(leftGrid); + leftColumn->addStretch(); + + QVBoxLayout *rightColumn = new QVBoxLayout; + rightColumn->addWidget(gameTypeFilterGroupBox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addLayout(leftColumn); + hbox->addLayout(rightColumn); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hbox); + mainLayout->addWidget(buttonBox); + + setLayout(mainLayout); + setWindowTitle(tr("Filter games")); } bool DlgFilterGames::getUnavailableGamesVisible() const { - return unavailableGamesVisibleCheckBox->isChecked(); + return unavailableGamesVisibleCheckBox->isChecked(); } void DlgFilterGames::setUnavailableGamesVisible(bool _unavailableGamesVisible) { - unavailableGamesVisibleCheckBox->setChecked(_unavailableGamesVisible); + unavailableGamesVisibleCheckBox->setChecked(_unavailableGamesVisible); } bool DlgFilterGames::getPasswordProtectedGamesVisible() const { - return passwordProtectedGamesVisibleCheckBox->isChecked(); + return passwordProtectedGamesVisibleCheckBox->isChecked(); } void DlgFilterGames::setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible) { - passwordProtectedGamesVisibleCheckBox->setChecked(_passwordProtectedGamesVisible); + passwordProtectedGamesVisibleCheckBox->setChecked(_passwordProtectedGamesVisible); } QString DlgFilterGames::getGameNameFilter() const { - return gameNameFilterEdit->text(); + return gameNameFilterEdit->text(); } void DlgFilterGames::setGameNameFilter(const QString &_gameNameFilter) { - gameNameFilterEdit->setText(_gameNameFilter); + gameNameFilterEdit->setText(_gameNameFilter); } QString DlgFilterGames::getCreatorNameFilter() const { - return creatorNameFilterEdit->text(); + return creatorNameFilterEdit->text(); } void DlgFilterGames::setCreatorNameFilter(const QString &_creatorNameFilter) { - creatorNameFilterEdit->setText(_creatorNameFilter); + creatorNameFilterEdit->setText(_creatorNameFilter); } QSet DlgFilterGames::getGameTypeFilter() const { - QSet result; - QMapIterator i(gameTypeFilterCheckBoxes); - while (i.hasNext()) { - i.next(); - if (i.value()->isChecked()) - result.insert(i.key()); - } - return result; + QSet result; + QMapIterator i(gameTypeFilterCheckBoxes); + while (i.hasNext()) { + i.next(); + if (i.value()->isChecked()) + result.insert(i.key()); + } + return result; } void DlgFilterGames::setGameTypeFilter(const QSet &_gameTypeFilter) { - QMapIterator i(gameTypeFilterCheckBoxes); - while (i.hasNext()) { - i.next(); - i.value()->setChecked(_gameTypeFilter.contains(i.key())); - } + QMapIterator i(gameTypeFilterCheckBoxes); + while (i.hasNext()) { + i.next(); + i.value()->setChecked(_gameTypeFilter.contains(i.key())); + } } int DlgFilterGames::getMaxPlayersFilterMin() const { - return maxPlayersFilterMinSpinBox->value(); + return maxPlayersFilterMinSpinBox->value(); } int DlgFilterGames::getMaxPlayersFilterMax() const { - return maxPlayersFilterMaxSpinBox->value(); + return maxPlayersFilterMaxSpinBox->value(); } void DlgFilterGames::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax) { - maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin); - maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax); + maxPlayersFilterMinSpinBox->setValue(_maxPlayersFilterMin); + maxPlayersFilterMaxSpinBox->setValue(_maxPlayersFilterMax == -1 ? maxPlayersFilterMaxSpinBox->maximum() : _maxPlayersFilterMax); } diff --git a/cockatrice/src/dlg_filter_games.h b/cockatrice/src/dlg_filter_games.h index 5c768bc1..8059da45 100644 --- a/cockatrice/src/dlg_filter_games.h +++ b/cockatrice/src/dlg_filter_games.h @@ -10,31 +10,31 @@ class QLineEdit; class QSpinBox; class DlgFilterGames : public QDialog { - Q_OBJECT + Q_OBJECT private: - QCheckBox *unavailableGamesVisibleCheckBox; - QCheckBox *passwordProtectedGamesVisibleCheckBox; - QLineEdit *gameNameFilterEdit; - QLineEdit *creatorNameFilterEdit; - QMap gameTypeFilterCheckBoxes; - QSpinBox *maxPlayersFilterMinSpinBox; - QSpinBox *maxPlayersFilterMaxSpinBox; + QCheckBox *unavailableGamesVisibleCheckBox; + QCheckBox *passwordProtectedGamesVisibleCheckBox; + QLineEdit *gameNameFilterEdit; + QLineEdit *creatorNameFilterEdit; + QMap gameTypeFilterCheckBoxes; + QSpinBox *maxPlayersFilterMinSpinBox; + QSpinBox *maxPlayersFilterMaxSpinBox; public: - DlgFilterGames(const QMap &allGameTypes, QWidget *parent = 0); - - bool getUnavailableGamesVisible() const; - void setUnavailableGamesVisible(bool _unavailableGamesVisible); - bool getPasswordProtectedGamesVisible() const; - void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); - QString getGameNameFilter() const; - void setGameNameFilter(const QString &_gameNameFilter); - QString getCreatorNameFilter() const; - void setCreatorNameFilter(const QString &_creatorNameFilter); - QSet getGameTypeFilter() const; - void setGameTypeFilter(const QSet &_gameTypeFilter); - int getMaxPlayersFilterMin() const; - int getMaxPlayersFilterMax() const; - void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); + DlgFilterGames(const QMap &allGameTypes, QWidget *parent = 0); + + bool getUnavailableGamesVisible() const; + void setUnavailableGamesVisible(bool _unavailableGamesVisible); + bool getPasswordProtectedGamesVisible() const; + void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); + QString getGameNameFilter() const; + void setGameNameFilter(const QString &_gameNameFilter); + QString getCreatorNameFilter() const; + void setCreatorNameFilter(const QString &_creatorNameFilter); + QSet getGameTypeFilter() const; + void setGameTypeFilter(const QSet &_gameTypeFilter); + int getMaxPlayersFilterMin() const; + int getMaxPlayersFilterMax() const; + void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); }; #endif diff --git a/cockatrice/src/dlg_load_deck_from_clipboard.cpp b/cockatrice/src/dlg_load_deck_from_clipboard.cpp index 0744ff7e..3eb3428f 100644 --- a/cockatrice/src/dlg_load_deck_from_clipboard.cpp +++ b/cockatrice/src/dlg_load_deck_from_clipboard.cpp @@ -12,47 +12,47 @@ #include "deck_loader.h" DlgLoadDeckFromClipboard::DlgLoadDeckFromClipboard(QWidget *parent) - : QDialog(parent), deckList(0) + : QDialog(parent), deckList(0) { - contentsEdit = new QPlainTextEdit; - - refreshButton = new QPushButton(tr("&Refresh")); - refreshButton->setShortcut(QKeySequence("F5")); - connect(refreshButton, SIGNAL(clicked()), this, SLOT(actRefresh())); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(contentsEdit); - mainLayout->addWidget(buttonBox); + contentsEdit = new QPlainTextEdit; + + refreshButton = new QPushButton(tr("&Refresh")); + refreshButton->setShortcut(QKeySequence("F5")); + connect(refreshButton, SIGNAL(clicked()), this, SLOT(actRefresh())); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOK())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(contentsEdit); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + setLayout(mainLayout); - setWindowTitle(tr("Load deck from clipboard")); - resize(500, 500); - - actRefresh(); + setWindowTitle(tr("Load deck from clipboard")); + resize(500, 500); + + actRefresh(); } void DlgLoadDeckFromClipboard::actRefresh() { - contentsEdit->setPlainText(QApplication::clipboard()->text()); + contentsEdit->setPlainText(QApplication::clipboard()->text()); } void DlgLoadDeckFromClipboard::actOK() { - QString buffer = contentsEdit->toPlainText(); - QTextStream stream(&buffer); - - DeckLoader *l = new DeckLoader; - if (l->loadFromStream_Plain(stream)) { - deckList = l; - accept(); - } else { - QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); - delete l; - } + QString buffer = contentsEdit->toPlainText(); + QTextStream stream(&buffer); + + DeckLoader *l = new DeckLoader; + if (l->loadFromStream_Plain(stream)) { + deckList = l; + accept(); + } else { + QMessageBox::critical(this, tr("Error"), tr("Invalid deck list.")); + delete l; + } } diff --git a/cockatrice/src/dlg_load_deck_from_clipboard.h b/cockatrice/src/dlg_load_deck_from_clipboard.h index 5fcd759e..375c713d 100644 --- a/cockatrice/src/dlg_load_deck_from_clipboard.h +++ b/cockatrice/src/dlg_load_deck_from_clipboard.h @@ -8,18 +8,18 @@ class QPlainTextEdit; class QPushButton; class DlgLoadDeckFromClipboard : public QDialog { - Q_OBJECT + Q_OBJECT private slots: - void actOK(); - void actRefresh(); + void actOK(); + void actRefresh(); private: - DeckLoader *deckList; + DeckLoader *deckList; public: - DlgLoadDeckFromClipboard(QWidget *parent = 0); - DeckLoader *getDeckList() const { return deckList; } + DlgLoadDeckFromClipboard(QWidget *parent = 0); + DeckLoader *getDeckList() const { return deckList; } private: - QPlainTextEdit *contentsEdit; - QPushButton *refreshButton; + QPlainTextEdit *contentsEdit; + QPushButton *refreshButton; }; #endif diff --git a/cockatrice/src/dlg_load_remote_deck.cpp b/cockatrice/src/dlg_load_remote_deck.cpp index 1ebcf056..09b820ac 100644 --- a/cockatrice/src/dlg_load_remote_deck.cpp +++ b/cockatrice/src/dlg_load_remote_deck.cpp @@ -7,34 +7,34 @@ #include "main.h" DlgLoadRemoteDeck::DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent) - : QDialog(parent), client(_client) + : QDialog(parent), client(_client) { - dirView = new RemoteDeckList_TreeWidget(client); - - buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + dirView = new RemoteDeckList_TreeWidget(client); + + buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(dirView); - mainLayout->addWidget(buttonBox); + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(dirView); + mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + setLayout(mainLayout); - setWindowTitle(tr("Load deck")); - setMinimumWidth(sizeHint().width()); - resize(400, 600); + setWindowTitle(tr("Load deck")); + setMinimumWidth(sizeHint().width()); + resize(400, 600); - connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &))); + connect(dirView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &))); } void DlgLoadRemoteDeck::currentItemChanged(const QModelIndex ¤t, const QModelIndex & /*previous*/) { - buttonBox->button(QDialogButtonBox::Ok)->setEnabled(dynamic_cast(dirView->getNode(current))); + buttonBox->button(QDialogButtonBox::Ok)->setEnabled(dynamic_cast(dirView->getNode(current))); } int DlgLoadRemoteDeck::getDeckId() const { - return dynamic_cast(dirView->getNode(dirView->selectionModel()->currentIndex()))->getId(); + return dynamic_cast(dirView->getNode(dirView->selectionModel()->currentIndex()))->getId(); } diff --git a/cockatrice/src/dlg_load_remote_deck.h b/cockatrice/src/dlg_load_remote_deck.h index 304934a5..5fd78258 100644 --- a/cockatrice/src/dlg_load_remote_deck.h +++ b/cockatrice/src/dlg_load_remote_deck.h @@ -10,16 +10,16 @@ class QPushButton; class QDialogButtonBox; class DlgLoadRemoteDeck: public QDialog { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - RemoteDeckList_TreeWidget *dirView; - QDialogButtonBox *buttonBox; + AbstractClient *client; + RemoteDeckList_TreeWidget *dirView; + QDialogButtonBox *buttonBox; private slots: - void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous); + void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous); public: - DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0); - int getDeckId() const; + DlgLoadRemoteDeck(AbstractClient *_client, QWidget *parent = 0); + int getDeckId() const; }; #endif diff --git a/cockatrice/src/dlg_settings.cpp b/cockatrice/src/dlg_settings.cpp index 112efad4..32d4f1fb 100644 --- a/cockatrice/src/dlg_settings.cpp +++ b/cockatrice/src/dlg_settings.cpp @@ -25,707 +25,707 @@ GeneralSettingsPage::GeneralSettingsPage() { - languageLabel = new QLabel; - languageBox = new QComboBox; - - QString setLanguage = settingsCache->getLang(); - QStringList qmFiles = findQmFiles(); - for (int i = 0; i < qmFiles.size(); i++) { - QString langName = languageName(qmFiles[i]); - languageBox->addItem(langName, qmFiles[i]); - if ((qmFiles[i] == setLanguage) || (setLanguage.isEmpty() && langName == tr("English"))) - languageBox->setCurrentIndex(i); - } - - picDownloadCheckBox = new QCheckBox; - picDownloadCheckBox->setChecked(settingsCache->getPicDownload()); - - connect(languageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(languageBoxChanged(int))); - connect(picDownloadCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPicDownload(int))); - - QGridLayout *personalGrid = new QGridLayout; - personalGrid->addWidget(languageLabel, 0, 0); - personalGrid->addWidget(languageBox, 0, 1); - personalGrid->addWidget(picDownloadCheckBox, 1, 0, 1, 2); - - personalGroupBox = new QGroupBox; - personalGroupBox->setLayout(personalGrid); - - deckPathLabel = new QLabel; - deckPathEdit = new QLineEdit(settingsCache->getDeckPath()); - deckPathEdit->setReadOnly(true); - QPushButton *deckPathButton = new QPushButton("..."); - connect(deckPathButton, SIGNAL(clicked()), this, SLOT(deckPathButtonClicked())); - - replaysPathLabel = new QLabel; - replaysPathEdit = new QLineEdit(settingsCache->getReplaysPath()); - replaysPathEdit->setReadOnly(true); - QPushButton *replaysPathButton = new QPushButton("..."); - connect(replaysPathButton, SIGNAL(clicked()), this, SLOT(replaysPathButtonClicked())); - - picsPathLabel = new QLabel; - picsPathEdit = new QLineEdit(settingsCache->getPicsPath()); - picsPathEdit->setReadOnly(true); - QPushButton *picsPathButton = new QPushButton("..."); - connect(picsPathButton, SIGNAL(clicked()), this, SLOT(picsPathButtonClicked())); - - cardDatabasePathLabel = new QLabel; - cardDatabasePathEdit = new QLineEdit(settingsCache->getCardDatabasePath()); - cardDatabasePathEdit->setReadOnly(true); - QPushButton *cardDatabasePathButton = new QPushButton("..."); - connect(cardDatabasePathButton, SIGNAL(clicked()), this, SLOT(cardDatabasePathButtonClicked())); - - tokenDatabasePathLabel = new QLabel; - tokenDatabasePathEdit = new QLineEdit(settingsCache->getTokenDatabasePath()); - tokenDatabasePathEdit->setReadOnly(true); - QPushButton *tokenDatabasePathButton = new QPushButton("..."); - connect(tokenDatabasePathButton, SIGNAL(clicked()), this, SLOT(tokenDatabasePathButtonClicked())); - - QGridLayout *pathsGrid = new QGridLayout; - pathsGrid->addWidget(deckPathLabel, 0, 0); - pathsGrid->addWidget(deckPathEdit, 0, 1); - pathsGrid->addWidget(deckPathButton, 0, 2); - pathsGrid->addWidget(replaysPathLabel, 1, 0); - pathsGrid->addWidget(replaysPathEdit, 1, 1); - pathsGrid->addWidget(replaysPathButton, 1, 2); - pathsGrid->addWidget(picsPathLabel, 2, 0); - pathsGrid->addWidget(picsPathEdit, 2, 1); - pathsGrid->addWidget(picsPathButton, 2, 2); - pathsGrid->addWidget(cardDatabasePathLabel, 3, 0); - pathsGrid->addWidget(cardDatabasePathEdit, 3, 1); - pathsGrid->addWidget(cardDatabasePathButton, 3, 2); - pathsGrid->addWidget(tokenDatabasePathLabel, 4, 0); - pathsGrid->addWidget(tokenDatabasePathEdit, 4, 1); - pathsGrid->addWidget(tokenDatabasePathButton, 4, 2); - pathsGroupBox = new QGroupBox; - pathsGroupBox->setLayout(pathsGrid); + languageLabel = new QLabel; + languageBox = new QComboBox; + + QString setLanguage = settingsCache->getLang(); + QStringList qmFiles = findQmFiles(); + for (int i = 0; i < qmFiles.size(); i++) { + QString langName = languageName(qmFiles[i]); + languageBox->addItem(langName, qmFiles[i]); + if ((qmFiles[i] == setLanguage) || (setLanguage.isEmpty() && langName == tr("English"))) + languageBox->setCurrentIndex(i); + } + + picDownloadCheckBox = new QCheckBox; + picDownloadCheckBox->setChecked(settingsCache->getPicDownload()); + + connect(languageBox, SIGNAL(currentIndexChanged(int)), this, SLOT(languageBoxChanged(int))); + connect(picDownloadCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPicDownload(int))); + + QGridLayout *personalGrid = new QGridLayout; + personalGrid->addWidget(languageLabel, 0, 0); + personalGrid->addWidget(languageBox, 0, 1); + personalGrid->addWidget(picDownloadCheckBox, 1, 0, 1, 2); + + personalGroupBox = new QGroupBox; + personalGroupBox->setLayout(personalGrid); + + deckPathLabel = new QLabel; + deckPathEdit = new QLineEdit(settingsCache->getDeckPath()); + deckPathEdit->setReadOnly(true); + QPushButton *deckPathButton = new QPushButton("..."); + connect(deckPathButton, SIGNAL(clicked()), this, SLOT(deckPathButtonClicked())); + + replaysPathLabel = new QLabel; + replaysPathEdit = new QLineEdit(settingsCache->getReplaysPath()); + replaysPathEdit->setReadOnly(true); + QPushButton *replaysPathButton = new QPushButton("..."); + connect(replaysPathButton, SIGNAL(clicked()), this, SLOT(replaysPathButtonClicked())); + + picsPathLabel = new QLabel; + picsPathEdit = new QLineEdit(settingsCache->getPicsPath()); + picsPathEdit->setReadOnly(true); + QPushButton *picsPathButton = new QPushButton("..."); + connect(picsPathButton, SIGNAL(clicked()), this, SLOT(picsPathButtonClicked())); + + cardDatabasePathLabel = new QLabel; + cardDatabasePathEdit = new QLineEdit(settingsCache->getCardDatabasePath()); + cardDatabasePathEdit->setReadOnly(true); + QPushButton *cardDatabasePathButton = new QPushButton("..."); + connect(cardDatabasePathButton, SIGNAL(clicked()), this, SLOT(cardDatabasePathButtonClicked())); + + tokenDatabasePathLabel = new QLabel; + tokenDatabasePathEdit = new QLineEdit(settingsCache->getTokenDatabasePath()); + tokenDatabasePathEdit->setReadOnly(true); + QPushButton *tokenDatabasePathButton = new QPushButton("..."); + connect(tokenDatabasePathButton, SIGNAL(clicked()), this, SLOT(tokenDatabasePathButtonClicked())); + + QGridLayout *pathsGrid = new QGridLayout; + pathsGrid->addWidget(deckPathLabel, 0, 0); + pathsGrid->addWidget(deckPathEdit, 0, 1); + pathsGrid->addWidget(deckPathButton, 0, 2); + pathsGrid->addWidget(replaysPathLabel, 1, 0); + pathsGrid->addWidget(replaysPathEdit, 1, 1); + pathsGrid->addWidget(replaysPathButton, 1, 2); + pathsGrid->addWidget(picsPathLabel, 2, 0); + pathsGrid->addWidget(picsPathEdit, 2, 1); + pathsGrid->addWidget(picsPathButton, 2, 2); + pathsGrid->addWidget(cardDatabasePathLabel, 3, 0); + pathsGrid->addWidget(cardDatabasePathEdit, 3, 1); + pathsGrid->addWidget(cardDatabasePathButton, 3, 2); + pathsGrid->addWidget(tokenDatabasePathLabel, 4, 0); + pathsGrid->addWidget(tokenDatabasePathEdit, 4, 1); + pathsGrid->addWidget(tokenDatabasePathButton, 4, 2); + pathsGroupBox = new QGroupBox; + pathsGroupBox->setLayout(pathsGrid); - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(personalGroupBox); - mainLayout->addWidget(pathsGroupBox); - - setLayout(mainLayout); + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(personalGroupBox); + mainLayout->addWidget(pathsGroupBox); + + setLayout(mainLayout); } QStringList GeneralSettingsPage::findQmFiles() { - QDir dir(translationPath); - QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name); - fileNames.replaceInStrings(QRegExp(translationPrefix + "_(.*)\\.qm"), "\\1"); - return fileNames; + QDir dir(translationPath); + QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name); + fileNames.replaceInStrings(QRegExp(translationPrefix + "_(.*)\\.qm"), "\\1"); + return fileNames; } QString GeneralSettingsPage::languageName(const QString &qmFile) { - QTranslator translator; - translator.load(translationPrefix + "_" + qmFile + ".qm", translationPath); - - return translator.translate("GeneralSettingsPage", "English"); + QTranslator translator; + translator.load(translationPrefix + "_" + qmFile + ".qm", translationPath); + + return translator.translate("GeneralSettingsPage", "English"); } void GeneralSettingsPage::deckPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - deckPathEdit->setText(path); - settingsCache->setDeckPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + deckPathEdit->setText(path); + settingsCache->setDeckPath(path); } void GeneralSettingsPage::replaysPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - replaysPathEdit->setText(path); - settingsCache->setReplaysPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + replaysPathEdit->setText(path); + settingsCache->setReplaysPath(path); } void GeneralSettingsPage::picsPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - picsPathEdit->setText(path); - settingsCache->setPicsPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + picsPathEdit->setText(path); + settingsCache->setPicsPath(path); } void GeneralSettingsPage::cardDatabasePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - cardDatabasePathEdit->setText(path); - settingsCache->setCardDatabasePath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + cardDatabasePathEdit->setText(path); + settingsCache->setCardDatabasePath(path); } void GeneralSettingsPage::tokenDatabasePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - tokenDatabasePathEdit->setText(path); - settingsCache->setTokenDatabasePath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + tokenDatabasePathEdit->setText(path); + settingsCache->setTokenDatabasePath(path); } void GeneralSettingsPage::languageBoxChanged(int index) { - settingsCache->setLang(languageBox->itemData(index).toString()); + settingsCache->setLang(languageBox->itemData(index).toString()); } void GeneralSettingsPage::retranslateUi() { - personalGroupBox->setTitle(tr("Personal settings")); - languageLabel->setText(tr("Language:")); - picDownloadCheckBox->setText(tr("Download card pictures on the fly")); - pathsGroupBox->setTitle(tr("Paths")); - deckPathLabel->setText(tr("Decks directory:")); - replaysPathLabel->setText(tr("Replays directory:")); - picsPathLabel->setText(tr("Pictures directory:")); - cardDatabasePathLabel->setText(tr("Path to card database:")); - tokenDatabasePathLabel->setText(tr("Path to token database:")); + personalGroupBox->setTitle(tr("Personal settings")); + languageLabel->setText(tr("Language:")); + picDownloadCheckBox->setText(tr("Download card pictures on the fly")); + pathsGroupBox->setTitle(tr("Paths")); + deckPathLabel->setText(tr("Decks directory:")); + replaysPathLabel->setText(tr("Replays directory:")); + picsPathLabel->setText(tr("Pictures directory:")); + cardDatabasePathLabel->setText(tr("Path to card database:")); + tokenDatabasePathLabel->setText(tr("Path to token database:")); } AppearanceSettingsPage::AppearanceSettingsPage() { - QIcon deleteIcon(":/resources/icon_delete.svg"); - - handBgLabel = new QLabel; - handBgEdit = new QLineEdit(settingsCache->getHandBgPath()); - handBgEdit->setReadOnly(true); - QPushButton *handBgClearButton = new QPushButton(deleteIcon, QString()); - connect(handBgClearButton, SIGNAL(clicked()), this, SLOT(handBgClearButtonClicked())); - QPushButton *handBgButton = new QPushButton("..."); - connect(handBgButton, SIGNAL(clicked()), this, SLOT(handBgButtonClicked())); - - stackBgLabel = new QLabel; - stackBgEdit = new QLineEdit(settingsCache->getStackBgPath()); - stackBgEdit->setReadOnly(true); - QPushButton *stackBgClearButton = new QPushButton(deleteIcon, QString()); - connect(stackBgClearButton, SIGNAL(clicked()), this, SLOT(stackBgClearButtonClicked())); - QPushButton *stackBgButton = new QPushButton("..."); - connect(stackBgButton, SIGNAL(clicked()), this, SLOT(stackBgButtonClicked())); + QIcon deleteIcon(":/resources/icon_delete.svg"); + + handBgLabel = new QLabel; + handBgEdit = new QLineEdit(settingsCache->getHandBgPath()); + handBgEdit->setReadOnly(true); + QPushButton *handBgClearButton = new QPushButton(deleteIcon, QString()); + connect(handBgClearButton, SIGNAL(clicked()), this, SLOT(handBgClearButtonClicked())); + QPushButton *handBgButton = new QPushButton("..."); + connect(handBgButton, SIGNAL(clicked()), this, SLOT(handBgButtonClicked())); + + stackBgLabel = new QLabel; + stackBgEdit = new QLineEdit(settingsCache->getStackBgPath()); + stackBgEdit->setReadOnly(true); + QPushButton *stackBgClearButton = new QPushButton(deleteIcon, QString()); + connect(stackBgClearButton, SIGNAL(clicked()), this, SLOT(stackBgClearButtonClicked())); + QPushButton *stackBgButton = new QPushButton("..."); + connect(stackBgButton, SIGNAL(clicked()), this, SLOT(stackBgButtonClicked())); - tableBgLabel = new QLabel; - tableBgEdit = new QLineEdit(settingsCache->getTableBgPath()); - tableBgEdit->setReadOnly(true); - QPushButton *tableBgClearButton = new QPushButton(deleteIcon, QString()); - connect(tableBgClearButton, SIGNAL(clicked()), this, SLOT(tableBgClearButtonClicked())); - QPushButton *tableBgButton = new QPushButton("..."); - connect(tableBgButton, SIGNAL(clicked()), this, SLOT(tableBgButtonClicked())); - - playerAreaBgLabel = new QLabel; - playerAreaBgEdit = new QLineEdit(settingsCache->getPlayerBgPath()); - playerAreaBgEdit->setReadOnly(true); - QPushButton *playerAreaBgClearButton = new QPushButton(deleteIcon, QString()); - connect(playerAreaBgClearButton, SIGNAL(clicked()), this, SLOT(playerAreaBgClearButtonClicked())); - QPushButton *playerAreaBgButton = new QPushButton("..."); - connect(playerAreaBgButton, SIGNAL(clicked()), this, SLOT(playerAreaBgButtonClicked())); - - cardBackPicturePathLabel = new QLabel; - cardBackPicturePathEdit = new QLineEdit(settingsCache->getCardBackPicturePath()); - cardBackPicturePathEdit->setReadOnly(true); - QPushButton *cardBackPicturePathClearButton = new QPushButton(deleteIcon, QString()); - connect(cardBackPicturePathClearButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathClearButtonClicked())); - QPushButton *cardBackPicturePathButton = new QPushButton("..."); - connect(cardBackPicturePathButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathButtonClicked())); - - QGridLayout *zoneBgGrid = new QGridLayout; - zoneBgGrid->addWidget(handBgLabel, 0, 0); - zoneBgGrid->addWidget(handBgEdit, 0, 1); - zoneBgGrid->addWidget(handBgClearButton, 0, 2); - zoneBgGrid->addWidget(handBgButton, 0, 3); - zoneBgGrid->addWidget(stackBgLabel, 1, 0); - zoneBgGrid->addWidget(stackBgEdit, 1, 1); - zoneBgGrid->addWidget(stackBgClearButton, 1, 2); - zoneBgGrid->addWidget(stackBgButton, 1, 3); - zoneBgGrid->addWidget(tableBgLabel, 2, 0); - zoneBgGrid->addWidget(tableBgEdit, 2, 1); - zoneBgGrid->addWidget(tableBgClearButton, 2, 2); - zoneBgGrid->addWidget(tableBgButton, 2, 3); - zoneBgGrid->addWidget(playerAreaBgLabel, 3, 0); - zoneBgGrid->addWidget(playerAreaBgEdit, 3, 1); - zoneBgGrid->addWidget(playerAreaBgClearButton, 3, 2); - zoneBgGrid->addWidget(playerAreaBgButton, 3, 3); - zoneBgGrid->addWidget(cardBackPicturePathLabel, 4, 0); - zoneBgGrid->addWidget(cardBackPicturePathEdit, 4, 1); - zoneBgGrid->addWidget(cardBackPicturePathClearButton, 4, 2); - zoneBgGrid->addWidget(cardBackPicturePathButton, 4, 3); + tableBgLabel = new QLabel; + tableBgEdit = new QLineEdit(settingsCache->getTableBgPath()); + tableBgEdit->setReadOnly(true); + QPushButton *tableBgClearButton = new QPushButton(deleteIcon, QString()); + connect(tableBgClearButton, SIGNAL(clicked()), this, SLOT(tableBgClearButtonClicked())); + QPushButton *tableBgButton = new QPushButton("..."); + connect(tableBgButton, SIGNAL(clicked()), this, SLOT(tableBgButtonClicked())); + + playerAreaBgLabel = new QLabel; + playerAreaBgEdit = new QLineEdit(settingsCache->getPlayerBgPath()); + playerAreaBgEdit->setReadOnly(true); + QPushButton *playerAreaBgClearButton = new QPushButton(deleteIcon, QString()); + connect(playerAreaBgClearButton, SIGNAL(clicked()), this, SLOT(playerAreaBgClearButtonClicked())); + QPushButton *playerAreaBgButton = new QPushButton("..."); + connect(playerAreaBgButton, SIGNAL(clicked()), this, SLOT(playerAreaBgButtonClicked())); + + cardBackPicturePathLabel = new QLabel; + cardBackPicturePathEdit = new QLineEdit(settingsCache->getCardBackPicturePath()); + cardBackPicturePathEdit->setReadOnly(true); + QPushButton *cardBackPicturePathClearButton = new QPushButton(deleteIcon, QString()); + connect(cardBackPicturePathClearButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathClearButtonClicked())); + QPushButton *cardBackPicturePathButton = new QPushButton("..."); + connect(cardBackPicturePathButton, SIGNAL(clicked()), this, SLOT(cardBackPicturePathButtonClicked())); + + QGridLayout *zoneBgGrid = new QGridLayout; + zoneBgGrid->addWidget(handBgLabel, 0, 0); + zoneBgGrid->addWidget(handBgEdit, 0, 1); + zoneBgGrid->addWidget(handBgClearButton, 0, 2); + zoneBgGrid->addWidget(handBgButton, 0, 3); + zoneBgGrid->addWidget(stackBgLabel, 1, 0); + zoneBgGrid->addWidget(stackBgEdit, 1, 1); + zoneBgGrid->addWidget(stackBgClearButton, 1, 2); + zoneBgGrid->addWidget(stackBgButton, 1, 3); + zoneBgGrid->addWidget(tableBgLabel, 2, 0); + zoneBgGrid->addWidget(tableBgEdit, 2, 1); + zoneBgGrid->addWidget(tableBgClearButton, 2, 2); + zoneBgGrid->addWidget(tableBgButton, 2, 3); + zoneBgGrid->addWidget(playerAreaBgLabel, 3, 0); + zoneBgGrid->addWidget(playerAreaBgEdit, 3, 1); + zoneBgGrid->addWidget(playerAreaBgClearButton, 3, 2); + zoneBgGrid->addWidget(playerAreaBgButton, 3, 3); + zoneBgGrid->addWidget(cardBackPicturePathLabel, 4, 0); + zoneBgGrid->addWidget(cardBackPicturePathEdit, 4, 1); + zoneBgGrid->addWidget(cardBackPicturePathClearButton, 4, 2); + zoneBgGrid->addWidget(cardBackPicturePathButton, 4, 3); - zoneBgGroupBox = new QGroupBox; - zoneBgGroupBox->setLayout(zoneBgGrid); + zoneBgGroupBox = new QGroupBox; + zoneBgGroupBox->setLayout(zoneBgGrid); - displayCardNamesCheckBox = new QCheckBox; - displayCardNamesCheckBox->setChecked(settingsCache->getDisplayCardNames()); - connect(displayCardNamesCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDisplayCardNames(int))); - - QGridLayout *cardsGrid = new QGridLayout; - cardsGrid->addWidget(displayCardNamesCheckBox, 0, 0, 1, 2); - - cardsGroupBox = new QGroupBox; - cardsGroupBox->setLayout(cardsGrid); - - horizontalHandCheckBox = new QCheckBox; - horizontalHandCheckBox->setChecked(settingsCache->getHorizontalHand()); - connect(horizontalHandCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setHorizontalHand(int))); - - QGridLayout *handGrid = new QGridLayout; - handGrid->addWidget(horizontalHandCheckBox, 0, 0, 1, 2); - - handGroupBox = new QGroupBox; - handGroupBox->setLayout(handGrid); - - invertVerticalCoordinateCheckBox = new QCheckBox; - invertVerticalCoordinateCheckBox->setChecked(settingsCache->getInvertVerticalCoordinate()); - connect(invertVerticalCoordinateCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setInvertVerticalCoordinate(int))); - - minPlayersForMultiColumnLayoutLabel = new QLabel; - minPlayersForMultiColumnLayoutEdit = new QSpinBox; - minPlayersForMultiColumnLayoutEdit->setMinimum(2); - minPlayersForMultiColumnLayoutEdit->setValue(settingsCache->getMinPlayersForMultiColumnLayout()); - connect(minPlayersForMultiColumnLayoutEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMinPlayersForMultiColumnLayout(int))); - minPlayersForMultiColumnLayoutLabel->setBuddy(minPlayersForMultiColumnLayoutEdit); - - QGridLayout *tableGrid = new QGridLayout; - tableGrid->addWidget(invertVerticalCoordinateCheckBox, 0, 0, 1, 2); - tableGrid->addWidget(minPlayersForMultiColumnLayoutLabel, 1, 0, 1, 1); - tableGrid->addWidget(minPlayersForMultiColumnLayoutEdit, 1, 1, 1, 1); - - tableGroupBox = new QGroupBox; - tableGroupBox->setLayout(tableGrid); - - zoneViewSortByNameCheckBox = new QCheckBox; - zoneViewSortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); - connect(zoneViewSortByNameCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByName(int))); - zoneViewSortByTypeCheckBox = new QCheckBox; - zoneViewSortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); - connect(zoneViewSortByTypeCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByType(int))); + displayCardNamesCheckBox = new QCheckBox; + displayCardNamesCheckBox->setChecked(settingsCache->getDisplayCardNames()); + connect(displayCardNamesCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDisplayCardNames(int))); + + QGridLayout *cardsGrid = new QGridLayout; + cardsGrid->addWidget(displayCardNamesCheckBox, 0, 0, 1, 2); + + cardsGroupBox = new QGroupBox; + cardsGroupBox->setLayout(cardsGrid); + + horizontalHandCheckBox = new QCheckBox; + horizontalHandCheckBox->setChecked(settingsCache->getHorizontalHand()); + connect(horizontalHandCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setHorizontalHand(int))); + + QGridLayout *handGrid = new QGridLayout; + handGrid->addWidget(horizontalHandCheckBox, 0, 0, 1, 2); + + handGroupBox = new QGroupBox; + handGroupBox->setLayout(handGrid); + + invertVerticalCoordinateCheckBox = new QCheckBox; + invertVerticalCoordinateCheckBox->setChecked(settingsCache->getInvertVerticalCoordinate()); + connect(invertVerticalCoordinateCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setInvertVerticalCoordinate(int))); + + minPlayersForMultiColumnLayoutLabel = new QLabel; + minPlayersForMultiColumnLayoutEdit = new QSpinBox; + minPlayersForMultiColumnLayoutEdit->setMinimum(2); + minPlayersForMultiColumnLayoutEdit->setValue(settingsCache->getMinPlayersForMultiColumnLayout()); + connect(minPlayersForMultiColumnLayoutEdit, SIGNAL(valueChanged(int)), settingsCache, SLOT(setMinPlayersForMultiColumnLayout(int))); + minPlayersForMultiColumnLayoutLabel->setBuddy(minPlayersForMultiColumnLayoutEdit); + + QGridLayout *tableGrid = new QGridLayout; + tableGrid->addWidget(invertVerticalCoordinateCheckBox, 0, 0, 1, 2); + tableGrid->addWidget(minPlayersForMultiColumnLayoutLabel, 1, 0, 1, 1); + tableGrid->addWidget(minPlayersForMultiColumnLayoutEdit, 1, 1, 1, 1); + + tableGroupBox = new QGroupBox; + tableGroupBox->setLayout(tableGrid); + + zoneViewSortByNameCheckBox = new QCheckBox; + zoneViewSortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); + connect(zoneViewSortByNameCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByName(int))); + zoneViewSortByTypeCheckBox = new QCheckBox; + zoneViewSortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); + connect(zoneViewSortByTypeCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setZoneViewSortByType(int))); - QGridLayout *zoneViewGrid = new QGridLayout; - zoneViewGrid->addWidget(zoneViewSortByNameCheckBox, 0, 0, 1, 2); - zoneViewGrid->addWidget(zoneViewSortByTypeCheckBox, 1, 0, 1, 2); + QGridLayout *zoneViewGrid = new QGridLayout; + zoneViewGrid->addWidget(zoneViewSortByNameCheckBox, 0, 0, 1, 2); + zoneViewGrid->addWidget(zoneViewSortByTypeCheckBox, 1, 0, 1, 2); - zoneViewGroupBox = new QGroupBox; - zoneViewGroupBox->setLayout(zoneViewGrid); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(zoneBgGroupBox); - mainLayout->addWidget(cardsGroupBox); - mainLayout->addWidget(handGroupBox); - mainLayout->addWidget(tableGroupBox); - mainLayout->addWidget(zoneViewGroupBox); - - setLayout(mainLayout); + zoneViewGroupBox = new QGroupBox; + zoneViewGroupBox->setLayout(zoneViewGrid); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(zoneBgGroupBox); + mainLayout->addWidget(cardsGroupBox); + mainLayout->addWidget(handGroupBox); + mainLayout->addWidget(tableGroupBox); + mainLayout->addWidget(zoneViewGroupBox); + + setLayout(mainLayout); } void AppearanceSettingsPage::retranslateUi() { - zoneBgGroupBox->setTitle(tr("Zone background pictures")); - handBgLabel->setText(tr("Path to hand background:")); - stackBgLabel->setText(tr("Path to stack background:")); - tableBgLabel->setText(tr("Path to table background:")); - playerAreaBgLabel->setText(tr("Path to player info background:")); - cardBackPicturePathLabel->setText(tr("Path to picture of card back:")); - - cardsGroupBox->setTitle(tr("Card rendering")); - displayCardNamesCheckBox->setText(tr("Display card names on cards having a picture")); - - handGroupBox->setTitle(tr("Hand layout")); - horizontalHandCheckBox->setText(tr("Display hand horizontally (wastes space)")); - - tableGroupBox->setTitle(tr("Table grid layout")); - invertVerticalCoordinateCheckBox->setText(tr("Invert vertical coordinate")); - minPlayersForMultiColumnLayoutLabel->setText(tr("Minimum player count for multi-column layout:")); - - zoneViewGroupBox->setTitle(tr("Zone view layout")); - zoneViewSortByNameCheckBox->setText(tr("Sort by name")); - zoneViewSortByTypeCheckBox->setText(tr("Sort by type")); + zoneBgGroupBox->setTitle(tr("Zone background pictures")); + handBgLabel->setText(tr("Path to hand background:")); + stackBgLabel->setText(tr("Path to stack background:")); + tableBgLabel->setText(tr("Path to table background:")); + playerAreaBgLabel->setText(tr("Path to player info background:")); + cardBackPicturePathLabel->setText(tr("Path to picture of card back:")); + + cardsGroupBox->setTitle(tr("Card rendering")); + displayCardNamesCheckBox->setText(tr("Display card names on cards having a picture")); + + handGroupBox->setTitle(tr("Hand layout")); + horizontalHandCheckBox->setText(tr("Display hand horizontally (wastes space)")); + + tableGroupBox->setTitle(tr("Table grid layout")); + invertVerticalCoordinateCheckBox->setText(tr("Invert vertical coordinate")); + minPlayersForMultiColumnLayoutLabel->setText(tr("Minimum player count for multi-column layout:")); + + zoneViewGroupBox->setTitle(tr("Zone view layout")); + zoneViewSortByNameCheckBox->setText(tr("Sort by name")); + zoneViewSortByTypeCheckBox->setText(tr("Sort by type")); } void AppearanceSettingsPage::handBgClearButtonClicked() { - handBgEdit->setText(QString()); - settingsCache->setHandBgPath(QString()); + handBgEdit->setText(QString()); + settingsCache->setHandBgPath(QString()); } void AppearanceSettingsPage::handBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - handBgEdit->setText(path); - settingsCache->setHandBgPath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + handBgEdit->setText(path); + settingsCache->setHandBgPath(path); } void AppearanceSettingsPage::stackBgClearButtonClicked() { - stackBgEdit->setText(QString()); - settingsCache->setStackBgPath(QString()); + stackBgEdit->setText(QString()); + settingsCache->setStackBgPath(QString()); } void AppearanceSettingsPage::stackBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - stackBgEdit->setText(path); - settingsCache->setStackBgPath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + stackBgEdit->setText(path); + settingsCache->setStackBgPath(path); } void AppearanceSettingsPage::tableBgClearButtonClicked() { - tableBgEdit->setText(QString()); - settingsCache->setTableBgPath(QString()); + tableBgEdit->setText(QString()); + settingsCache->setTableBgPath(QString()); } void AppearanceSettingsPage::tableBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; - tableBgEdit->setText(path); - settingsCache->setTableBgPath(path); + tableBgEdit->setText(path); + settingsCache->setTableBgPath(path); } void AppearanceSettingsPage::playerAreaBgClearButtonClicked() { - playerAreaBgEdit->setText(QString()); - settingsCache->setPlayerBgPath(QString()); + playerAreaBgEdit->setText(QString()); + settingsCache->setPlayerBgPath(QString()); } void AppearanceSettingsPage::playerAreaBgButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - playerAreaBgEdit->setText(path); - settingsCache->setPlayerBgPath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + playerAreaBgEdit->setText(path); + settingsCache->setPlayerBgPath(path); } void AppearanceSettingsPage::cardBackPicturePathClearButtonClicked() { - cardBackPicturePathEdit->setText(QString()); - settingsCache->setCardBackPicturePath(QString()); + cardBackPicturePathEdit->setText(QString()); + settingsCache->setCardBackPicturePath(QString()); } void AppearanceSettingsPage::cardBackPicturePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); - if (path.isEmpty()) - return; - - cardBackPicturePathEdit->setText(path); - settingsCache->setCardBackPicturePath(path); + QString path = QFileDialog::getOpenFileName(this, tr("Choose path")); + if (path.isEmpty()) + return; + + cardBackPicturePathEdit->setText(path); + settingsCache->setCardBackPicturePath(path); } UserInterfaceSettingsPage::UserInterfaceSettingsPage() { - QIcon deleteIcon(":/resources/icon_delete.svg"); + QIcon deleteIcon(":/resources/icon_delete.svg"); - notificationsEnabledCheckBox = new QCheckBox; - notificationsEnabledCheckBox->setChecked(settingsCache->getNotificationsEnabled()); - connect(notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotificationsEnabled(int))); + notificationsEnabledCheckBox = new QCheckBox; + notificationsEnabledCheckBox->setChecked(settingsCache->getNotificationsEnabled()); + connect(notificationsEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setNotificationsEnabled(int))); - doubleClickToPlayCheckBox = new QCheckBox; - doubleClickToPlayCheckBox->setChecked(settingsCache->getDoubleClickToPlay()); - connect(doubleClickToPlayCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDoubleClickToPlay(int))); - - playToStackCheckBox = new QCheckBox; - playToStackCheckBox->setChecked(settingsCache->getPlayToStack()); - connect(playToStackCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPlayToStack(int))); - - QGridLayout *generalGrid = new QGridLayout; - generalGrid->addWidget(notificationsEnabledCheckBox, 0, 0); - generalGrid->addWidget(doubleClickToPlayCheckBox, 1, 0); - generalGrid->addWidget(playToStackCheckBox, 2, 0); - - generalGroupBox = new QGroupBox; - generalGroupBox->setLayout(generalGrid); - - tapAnimationCheckBox = new QCheckBox; - tapAnimationCheckBox->setChecked(settingsCache->getTapAnimation()); - connect(tapAnimationCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setTapAnimation(int))); - - soundEnabledCheckBox = new QCheckBox; - soundEnabledCheckBox->setChecked(settingsCache->getSoundEnabled()); - connect(soundEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setSoundEnabled(int))); - - soundPathLabel = new QLabel; - soundPathEdit = new QLineEdit(settingsCache->getSoundPath()); - soundPathEdit->setReadOnly(true); - QPushButton *soundPathClearButton = new QPushButton(deleteIcon, QString()); - connect(soundPathClearButton, SIGNAL(clicked()), this, SLOT(soundPathClearButtonClicked())); - QPushButton *soundPathButton = new QPushButton("..."); - connect(soundPathButton, SIGNAL(clicked()), this, SLOT(soundPathButtonClicked())); - - QGridLayout *soundGrid = new QGridLayout; - soundGrid->addWidget(soundEnabledCheckBox, 0, 0, 1, 4); - soundGrid->addWidget(soundPathLabel, 1, 0); - soundGrid->addWidget(soundPathEdit, 1, 1); - soundGrid->addWidget(soundPathClearButton, 1, 2); - soundGrid->addWidget(soundPathButton, 1, 3); - - soundGroupBox = new QGroupBox; - soundGroupBox->setLayout(soundGrid); - - QGridLayout *animationGrid = new QGridLayout; - animationGrid->addWidget(tapAnimationCheckBox, 0, 0); - - animationGroupBox = new QGroupBox; - animationGroupBox->setLayout(animationGrid); + doubleClickToPlayCheckBox = new QCheckBox; + doubleClickToPlayCheckBox->setChecked(settingsCache->getDoubleClickToPlay()); + connect(doubleClickToPlayCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setDoubleClickToPlay(int))); + + playToStackCheckBox = new QCheckBox; + playToStackCheckBox->setChecked(settingsCache->getPlayToStack()); + connect(playToStackCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPlayToStack(int))); + + QGridLayout *generalGrid = new QGridLayout; + generalGrid->addWidget(notificationsEnabledCheckBox, 0, 0); + generalGrid->addWidget(doubleClickToPlayCheckBox, 1, 0); + generalGrid->addWidget(playToStackCheckBox, 2, 0); + + generalGroupBox = new QGroupBox; + generalGroupBox->setLayout(generalGrid); + + tapAnimationCheckBox = new QCheckBox; + tapAnimationCheckBox->setChecked(settingsCache->getTapAnimation()); + connect(tapAnimationCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setTapAnimation(int))); + + soundEnabledCheckBox = new QCheckBox; + soundEnabledCheckBox->setChecked(settingsCache->getSoundEnabled()); + connect(soundEnabledCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setSoundEnabled(int))); + + soundPathLabel = new QLabel; + soundPathEdit = new QLineEdit(settingsCache->getSoundPath()); + soundPathEdit->setReadOnly(true); + QPushButton *soundPathClearButton = new QPushButton(deleteIcon, QString()); + connect(soundPathClearButton, SIGNAL(clicked()), this, SLOT(soundPathClearButtonClicked())); + QPushButton *soundPathButton = new QPushButton("..."); + connect(soundPathButton, SIGNAL(clicked()), this, SLOT(soundPathButtonClicked())); + + QGridLayout *soundGrid = new QGridLayout; + soundGrid->addWidget(soundEnabledCheckBox, 0, 0, 1, 4); + soundGrid->addWidget(soundPathLabel, 1, 0); + soundGrid->addWidget(soundPathEdit, 1, 1); + soundGrid->addWidget(soundPathClearButton, 1, 2); + soundGrid->addWidget(soundPathButton, 1, 3); + + soundGroupBox = new QGroupBox; + soundGroupBox->setLayout(soundGrid); + + QGridLayout *animationGrid = new QGridLayout; + animationGrid->addWidget(tapAnimationCheckBox, 0, 0); + + animationGroupBox = new QGroupBox; + animationGroupBox->setLayout(animationGrid); - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(generalGroupBox); - mainLayout->addWidget(animationGroupBox); - mainLayout->addWidget(soundGroupBox); - - setLayout(mainLayout); + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(generalGroupBox); + mainLayout->addWidget(animationGroupBox); + mainLayout->addWidget(soundGroupBox); + + setLayout(mainLayout); } void UserInterfaceSettingsPage::retranslateUi() { - generalGroupBox->setTitle(tr("General interface settings")); - notificationsEnabledCheckBox->setText(tr("Enable notifications in taskbar")); - doubleClickToPlayCheckBox->setText(tr("&Double-click cards to play them (instead of single-click)")); - playToStackCheckBox->setText(tr("&Play all nonlands onto the stack (not the battlefield) by default")); - animationGroupBox->setTitle(tr("Animation settings")); - tapAnimationCheckBox->setText(tr("&Tap/untap animation")); - soundEnabledCheckBox->setText(tr("Enable &sounds")); - soundPathLabel->setText(tr("Path to sounds directory:")); + generalGroupBox->setTitle(tr("General interface settings")); + notificationsEnabledCheckBox->setText(tr("Enable notifications in taskbar")); + doubleClickToPlayCheckBox->setText(tr("&Double-click cards to play them (instead of single-click)")); + playToStackCheckBox->setText(tr("&Play all nonlands onto the stack (not the battlefield) by default")); + animationGroupBox->setTitle(tr("Animation settings")); + tapAnimationCheckBox->setText(tr("&Tap/untap animation")); + soundEnabledCheckBox->setText(tr("Enable &sounds")); + soundPathLabel->setText(tr("Path to sounds directory:")); } void UserInterfaceSettingsPage::soundPathClearButtonClicked() { - soundPathEdit->setText(QString()); - settingsCache->setSoundPath(QString()); + soundPathEdit->setText(QString()); + settingsCache->setSoundPath(QString()); } void UserInterfaceSettingsPage::soundPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); - if (path.isEmpty()) - return; - - soundPathEdit->setText(path); - settingsCache->setSoundPath(path); + QString path = QFileDialog::getExistingDirectory(this, tr("Choose path")); + if (path.isEmpty()) + return; + + soundPathEdit->setText(path); + settingsCache->setSoundPath(path); } DeckEditorSettingsPage::DeckEditorSettingsPage() { - priceTagsCheckBox = new QCheckBox; - priceTagsCheckBox->setChecked(settingsCache->getPriceTagFeature()); - connect(priceTagsCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPriceTagFeature(int))); - - QGridLayout *generalGrid = new QGridLayout; - generalGrid->addWidget(priceTagsCheckBox, 0, 0); - - generalGroupBox = new QGroupBox; - generalGroupBox->setLayout(generalGrid); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(generalGroupBox); - - setLayout(mainLayout); + priceTagsCheckBox = new QCheckBox; + priceTagsCheckBox->setChecked(settingsCache->getPriceTagFeature()); + connect(priceTagsCheckBox, SIGNAL(stateChanged(int)), settingsCache, SLOT(setPriceTagFeature(int))); + + QGridLayout *generalGrid = new QGridLayout; + generalGrid->addWidget(priceTagsCheckBox, 0, 0); + + generalGroupBox = new QGroupBox; + generalGroupBox->setLayout(generalGrid); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(generalGroupBox); + + setLayout(mainLayout); } void DeckEditorSettingsPage::retranslateUi() { - priceTagsCheckBox->setText(tr("Enable &price tag feature (using data from blacklotusproject.com)")); - generalGroupBox->setTitle(tr("General")); + priceTagsCheckBox->setText(tr("Enable &price tag feature (using data from blacklotusproject.com)")); + generalGroupBox->setTitle(tr("General")); } MessagesSettingsPage::MessagesSettingsPage() { - aAdd = new QAction(this); - connect(aAdd, SIGNAL(triggered()), this, SLOT(actAdd())); - aRemove = new QAction(this); - connect(aRemove, SIGNAL(triggered()), this, SLOT(actRemove())); - - messageList = new QListWidget; - QToolBar *messageToolBar = new QToolBar; - messageToolBar->setOrientation(Qt::Vertical); - messageToolBar->addAction(aAdd); - messageToolBar->addAction(aRemove); + aAdd = new QAction(this); + connect(aAdd, SIGNAL(triggered()), this, SLOT(actAdd())); + aRemove = new QAction(this); + connect(aRemove, SIGNAL(triggered()), this, SLOT(actRemove())); + + messageList = new QListWidget; + QToolBar *messageToolBar = new QToolBar; + messageToolBar->setOrientation(Qt::Vertical); + messageToolBar->addAction(aAdd); + messageToolBar->addAction(aRemove); - QSettings settings; - settings.beginGroup("messages"); - int count = settings.value("count", 0).toInt(); - for (int i = 0; i < count; i++) - messageList->addItem(settings.value(QString("msg%1").arg(i)).toString()); - - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addWidget(messageList); - mainLayout->addWidget(messageToolBar); + QSettings settings; + settings.beginGroup("messages"); + int count = settings.value("count", 0).toInt(); + for (int i = 0; i < count; i++) + messageList->addItem(settings.value(QString("msg%1").arg(i)).toString()); + + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addWidget(messageList); + mainLayout->addWidget(messageToolBar); - setLayout(mainLayout); - - retranslateUi(); + setLayout(mainLayout); + + retranslateUi(); } void MessagesSettingsPage::storeSettings() { - QSettings settings; - settings.beginGroup("messages"); - settings.setValue("count", messageList->count()); - for (int i = 0; i < messageList->count(); i++) - settings.setValue(QString("msg%1").arg(i), messageList->item(i)->text()); + QSettings settings; + settings.beginGroup("messages"); + settings.setValue("count", messageList->count()); + for (int i = 0; i < messageList->count(); i++) + settings.setValue(QString("msg%1").arg(i), messageList->item(i)->text()); } void MessagesSettingsPage::actAdd() { - bool ok; - QString msg = QInputDialog::getText(this, tr("Add message"), tr("Message:"), QLineEdit::Normal, QString(), &ok); - if (ok) { - messageList->addItem(msg); - storeSettings(); - } + bool ok; + QString msg = QInputDialog::getText(this, tr("Add message"), tr("Message:"), QLineEdit::Normal, QString(), &ok); + if (ok) { + messageList->addItem(msg); + storeSettings(); + } } void MessagesSettingsPage::actRemove() { - if (messageList->currentItem()) { - delete messageList->takeItem(messageList->currentRow()); - storeSettings(); - } + if (messageList->currentItem()) { + delete messageList->takeItem(messageList->currentRow()); + storeSettings(); + } } void MessagesSettingsPage::retranslateUi() { - aAdd->setText(tr("&Add")); - aRemove->setText(tr("&Remove")); + aAdd->setText(tr("&Add")); + aRemove->setText(tr("&Remove")); } DlgSettings::DlgSettings(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage())); - - contentsWidget = new QListWidget; - contentsWidget->setViewMode(QListView::IconMode); - contentsWidget->setIconSize(QSize(96, 84)); - contentsWidget->setMovement(QListView::Static); - contentsWidget->setMinimumWidth(130); - contentsWidget->setMaximumWidth(150); - contentsWidget->setSpacing(12); - - pagesWidget = new QStackedWidget; - pagesWidget->addWidget(new GeneralSettingsPage); - pagesWidget->addWidget(new AppearanceSettingsPage); - pagesWidget->addWidget(new UserInterfaceSettingsPage); - pagesWidget->addWidget(new DeckEditorSettingsPage); - pagesWidget->addWidget(new MessagesSettingsPage); - - createIcons(); - contentsWidget->setCurrentRow(0); - - QHBoxLayout *hboxLayout = new QHBoxLayout; - hboxLayout->addWidget(contentsWidget); - hboxLayout->addWidget(pagesWidget); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(close())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(hboxLayout); - mainLayout->addSpacing(12); - mainLayout->addWidget(buttonBox); - setLayout(mainLayout); - - retranslateUi(); - - resize(800, 450); + connect(settingsCache, SIGNAL(langChanged()), this, SLOT(updateLanguage())); + + contentsWidget = new QListWidget; + contentsWidget->setViewMode(QListView::IconMode); + contentsWidget->setIconSize(QSize(96, 84)); + contentsWidget->setMovement(QListView::Static); + contentsWidget->setMinimumWidth(130); + contentsWidget->setMaximumWidth(150); + contentsWidget->setSpacing(12); + + pagesWidget = new QStackedWidget; + pagesWidget->addWidget(new GeneralSettingsPage); + pagesWidget->addWidget(new AppearanceSettingsPage); + pagesWidget->addWidget(new UserInterfaceSettingsPage); + pagesWidget->addWidget(new DeckEditorSettingsPage); + pagesWidget->addWidget(new MessagesSettingsPage); + + createIcons(); + contentsWidget->setCurrentRow(0); + + QHBoxLayout *hboxLayout = new QHBoxLayout; + hboxLayout->addWidget(contentsWidget); + hboxLayout->addWidget(pagesWidget); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(close())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(hboxLayout); + mainLayout->addSpacing(12); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); + + retranslateUi(); + + resize(800, 450); } void DlgSettings::createIcons() { - generalButton = new QListWidgetItem(contentsWidget); - generalButton->setTextAlignment(Qt::AlignHCenter); - generalButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - generalButton->setIcon(QIcon(":/resources/icon_config_general.svg")); - - appearanceButton = new QListWidgetItem(contentsWidget); - appearanceButton->setTextAlignment(Qt::AlignHCenter); - appearanceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - appearanceButton->setIcon(QIcon(":/resources/icon_config_appearance.svg")); - - userInterfaceButton = new QListWidgetItem(contentsWidget); - userInterfaceButton->setTextAlignment(Qt::AlignHCenter); - userInterfaceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - userInterfaceButton->setIcon(QIcon(":/resources/icon_config_interface.svg")); - - deckEditorButton = new QListWidgetItem(contentsWidget); - deckEditorButton->setTextAlignment(Qt::AlignHCenter); - deckEditorButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - deckEditorButton->setIcon(QIcon(":/resources/icon_config_deckeditor.svg")); - - messagesButton = new QListWidgetItem(contentsWidget); - messagesButton->setTextAlignment(Qt::AlignHCenter); - messagesButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - messagesButton->setIcon(QIcon(":/resources/icon_config_messages.svg")); - - connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(changePage(QListWidgetItem *, QListWidgetItem *))); + generalButton = new QListWidgetItem(contentsWidget); + generalButton->setTextAlignment(Qt::AlignHCenter); + generalButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + generalButton->setIcon(QIcon(":/resources/icon_config_general.svg")); + + appearanceButton = new QListWidgetItem(contentsWidget); + appearanceButton->setTextAlignment(Qt::AlignHCenter); + appearanceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + appearanceButton->setIcon(QIcon(":/resources/icon_config_appearance.svg")); + + userInterfaceButton = new QListWidgetItem(contentsWidget); + userInterfaceButton->setTextAlignment(Qt::AlignHCenter); + userInterfaceButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + userInterfaceButton->setIcon(QIcon(":/resources/icon_config_interface.svg")); + + deckEditorButton = new QListWidgetItem(contentsWidget); + deckEditorButton->setTextAlignment(Qt::AlignHCenter); + deckEditorButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + deckEditorButton->setIcon(QIcon(":/resources/icon_config_deckeditor.svg")); + + messagesButton = new QListWidgetItem(contentsWidget); + messagesButton->setTextAlignment(Qt::AlignHCenter); + messagesButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + messagesButton->setIcon(QIcon(":/resources/icon_config_messages.svg")); + + connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(changePage(QListWidgetItem *, QListWidgetItem *))); } void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous) { - if (!current) - current = previous; - - pagesWidget->setCurrentIndex(contentsWidget->row(current)); + if (!current) + current = previous; + + pagesWidget->setCurrentIndex(contentsWidget->row(current)); } void DlgSettings::updateLanguage() { - qApp->removeTranslator(translator); - installNewTranslator(); + qApp->removeTranslator(translator); + installNewTranslator(); } void DlgSettings::changeEvent(QEvent *event) { - if (event->type() == QEvent::LanguageChange) - retranslateUi(); - QDialog::changeEvent(event); + if (event->type() == QEvent::LanguageChange) + retranslateUi(); + QDialog::changeEvent(event); } void DlgSettings::closeEvent(QCloseEvent *event) { - if (!db->getLoadSuccess()) - if (QMessageBox::critical(this, tr("Error"), tr("Your card database is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - event->ignore(); - return; - } - if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) - if (QMessageBox::critical(this, tr("Error"), tr("The path to your deck directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - event->ignore(); - return; - } - if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) - if (QMessageBox::critical(this, tr("Error"), tr("The path to your card pictures directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - event->ignore(); - return; - } - event->accept(); + if (!db->getLoadSuccess()) + if (QMessageBox::critical(this, tr("Error"), tr("Your card database is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + event->ignore(); + return; + } + if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) + if (QMessageBox::critical(this, tr("Error"), tr("The path to your deck directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + event->ignore(); + return; + } + if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) + if (QMessageBox::critical(this, tr("Error"), tr("The path to your card pictures directory is invalid. Would you like to go back and set the correct path?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + event->ignore(); + return; + } + event->accept(); } void DlgSettings::retranslateUi() { - setWindowTitle(tr("Settings")); - - generalButton->setText(tr("General")); - appearanceButton->setText(tr("Appearance")); - userInterfaceButton->setText(tr("User interface")); - deckEditorButton->setText(tr("Deck editor")); - messagesButton->setText(tr("Messages")); - - for (int i = 0; i < pagesWidget->count(); i++) - dynamic_cast(pagesWidget->widget(i))->retranslateUi(); + setWindowTitle(tr("Settings")); + + generalButton->setText(tr("General")); + appearanceButton->setText(tr("Appearance")); + userInterfaceButton->setText(tr("User interface")); + deckEditorButton->setText(tr("Deck editor")); + messagesButton->setText(tr("Messages")); + + for (int i = 0; i < pagesWidget->count(); i++) + dynamic_cast(pagesWidget->widget(i))->retranslateUi(); } diff --git a/cockatrice/src/dlg_settings.h b/cockatrice/src/dlg_settings.h index 7911ccd9..5f87887c 100644 --- a/cockatrice/src/dlg_settings.h +++ b/cockatrice/src/dlg_settings.h @@ -18,123 +18,123 @@ class QSpinBox; class AbstractSettingsPage : public QWidget { public: - virtual void retranslateUi() = 0; + virtual void retranslateUi() = 0; }; class GeneralSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT public: - GeneralSettingsPage(); - void retranslateUi(); + GeneralSettingsPage(); + void retranslateUi(); private slots: - void deckPathButtonClicked(); - void replaysPathButtonClicked(); - void picsPathButtonClicked(); - void cardDatabasePathButtonClicked(); - void tokenDatabasePathButtonClicked(); - void languageBoxChanged(int index); + void deckPathButtonClicked(); + void replaysPathButtonClicked(); + void picsPathButtonClicked(); + void cardDatabasePathButtonClicked(); + void tokenDatabasePathButtonClicked(); + void languageBoxChanged(int index); private: - QStringList findQmFiles(); - QString languageName(const QString &qmFile); - QLineEdit *deckPathEdit, *replaysPathEdit, *picsPathEdit, *cardDatabasePathEdit, *tokenDatabasePathEdit; - QGroupBox *personalGroupBox, *pathsGroupBox; - QComboBox *languageBox; - QCheckBox *picDownloadCheckBox; - QLabel *languageLabel, *deckPathLabel, *replaysPathLabel, *picsPathLabel, *cardDatabasePathLabel, *tokenDatabasePathLabel; + QStringList findQmFiles(); + QString languageName(const QString &qmFile); + QLineEdit *deckPathEdit, *replaysPathEdit, *picsPathEdit, *cardDatabasePathEdit, *tokenDatabasePathEdit; + QGroupBox *personalGroupBox, *pathsGroupBox; + QComboBox *languageBox; + QCheckBox *picDownloadCheckBox; + QLabel *languageLabel, *deckPathLabel, *replaysPathLabel, *picsPathLabel, *cardDatabasePathLabel, *tokenDatabasePathLabel; }; class AppearanceSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT private slots: - void handBgClearButtonClicked(); - void handBgButtonClicked(); - void stackBgClearButtonClicked(); - void stackBgButtonClicked(); - void tableBgClearButtonClicked(); - void tableBgButtonClicked(); - void playerAreaBgClearButtonClicked(); - void playerAreaBgButtonClicked(); - void cardBackPicturePathClearButtonClicked(); - void cardBackPicturePathButtonClicked(); + void handBgClearButtonClicked(); + void handBgButtonClicked(); + void stackBgClearButtonClicked(); + void stackBgButtonClicked(); + void tableBgClearButtonClicked(); + void tableBgButtonClicked(); + void playerAreaBgClearButtonClicked(); + void playerAreaBgButtonClicked(); + void cardBackPicturePathClearButtonClicked(); + void cardBackPicturePathButtonClicked(); signals: - void handBgChanged(const QString &path); - void stackBgChanged(const QString &path); - void tableBgChanged(const QString &path); - void playerAreaBgChanged(const QString &path); - void cardBackPicturePathChanged(const QString &path); + void handBgChanged(const QString &path); + void stackBgChanged(const QString &path); + void tableBgChanged(const QString &path); + void playerAreaBgChanged(const QString &path); + void cardBackPicturePathChanged(const QString &path); private: - QLabel *handBgLabel, *stackBgLabel, *tableBgLabel, *playerAreaBgLabel, *cardBackPicturePathLabel, *minPlayersForMultiColumnLayoutLabel; - QLineEdit *handBgEdit, *stackBgEdit, *tableBgEdit, *playerAreaBgEdit, *cardBackPicturePathEdit; - QCheckBox *displayCardNamesCheckBox, *horizontalHandCheckBox, *invertVerticalCoordinateCheckBox, *zoneViewSortByNameCheckBox, *zoneViewSortByTypeCheckBox; - QGroupBox *zoneBgGroupBox, *cardsGroupBox, *handGroupBox, *tableGroupBox, *zoneViewGroupBox; - QSpinBox *minPlayersForMultiColumnLayoutEdit; + QLabel *handBgLabel, *stackBgLabel, *tableBgLabel, *playerAreaBgLabel, *cardBackPicturePathLabel, *minPlayersForMultiColumnLayoutLabel; + QLineEdit *handBgEdit, *stackBgEdit, *tableBgEdit, *playerAreaBgEdit, *cardBackPicturePathEdit; + QCheckBox *displayCardNamesCheckBox, *horizontalHandCheckBox, *invertVerticalCoordinateCheckBox, *zoneViewSortByNameCheckBox, *zoneViewSortByTypeCheckBox; + QGroupBox *zoneBgGroupBox, *cardsGroupBox, *handGroupBox, *tableGroupBox, *zoneViewGroupBox; + QSpinBox *minPlayersForMultiColumnLayoutEdit; public: - AppearanceSettingsPage(); - void retranslateUi(); + AppearanceSettingsPage(); + void retranslateUi(); }; class UserInterfaceSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT private slots: - void soundPathClearButtonClicked(); - void soundPathButtonClicked(); + void soundPathClearButtonClicked(); + void soundPathButtonClicked(); signals: - void soundPathChanged(); + void soundPathChanged(); private: - QCheckBox *notificationsEnabledCheckBox; - QCheckBox *doubleClickToPlayCheckBox; - QCheckBox *playToStackCheckBox; - QCheckBox *tapAnimationCheckBox; - QCheckBox *soundEnabledCheckBox; - QLabel *soundPathLabel; - QLineEdit *soundPathEdit; - QGroupBox *generalGroupBox, *animationGroupBox, *soundGroupBox; + QCheckBox *notificationsEnabledCheckBox; + QCheckBox *doubleClickToPlayCheckBox; + QCheckBox *playToStackCheckBox; + QCheckBox *tapAnimationCheckBox; + QCheckBox *soundEnabledCheckBox; + QLabel *soundPathLabel; + QLineEdit *soundPathEdit; + QGroupBox *generalGroupBox, *animationGroupBox, *soundGroupBox; public: - UserInterfaceSettingsPage(); - void retranslateUi(); + UserInterfaceSettingsPage(); + void retranslateUi(); }; class DeckEditorSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT public: - DeckEditorSettingsPage(); - void retranslateUi(); + DeckEditorSettingsPage(); + void retranslateUi(); private: - QCheckBox *priceTagsCheckBox; - QGroupBox *generalGroupBox; + QCheckBox *priceTagsCheckBox; + QGroupBox *generalGroupBox; }; class MessagesSettingsPage : public AbstractSettingsPage { - Q_OBJECT + Q_OBJECT public: - MessagesSettingsPage(); - void retranslateUi(); + MessagesSettingsPage(); + void retranslateUi(); private slots: - void actAdd(); - void actRemove(); + void actAdd(); + void actRemove(); private: - QListWidget *messageList; - QAction *aAdd, *aRemove; - - void storeSettings(); + QListWidget *messageList; + QAction *aAdd, *aRemove; + + void storeSettings(); }; class DlgSettings : public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgSettings(QWidget *parent = 0); + DlgSettings(QWidget *parent = 0); private slots: - void changePage(QListWidgetItem *current, QListWidgetItem *previous); - void updateLanguage(); + void changePage(QListWidgetItem *current, QListWidgetItem *previous); + void updateLanguage(); private: - QListWidget *contentsWidget; - QStackedWidget *pagesWidget; - QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton; - void createIcons(); - void retranslateUi(); + QListWidget *contentsWidget; + QStackedWidget *pagesWidget; + QListWidgetItem *generalButton, *appearanceButton, *userInterfaceButton, *deckEditorButton, *messagesButton; + void createIcons(); + void retranslateUi(); protected: - void changeEvent(QEvent *event); - void closeEvent(QCloseEvent *event); + void changeEvent(QEvent *event); + void closeEvent(QCloseEvent *event); }; #endif diff --git a/cockatrice/src/gamescene.cpp b/cockatrice/src/gamescene.cpp index ce083c76..8e777168 100644 --- a/cockatrice/src/gamescene.cpp +++ b/cockatrice/src/gamescene.cpp @@ -13,103 +13,103 @@ #include GameScene::GameScene(PhasesToolbar *_phasesToolbar, QObject *parent) - : QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()) + : QGraphicsScene(parent), phasesToolbar(_phasesToolbar), viewSize(QSize()) { - animationTimer = new QBasicTimer; - addItem(phasesToolbar); - connect(settingsCache, SIGNAL(minPlayersForMultiColumnLayoutChanged()), this, SLOT(rearrange())); - - rearrange(); + animationTimer = new QBasicTimer; + addItem(phasesToolbar); + connect(settingsCache, SIGNAL(minPlayersForMultiColumnLayoutChanged()), this, SLOT(rearrange())); + + rearrange(); } GameScene::~GameScene() { - delete animationTimer; + delete animationTimer; } void GameScene::retranslateUi() { - for (int i = 0; i < zoneViews.size(); ++i) - zoneViews[i]->retranslateUi(); + for (int i = 0; i < zoneViews.size(); ++i) + zoneViews[i]->retranslateUi(); } void GameScene::addPlayer(Player *player) { - qDebug("GameScene::addPlayer"); - players << player; - addItem(player); - connect(player, SIGNAL(sizeChanged()), this, SLOT(rearrange())); - connect(player, SIGNAL(gameConceded()), this, SLOT(rearrange())); + qDebug("GameScene::addPlayer"); + players << player; + addItem(player); + connect(player, SIGNAL(sizeChanged()), this, SLOT(rearrange())); + connect(player, SIGNAL(gameConceded()), this, SLOT(rearrange())); } void GameScene::removePlayer(Player *player) { - qDebug("GameScene::removePlayer"); - players.removeAt(players.indexOf(player)); - removeItem(player); - rearrange(); + qDebug("GameScene::removePlayer"); + players.removeAt(players.indexOf(player)); + removeItem(player); + rearrange(); } void GameScene::rearrange() { - playersByColumn.clear(); + playersByColumn.clear(); - QList playersPlaying; - int firstPlayer = -1; - for (int i = 0; i < players.size(); ++i) - if (!players[i]->getConceded()) { - playersPlaying.append(players[i]); - if ((firstPlayer == -1) && (players[i]->getLocal())) - firstPlayer = playersPlaying.size() - 1; - } - if (firstPlayer == -1) - firstPlayer = 0; - const int playersCount = playersPlaying.size(); - const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2; - const int rows = ceil((qreal) playersCount / columns); - qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing; - QList columnWidth; - int firstPlayerOfColumn = firstPlayer; - for (int col = 0; col < columns; ++col) { - playersByColumn.append(QList()); - columnWidth.append(0); - qreal thisColumnHeight = -playerAreaSpacing; - const int rowsInColumn = rows - (playersCount % columns) * col; // only correct for max. 2 cols - for (int j = 0; j < rowsInColumn; ++j) { - Player *player = playersPlaying[(firstPlayerOfColumn + j) % playersCount]; - if (col == 0) - playersByColumn[col].prepend(player); - else - playersByColumn[col].append(player); - thisColumnHeight += player->boundingRect().height() + playerAreaSpacing; - if (player->boundingRect().width() > columnWidth[col]) - columnWidth[col] = player->boundingRect().width(); - } - if (thisColumnHeight > sceneHeight) - sceneHeight = thisColumnHeight; - sceneWidth += columnWidth[col] + playerAreaSpacing; + QList playersPlaying; + int firstPlayer = -1; + for (int i = 0; i < players.size(); ++i) + if (!players[i]->getConceded()) { + playersPlaying.append(players[i]); + if ((firstPlayer == -1) && (players[i]->getLocal())) + firstPlayer = playersPlaying.size() - 1; + } + if (firstPlayer == -1) + firstPlayer = 0; + const int playersCount = playersPlaying.size(); + const int columns = playersCount < settingsCache->getMinPlayersForMultiColumnLayout() ? 1 : 2; + const int rows = ceil((qreal) playersCount / columns); + qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing; + QList columnWidth; + int firstPlayerOfColumn = firstPlayer; + for (int col = 0; col < columns; ++col) { + playersByColumn.append(QList()); + columnWidth.append(0); + qreal thisColumnHeight = -playerAreaSpacing; + const int rowsInColumn = rows - (playersCount % columns) * col; // only correct for max. 2 cols + for (int j = 0; j < rowsInColumn; ++j) { + Player *player = playersPlaying[(firstPlayerOfColumn + j) % playersCount]; + if (col == 0) + playersByColumn[col].prepend(player); + else + playersByColumn[col].append(player); + thisColumnHeight += player->boundingRect().height() + playerAreaSpacing; + if (player->boundingRect().width() > columnWidth[col]) + columnWidth[col] = player->boundingRect().width(); + } + if (thisColumnHeight > sceneHeight) + sceneHeight = thisColumnHeight; + sceneWidth += columnWidth[col] + playerAreaSpacing; - firstPlayerOfColumn += rowsInColumn; - } + firstPlayerOfColumn += rowsInColumn; + } - phasesToolbar->setHeight(sceneHeight); - qreal phasesWidth = phasesToolbar->getWidth(); - sceneWidth += phasesWidth; + phasesToolbar->setHeight(sceneHeight); + qreal phasesWidth = phasesToolbar->getWidth(); + sceneWidth += phasesWidth; - qreal x = phasesWidth; - for (int col = 0; col < columns; ++col) { - qreal y = 0; - for (int row = 0; row < playersByColumn[col].size(); ++row) { - Player *player = playersByColumn[col][row]; - player->setPos(x, y); - player->setMirrored(row != rows - 1); - y += player->boundingRect().height() + playerAreaSpacing; - } - x += columnWidth[col] + playerAreaSpacing; - } + qreal x = phasesWidth; + for (int col = 0; col < columns; ++col) { + qreal y = 0; + for (int row = 0; row < playersByColumn[col].size(); ++row) { + Player *player = playersByColumn[col][row]; + player->setPos(x, y); + player->setMirrored(row != rows - 1); + y += player->boundingRect().height() + playerAreaSpacing; + } + x += columnWidth[col] + playerAreaSpacing; + } - setSceneRect(sceneRect().x(), sceneRect().y(), sceneWidth, sceneHeight); - processViewSizeChange(viewSize); + setSceneRect(sceneRect().x(), sceneRect().y(), sceneWidth, sceneHeight); + processViewSizeChange(viewSize); } void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numberCards) @@ -123,166 +123,166 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb } } - ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false); + ZoneViewWidget *item = new ZoneViewWidget(player, player->getZones().value(zoneName), numberCards, false); zoneViews.append(item); connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); - addItem(item); - item->setPos(50, 50); + addItem(item); + item->setPos(50, 50); } void GameScene::addRevealedZoneView(Player *player, CardZone *zone, const QList &cardList, bool withWritePermission) { - ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList); - zoneViews.append(item); + ZoneViewWidget *item = new ZoneViewWidget(player, zone, -2, true, withWritePermission, cardList); + zoneViews.append(item); connect(item, SIGNAL(closePressed(ZoneViewWidget *)), this, SLOT(removeZoneView(ZoneViewWidget *))); - addItem(item); - item->setPos(50, 50); + addItem(item); + item->setPos(50, 50); } void GameScene::removeZoneView(ZoneViewWidget *item) { zoneViews.removeAt(zoneViews.indexOf(item)); - removeItem(item); + removeItem(item); } void GameScene::clearViews() { - while (!zoneViews.isEmpty()) - zoneViews.first()->close(); + while (!zoneViews.isEmpty()) + zoneViews.first()->close(); } void GameScene::closeMostRecentZoneView() { - if (!zoneViews.isEmpty()) - zoneViews.last()->close(); + if (!zoneViews.isEmpty()) + zoneViews.last()->close(); } QTransform GameScene::getViewTransform() const { - return views().at(0)->transform(); + return views().at(0)->transform(); } QTransform GameScene::getViewportTransform() const { - return views().at(0)->viewportTransform(); + return views().at(0)->viewportTransform(); } void GameScene::processViewSizeChange(const QSize &newSize) { - viewSize = newSize; - - qreal newRatio = ((qreal) newSize.width()) / newSize.height(); - qreal minWidth = 0; - QList minWidthByColumn; - for (int col = 0; col < playersByColumn.size(); ++col) { - minWidthByColumn.append(0); - for (int row = 0; row < playersByColumn[col].size(); ++row) { - qreal w = playersByColumn[col][row]->getMinimumWidth(); - if (w > minWidthByColumn[col]) - minWidthByColumn[col] = w; - } - minWidth += minWidthByColumn[col]; - } - minWidth += phasesToolbar->getWidth(); - - qreal minRatio = minWidth / sceneRect().height(); - qreal newWidth; - if (minRatio > newRatio) { - // Aspect ratio is dominated by table width. - newWidth = minWidth; - } else { - // Aspect ratio is dominated by window dimensions. - newWidth = newRatio * sceneRect().height(); - } - setSceneRect(0, 0, newWidth, sceneRect().height()); + viewSize = newSize; + + qreal newRatio = ((qreal) newSize.width()) / newSize.height(); + qreal minWidth = 0; + QList minWidthByColumn; + for (int col = 0; col < playersByColumn.size(); ++col) { + minWidthByColumn.append(0); + for (int row = 0; row < playersByColumn[col].size(); ++row) { + qreal w = playersByColumn[col][row]->getMinimumWidth(); + if (w > minWidthByColumn[col]) + minWidthByColumn[col] = w; + } + minWidth += minWidthByColumn[col]; + } + minWidth += phasesToolbar->getWidth(); + + qreal minRatio = minWidth / sceneRect().height(); + qreal newWidth; + if (minRatio > newRatio) { + // Aspect ratio is dominated by table width. + newWidth = minWidth; + } else { + // Aspect ratio is dominated by window dimensions. + newWidth = newRatio * sceneRect().height(); + } + setSceneRect(0, 0, newWidth, sceneRect().height()); - qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); - for (int col = 0; col < playersByColumn.size(); ++col) - for (int row = 0; row < playersByColumn[col].size(); ++row) - playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn); + qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); + for (int col = 0; col < playersByColumn.size(); ++col) + for (int row = 0; row < playersByColumn[col].size(); ++row) + playersByColumn[col][row]->processSceneSizeChange(minWidthByColumn[col] + extraWidthPerColumn); } void GameScene::updateHover(const QPointF &scenePos) { - QList itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); - - // Search for the topmost zone and ignore all cards not belonging to that zone. - CardZone *zone = 0; - for (int i = 0; i < itemList.size(); ++i) - if ((zone = qgraphicsitem_cast(itemList[i]))) - break; - - CardItem *maxZCard = 0; - if (zone) { - qreal maxZ = -1; - for (int i = 0; i < itemList.size(); ++i) { - CardItem *card = qgraphicsitem_cast(itemList[i]); - if (!card) - continue; - if (card->getAttachedTo()) { - if (card->getAttachedTo()->getZone() != zone) - continue; - } else if (card->getZone() != zone) - continue; - - if (card->getRealZValue() > maxZ) { - maxZ = card->getRealZValue(); - maxZCard = card; - } - } - } - if (hoveredCard && (maxZCard != hoveredCard)) - hoveredCard->setHovered(false); - if (maxZCard && (maxZCard != hoveredCard)) - maxZCard->setHovered(true); - hoveredCard = maxZCard; + QList itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); + + // Search for the topmost zone and ignore all cards not belonging to that zone. + CardZone *zone = 0; + for (int i = 0; i < itemList.size(); ++i) + if ((zone = qgraphicsitem_cast(itemList[i]))) + break; + + CardItem *maxZCard = 0; + if (zone) { + qreal maxZ = -1; + for (int i = 0; i < itemList.size(); ++i) { + CardItem *card = qgraphicsitem_cast(itemList[i]); + if (!card) + continue; + if (card->getAttachedTo()) { + if (card->getAttachedTo()->getZone() != zone) + continue; + } else if (card->getZone() != zone) + continue; + + if (card->getRealZValue() > maxZ) { + maxZ = card->getRealZValue(); + maxZCard = card; + } + } + } + if (hoveredCard && (maxZCard != hoveredCard)) + hoveredCard->setHovered(false); + if (maxZCard && (maxZCard != hoveredCard)) + maxZCard->setHovered(true); + hoveredCard = maxZCard; } bool GameScene::event(QEvent *event) { - if (event->type() == QEvent::GraphicsSceneMouseMove) - updateHover(static_cast(event)->scenePos()); - - return QGraphicsScene::event(event); + if (event->type() == QEvent::GraphicsSceneMouseMove) + updateHover(static_cast(event)->scenePos()); + + return QGraphicsScene::event(event); } void GameScene::timerEvent(QTimerEvent * /*event*/) { - QMutableSetIterator i(cardsToAnimate); - while (i.hasNext()) { - i.next(); - if (!i.value()->animationEvent()) - i.remove(); - } - if (cardsToAnimate.isEmpty()) - animationTimer->stop(); + QMutableSetIterator i(cardsToAnimate); + while (i.hasNext()) { + i.next(); + if (!i.value()->animationEvent()) + i.remove(); + } + if (cardsToAnimate.isEmpty()) + animationTimer->stop(); } void GameScene::registerAnimationItem(AbstractCardItem *card) { - cardsToAnimate.insert(static_cast(card)); - if (!animationTimer->isActive()) - animationTimer->start(50, this); + cardsToAnimate.insert(static_cast(card)); + if (!animationTimer->isActive()) + animationTimer->start(50, this); } void GameScene::unregisterAnimationItem(AbstractCardItem *card) { - cardsToAnimate.remove(static_cast(card)); - if (cardsToAnimate.isEmpty()) - animationTimer->stop(); + cardsToAnimate.remove(static_cast(card)); + if (cardsToAnimate.isEmpty()) + animationTimer->stop(); } void GameScene::startRubberBand(const QPointF &selectionOrigin) { - emit sigStartRubberBand(selectionOrigin); + emit sigStartRubberBand(selectionOrigin); } void GameScene::resizeRubberBand(const QPointF &cursorPoint) { - emit sigResizeRubberBand(cursorPoint); + emit sigResizeRubberBand(cursorPoint); } void GameScene::stopRubberBand() { - emit sigStopRubberBand(); + emit sigStopRubberBand(); } diff --git a/cockatrice/src/gamescene.h b/cockatrice/src/gamescene.h index 7deb78c8..b542f0ec 100644 --- a/cockatrice/src/gamescene.h +++ b/cockatrice/src/gamescene.h @@ -16,49 +16,49 @@ class PhasesToolbar; class QBasicTimer; class GameScene : public QGraphicsScene { - Q_OBJECT + Q_OBJECT private: - static const int playerAreaSpacing = 5; - - PhasesToolbar *phasesToolbar; - QList players; - QList > playersByColumn; - QList zoneViews; - QSize viewSize; - QPointer hoveredCard; - QBasicTimer *animationTimer; - QSet cardsToAnimate; - void updateHover(const QPointF &scenePos); + static const int playerAreaSpacing = 5; + + PhasesToolbar *phasesToolbar; + QList players; + QList > playersByColumn; + QList zoneViews; + QSize viewSize; + QPointer hoveredCard; + QBasicTimer *animationTimer; + QSet cardsToAnimate; + void updateHover(const QPointF &scenePos); public: - GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0); - ~GameScene(); - void retranslateUi(); - void processViewSizeChange(const QSize &newSize); - QTransform getViewTransform() const; - QTransform getViewportTransform() const; - - void startRubberBand(const QPointF &selectionOrigin); - void resizeRubberBand(const QPointF &cursorPoint); - void stopRubberBand(); - - void registerAnimationItem(AbstractCardItem *item); - void unregisterAnimationItem(AbstractCardItem *card); + GameScene(PhasesToolbar *_phasesToolbar, QObject *parent = 0); + ~GameScene(); + void retranslateUi(); + void processViewSizeChange(const QSize &newSize); + QTransform getViewTransform() const; + QTransform getViewportTransform() const; + + void startRubberBand(const QPointF &selectionOrigin); + void resizeRubberBand(const QPointF &cursorPoint); + void stopRubberBand(); + + void registerAnimationItem(AbstractCardItem *item); + void unregisterAnimationItem(AbstractCardItem *card); public slots: - void toggleZoneView(Player *player, const QString &zoneName, int numberCards); - void addRevealedZoneView(Player *player, CardZone *zone, const QList &cardList, bool withWritePermission); - void removeZoneView(ZoneViewWidget *item); - void addPlayer(Player *player); - void removePlayer(Player *player); - void clearViews(); - void closeMostRecentZoneView(); - void rearrange(); + void toggleZoneView(Player *player, const QString &zoneName, int numberCards); + void addRevealedZoneView(Player *player, CardZone *zone, const QList &cardList, bool withWritePermission); + void removeZoneView(ZoneViewWidget *item); + void addPlayer(Player *player); + void removePlayer(Player *player); + void clearViews(); + void closeMostRecentZoneView(); + void rearrange(); protected: - bool event(QEvent *event); - void timerEvent(QTimerEvent *event); + bool event(QEvent *event); + void timerEvent(QTimerEvent *event); signals: - void sigStartRubberBand(const QPointF &selectionOrigin); - void sigResizeRubberBand(const QPointF &cursorPoint); - void sigStopRubberBand(); + void sigStartRubberBand(const QPointF &selectionOrigin); + void sigResizeRubberBand(const QPointF &cursorPoint); + void sigStopRubberBand(); }; #endif diff --git a/cockatrice/src/gameselector.cpp b/cockatrice/src/gameselector.cpp index 86f86df9..6a05d905 100644 --- a/cockatrice/src/gameselector.cpp +++ b/cockatrice/src/gameselector.cpp @@ -18,173 +18,173 @@ #include "pb/response.pb.h" GameSelector::GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, QWidget *parent) - : QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room) + : QGroupBox(parent), client(_client), tabSupervisor(_tabSupervisor), room(_room) { - gameListView = new QTreeView; - gameListModel = new GamesModel(_rooms, _gameTypes, this); - gameListProxyModel = new GamesProxyModel(this, tabSupervisor->getUserInfo()); - gameListProxyModel->setSourceModel(gameListModel); - gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); - gameListView->setModel(gameListProxyModel); - gameListView->setSortingEnabled(true); - gameListView->setAlternatingRowColors(true); - gameListView->setRootIsDecorated(true); - if (_room) - gameListView->header()->hideSection(1); - else - gameListProxyModel->setUnavailableGamesVisible(true); - gameListView->header()->setResizeMode(1, QHeaderView::ResizeToContents); + gameListView = new QTreeView; + gameListModel = new GamesModel(_rooms, _gameTypes, this); + gameListProxyModel = new GamesProxyModel(this, tabSupervisor->getUserInfo()); + gameListProxyModel->setSourceModel(gameListModel); + gameListProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + gameListView->setModel(gameListProxyModel); + gameListView->setSortingEnabled(true); + gameListView->setAlternatingRowColors(true); + gameListView->setRootIsDecorated(true); + if (_room) + gameListView->header()->hideSection(1); + else + gameListProxyModel->setUnavailableGamesVisible(true); + gameListView->header()->setResizeMode(1, QHeaderView::ResizeToContents); - filterButton = new QPushButton; - filterButton->setIcon(QIcon(":/resources/icon_search.svg")); - connect(filterButton, SIGNAL(clicked()), this, SLOT(actSetFilter())); - clearFilterButton = new QPushButton; - clearFilterButton->setIcon(QIcon(":/resources/icon_clearsearch.svg")); - clearFilterButton->setEnabled(false); - connect(clearFilterButton, SIGNAL(clicked()), this, SLOT(actClearFilter())); + filterButton = new QPushButton; + filterButton->setIcon(QIcon(":/resources/icon_search.svg")); + connect(filterButton, SIGNAL(clicked()), this, SLOT(actSetFilter())); + clearFilterButton = new QPushButton; + clearFilterButton->setIcon(QIcon(":/resources/icon_clearsearch.svg")); + clearFilterButton->setEnabled(false); + connect(clearFilterButton, SIGNAL(clicked()), this, SLOT(actClearFilter())); - if (room) { - createButton = new QPushButton; - connect(createButton, SIGNAL(clicked()), this, SLOT(actCreate())); - } else - createButton = 0; - joinButton = new QPushButton; - spectateButton = new QPushButton; - - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addWidget(filterButton); - buttonLayout->addWidget(clearFilterButton); - buttonLayout->addStretch(); - if (room) - buttonLayout->addWidget(createButton); - buttonLayout->addWidget(joinButton); - buttonLayout->addWidget(spectateButton); - buttonLayout->setAlignment(Qt::AlignTop); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(gameListView); - mainLayout->addLayout(buttonLayout); + if (room) { + createButton = new QPushButton; + connect(createButton, SIGNAL(clicked()), this, SLOT(actCreate())); + } else + createButton = 0; + joinButton = new QPushButton; + spectateButton = new QPushButton; + + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addWidget(filterButton); + buttonLayout->addWidget(clearFilterButton); + buttonLayout->addStretch(); + if (room) + buttonLayout->addWidget(createButton); + buttonLayout->addWidget(joinButton); + buttonLayout->addWidget(spectateButton); + buttonLayout->setAlignment(Qt::AlignTop); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(gameListView); + mainLayout->addLayout(buttonLayout); - retranslateUi(); - setLayout(mainLayout); + retranslateUi(); + setLayout(mainLayout); - setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5); - setMinimumHeight(200); + setMinimumWidth((qreal) (gameListView->columnWidth(0) * gameListModel->columnCount()) / 1.5); + setMinimumHeight(200); - connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin())); - connect(spectateButton, SIGNAL(clicked()), this, SLOT(actJoin())); + connect(joinButton, SIGNAL(clicked()), this, SLOT(actJoin())); + connect(spectateButton, SIGNAL(clicked()), this, SLOT(actJoin())); } void GameSelector::actSetFilter() { - GameTypeMap gameTypeMap; - if (room) - gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId()); - DlgFilterGames dlg(gameTypeMap, this); - dlg.setUnavailableGamesVisible(gameListProxyModel->getUnavailableGamesVisible()); - dlg.setPasswordProtectedGamesVisible(gameListProxyModel->getPasswordProtectedGamesVisible()); - dlg.setGameNameFilter(gameListProxyModel->getGameNameFilter()); - dlg.setCreatorNameFilter(gameListProxyModel->getCreatorNameFilter()); - dlg.setGameTypeFilter(gameListProxyModel->getGameTypeFilter()); - dlg.setMaxPlayersFilter(gameListProxyModel->getMaxPlayersFilterMin(), gameListProxyModel->getMaxPlayersFilterMax()); - - if (!dlg.exec()) - return; - - clearFilterButton->setEnabled(true); - - gameListProxyModel->setUnavailableGamesVisible(dlg.getUnavailableGamesVisible()); - gameListProxyModel->setPasswordProtectedGamesVisible(dlg.getPasswordProtectedGamesVisible()); - gameListProxyModel->setGameNameFilter(dlg.getGameNameFilter()); - gameListProxyModel->setCreatorNameFilter(dlg.getCreatorNameFilter()); - gameListProxyModel->setGameTypeFilter(dlg.getGameTypeFilter()); - gameListProxyModel->setMaxPlayersFilter(dlg.getMaxPlayersFilterMin(), dlg.getMaxPlayersFilterMax()); + GameTypeMap gameTypeMap; + if (room) + gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId()); + DlgFilterGames dlg(gameTypeMap, this); + dlg.setUnavailableGamesVisible(gameListProxyModel->getUnavailableGamesVisible()); + dlg.setPasswordProtectedGamesVisible(gameListProxyModel->getPasswordProtectedGamesVisible()); + dlg.setGameNameFilter(gameListProxyModel->getGameNameFilter()); + dlg.setCreatorNameFilter(gameListProxyModel->getCreatorNameFilter()); + dlg.setGameTypeFilter(gameListProxyModel->getGameTypeFilter()); + dlg.setMaxPlayersFilter(gameListProxyModel->getMaxPlayersFilterMin(), gameListProxyModel->getMaxPlayersFilterMax()); + + if (!dlg.exec()) + return; + + clearFilterButton->setEnabled(true); + + gameListProxyModel->setUnavailableGamesVisible(dlg.getUnavailableGamesVisible()); + gameListProxyModel->setPasswordProtectedGamesVisible(dlg.getPasswordProtectedGamesVisible()); + gameListProxyModel->setGameNameFilter(dlg.getGameNameFilter()); + gameListProxyModel->setCreatorNameFilter(dlg.getCreatorNameFilter()); + gameListProxyModel->setGameTypeFilter(dlg.getGameTypeFilter()); + gameListProxyModel->setMaxPlayersFilter(dlg.getMaxPlayersFilterMin(), dlg.getMaxPlayersFilterMax()); } void GameSelector::actClearFilter() { - clearFilterButton->setEnabled(false); - - gameListProxyModel->resetFilterParameters(); + clearFilterButton->setEnabled(false); + + gameListProxyModel->resetFilterParameters(); } void GameSelector::actCreate() { - DlgCreateGame dlg(room, room->getGameTypes(), this); - dlg.exec(); + DlgCreateGame dlg(room, room->getGameTypes(), this); + dlg.exec(); } void GameSelector::checkResponse(const Response &response) { - if (createButton) - createButton->setEnabled(true); - joinButton->setEnabled(true); - spectateButton->setEnabled(true); + if (createButton) + createButton->setEnabled(true); + joinButton->setEnabled(true); + spectateButton->setEnabled(true); - switch (response.response_code()) { - case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break; - case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break; - case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break; - case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break; - case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break; - case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break; - case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break; - case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break; - default: ; - } + switch (response.response_code()) { + case Response::RespNotInRoom: QMessageBox::critical(this, tr("Error"), tr("Please join the appropriate room first.")); break; + case Response::RespWrongPassword: QMessageBox::critical(this, tr("Error"), tr("Wrong password.")); break; + case Response::RespSpectatorsNotAllowed: QMessageBox::critical(this, tr("Error"), tr("Spectators are not allowed in this game.")); break; + case Response::RespGameFull: QMessageBox::critical(this, tr("Error"), tr("The game is already full.")); break; + case Response::RespNameNotFound: QMessageBox::critical(this, tr("Error"), tr("The game does not exist any more.")); break; + case Response::RespUserLevelTooLow: QMessageBox::critical(this, tr("Error"), tr("This game is only open to registered users.")); break; + case Response::RespOnlyBuddies: QMessageBox::critical(this, tr("Error"), tr("This game is only open to its creator's buddies.")); break; + case Response::RespInIgnoreList: QMessageBox::critical(this, tr("Error"), tr("You are being ignored by the creator of this game.")); break; + default: ; + } } void GameSelector::actJoin() { - bool spectator = sender() == spectateButton; - - QModelIndex ind = gameListView->currentIndex(); - if (!ind.isValid()) - return; - const ServerInfo_Game &game = gameListModel->getGame(ind.data(Qt::UserRole).toInt()); - bool overrideRestrictions = !tabSupervisor->getAdminLocked(); - QString password; - if (game.with_password() && !(spectator && !game.spectators_need_password()) && !overrideRestrictions) { - bool ok; - password = QInputDialog::getText(this, tr("Join game"), tr("Password:"), QLineEdit::Password, QString(), &ok); - if (!ok) - return; - } - - Command_JoinGame cmd; - cmd.set_game_id(game.game_id()); - cmd.set_password(password.toStdString()); - cmd.set_spectator(spectator); - cmd.set_override_restrictions(overrideRestrictions); - - TabRoom *r = tabSupervisor->getRoomTabs().value(game.room_id()); - if (!r) { - QMessageBox::critical(this, tr("Error"), tr("Please join the respective room first.")); - return; - } - - PendingCommand *pend = r->prepareRoomCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); - r->sendRoomCommand(pend); + bool spectator = sender() == spectateButton; + + QModelIndex ind = gameListView->currentIndex(); + if (!ind.isValid()) + return; + const ServerInfo_Game &game = gameListModel->getGame(ind.data(Qt::UserRole).toInt()); + bool overrideRestrictions = !tabSupervisor->getAdminLocked(); + QString password; + if (game.with_password() && !(spectator && !game.spectators_need_password()) && !overrideRestrictions) { + bool ok; + password = QInputDialog::getText(this, tr("Join game"), tr("Password:"), QLineEdit::Password, QString(), &ok); + if (!ok) + return; + } + + Command_JoinGame cmd; + cmd.set_game_id(game.game_id()); + cmd.set_password(password.toStdString()); + cmd.set_spectator(spectator); + cmd.set_override_restrictions(overrideRestrictions); + + TabRoom *r = tabSupervisor->getRoomTabs().value(game.room_id()); + if (!r) { + QMessageBox::critical(this, tr("Error"), tr("Please join the respective room first.")); + return; + } + + PendingCommand *pend = r->prepareRoomCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(checkResponse(Response))); + r->sendRoomCommand(pend); - if (createButton) - createButton->setEnabled(false); - joinButton->setEnabled(false); - spectateButton->setEnabled(false); + if (createButton) + createButton->setEnabled(false); + joinButton->setEnabled(false); + spectateButton->setEnabled(false); } void GameSelector::retranslateUi() { - setTitle(tr("Games")); - filterButton->setText(tr("&Filter games")); - clearFilterButton->setText(tr("C&lear filter")); - if (createButton) - createButton->setText(tr("C&reate")); - joinButton->setText(tr("&Join")); - spectateButton->setText(tr("J&oin as spectator")); + setTitle(tr("Games")); + filterButton->setText(tr("&Filter games")); + clearFilterButton->setText(tr("C&lear filter")); + if (createButton) + createButton->setText(tr("C&reate")); + joinButton->setText(tr("&Join")); + spectateButton->setText(tr("J&oin as spectator")); } void GameSelector::processGameInfo(const ServerInfo_Game &info) { - gameListModel->updateGameList(info); + gameListModel->updateGameList(info); } diff --git a/cockatrice/src/gameselector.h b/cockatrice/src/gameselector.h index 4712e3a8..47a9c395 100644 --- a/cockatrice/src/gameselector.h +++ b/cockatrice/src/gameselector.h @@ -16,28 +16,28 @@ class ServerInfo_Game; class Response; class GameSelector : public QGroupBox { - Q_OBJECT + Q_OBJECT private slots: - void actSetFilter(); - void actClearFilter(); - void actCreate(); - void actJoin(); - void checkResponse(const Response &response); + void actSetFilter(); + void actClearFilter(); + void actCreate(); + void actJoin(); + void checkResponse(const Response &response); signals: - void gameJoined(int gameId); + void gameJoined(int gameId); private: - AbstractClient *client; - const TabSupervisor *tabSupervisor; - TabRoom *room; + AbstractClient *client; + const TabSupervisor *tabSupervisor; + TabRoom *room; - QTreeView *gameListView; - GamesModel *gameListModel; - GamesProxyModel *gameListProxyModel; - QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton; + QTreeView *gameListView; + GamesModel *gameListModel; + GamesProxyModel *gameListProxyModel; + QPushButton *filterButton, *clearFilterButton, *createButton, *joinButton, *spectateButton; public: - GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, QWidget *parent = 0); - void retranslateUi(); - void processGameInfo(const ServerInfo_Game &info); + GameSelector(AbstractClient *_client, const TabSupervisor *_tabSupervisor, TabRoom *_room, const QMap &_rooms, const QMap &_gameTypes, QWidget *parent = 0); + void retranslateUi(); + void processGameInfo(const ServerInfo_Game &info); }; #endif diff --git a/cockatrice/src/gamesmodel.cpp b/cockatrice/src/gamesmodel.cpp index cbffc86d..0ee41f35 100644 --- a/cockatrice/src/gamesmodel.cpp +++ b/cockatrice/src/gamesmodel.cpp @@ -3,187 +3,187 @@ #include GamesModel::GamesModel(const QMap &_rooms, const QMap &_gameTypes, QObject *parent) - : QAbstractTableModel(parent), rooms(_rooms), gameTypes(_gameTypes) + : QAbstractTableModel(parent), rooms(_rooms), gameTypes(_gameTypes) { } QVariant GamesModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if (role == Qt::UserRole) - return index.row(); - if (role != Qt::DisplayRole) - return QVariant(); - if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) - return QVariant(); - - const ServerInfo_Game &g = gameList[index.row()]; - switch (index.column()) { - case 0: return QString::fromStdString(g.description()); - case 1: return rooms.value(g.room_id()); - case 2: return QString::fromStdString(g.creator_info().name()); - case 3: { - QStringList result; - GameTypeMap gameTypeMap = gameTypes.value(g.room_id()); - for (int i = g.game_types_size() - 1; i >= 0; --i) - result.append(gameTypeMap.value(g.game_types(i))); - return result.join(", "); - } - case 4: return g.with_password() ? ((g.spectators_need_password() || !g.spectators_allowed()) ? tr("yes") : tr("yes, free for spectators")) : tr("no"); - case 5: { - QStringList result; - if (g.only_buddies()) - result.append(tr("buddies only")); - if (g.only_registered()) - result.append(tr("reg. users only")); - return result.join(", "); - } - case 6: return QString("%1/%2").arg(g.player_count()).arg(g.max_players()); - case 7: return g.spectators_allowed() ? QVariant(g.spectators_count()) : QVariant(tr("not allowed")); - default: return QVariant(); - } + if (!index.isValid()) + return QVariant(); + if (role == Qt::UserRole) + return index.row(); + if (role != Qt::DisplayRole) + return QVariant(); + if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) + return QVariant(); + + const ServerInfo_Game &g = gameList[index.row()]; + switch (index.column()) { + case 0: return QString::fromStdString(g.description()); + case 1: return rooms.value(g.room_id()); + case 2: return QString::fromStdString(g.creator_info().name()); + case 3: { + QStringList result; + GameTypeMap gameTypeMap = gameTypes.value(g.room_id()); + for (int i = g.game_types_size() - 1; i >= 0; --i) + result.append(gameTypeMap.value(g.game_types(i))); + return result.join(", "); + } + case 4: return g.with_password() ? ((g.spectators_need_password() || !g.spectators_allowed()) ? tr("yes") : tr("yes, free for spectators")) : tr("no"); + case 5: { + QStringList result; + if (g.only_buddies()) + result.append(tr("buddies only")); + if (g.only_registered()) + result.append(tr("reg. users only")); + return result.join(", "); + } + case 6: return QString("%1/%2").arg(g.player_count()).arg(g.max_players()); + case 7: return g.spectators_allowed() ? QVariant(g.spectators_count()) : QVariant(tr("not allowed")); + default: return QVariant(); + } } QVariant GamesModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) - return QVariant(); - switch (section) { - case 0: return tr("Description"); - case 1: return tr("Room"); - case 2: return tr("Creator"); - case 3: return tr("Game type"); - case 4: return tr("Password"); - case 5: return tr("Restrictions"); - case 6: return tr("Players"); - case 7: return tr("Spectators"); - default: return QVariant(); - } + if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) + return QVariant(); + switch (section) { + case 0: return tr("Description"); + case 1: return tr("Room"); + case 2: return tr("Creator"); + case 3: return tr("Game type"); + case 4: return tr("Password"); + case 5: return tr("Restrictions"); + case 6: return tr("Players"); + case 7: return tr("Spectators"); + default: return QVariant(); + } } const ServerInfo_Game &GamesModel::getGame(int row) { - Q_ASSERT(row < gameList.size()); - return gameList[row]; + Q_ASSERT(row < gameList.size()); + return gameList[row]; } void GamesModel::updateGameList(const ServerInfo_Game &game) { - for (int i = 0; i < gameList.size(); i++) - if (gameList[i].game_id() == game.game_id()) { - if (game.closed()) { - beginRemoveRows(QModelIndex(), i, i); - gameList.removeAt(i); - endRemoveRows(); - } else { - gameList[i].MergeFrom(game); - emit dataChanged(index(i, 0), index(i, 7)); - } - return; - } - if (game.player_count() <= 0) - return; - beginInsertRows(QModelIndex(), gameList.size(), gameList.size()); - gameList.append(game); - endInsertRows(); + for (int i = 0; i < gameList.size(); i++) + if (gameList[i].game_id() == game.game_id()) { + if (game.closed()) { + beginRemoveRows(QModelIndex(), i, i); + gameList.removeAt(i); + endRemoveRows(); + } else { + gameList[i].MergeFrom(game); + emit dataChanged(index(i, 0), index(i, 7)); + } + return; + } + if (game.player_count() <= 0) + return; + beginInsertRows(QModelIndex(), gameList.size(), gameList.size()); + gameList.append(game); + endInsertRows(); } GamesProxyModel::GamesProxyModel(QObject *parent, ServerInfo_User *_ownUser) - : QSortFilterProxyModel(parent), + : QSortFilterProxyModel(parent), ownUser(_ownUser), unavailableGamesVisible(false), maxPlayersFilterMin(-1), maxPlayersFilterMax(-1) { - setDynamicSortFilter(true); + setDynamicSortFilter(true); } void GamesProxyModel::setUnavailableGamesVisible(bool _unavailableGamesVisible) { - unavailableGamesVisible = _unavailableGamesVisible; - invalidateFilter(); + unavailableGamesVisible = _unavailableGamesVisible; + invalidateFilter(); } void GamesProxyModel::setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible) { - passwordProtectedGamesVisible = _passwordProtectedGamesVisible; - invalidateFilter(); + passwordProtectedGamesVisible = _passwordProtectedGamesVisible; + invalidateFilter(); } void GamesProxyModel::setGameNameFilter(const QString &_gameNameFilter) { - gameNameFilter = _gameNameFilter; - invalidateFilter(); + gameNameFilter = _gameNameFilter; + invalidateFilter(); } void GamesProxyModel::setCreatorNameFilter(const QString &_creatorNameFilter) { - creatorNameFilter = _creatorNameFilter; - invalidateFilter(); + creatorNameFilter = _creatorNameFilter; + invalidateFilter(); } void GamesProxyModel::setGameTypeFilter(const QSet &_gameTypeFilter) { - gameTypeFilter = _gameTypeFilter; - invalidateFilter(); + gameTypeFilter = _gameTypeFilter; + invalidateFilter(); } void GamesProxyModel::setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax) { - maxPlayersFilterMin = _maxPlayersFilterMin; - maxPlayersFilterMax = _maxPlayersFilterMax; - invalidateFilter(); + maxPlayersFilterMin = _maxPlayersFilterMin; + maxPlayersFilterMax = _maxPlayersFilterMax; + invalidateFilter(); } void GamesProxyModel::resetFilterParameters() { - unavailableGamesVisible = false; - passwordProtectedGamesVisible = false; - gameNameFilter = QString(); - creatorNameFilter = QString(); - gameTypeFilter.clear(); - maxPlayersFilterMin = -1; - maxPlayersFilterMax = -1; - - invalidateFilter(); + unavailableGamesVisible = false; + passwordProtectedGamesVisible = false; + gameNameFilter = QString(); + creatorNameFilter = QString(); + gameTypeFilter.clear(); + maxPlayersFilterMin = -1; + maxPlayersFilterMax = -1; + + invalidateFilter(); } bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &/*sourceParent*/) const { - GamesModel *model = qobject_cast(sourceModel()); - if (!model) - return false; - - const ServerInfo_Game &game = model->getGame(sourceRow); - if (!unavailableGamesVisible) { - if (game.player_count() == game.max_players()) - return false; - if (game.started()) - return false; - if (!(ownUser->user_level() & ServerInfo_User::IsRegistered)) - if (game.only_registered()) - return false; - } - if (!passwordProtectedGamesVisible && game.with_password()) - return false; - if (!gameNameFilter.isEmpty()) - if (!QString::fromStdString(game.description()).contains(gameNameFilter, Qt::CaseInsensitive)) - return false; - if (!creatorNameFilter.isEmpty()) - if (!QString::fromStdString(game.creator_info().name()).contains(creatorNameFilter, Qt::CaseInsensitive)) - return false; - - QSet gameTypes; - for (int i = 0; i < game.game_types_size(); ++i) - gameTypes.insert(game.game_types(i)); - if (!gameTypeFilter.isEmpty() && gameTypes.intersect(gameTypeFilter).isEmpty()) - return false; - - if ((maxPlayersFilterMin != -1) && (game.max_players() < maxPlayersFilterMin)) - return false; - if ((maxPlayersFilterMax != -1) && (game.max_players() > maxPlayersFilterMax)) - return false; - - return true; + GamesModel *model = qobject_cast(sourceModel()); + if (!model) + return false; + + const ServerInfo_Game &game = model->getGame(sourceRow); + if (!unavailableGamesVisible) { + if (game.player_count() == game.max_players()) + return false; + if (game.started()) + return false; + if (!(ownUser->user_level() & ServerInfo_User::IsRegistered)) + if (game.only_registered()) + return false; + } + if (!passwordProtectedGamesVisible && game.with_password()) + return false; + if (!gameNameFilter.isEmpty()) + if (!QString::fromStdString(game.description()).contains(gameNameFilter, Qt::CaseInsensitive)) + return false; + if (!creatorNameFilter.isEmpty()) + if (!QString::fromStdString(game.creator_info().name()).contains(creatorNameFilter, Qt::CaseInsensitive)) + return false; + + QSet gameTypes; + for (int i = 0; i < game.game_types_size(); ++i) + gameTypes.insert(game.game_types(i)); + if (!gameTypeFilter.isEmpty() && gameTypes.intersect(gameTypeFilter).isEmpty()) + return false; + + if ((maxPlayersFilterMin != -1) && (game.max_players() < maxPlayersFilterMin)) + return false; + if ((maxPlayersFilterMax != -1) && (game.max_players() > maxPlayersFilterMax)) + return false; + + return true; } diff --git a/cockatrice/src/gamesmodel.h b/cockatrice/src/gamesmodel.h index 843fb043..aeb37e95 100644 --- a/cockatrice/src/gamesmodel.h +++ b/cockatrice/src/gamesmodel.h @@ -11,51 +11,51 @@ class ServerInfo_User; class GamesModel : public QAbstractTableModel { - Q_OBJECT + Q_OBJECT private: - QList gameList; - QMap rooms; - QMap gameTypes; + QList gameList; + QMap rooms; + QMap gameTypes; public: - GamesModel(const QMap &_rooms, const QMap &_gameTypes, QObject *parent = 0); - int rowCount(const QModelIndex &parent = QModelIndex()) const { return parent.isValid() ? 0 : gameList.size(); } - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return 8; } - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - - const ServerInfo_Game &getGame(int row); - void updateGameList(const ServerInfo_Game &game); - const QMap &getGameTypes() { return gameTypes; } + GamesModel(const QMap &_rooms, const QMap &_gameTypes, QObject *parent = 0); + int rowCount(const QModelIndex &parent = QModelIndex()) const { return parent.isValid() ? 0 : gameList.size(); } + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return 8; } + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + + const ServerInfo_Game &getGame(int row); + void updateGameList(const ServerInfo_Game &game); + const QMap &getGameTypes() { return gameTypes; } }; class GamesProxyModel : public QSortFilterProxyModel { - Q_OBJECT + Q_OBJECT private: - ServerInfo_User *ownUser; - bool unavailableGamesVisible; - bool passwordProtectedGamesVisible; - QString gameNameFilter, creatorNameFilter; - QSet gameTypeFilter; - int maxPlayersFilterMin, maxPlayersFilterMax; + ServerInfo_User *ownUser; + bool unavailableGamesVisible; + bool passwordProtectedGamesVisible; + QString gameNameFilter, creatorNameFilter; + QSet gameTypeFilter; + int maxPlayersFilterMin, maxPlayersFilterMax; public: - GamesProxyModel(QObject *parent = 0, ServerInfo_User *_ownUser = 0); - - bool getUnavailableGamesVisible() const { return unavailableGamesVisible; } - void setUnavailableGamesVisible(bool _unavailableGamesVisible); - bool getPasswordProtectedGamesVisible() const { return passwordProtectedGamesVisible; } - void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); - QString getGameNameFilter() const { return gameNameFilter; } - void setGameNameFilter(const QString &_gameNameFilter); - QString getCreatorNameFilter() const { return creatorNameFilter; } - void setCreatorNameFilter(const QString &_creatorNameFilter); - QSet getGameTypeFilter() const { return gameTypeFilter; } - void setGameTypeFilter(const QSet &_gameTypeFilter); - int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; } - int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; } - void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); - void resetFilterParameters(); + GamesProxyModel(QObject *parent = 0, ServerInfo_User *_ownUser = 0); + + bool getUnavailableGamesVisible() const { return unavailableGamesVisible; } + void setUnavailableGamesVisible(bool _unavailableGamesVisible); + bool getPasswordProtectedGamesVisible() const { return passwordProtectedGamesVisible; } + void setPasswordProtectedGamesVisible(bool _passwordProtectedGamesVisible); + QString getGameNameFilter() const { return gameNameFilter; } + void setGameNameFilter(const QString &_gameNameFilter); + QString getCreatorNameFilter() const { return creatorNameFilter; } + void setCreatorNameFilter(const QString &_creatorNameFilter); + QSet getGameTypeFilter() const { return gameTypeFilter; } + void setGameTypeFilter(const QSet &_gameTypeFilter); + int getMaxPlayersFilterMin() const { return maxPlayersFilterMin; } + int getMaxPlayersFilterMax() const { return maxPlayersFilterMax; } + void setMaxPlayersFilter(int _maxPlayersFilterMin, int _maxPlayersFilterMax); + void resetFilterParameters(); protected: - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; #endif diff --git a/cockatrice/src/gameview.cpp b/cockatrice/src/gameview.cpp index 75a4024b..7a28b492 100644 --- a/cockatrice/src/gameview.cpp +++ b/cockatrice/src/gameview.cpp @@ -5,57 +5,57 @@ #include GameView::GameView(QGraphicsScene *scene, QWidget *parent) - : QGraphicsView(scene, parent), rubberBand(0) + : QGraphicsView(scene, parent), rubberBand(0) { - setBackgroundBrush(QBrush(QColor(0, 0, 0))); - setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing); - setFocusPolicy(Qt::NoFocus); - setViewportUpdateMode(BoundingRectViewportUpdate); + setBackgroundBrush(QBrush(QColor(0, 0, 0))); + setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing); + setFocusPolicy(Qt::NoFocus); + setViewportUpdateMode(BoundingRectViewportUpdate); - connect(scene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); - - connect(scene, SIGNAL(sigStartRubberBand(const QPointF &)), this, SLOT(startRubberBand(const QPointF &))); - connect(scene, SIGNAL(sigResizeRubberBand(const QPointF &)), this, SLOT(resizeRubberBand(const QPointF &))); - connect(scene, SIGNAL(sigStopRubberBand()), this, SLOT(stopRubberBand())); + connect(scene, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(updateSceneRect(const QRectF &))); + + connect(scene, SIGNAL(sigStartRubberBand(const QPointF &)), this, SLOT(startRubberBand(const QPointF &))); + connect(scene, SIGNAL(sigResizeRubberBand(const QPointF &)), this, SLOT(resizeRubberBand(const QPointF &))); + connect(scene, SIGNAL(sigStopRubberBand()), this, SLOT(stopRubberBand())); - aCloseMostRecentZoneView = new QAction(this); - aCloseMostRecentZoneView->setShortcut(tr("Esc")); - connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView())); - addAction(aCloseMostRecentZoneView); + aCloseMostRecentZoneView = new QAction(this); + aCloseMostRecentZoneView->setShortcut(tr("Esc")); + connect(aCloseMostRecentZoneView, SIGNAL(triggered()), scene, SLOT(closeMostRecentZoneView())); + addAction(aCloseMostRecentZoneView); - rubberBand = new QRubberBand(QRubberBand::Rectangle, this); + rubberBand = new QRubberBand(QRubberBand::Rectangle, this); } void GameView::resizeEvent(QResizeEvent *event) { - QGraphicsView::resizeEvent(event); + QGraphicsView::resizeEvent(event); - GameScene *s = dynamic_cast(scene()); - if (s) - s->processViewSizeChange(event->size()); - - updateSceneRect(scene()->sceneRect()); + GameScene *s = dynamic_cast(scene()); + if (s) + s->processViewSizeChange(event->size()); + + updateSceneRect(scene()->sceneRect()); } void GameView::updateSceneRect(const QRectF &rect) { - fitInView(rect, Qt::KeepAspectRatio); + fitInView(rect, Qt::KeepAspectRatio); } void GameView::startRubberBand(const QPointF &_selectionOrigin) { - selectionOrigin = _selectionOrigin; - rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0))); - rubberBand->show(); + selectionOrigin = _selectionOrigin; + rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0))); + rubberBand->show(); } void GameView::resizeRubberBand(const QPointF &cursorPoint) { - if (rubberBand) - rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized()); + if (rubberBand) + rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized()); } void GameView::stopRubberBand() { - rubberBand->hide(); + rubberBand->hide(); } diff --git a/cockatrice/src/gameview.h b/cockatrice/src/gameview.h index 84acf45e..e678f293 100644 --- a/cockatrice/src/gameview.h +++ b/cockatrice/src/gameview.h @@ -6,21 +6,21 @@ class QRubberBand; class GameView : public QGraphicsView { - Q_OBJECT + Q_OBJECT private: - QAction *aCloseMostRecentZoneView; - QRubberBand *rubberBand; - QPointF selectionOrigin; + QAction *aCloseMostRecentZoneView; + QRubberBand *rubberBand; + QPointF selectionOrigin; protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); private slots: - void startRubberBand(const QPointF &selectionOrigin); - void resizeRubberBand(const QPointF &cursorPoint); - void stopRubberBand(); + void startRubberBand(const QPointF &selectionOrigin); + void resizeRubberBand(const QPointF &cursorPoint); + void stopRubberBand(); public slots: - void updateSceneRect(const QRectF &rect); + void updateSceneRect(const QRectF &rect); public: - GameView(QGraphicsScene *scene, QWidget *parent = 0); + GameView(QGraphicsScene *scene, QWidget *parent = 0); }; #endif diff --git a/cockatrice/src/handcounter.cpp b/cockatrice/src/handcounter.cpp index f5210dd1..4aa33d69 100644 --- a/cockatrice/src/handcounter.cpp +++ b/cockatrice/src/handcounter.cpp @@ -6,9 +6,9 @@ #include "cardzone.h" HandCounter::HandCounter(QGraphicsItem *parent) - : AbstractGraphicsItem(parent), number(0) + : AbstractGraphicsItem(parent), number(0) { - setCacheMode(DeviceCoordinateCache); + setCacheMode(DeviceCoordinateCache); } HandCounter::~HandCounter() @@ -17,43 +17,43 @@ HandCounter::~HandCounter() void HandCounter::updateNumber() { - number = static_cast(sender())->getCards().size(); - update(); + number = static_cast(sender())->getCards().size(); + update(); } QRectF HandCounter::boundingRect() const { - return QRectF(0, 0, 72, 72); + return QRectF(0, 0, 72, 72); } void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - painter->save(); - QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize(); - QPixmap cachedPixmap; + painter->save(); + QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize(); + QPixmap cachedPixmap; #if QT_VERSION >= 0x040600 - if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) { + if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) { #else - if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), cachedPixmap)) { + if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), cachedPixmap)) { #endif - QSvgRenderer svg(QString(":/resources/hand.svg")); - cachedPixmap = QPixmap(translatedSize); - cachedPixmap.fill(Qt::transparent); - QPainter painter(&cachedPixmap); - svg.render(&painter, QRectF(0, 0, translatedSize.width(), translatedSize.height())); - QPixmapCache::insert("handCounter" + QString::number(translatedSize.width()), cachedPixmap); - } - painter->resetTransform(); - painter->drawPixmap(cachedPixmap.rect(), cachedPixmap, cachedPixmap.rect()); - painter->restore(); - - paintNumberEllipse(number, 24, Qt::white, -1, -1, painter); + QSvgRenderer svg(QString(":/resources/hand.svg")); + cachedPixmap = QPixmap(translatedSize); + cachedPixmap.fill(Qt::transparent); + QPainter painter(&cachedPixmap); + svg.render(&painter, QRectF(0, 0, translatedSize.width(), translatedSize.height())); + QPixmapCache::insert("handCounter" + QString::number(translatedSize.width()), cachedPixmap); + } + painter->resetTransform(); + painter->drawPixmap(cachedPixmap.rect(), cachedPixmap, cachedPixmap.rect()); + painter->restore(); + + paintNumberEllipse(number, 24, Qt::white, -1, -1, painter); } void HandCounter::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::RightButton) { - emit showContextMenu(event->screenPos()); - event->accept(); - } + if (event->button() == Qt::RightButton) { + emit showContextMenu(event->screenPos()); + event->accept(); + } } diff --git a/cockatrice/src/handcounter.h b/cockatrice/src/handcounter.h index 7e3b7346..af1cf3e4 100644 --- a/cockatrice/src/handcounter.h +++ b/cockatrice/src/handcounter.h @@ -8,22 +8,22 @@ class QPainter; class QPixmap; class HandCounter : public AbstractGraphicsItem { - Q_OBJECT + Q_OBJECT private: - int number; + int number; protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); public slots: - void updateNumber(); + void updateNumber(); signals: - void showContextMenu(const QPoint &screenPos); + void showContextMenu(const QPoint &screenPos); public: - enum { Type = typeOther }; - int type() const { return Type; } - HandCounter(QGraphicsItem *parent = 0); - ~HandCounter(); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + enum { Type = typeOther }; + int type() const { return Type; } + HandCounter(QGraphicsItem *parent = 0); + ~HandCounter(); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; #endif diff --git a/cockatrice/src/handzone.cpp b/cockatrice/src/handzone.cpp index 2827f41f..1799b65f 100644 --- a/cockatrice/src/handzone.cpp +++ b/cockatrice/src/handzone.cpp @@ -8,137 +8,137 @@ #include "pb/command_move_card.pb.h" HandZone::HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent) - : SelectZone(_p, "hand", false, false, _contentsKnown, parent), zoneHeight(_zoneHeight) + : SelectZone(_p, "hand", false, false, _contentsKnown, parent), zoneHeight(_zoneHeight) { - connect(settingsCache, SIGNAL(handBgPathChanged()), this, SLOT(updateBgPixmap())); - updateBgPixmap(); - setCacheMode(DeviceCoordinateCache); + connect(settingsCache, SIGNAL(handBgPathChanged()), this, SLOT(updateBgPixmap())); + updateBgPixmap(); + setCacheMode(DeviceCoordinateCache); } void HandZone::updateBgPixmap() { - QString bgPath = settingsCache->getHandBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); - update(); + QString bgPath = settingsCache->getHandBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); + update(); } void HandZone::addCardImpl(CardItem *card, int x, int /*y*/) { - if (x == -1) - x = cards.size(); - cards.insert(x, card); + if (x == -1) + x = cards.size(); + cards.insert(x, card); - if (!cards.getContentsKnown()) { - card->setId(-1); - card->setName(); - } - card->setParentItem(this); - card->resetState(); - card->setVisible(true); - card->update(); + if (!cards.getContentsKnown()) { + card->setId(-1); + card->setName(); + } + card->setParentItem(this); + card->resetState(); + card->setVisible(true); + card->update(); } void HandZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint & dropPoint) { - QPoint point = dropPoint + scenePos().toPoint(); - int x = -1; - if (settingsCache->getHorizontalHand()) { - for (x = 0; x < cards.size(); x++) - if (point.x() < ((CardItem *) cards.at(x))->scenePos().x()) - break; - } else { - for (x = 0; x < cards.size(); x++) - if (point.y() < ((CardItem *) cards.at(x))->scenePos().y()) - break; - } - - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(x); - cmd.set_y(-1); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - - player->sendGameCommand(cmd); + QPoint point = dropPoint + scenePos().toPoint(); + int x = -1; + if (settingsCache->getHorizontalHand()) { + for (x = 0; x < cards.size(); x++) + if (point.x() < ((CardItem *) cards.at(x))->scenePos().x()) + break; + } else { + for (x = 0; x < cards.size(); x++) + if (point.y() < ((CardItem *) cards.at(x))->scenePos().y()) + break; + } + + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(x); + cmd.set_y(-1); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + + player->sendGameCommand(cmd); } QRectF HandZone::boundingRect() const { - if (settingsCache->getHorizontalHand()) - return QRectF(0, 0, width, CARD_HEIGHT + 10); - else - return QRectF(0, 0, 100, zoneHeight); + if (settingsCache->getHorizontalHand()) + return QRectF(0, 0, width, CARD_HEIGHT + 10); + else + return QRectF(0, 0, 100, zoneHeight); } void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), Qt::darkGreen); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), Qt::darkGreen); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); } void HandZone::reorganizeCards() { - if (!cards.isEmpty()) { - const int cardCount = cards.size(); - if (settingsCache->getHorizontalHand()) { - const int xPadding = 5; - qreal totalWidth = boundingRect().width() - 2 * xPadding; - qreal cardWidth = cards.at(0)->boundingRect().width(); - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cards.at(i); - - // If the total width of the cards is smaller than the available width, - // the cards do not need to overlap and are displayed in the center of the area. - if (cardWidth * cardCount > totalWidth) - c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5); - else - c->setPos(xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2, 5); - c->setRealZValue(i); - } - } else { - qreal totalWidth = boundingRect().width(); - qreal totalHeight = boundingRect().height(); - qreal cardWidth = cards.at(0)->boundingRect().width(); - qreal cardHeight = cards.at(0)->boundingRect().height(); - qreal xspace = 5; - qreal x1 = xspace; - qreal x2 = totalWidth - xspace - cardWidth; - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cards.at(i); - qreal x = i % 2 ? x2 : x1; - // If the total height of the cards is smaller than the available height, - // the cards do not need to overlap and are displayed in the center of the area. - if (cardHeight * cardCount > totalHeight) - c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); - else - c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); - c->setRealZValue(i); - } - } - } - update(); + if (!cards.isEmpty()) { + const int cardCount = cards.size(); + if (settingsCache->getHorizontalHand()) { + const int xPadding = 5; + qreal totalWidth = boundingRect().width() - 2 * xPadding; + qreal cardWidth = cards.at(0)->boundingRect().width(); + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + + // If the total width of the cards is smaller than the available width, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardWidth * cardCount > totalWidth) + c->setPos(xPadding + ((qreal) i) * (totalWidth - cardWidth) / (cardCount - 1), 5); + else + c->setPos(xPadding + ((qreal) i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2, 5); + c->setRealZValue(i); + } + } else { + qreal totalWidth = boundingRect().width(); + qreal totalHeight = boundingRect().height(); + qreal cardWidth = cards.at(0)->boundingRect().width(); + qreal cardHeight = cards.at(0)->boundingRect().height(); + qreal xspace = 5; + qreal x1 = xspace; + qreal x2 = totalWidth - xspace - cardWidth; + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + qreal x = i % 2 ? x2 : x1; + // If the total height of the cards is smaller than the available height, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardHeight * cardCount > totalHeight) + c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); + else + c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); + c->setRealZValue(i); + } + } + } + update(); } void HandZone::setWidth(qreal _width) { - if (settingsCache->getHorizontalHand()) { - prepareGeometryChange(); - width = _width; - reorganizeCards(); - } + if (settingsCache->getHorizontalHand()) { + prepareGeometryChange(); + width = _width; + reorganizeCards(); + } } void HandZone::updateOrientation() { - prepareGeometryChange(); - reorganizeCards(); + prepareGeometryChange(); + reorganizeCards(); } diff --git a/cockatrice/src/handzone.h b/cockatrice/src/handzone.h index fb51cecb..66245c50 100644 --- a/cockatrice/src/handzone.h +++ b/cockatrice/src/handzone.h @@ -4,23 +4,23 @@ #include "selectzone.h" class HandZone : public SelectZone { - Q_OBJECT + Q_OBJECT private: - qreal width, zoneHeight; - QPixmap bgPixmap; + qreal width, zoneHeight; + QPixmap bgPixmap; private slots: - void updateBgPixmap(); + void updateBgPixmap(); public slots: - void updateOrientation(); + void updateOrientation(); public: - HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent = 0); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); - void setWidth(qreal _width); + HandZone(Player *_p, bool _contentsKnown, int _zoneHeight, QGraphicsItem *parent = 0); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); + void setWidth(qreal _width); protected: - void addCardImpl(CardItem *card, int x, int y); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/localclient.cpp b/cockatrice/src/localclient.cpp index f9ee06ec..3ad7c809 100644 --- a/cockatrice/src/localclient.cpp +++ b/cockatrice/src/localclient.cpp @@ -4,17 +4,17 @@ #include "pb/session_commands.pb.h" LocalClient::LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent) - : AbstractClient(parent), lsi(_lsi) + : AbstractClient(parent), lsi(_lsi) { - connect(lsi, SIGNAL(itemToClient(const ServerMessage &)), this, SLOT(itemFromServer(const ServerMessage &))); - - Command_Login loginCmd; - loginCmd.set_user_name(_playerName.toStdString()); - sendCommand(prepareSessionCommand(loginCmd)); - - Command_JoinRoom joinCmd; - joinCmd.set_room_id(0); - sendCommand(prepareSessionCommand(joinCmd)); + connect(lsi, SIGNAL(itemToClient(const ServerMessage &)), this, SLOT(itemFromServer(const ServerMessage &))); + + Command_Login loginCmd; + loginCmd.set_user_name(_playerName.toStdString()); + sendCommand(prepareSessionCommand(loginCmd)); + + Command_JoinRoom joinCmd; + joinCmd.set_room_id(0); + sendCommand(prepareSessionCommand(joinCmd)); } LocalClient::~LocalClient() @@ -23,10 +23,10 @@ LocalClient::~LocalClient() void LocalClient::sendCommandContainer(const CommandContainer &cont) { - lsi->itemFromClient(cont); + lsi->itemFromClient(cont); } void LocalClient::itemFromServer(const ServerMessage &item) { - processProtocolItem(item); + processProtocolItem(item); } diff --git a/cockatrice/src/localclient.h b/cockatrice/src/localclient.h index 6cf5382e..febacada 100644 --- a/cockatrice/src/localclient.h +++ b/cockatrice/src/localclient.h @@ -6,16 +6,16 @@ class LocalServerInterface; class LocalClient : public AbstractClient { - Q_OBJECT + Q_OBJECT private: - LocalServerInterface *lsi; + LocalServerInterface *lsi; public: - LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent = 0); - ~LocalClient(); - - void sendCommandContainer(const CommandContainer &cont); + LocalClient(LocalServerInterface *_lsi, const QString &_playerName, QObject *parent = 0); + ~LocalClient(); + + void sendCommandContainer(const CommandContainer &cont); private slots: - void itemFromServer(const ServerMessage &item); + void itemFromServer(const ServerMessage &item); }; #endif diff --git a/cockatrice/src/localserver.cpp b/cockatrice/src/localserver.cpp index 833b4446..dc49078a 100644 --- a/cockatrice/src/localserver.cpp +++ b/cockatrice/src/localserver.cpp @@ -3,37 +3,37 @@ #include "server_room.h" LocalServer::LocalServer(QObject *parent) - : Server(false, parent) + : Server(false, parent) { - setDatabaseInterface(new LocalServer_DatabaseInterface(this)); - addRoom(new Server_Room(0, QString(), QString(), false, QString(), QStringList(), this)); + setDatabaseInterface(new LocalServer_DatabaseInterface(this)); + addRoom(new Server_Room(0, QString(), QString(), false, QString(), QStringList(), this)); } LocalServer::~LocalServer() { - prepareDestroy(); + prepareDestroy(); } LocalServerInterface *LocalServer::newConnection() { - LocalServerInterface *lsi = new LocalServerInterface(this, getDatabaseInterface()); - addClient(lsi); - return lsi; + LocalServerInterface *lsi = new LocalServerInterface(this, getDatabaseInterface()); + addClient(lsi); + return lsi; } LocalServer_DatabaseInterface::LocalServer_DatabaseInterface(LocalServer *_localServer) - : Server_DatabaseInterface(_localServer), localServer(_localServer) + : Server_DatabaseInterface(_localServer), localServer(_localServer) { } ServerInfo_User LocalServer_DatabaseInterface::getUserData(const QString &name, bool /*withId*/) { - ServerInfo_User result; - result.set_name(name.toStdString()); - return result; + ServerInfo_User result; + result.set_name(name.toStdString()); + return result; } AuthenticationResult LocalServer_DatabaseInterface::checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft) { - return UnknownUser; + return UnknownUser; } diff --git a/cockatrice/src/localserver.h b/cockatrice/src/localserver.h index c77e6e7c..f47187f2 100644 --- a/cockatrice/src/localserver.h +++ b/cockatrice/src/localserver.h @@ -8,25 +8,25 @@ class LocalServerInterface; class LocalServer : public Server { - Q_OBJECT + Q_OBJECT public: - LocalServer(QObject *parent = 0); - ~LocalServer(); - - LocalServerInterface *newConnection(); + LocalServer(QObject *parent = 0); + ~LocalServer(); + + LocalServerInterface *newConnection(); }; class LocalServer_DatabaseInterface : public Server_DatabaseInterface { - Q_OBJECT + Q_OBJECT private: - LocalServer *localServer; + LocalServer *localServer; protected: - ServerInfo_User getUserData(const QString &name, bool withId = false); + ServerInfo_User getUserData(const QString &name, bool withId = false); public: - LocalServer_DatabaseInterface(LocalServer *_localServer); - AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft); - int getNextGameId() { return localServer->getNextLocalGameId(); } - int getNextReplayId() { return -1; } + LocalServer_DatabaseInterface(LocalServer *_localServer); + AuthenticationResult checkUserPassword(Server_ProtocolHandler *handler, const QString &user, const QString &password, QString &reasonStr, int &secondsLeft); + int getNextGameId() { return localServer->getNextLocalGameId(); } + int getNextReplayId() { return -1; } }; #endif diff --git a/cockatrice/src/localserverinterface.cpp b/cockatrice/src/localserverinterface.cpp index ebf873b8..291da146 100644 --- a/cockatrice/src/localserverinterface.cpp +++ b/cockatrice/src/localserverinterface.cpp @@ -3,7 +3,7 @@ #include LocalServerInterface::LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface) - : Server_ProtocolHandler(_server, _databaseInterface, _server) + : Server_ProtocolHandler(_server, _databaseInterface, _server) { } @@ -13,10 +13,10 @@ LocalServerInterface::~LocalServerInterface() void LocalServerInterface::transmitProtocolItem(const ServerMessage &item) { - emit itemToClient(item); + emit itemToClient(item); } void LocalServerInterface::itemFromClient(const CommandContainer &item) { - processCommandContainer(item); + processCommandContainer(item); } diff --git a/cockatrice/src/localserverinterface.h b/cockatrice/src/localserverinterface.h index d9c9d8c6..1ad895e7 100644 --- a/cockatrice/src/localserverinterface.h +++ b/cockatrice/src/localserverinterface.h @@ -7,17 +7,17 @@ class LocalServer; class LocalServerInterface : public Server_ProtocolHandler { - Q_OBJECT + Q_OBJECT public: - LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface); - ~LocalServerInterface(); - - QString getAddress() const { return QString(); } - void transmitProtocolItem(const ServerMessage &item); + LocalServerInterface(LocalServer *_server, Server_DatabaseInterface *_databaseInterface); + ~LocalServerInterface(); + + QString getAddress() const { return QString(); } + void transmitProtocolItem(const ServerMessage &item); signals: - void itemToClient(const ServerMessage &item); + void itemToClient(const ServerMessage &item); public slots: - void itemFromClient(const CommandContainer &item); + void itemFromClient(const CommandContainer &item); }; #endif diff --git a/cockatrice/src/main.cpp b/cockatrice/src/main.cpp index 90c743d5..595a6534 100644 --- a/cockatrice/src/main.cpp +++ b/cockatrice/src/main.cpp @@ -56,118 +56,118 @@ QString translationPath = QString(); void myMessageOutput(QtMsgType /*type*/, const char *msg) { - static FILE *f = NULL; - if (!f) - f = fopen("qdebug.txt", "w"); - fprintf(f, "%s\n", msg); - fflush(f); + static FILE *f = NULL; + if (!f) + f = fopen("qdebug.txt", "w"); + fprintf(f, "%s\n", msg); + fflush(f); } void installNewTranslator() { - QString lang = settingsCache->getLang(); + QString lang = settingsCache->getLang(); - qtTranslator->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); - qApp->installTranslator(qtTranslator); - translator->load(translationPrefix + "_" + lang, translationPath); - qApp->installTranslator(translator); + qtTranslator->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + qApp->installTranslator(qtTranslator); + translator->load(translationPrefix + "_" + lang, translationPath); + qApp->installTranslator(translator); } int main(int argc, char *argv[]) { - QApplication app(argc, argv); - - if (app.arguments().contains("--debug-output")) - qInstallMsgHandler(myMessageOutput); + QApplication app(argc, argv); + + if (app.arguments().contains("--debug-output")) + qInstallMsgHandler(myMessageOutput); #ifdef Q_OS_MAC - QDir baseDir(app.applicationDirPath()); - baseDir.cdUp(); - baseDir.cdUp(); - baseDir.cdUp(); - QDir pluginsDir = baseDir; - pluginsDir.cd("PlugIns"); - app.addLibraryPath(pluginsDir.absolutePath()); + QDir baseDir(app.applicationDirPath()); + baseDir.cdUp(); + baseDir.cdUp(); + baseDir.cdUp(); + QDir pluginsDir = baseDir; + pluginsDir.cd("PlugIns"); + app.addLibraryPath(pluginsDir.absolutePath()); #endif #ifdef Q_OS_WIN - app.addLibraryPath(app.applicationDirPath() + "/plugins"); + app.addLibraryPath(app.applicationDirPath() + "/plugins"); #endif - QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); - QCoreApplication::setOrganizationName("Cockatrice"); - QCoreApplication::setOrganizationDomain("cockatrice.de"); - QCoreApplication::setApplicationName("Cockatrice"); - - if (translationPath.isEmpty()) { + QCoreApplication::setOrganizationName("Cockatrice"); + QCoreApplication::setOrganizationDomain("cockatrice.de"); + QCoreApplication::setApplicationName("Cockatrice"); + + if (translationPath.isEmpty()) { #ifdef Q_OS_MAC - QDir translationsDir = baseDir; - translationsDir.cd("translations"); - translationPath = translationsDir.absolutePath(); + QDir translationsDir = baseDir; + translationsDir.cd("translations"); + translationPath = translationsDir.absolutePath(); #endif #ifdef Q_OS_WIN - translationPath = app.applicationDirPath() + "/translations"; + translationPath = app.applicationDirPath() + "/translations"; #endif - } - - rng = new RNG_SFMT; - settingsCache = new SettingsCache; - db = new CardDatabase; + } + + rng = new RNG_SFMT; + settingsCache = new SettingsCache; + db = new CardDatabase; - qtTranslator = new QTranslator; - translator = new QTranslator; - installNewTranslator(); - - qsrand(QDateTime::currentDateTime().toTime_t()); - - bool startMainProgram = true; - const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); - if (!db->getLoadSuccess()) - if (db->loadCardDatabase(dataDir + "/cards.xml")) - settingsCache->setCardDatabasePath(dataDir + "/cards.xml"); - if (settingsCache->getTokenDatabasePath().isEmpty()) - settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml"); - if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) { - QDir().mkpath(dataDir + "/decks"); - settingsCache->setDeckPath(dataDir + "/decks"); - } - if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) { - QDir().mkpath(dataDir + "/replays"); - settingsCache->setReplaysPath(dataDir + "/replays"); - } - if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) { - QDir().mkpath(dataDir + "/pics"); - settingsCache->setPicsPath(dataDir + "/pics"); - } - if (!db->getLoadSuccess() || !QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty() || settingsCache->getPicsPath().isEmpty() || !QDir(settingsCache->getPicsPath()).exists()) { - DlgSettings dlgSettings; - dlgSettings.show(); - app.exec(); - startMainProgram = (db->getLoadSuccess() && QDir(settingsCache->getDeckPath()).exists() && !settingsCache->getDeckPath().isEmpty() && QDir(settingsCache->getPicsPath()).exists() && !settingsCache->getPicsPath().isEmpty()); - } - - if (startMainProgram) { - qDebug("main(): starting main program"); - soundEngine = new SoundEngine; - qDebug("main(): SoundEngine constructor finished"); + qtTranslator = new QTranslator; + translator = new QTranslator; + installNewTranslator(); + + qsrand(QDateTime::currentDateTime().toTime_t()); + + bool startMainProgram = true; + const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); + if (!db->getLoadSuccess()) + if (db->loadCardDatabase(dataDir + "/cards.xml")) + settingsCache->setCardDatabasePath(dataDir + "/cards.xml"); + if (settingsCache->getTokenDatabasePath().isEmpty()) + settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml"); + if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) { + QDir().mkpath(dataDir + "/decks"); + settingsCache->setDeckPath(dataDir + "/decks"); + } + if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) { + QDir().mkpath(dataDir + "/replays"); + settingsCache->setReplaysPath(dataDir + "/replays"); + } + if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) { + QDir().mkpath(dataDir + "/pics"); + settingsCache->setPicsPath(dataDir + "/pics"); + } + if (!db->getLoadSuccess() || !QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty() || settingsCache->getPicsPath().isEmpty() || !QDir(settingsCache->getPicsPath()).exists()) { + DlgSettings dlgSettings; + dlgSettings.show(); + app.exec(); + startMainProgram = (db->getLoadSuccess() && QDir(settingsCache->getDeckPath()).exists() && !settingsCache->getDeckPath().isEmpty() && QDir(settingsCache->getPicsPath()).exists() && !settingsCache->getPicsPath().isEmpty()); + } + + if (startMainProgram) { + qDebug("main(): starting main program"); + soundEngine = new SoundEngine; + qDebug("main(): SoundEngine constructor finished"); - MainWindow ui; - qDebug("main(): MainWindow constructor finished"); - - QIcon icon(":/resources/appicon.svg"); - ui.setWindowIcon(icon); - - ui.show(); - qDebug("main(): ui.show() finished"); - - app.exec(); - } - - qDebug("Event loop finished, terminating..."); - delete db; - delete settingsCache; - delete rng; - PingPixmapGenerator::clear(); - CountryPixmapGenerator::clear(); - UserLevelPixmapGenerator::clear(); - - return 0; + MainWindow ui; + qDebug("main(): MainWindow constructor finished"); + + QIcon icon(":/resources/appicon.svg"); + ui.setWindowIcon(icon); + + ui.show(); + qDebug("main(): ui.show() finished"); + + app.exec(); + } + + qDebug("Event loop finished, terminating..."); + delete db; + delete settingsCache; + delete rng; + PingPixmapGenerator::clear(); + CountryPixmapGenerator::clear(); + UserLevelPixmapGenerator::clear(); + + return 0; } diff --git a/cockatrice/src/messagelogwidget.cpp b/cockatrice/src/messagelogwidget.cpp index a5f59a3f..ec9b90cb 100644 --- a/cockatrice/src/messagelogwidget.cpp +++ b/cockatrice/src/messagelogwidget.cpp @@ -11,867 +11,867 @@ QString MessageLogWidget::sanitizeHtml(QString dirty) const { - return dirty - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") - .replace("\"", """); + return dirty + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """); } QString MessageLogWidget::cardLink(const QString &cardName) const { - return QString("%2").arg(cardName).arg(cardName); + return QString("%2").arg(cardName).arg(cardName); } bool MessageLogWidget::isFemale(Player *player) const { - return player->getUserInfo()->gender() == ServerInfo_User::Female; + return player->getUserInfo()->gender() == ServerInfo_User::Female; } bool MessageLogWidget::userIsFemale() const { - return (tabSupervisor && tabSupervisor->getUserInfo() && (tabSupervisor->getUserInfo()->gender() & ServerInfo_User::Female)); + return (tabSupervisor && tabSupervisor->getUserInfo() && (tabSupervisor->getUserInfo()->gender() & ServerInfo_User::Female)); } void MessageLogWidget::logGameJoined(int gameId) { - if (userIsFemale()) - appendHtml(tr("You have joined game #%1.", "female").arg(gameId)); - else - appendHtml(tr("You have joined game #%1.", "male").arg(gameId)); + if (userIsFemale()) + appendHtml(tr("You have joined game #%1.", "female").arg(gameId)); + else + appendHtml(tr("You have joined game #%1.", "male").arg(gameId)); } void MessageLogWidget::logReplayStarted(int gameId) { - if (userIsFemale()) - appendHtml(tr("You are watching a replay of game #%1.", "female").arg(gameId)); - else - appendHtml(tr("You are watching a replay of game #%1.", "male").arg(gameId)); + if (userIsFemale()) + appendHtml(tr("You are watching a replay of game #%1.", "female").arg(gameId)); + else + appendHtml(tr("You are watching a replay of game #%1.", "male").arg(gameId)); } void MessageLogWidget::logJoin(Player *player) { - soundEngine->cuckoo(); - if (isFemale(player)) - appendHtml(tr("%1 has joined the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has joined the game.", "male").arg(sanitizeHtml(player->getName()))); + soundEngine->cuckoo(); + if (isFemale(player)) + appendHtml(tr("%1 has joined the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has joined the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logLeave(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 has left the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has left the game.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 has left the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has left the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logGameClosed() { - appendHtml(tr("The game has been closed.")); + appendHtml(tr("The game has been closed.")); } void MessageLogWidget::logKicked() { - appendHtml(tr("You have been kicked out of the game.")); + appendHtml(tr("You have been kicked out of the game.")); } void MessageLogWidget::logJoinSpectator(QString name) { - appendHtml(tr("%1 is now watching the game.").arg(sanitizeHtml(name))); + appendHtml(tr("%1 is now watching the game.").arg(sanitizeHtml(name))); } void MessageLogWidget::logLeaveSpectator(QString name) { - appendHtml(tr("%1 is not watching the game any more.").arg(sanitizeHtml(name))); + appendHtml(tr("%1 is not watching the game any more.").arg(sanitizeHtml(name))); } void MessageLogWidget::logDeckSelect(Player *player, QString deckHash) { - if (isFemale(player)) - appendHtml(tr("%1 has loaded a deck (%2).", "female").arg(sanitizeHtml(player->getName())).arg(deckHash)); - else - appendHtml(tr("%1 has loaded a deck (%2).", "male").arg(sanitizeHtml(player->getName())).arg(deckHash)); + if (isFemale(player)) + appendHtml(tr("%1 has loaded a deck (%2).", "female").arg(sanitizeHtml(player->getName())).arg(deckHash)); + else + appendHtml(tr("%1 has loaded a deck (%2).", "male").arg(sanitizeHtml(player->getName())).arg(deckHash)); } void MessageLogWidget::logReadyStart(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 is ready to start the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 is ready to start the game.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 is ready to start the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 is ready to start the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logNotReadyStart(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 is not ready to start the game any more.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 is not ready to start the game any more.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 is not ready to start the game any more.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 is not ready to start the game any more.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logSetSideboardLock(Player *player, bool locked) { - if (locked) { - if (isFemale(player)) - appendHtml(tr("%1 has locked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has locked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 has unlocked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has unlocked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); - } + if (locked) { + if (isFemale(player)) + appendHtml(tr("%1 has locked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has locked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 has unlocked her sideboard.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has unlocked his sideboard.", "male").arg(sanitizeHtml(player->getName()))); + } } void MessageLogWidget::logConcede(Player *player) { - if (isFemale(player)) - appendHtml(tr("%1 has conceded the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has conceded the game.", "male").arg(sanitizeHtml(player->getName()))); + if (isFemale(player)) + appendHtml(tr("%1 has conceded the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has conceded the game.", "male").arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logGameStart() { - appendHtml(tr("The game has started.")); + appendHtml(tr("The game has started.")); } void MessageLogWidget::logConnectionStateChanged(Player *player, bool connectionState) { - if (connectionState) { - if (isFemale(player)) - appendHtml(tr("%1 has restored connection to the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has restored connection to the game.", "male").arg(sanitizeHtml(player->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 has lost connection to the game.", "female").arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 has lost connection to the game.", "male").arg(sanitizeHtml(player->getName()))); - } + if (connectionState) { + if (isFemale(player)) + appendHtml(tr("%1 has restored connection to the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has restored connection to the game.", "male").arg(sanitizeHtml(player->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 has lost connection to the game.", "female").arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 has lost connection to the game.", "male").arg(sanitizeHtml(player->getName()))); + } } void MessageLogWidget::logSay(Player *player, QString message) { - appendMessage(message, player->getName(), UserLevelFlags(player->getUserInfo()->user_level()), true); + appendMessage(message, player->getName(), UserLevelFlags(player->getUserInfo()->user_level()), true); } void MessageLogWidget::logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message) { - appendMessage(message, spectatorName, spectatorUserLevel, false); + appendMessage(message, spectatorName, spectatorUserLevel, false); } void MessageLogWidget::logShuffle(Player *player, CardZone *zone) { - soundEngine->shuffle(); - if (currentContext != MessageContext_Mulligan) { - appendHtml((isFemale(player) - ? tr("%1 shuffles %2.", "female") - : tr("%1 shuffles %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseShuffleZone))); - } + soundEngine->shuffle(); + if (currentContext != MessageContext_Mulligan) { + appendHtml((isFemale(player) + ? tr("%1 shuffles %2.", "female") + : tr("%1 shuffles %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseShuffleZone))); + } } void MessageLogWidget::logRollDie(Player *player, int sides, int roll) { - if (isFemale(player)) - appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "female").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); - else - appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "male").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); + if (isFemale(player)) + appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "female").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); + else + appendHtml(tr("%1 rolls a %2 with a %3-sided die.", "male").arg(sanitizeHtml(player->getName())).arg(roll).arg(sides)); } void MessageLogWidget::logDrawCards(Player *player, int number) { - if (currentContext == MessageContext_Mulligan) - mulliganPlayer = player; - else { - soundEngine->draw(); - if (isFemale(player)) - appendHtml(tr("%1 draws %n card(s).", "female", number).arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 draws %n card(s).", "male", number).arg(sanitizeHtml(player->getName()))); - } + if (currentContext == MessageContext_Mulligan) + mulliganPlayer = player; + else { + soundEngine->draw(); + if (isFemale(player)) + appendHtml(tr("%1 draws %n card(s).", "female", number).arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 draws %n card(s).", "male", number).arg(sanitizeHtml(player->getName()))); + } } void MessageLogWidget::logUndoDraw(Player *player, QString cardName) { - if (cardName.isEmpty()) - appendHtml((isFemale(player) ? tr("%1 undoes her last draw.") : tr("%1 undoes his last draw.")).arg(sanitizeHtml(player->getName()))); - else - appendHtml((isFemale(player) ? tr("%1 undoes her last draw (%2).") : tr("%1 undoes his last draw (%2).")).arg(sanitizeHtml(player->getName())).arg(QString("%2").arg(sanitizeHtml(cardName)).arg(sanitizeHtml(cardName)))); + if (cardName.isEmpty()) + appendHtml((isFemale(player) ? tr("%1 undoes her last draw.") : tr("%1 undoes his last draw.")).arg(sanitizeHtml(player->getName()))); + else + appendHtml((isFemale(player) ? tr("%1 undoes her last draw (%2).") : tr("%1 undoes his last draw (%2).")).arg(sanitizeHtml(player->getName())).arg(QString("%2").arg(sanitizeHtml(cardName)).arg(sanitizeHtml(cardName)))); } QPair MessageLogWidget::getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const { - bool cardNameContainsStartZone = false; - QString fromStr; - QString startName = zone->getName(); - - if (startName == "table") - fromStr = tr(" from table"); - else if (startName == "grave") - fromStr = tr(" from graveyard"); - else if (startName == "rfg") - fromStr = tr(" from exile"); - else if (startName == "hand") - fromStr = tr(" from hand"); - else if (startName == "deck") { - if (position >= zone->getCards().size() - 1) { - if (cardName.isEmpty()) { - if (ownerChange) - cardName = tr("the bottom card of %1's library").arg(zone->getPlayer()->getName()); - else - cardName = isFemale(zone->getPlayer()) ? tr("the bottom card of her library") : tr("the bottom card of his library"); - cardNameContainsStartZone = true; - } else { - if (ownerChange) - fromStr = tr(" from the bottom of %1's library").arg(zone->getPlayer()->getName()); - else - fromStr = isFemale(zone->getPlayer()) ? tr(" from the bottom of her library") : tr(" from the bottom of his library"); - } - } else if (position == 0) { - if (cardName.isEmpty()) { - if (ownerChange) - cardName = tr("the top card of %1's library").arg(zone->getPlayer()->getName()); - else - cardName = isFemale(zone->getPlayer()) ? tr("the top card of her library") : tr("the top card of his library"); - cardNameContainsStartZone = true; - } else { - if (ownerChange) - fromStr = tr(" from the top of %1's library").arg(zone->getPlayer()->getName()); - else - fromStr = isFemale(zone->getPlayer()) ? tr(" from the top of her library") : tr(" from the top of his library"); - } - } else { - if (ownerChange) - fromStr = tr(" from %1's library").arg(zone->getPlayer()->getName()); - else - fromStr = tr(" from library"); - } - } else if (startName == "sb") - fromStr = tr(" from sideboard"); - else if (startName == "stack") - fromStr = tr(" from the stack"); + bool cardNameContainsStartZone = false; + QString fromStr; + QString startName = zone->getName(); + + if (startName == "table") + fromStr = tr(" from table"); + else if (startName == "grave") + fromStr = tr(" from graveyard"); + else if (startName == "rfg") + fromStr = tr(" from exile"); + else if (startName == "hand") + fromStr = tr(" from hand"); + else if (startName == "deck") { + if (position >= zone->getCards().size() - 1) { + if (cardName.isEmpty()) { + if (ownerChange) + cardName = tr("the bottom card of %1's library").arg(zone->getPlayer()->getName()); + else + cardName = isFemale(zone->getPlayer()) ? tr("the bottom card of her library") : tr("the bottom card of his library"); + cardNameContainsStartZone = true; + } else { + if (ownerChange) + fromStr = tr(" from the bottom of %1's library").arg(zone->getPlayer()->getName()); + else + fromStr = isFemale(zone->getPlayer()) ? tr(" from the bottom of her library") : tr(" from the bottom of his library"); + } + } else if (position == 0) { + if (cardName.isEmpty()) { + if (ownerChange) + cardName = tr("the top card of %1's library").arg(zone->getPlayer()->getName()); + else + cardName = isFemale(zone->getPlayer()) ? tr("the top card of her library") : tr("the top card of his library"); + cardNameContainsStartZone = true; + } else { + if (ownerChange) + fromStr = tr(" from the top of %1's library").arg(zone->getPlayer()->getName()); + else + fromStr = isFemale(zone->getPlayer()) ? tr(" from the top of her library") : tr(" from the top of his library"); + } + } else { + if (ownerChange) + fromStr = tr(" from %1's library").arg(zone->getPlayer()->getName()); + else + fromStr = tr(" from library"); + } + } else if (startName == "sb") + fromStr = tr(" from sideboard"); + else if (startName == "stack") + fromStr = tr(" from the stack"); - if (!cardNameContainsStartZone) - cardName.clear(); - return QPair(cardName, fromStr); + if (!cardNameContainsStartZone) + cardName.clear(); + return QPair(cardName, fromStr); } void MessageLogWidget::doMoveCard(LogMoveCard &attributes) { - bool ownerChange = attributes.startZone->getPlayer() != attributes.targetZone->getPlayer(); - QString startName = attributes.startZone->getName(); - QString targetName = attributes.targetZone->getName(); - if (((startName == "table") && (targetName == "table") && (attributes.startZone == attributes.targetZone)) || ((startName == "hand") && (targetName == "hand"))) - return; - QString cardName = attributes.cardName; - QPair temp = getFromStr(attributes.startZone, cardName, attributes.oldX, ownerChange); - bool cardNameContainsStartZone = false; - if (!temp.first.isEmpty()) { - cardNameContainsStartZone = true; - cardName = temp.first; - } - QString fromStr = temp.second; - QString cardStr; - if (cardNameContainsStartZone) - cardStr = cardName; - else if (cardName.isEmpty()) - cardStr = tr("a card"); - else - cardStr = cardLink(cardName); - - if (ownerChange && (attributes.startZone->getPlayer() == attributes.player)) { - appendHtml(tr("%1 gives %2 control over %3.").arg(sanitizeHtml(attributes.player->getName())).arg(sanitizeHtml(attributes.targetZone->getPlayer()->getName())).arg(cardStr)); - return; - } - - QString finalStr; - if (targetName == "table") { - soundEngine->playCard(); - if (moveCardTapped.value(attributes.card)) - finalStr = tr("%1 puts %2 into play tapped%3."); - else - finalStr = tr("%1 puts %2 into play%3."); - } else if (targetName == "grave") - finalStr = tr("%1 puts %2%3 into graveyard."); - else if (targetName == "rfg") - finalStr = tr("%1 exiles %2%3."); - else if (targetName == "hand") - finalStr = tr("%1 moves %2%3 to hand."); - else if (targetName == "deck") { - if (attributes.newX == -1) - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library.") : tr("%1 puts %2%3 into his library."); - else if (attributes.newX == attributes.targetZone->getCards().size() - 1) - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on bottom of her library.") : tr("%1 puts %2%3 on bottom of his library."); - else if (attributes.newX == 0) - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on top of her library.") : tr("%1 puts %2%3 on top of his library."); - else - finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library at position %4.") : tr("%1 puts %2%3 into his library at position %4."); - } else if (targetName == "sb") - finalStr = tr("%1 moves %2%3 to sideboard."); - else if (targetName == "stack") { - soundEngine->playCard(); - finalStr = tr("%1 plays %2%3."); - } - - appendHtml(finalStr.arg(sanitizeHtml(attributes.player->getName())).arg(cardStr).arg(fromStr).arg(attributes.newX)); + bool ownerChange = attributes.startZone->getPlayer() != attributes.targetZone->getPlayer(); + QString startName = attributes.startZone->getName(); + QString targetName = attributes.targetZone->getName(); + if (((startName == "table") && (targetName == "table") && (attributes.startZone == attributes.targetZone)) || ((startName == "hand") && (targetName == "hand"))) + return; + QString cardName = attributes.cardName; + QPair temp = getFromStr(attributes.startZone, cardName, attributes.oldX, ownerChange); + bool cardNameContainsStartZone = false; + if (!temp.first.isEmpty()) { + cardNameContainsStartZone = true; + cardName = temp.first; + } + QString fromStr = temp.second; + QString cardStr; + if (cardNameContainsStartZone) + cardStr = cardName; + else if (cardName.isEmpty()) + cardStr = tr("a card"); + else + cardStr = cardLink(cardName); + + if (ownerChange && (attributes.startZone->getPlayer() == attributes.player)) { + appendHtml(tr("%1 gives %2 control over %3.").arg(sanitizeHtml(attributes.player->getName())).arg(sanitizeHtml(attributes.targetZone->getPlayer()->getName())).arg(cardStr)); + return; + } + + QString finalStr; + if (targetName == "table") { + soundEngine->playCard(); + if (moveCardTapped.value(attributes.card)) + finalStr = tr("%1 puts %2 into play tapped%3."); + else + finalStr = tr("%1 puts %2 into play%3."); + } else if (targetName == "grave") + finalStr = tr("%1 puts %2%3 into graveyard."); + else if (targetName == "rfg") + finalStr = tr("%1 exiles %2%3."); + else if (targetName == "hand") + finalStr = tr("%1 moves %2%3 to hand."); + else if (targetName == "deck") { + if (attributes.newX == -1) + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library.") : tr("%1 puts %2%3 into his library."); + else if (attributes.newX == attributes.targetZone->getCards().size() - 1) + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on bottom of her library.") : tr("%1 puts %2%3 on bottom of his library."); + else if (attributes.newX == 0) + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 on top of her library.") : tr("%1 puts %2%3 on top of his library."); + else + finalStr = isFemale(attributes.targetZone->getPlayer()) ? tr("%1 puts %2%3 into her library at position %4.") : tr("%1 puts %2%3 into his library at position %4."); + } else if (targetName == "sb") + finalStr = tr("%1 moves %2%3 to sideboard."); + else if (targetName == "stack") { + soundEngine->playCard(); + finalStr = tr("%1 plays %2%3."); + } + + appendHtml(finalStr.arg(sanitizeHtml(attributes.player->getName())).arg(cardStr).arg(fromStr).arg(attributes.newX)); } void MessageLogWidget::logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX) { - LogMoveCard attributes = {player, card, card->getName(), startZone, oldX, targetZone, newX}; - if (currentContext == MessageContext_MoveCard) - moveCardQueue.append(attributes); - else if (currentContext == MessageContext_Mulligan) - mulliganPlayer = player; - else - doMoveCard(attributes); + LogMoveCard attributes = {player, card, card->getName(), startZone, oldX, targetZone, newX}; + if (currentContext == MessageContext_MoveCard) + moveCardQueue.append(attributes); + else if (currentContext == MessageContext_Mulligan) + mulliganPlayer = player; + else + doMoveCard(attributes); } void MessageLogWidget::logMulligan(Player *player, int number) { - if (!player) - return; + if (!player) + return; - if (number > -1) { - if (isFemale(player)) - appendHtml(tr("%1 takes a mulligan to %n.", "female", number).arg(sanitizeHtml(player->getName()))); - else - appendHtml(tr("%1 takes a mulligan to %n.", "male", number).arg(sanitizeHtml(player->getName()))); - } else - appendHtml((isFemale(player) ? tr("%1 draws her initial hand.") : tr("%1 draws his initial hand.")).arg(sanitizeHtml(player->getName()))); + if (number > -1) { + if (isFemale(player)) + appendHtml(tr("%1 takes a mulligan to %n.", "female", number).arg(sanitizeHtml(player->getName()))); + else + appendHtml(tr("%1 takes a mulligan to %n.", "male", number).arg(sanitizeHtml(player->getName()))); + } else + appendHtml((isFemale(player) ? tr("%1 draws her initial hand.") : tr("%1 draws his initial hand.")).arg(sanitizeHtml(player->getName()))); } void MessageLogWidget::logFlipCard(Player *player, QString cardName, bool faceDown) { - if (faceDown) { - if (isFemale(player)) - appendHtml(tr("%1 flips %2 face-down.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); - else - appendHtml(tr("%1 flips %2 face-down.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); - } else { - if (isFemale(player)) - appendHtml(tr("%1 flips %2 face-up.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); - else - appendHtml(tr("%1 flips %2 face-up.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); - } + if (faceDown) { + if (isFemale(player)) + appendHtml(tr("%1 flips %2 face-down.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); + else + appendHtml(tr("%1 flips %2 face-down.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); + } else { + if (isFemale(player)) + appendHtml(tr("%1 flips %2 face-up.", "female").arg(sanitizeHtml(player->getName())).arg(cardName)); + else + appendHtml(tr("%1 flips %2 face-up.", "male").arg(sanitizeHtml(player->getName())).arg(cardName)); + } } void MessageLogWidget::logDestroyCard(Player *player, QString cardName) { - if (isFemale(player)) - appendHtml(tr("%1 destroys %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); - else - appendHtml(tr("%1 destroys %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + if (isFemale(player)) + appendHtml(tr("%1 destroys %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + else + appendHtml(tr("%1 destroys %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); } void MessageLogWidget::logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName) { - QString str; - if (isFemale(player)) { - if (isFemale(targetPlayer)) - str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 female"); - else - str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 female"); - else - str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 male"); - } - - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(sanitizeHtml(targetPlayer->getName())).arg(cardLink(targetCardName))); + QString str; + if (isFemale(player)) { + if (isFemale(targetPlayer)) + str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 female"); + else + str = tr("%1 attaches %2 to %3's %4.", "p1 female, p2 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 female"); + else + str = tr("%1 attaches %2 to %3's %4.", "p1 male, p2 male"); + } + + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(sanitizeHtml(targetPlayer->getName())).arg(cardLink(targetCardName))); } void MessageLogWidget::logUnattachCard(Player *player, QString cardName) { - if (isFemale(player)) - appendHtml(tr("%1 unattaches %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); - else - appendHtml(tr("%1 unattaches %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + if (isFemale(player)) + appendHtml(tr("%1 unattaches %2.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); + else + appendHtml(tr("%1 unattaches %2.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName))); } void MessageLogWidget::logCreateToken(Player *player, QString cardName, QString pt) { - if (isFemale(player)) - appendHtml(tr("%1 creates token: %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); - else - appendHtml(tr("%1 creates token: %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); + if (isFemale(player)) + appendHtml(tr("%1 creates token: %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); + else + appendHtml(tr("%1 creates token: %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardLink(cardName)).arg(pt.isEmpty() ? QString() : QString(" (%1)").arg(sanitizeHtml(pt)))); } void MessageLogWidget::logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget) { - startCard = cardLink(startCard); - targetCard = cardLink(targetCard); - QString str; - if (playerTarget) { - if ((player == startPlayer) && (player == targetPlayer)) { - if (isFemale(player)) - str = tr("%1 points from her %2 to herself.", "female"); - else - str = tr("%1 points from his %2 to himself.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard)); - } else if (player == startPlayer) { - if (isFemale(player)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from her %2 to %3.", "p1 female, p2 female"); - else - str = tr("%1 points from her %2 to %3.", "p1 female, p2 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from his %2 to %3.", "p1 male, p2 female"); - else - str = tr("%1 points from his %2 to %3.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); - } else if (player == targetPlayer) { - if (isFemale(player)) { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to herself.", "card owner female, target female"); - else - str = tr("%1 points from %2's %3 to herself.", "card owner male, target female"); - } else { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to himself.", "card owner female, target male"); - else - str = tr("%1 points from %2's %3 to himself.", "card owner male, target male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard)); - } else { - if (isFemale(player)) { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 male"); - } - } else { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 male"); - } - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); - } - } else { - if ((player == startPlayer) && (player == targetPlayer)) { - if (isFemale(player)) - str = tr("%1 points from her %2 to her %3.", "female"); - else - str = tr("%1 points from his %2 to his %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(targetCard)); - } else if (player == startPlayer) { - if (isFemale(player)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 female"); - else - str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 female"); - else - str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); - } else if (player == targetPlayer) { - if (isFemale(player)) { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to her own %4.", "card owner female, target female"); - else - str = tr("%1 points from %2's %3 to her own %4.", "card owner male, target female"); - } else { - if (isFemale(startPlayer)) - str = tr("%1 points from %2's %3 to his own %4.", "card owner female, target male"); - else - str = tr("%1 points from %2's %3 to his own %4.", "card owner male, target male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(targetCard)); - } else { - if (isFemale(player)) { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 male"); - } - } else { - if (isFemale(startPlayer)) { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 male"); - } else { - if (isFemale(targetPlayer)) - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 female"); - else - str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 male"); - } - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); - } - } + startCard = cardLink(startCard); + targetCard = cardLink(targetCard); + QString str; + if (playerTarget) { + if ((player == startPlayer) && (player == targetPlayer)) { + if (isFemale(player)) + str = tr("%1 points from her %2 to herself.", "female"); + else + str = tr("%1 points from his %2 to himself.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard)); + } else if (player == startPlayer) { + if (isFemale(player)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from her %2 to %3.", "p1 female, p2 female"); + else + str = tr("%1 points from her %2 to %3.", "p1 female, p2 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from his %2 to %3.", "p1 male, p2 female"); + else + str = tr("%1 points from his %2 to %3.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); + } else if (player == targetPlayer) { + if (isFemale(player)) { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to herself.", "card owner female, target female"); + else + str = tr("%1 points from %2's %3 to herself.", "card owner male, target female"); + } else { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to himself.", "card owner female, target male"); + else + str = tr("%1 points from %2's %3 to himself.", "card owner male, target male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard)); + } else { + if (isFemale(player)) { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 female, p2 male, p3 male"); + } + } else { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4.", "p1 male, p2 male, p3 male"); + } + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName()))); + } + } else { + if ((player == startPlayer) && (player == targetPlayer)) { + if (isFemale(player)) + str = tr("%1 points from her %2 to her %3.", "female"); + else + str = tr("%1 points from his %2 to his %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(targetCard)); + } else if (player == startPlayer) { + if (isFemale(player)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 female"); + else + str = tr("%1 points from her %2 to %3's %4.", "p1 female, p2 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 female"); + else + str = tr("%1 points from his %2 to %3's %4.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); + } else if (player == targetPlayer) { + if (isFemale(player)) { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to her own %4.", "card owner female, target female"); + else + str = tr("%1 points from %2's %3 to her own %4.", "card owner male, target female"); + } else { + if (isFemale(startPlayer)) + str = tr("%1 points from %2's %3 to his own %4.", "card owner female, target male"); + else + str = tr("%1 points from %2's %3 to his own %4.", "card owner male, target male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(targetCard)); + } else { + if (isFemale(player)) { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 female, p2 male, p3 male"); + } + } else { + if (isFemale(startPlayer)) { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 female, p3 male"); + } else { + if (isFemale(targetPlayer)) + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 female"); + else + str = tr("%1 points from %2's %3 to %4's %5.", "p1 male, p2 male, p3 male"); + } + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(sanitizeHtml(startPlayer->getName())).arg(startCard).arg(sanitizeHtml(targetPlayer->getName())).arg(targetCard)); + } + } } void MessageLogWidget::logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue) { - QString finalStr, colorStr; - - int delta = abs(oldValue - value); - if (value > oldValue) { - if (isFemale(player)) - finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "female", delta); - else - finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "male", delta); - } else { - if (isFemale(player)) - finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "female", delta); - else - finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "male", delta); - } - - switch (counterId) { - case 0: colorStr = tr("red", "", delta); break; - case 1: colorStr = tr("yellow", "", delta); break; - case 2: colorStr = tr("green", "", delta); break; - default: ; - } - - appendHtml(finalStr.arg(sanitizeHtml(player->getName())).arg(colorStr).arg(cardLink(cardName)).arg(value)); + QString finalStr, colorStr; + + int delta = abs(oldValue - value); + if (value > oldValue) { + if (isFemale(player)) + finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "female", delta); + else + finalStr = tr("%1 places %n %2 counter(s) on %3 (now %4).", "male", delta); + } else { + if (isFemale(player)) + finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "female", delta); + else + finalStr = tr("%1 removes %n %2 counter(s) from %3 (now %4).", "male", delta); + } + + switch (counterId) { + case 0: colorStr = tr("red", "", delta); break; + case 1: colorStr = tr("yellow", "", delta); break; + case 2: colorStr = tr("green", "", delta); break; + default: ; + } + + appendHtml(finalStr.arg(sanitizeHtml(player->getName())).arg(colorStr).arg(cardLink(cardName)).arg(value)); } void MessageLogWidget::logSetTapped(Player *player, CardItem *card, bool tapped) { - if (tapped) - soundEngine->tap(); - else - soundEngine->untap(); - - if (currentContext == MessageContext_MoveCard) - moveCardTapped.insert(card, tapped); - else { - QString str; - if (!card) { - if (isFemale(player)) { - if (tapped) - str = tr("%1 taps her permanents.", "female"); - else - str = tr("%1 untaps her permanents.", "female"); - } else { - if (tapped) - str = tr("%1 taps his permanents.", "male"); - else - str = tr("%1 untaps his permanents.", "male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName()))); - } else { - if (isFemale(player)) { - if (tapped) - str = tr("%1 taps %2.", "female"); - else - str = tr("%1 untaps %2.", "female"); - } else { - if (tapped) - str = tr("%1 taps %2.", "male"); - else - str = tr("%1 untaps %2.", "male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); - } - } + if (tapped) + soundEngine->tap(); + else + soundEngine->untap(); + + if (currentContext == MessageContext_MoveCard) + moveCardTapped.insert(card, tapped); + else { + QString str; + if (!card) { + if (isFemale(player)) { + if (tapped) + str = tr("%1 taps her permanents.", "female"); + else + str = tr("%1 untaps her permanents.", "female"); + } else { + if (tapped) + str = tr("%1 taps his permanents.", "male"); + else + str = tr("%1 untaps his permanents.", "male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName()))); + } else { + if (isFemale(player)) { + if (tapped) + str = tr("%1 taps %2.", "female"); + else + str = tr("%1 untaps %2.", "female"); + } else { + if (tapped) + str = tr("%1 taps %2.", "male"); + else + str = tr("%1 untaps %2.", "male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); + } + } } void MessageLogWidget::logSetCounter(Player *player, QString counterName, int value, int oldValue) { - QString str; - if (isFemale(player)) - str = tr("%1 sets counter %2 to %3 (%4%5).", "female"); - else - str = tr("%1 sets counter %2 to %3 (%4%5).", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(QString("%1").arg(sanitizeHtml(counterName))).arg(QString("%1").arg(value)).arg(value > oldValue ? "+" : "").arg(value - oldValue)); + QString str; + if (isFemale(player)) + str = tr("%1 sets counter %2 to %3 (%4%5).", "female"); + else + str = tr("%1 sets counter %2 to %3 (%4%5).", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(QString("%1").arg(sanitizeHtml(counterName))).arg(QString("%1").arg(value)).arg(value > oldValue ? "+" : "").arg(value - oldValue)); } void MessageLogWidget::logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap) { - QString str; - if (doesntUntap) { - if (isFemale(player)) - str = tr("%1 sets %2 to not untap normally.", "female"); - else - str = tr("%1 sets %2 to not untap normally.", "male"); - } else { - if (isFemale(player)) - str = tr("%1 sets %2 to untap normally.", "female"); - else - str = tr("%1 sets %2 to untap normally.", "male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); + QString str; + if (doesntUntap) { + if (isFemale(player)) + str = tr("%1 sets %2 to not untap normally.", "female"); + else + str = tr("%1 sets %2 to not untap normally.", "male"); + } else { + if (isFemale(player)) + str = tr("%1 sets %2 to untap normally.", "female"); + else + str = tr("%1 sets %2 to untap normally.", "male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName()))); } void MessageLogWidget::logSetPT(Player *player, CardItem *card, QString newPT) { - if (currentContext == MessageContext_MoveCard) - moveCardPT.insert(card, newPT); - else { - QString str; - if (isFemale(player)) - str = tr("%1 sets PT of %2 to %3.", "female"); - else - str = tr("%1 sets PT of %2 to %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString("%1").arg(sanitizeHtml(newPT)))); - } + if (currentContext == MessageContext_MoveCard) + moveCardPT.insert(card, newPT); + else { + QString str; + if (isFemale(player)) + str = tr("%1 sets PT of %2 to %3.", "female"); + else + str = tr("%1 sets PT of %2 to %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString("%1").arg(sanitizeHtml(newPT)))); + } } void MessageLogWidget::logSetAnnotation(Player *player, CardItem *card, QString newAnnotation) { - QString str; - if (isFemale(player)) - str = tr("%1 sets annotation of %2 to %3.", "female"); - else - str = tr("%1 sets annotation of %2 to %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString(""%1"").arg(sanitizeHtml(newAnnotation)))); + QString str; + if (isFemale(player)) + str = tr("%1 sets annotation of %2 to %3.", "female"); + else + str = tr("%1 sets annotation of %2 to %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardLink(card->getName())).arg(QString(""%1"").arg(sanitizeHtml(newAnnotation)))); } void MessageLogWidget::logDumpZone(Player *player, CardZone *zone, int numberCards) { - if (numberCards == -1) - appendHtml((isFemale(player) - ? tr("%1 is looking at %2.", "female") - : tr("%1 is looking at %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); - else - appendHtml((isFemale(player) - ? tr("%1 is looking at the top %n card(s) %2.", "female", numberCards) - : tr("%1 is looking at the top %n card(s) %2.", "male", numberCards) - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseTopCardsOfZone))); + if (numberCards == -1) + appendHtml((isFemale(player) + ? tr("%1 is looking at %2.", "female") + : tr("%1 is looking at %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); + else + appendHtml((isFemale(player) + ? tr("%1 is looking at the top %n card(s) %2.", "female", numberCards) + : tr("%1 is looking at the top %n card(s) %2.", "male", numberCards) + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseTopCardsOfZone))); } void MessageLogWidget::logStopDumpZone(Player *player, CardZone *zone) { - appendHtml((isFemale(player) - ? tr("%1 stops looking at %2.", "female") - : tr("%1 stops looking at %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); + appendHtml((isFemale(player) + ? tr("%1 stops looking at %2.", "female") + : tr("%1 stops looking at %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(zone->getPlayer() == player, CaseLookAtZone))); } void MessageLogWidget::logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown) { - QPair temp = getFromStr(zone, cardName, cardId, false); - bool cardNameContainsStartZone = false; - if (!temp.first.isEmpty()) { - cardNameContainsStartZone = true; - cardName = temp.first; - } - QString fromStr = temp.second; + QPair temp = getFromStr(zone, cardName, cardId, false); + bool cardNameContainsStartZone = false; + if (!temp.first.isEmpty()) { + cardNameContainsStartZone = true; + cardName = temp.first; + } + QString fromStr = temp.second; - QString cardStr; - if (cardNameContainsStartZone) - cardStr = cardName; - else if (cardName.isEmpty()) - cardStr = tr("a card"); - else - cardStr = cardLink(cardName); + QString cardStr; + if (cardNameContainsStartZone) + cardStr = cardName; + else if (cardName.isEmpty()) + cardStr = tr("a card"); + else + cardStr = cardLink(cardName); - QString str; - if (cardId == -1) { - if (otherPlayer) { - if (isFemale(player)) { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2 to %3.", "p1 female, p2 female"); - else - str = tr("%1 reveals %2 to %3.", "p1 female, p2 male"); - } else { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2 to %3.", "p1 male, p2 female"); - else - str = tr("%1 reveals %2 to %3.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(zone->getTranslatedName(true, CaseRevealZone)).arg(sanitizeHtml(otherPlayer->getName()))); - } else { - appendHtml((isFemale(player) - ? tr("%1 reveals %2.", "female") - : tr("%1 reveals %2.", "male") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseRevealZone))); - } - } else if (cardId == -2) { - if (otherPlayer) { - if (isFemale(player)) { - if (isFemale(otherPlayer)) - str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 female"); - else - str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 male"); - } else { - if (isFemale(otherPlayer)) - str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 female"); - else - str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 randomly reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - else - appendHtml(tr("%1 randomly reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - } - } else { - if (faceDown && (player == otherPlayer)) { - if (cardName.isEmpty()) { - if (isFemale(player)) - str = tr("%1 peeks at face down card #%2.", "female"); - else - str = tr("%1 peeks at face down card #%2.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId)); - } else { - if (isFemale(player)) - str = tr("%1 peeks at face down card #%2: %3.", "female"); - else - str = tr("%1 peeks at face down card #%2: %3.", "male"); - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId).arg(cardStr)); - } - } else if (otherPlayer) { - if (isFemale(player)) { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 female"); - else - str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 male"); - } else { - if (isFemale(otherPlayer)) - str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 female"); - else - str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 male"); - } - appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); - } else { - if (isFemale(player)) - appendHtml(tr("%1 reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - else - appendHtml(tr("%1 reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); - } - } + QString str; + if (cardId == -1) { + if (otherPlayer) { + if (isFemale(player)) { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2 to %3.", "p1 female, p2 female"); + else + str = tr("%1 reveals %2 to %3.", "p1 female, p2 male"); + } else { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2 to %3.", "p1 male, p2 female"); + else + str = tr("%1 reveals %2 to %3.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(zone->getTranslatedName(true, CaseRevealZone)).arg(sanitizeHtml(otherPlayer->getName()))); + } else { + appendHtml((isFemale(player) + ? tr("%1 reveals %2.", "female") + : tr("%1 reveals %2.", "male") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseRevealZone))); + } + } else if (cardId == -2) { + if (otherPlayer) { + if (isFemale(player)) { + if (isFemale(otherPlayer)) + str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 female"); + else + str = tr("%1 randomly reveals %2%3 to %4.", "p1 female, p2 male"); + } else { + if (isFemale(otherPlayer)) + str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 female"); + else + str = tr("%1 randomly reveals %2%3 to %4.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 randomly reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + else + appendHtml(tr("%1 randomly reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + } + } else { + if (faceDown && (player == otherPlayer)) { + if (cardName.isEmpty()) { + if (isFemale(player)) + str = tr("%1 peeks at face down card #%2.", "female"); + else + str = tr("%1 peeks at face down card #%2.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId)); + } else { + if (isFemale(player)) + str = tr("%1 peeks at face down card #%2: %3.", "female"); + else + str = tr("%1 peeks at face down card #%2: %3.", "male"); + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardId).arg(cardStr)); + } + } else if (otherPlayer) { + if (isFemale(player)) { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 female"); + else + str = tr("%1 reveals %2%3 to %4.", "p1 female, p2 male"); + } else { + if (isFemale(otherPlayer)) + str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 female"); + else + str = tr("%1 reveals %2%3 to %4.", "p1 male, p2 male"); + } + appendHtml(str.arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr).arg(sanitizeHtml(otherPlayer->getName()))); + } else { + if (isFemale(player)) + appendHtml(tr("%1 reveals %2%3.", "female").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + else + appendHtml(tr("%1 reveals %2%3.", "male").arg(sanitizeHtml(player->getName())).arg(cardStr).arg(fromStr)); + } + } } void MessageLogWidget::logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal) { - appendHtml((reveal - ? tr("%1 is now keeping the top card %2 revealed.") - : tr("%1 is not revealing the top card %2 any longer.") - ).arg(sanitizeHtml(player->getName())) - .arg(zone->getTranslatedName(true, CaseTopCardsOfZone)) - ); + appendHtml((reveal + ? tr("%1 is now keeping the top card %2 revealed.") + : tr("%1 is not revealing the top card %2 any longer.") + ).arg(sanitizeHtml(player->getName())) + .arg(zone->getTranslatedName(true, CaseTopCardsOfZone)) + ); } void MessageLogWidget::logSetActivePlayer(Player *player) { - soundEngine->notification(); - - QString str; - if (isFemale(player)) - str = tr("It is now %1's turn.", "female"); - else - str = tr("It is now %1's turn.", "male"); - appendHtml("
" + str.arg(player->getName()) + "
"); + soundEngine->notification(); + + QString str; + if (isFemale(player)) + str = tr("It is now %1's turn.", "female"); + else + str = tr("It is now %1's turn.", "male"); + appendHtml("
" + str.arg(player->getName()) + "
"); } void MessageLogWidget::logSetActivePhase(int phase) { - soundEngine->notification(); - QString phaseName; - switch (phase) { - case 0: phaseName = tr("untap step"); break; - case 1: phaseName = tr("upkeep step"); break; - case 2: phaseName = tr("draw step"); break; - case 3: phaseName = tr("first main phase"); break; - case 4: phaseName = tr("beginning of combat step"); break; - case 5: phaseName = tr("declare attackers step"); break; - case 6: phaseName = tr("declare blockers step"); break; - case 7: phaseName = tr("combat damage step"); break; - case 8: phaseName = tr("end of combat step"); break; - case 9: phaseName = tr("second main phase"); break; - case 10: phaseName = tr("ending phase"); break; - } - appendHtml("" + tr("It is now the %1.").arg(phaseName) + ""); + soundEngine->notification(); + QString phaseName; + switch (phase) { + case 0: phaseName = tr("untap step"); break; + case 1: phaseName = tr("upkeep step"); break; + case 2: phaseName = tr("draw step"); break; + case 3: phaseName = tr("first main phase"); break; + case 4: phaseName = tr("beginning of combat step"); break; + case 5: phaseName = tr("declare attackers step"); break; + case 6: phaseName = tr("declare blockers step"); break; + case 7: phaseName = tr("combat damage step"); break; + case 8: phaseName = tr("end of combat step"); break; + case 9: phaseName = tr("second main phase"); break; + case 10: phaseName = tr("ending phase"); break; + } + appendHtml("" + tr("It is now the %1.").arg(phaseName) + ""); } void MessageLogWidget::containerProcessingStarted(const GameEventContext &_context) { - if (_context.HasExtension(Context_MoveCard::ext)) - currentContext = MessageContext_MoveCard; - else if (_context.HasExtension(Context_Mulligan::ext)) { - const Context_Mulligan &contextMulligan = _context.GetExtension(Context_Mulligan::ext); - currentContext = MessageContext_Mulligan; - mulliganPlayer = 0; - mulliganNumber = contextMulligan.number(); - } + if (_context.HasExtension(Context_MoveCard::ext)) + currentContext = MessageContext_MoveCard; + else if (_context.HasExtension(Context_Mulligan::ext)) { + const Context_Mulligan &contextMulligan = _context.GetExtension(Context_Mulligan::ext); + currentContext = MessageContext_Mulligan; + mulliganPlayer = 0; + mulliganNumber = contextMulligan.number(); + } } void MessageLogWidget::containerProcessingDone() { - if (currentContext == MessageContext_MoveCard) { - for (int i = 0; i < moveCardQueue.size(); ++i) - doMoveCard(moveCardQueue[i]); - moveCardQueue.clear(); - moveCardPT.clear(); - moveCardTapped.clear(); - } else if (currentContext == MessageContext_Mulligan) { - logMulligan(mulliganPlayer, mulliganNumber); - mulliganPlayer = 0; - mulliganNumber = 0; - } - - currentContext = MessageContext_None; + if (currentContext == MessageContext_MoveCard) { + for (int i = 0; i < moveCardQueue.size(); ++i) + doMoveCard(moveCardQueue[i]); + moveCardQueue.clear(); + moveCardPT.clear(); + moveCardTapped.clear(); + } else if (currentContext == MessageContext_Mulligan) { + logMulligan(mulliganPlayer, mulliganNumber); + mulliganPlayer = 0; + mulliganNumber = 0; + } + + currentContext = MessageContext_None; } void MessageLogWidget::connectToPlayer(Player *player) { - connect(player, SIGNAL(logSay(Player *, QString)), this, SLOT(logSay(Player *, QString))); - connect(player, SIGNAL(logShuffle(Player *, CardZone *)), this, SLOT(logShuffle(Player *, CardZone *))); - connect(player, SIGNAL(logRollDie(Player *, int, int)), this, SLOT(logRollDie(Player *, int, int))); - connect(player, SIGNAL(logCreateArrow(Player *, Player *, QString, Player *, QString, bool)), this, SLOT(logCreateArrow(Player *, Player *, QString, Player *, QString, bool))); - connect(player, SIGNAL(logCreateToken(Player *, QString, QString)), this, SLOT(logCreateToken(Player *, QString, QString))); - connect(player, SIGNAL(logSetCounter(Player *, QString, int, int)), this, SLOT(logSetCounter(Player *, QString, int, int))); - connect(player, SIGNAL(logSetCardCounter(Player *, QString, int, int, int)), this, SLOT(logSetCardCounter(Player *, QString, int, int, int))); - connect(player, SIGNAL(logSetTapped(Player *, CardItem *, bool)), this, SLOT(logSetTapped(Player *, CardItem *, bool))); - connect(player, SIGNAL(logSetDoesntUntap(Player *, CardItem *, bool)), this, SLOT(logSetDoesntUntap(Player *, CardItem *, bool))); - connect(player, SIGNAL(logSetPT(Player *, CardItem *, QString)), this, SLOT(logSetPT(Player *, CardItem *, QString))); - connect(player, SIGNAL(logSetAnnotation(Player *, CardItem *, QString)), this, SLOT(logSetAnnotation(Player *, CardItem *, QString))); - connect(player, SIGNAL(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int)), this, SLOT(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int))); - connect(player, SIGNAL(logFlipCard(Player *, QString, bool)), this, SLOT(logFlipCard(Player *, QString, bool))); - connect(player, SIGNAL(logDestroyCard(Player *, QString)), this, SLOT(logDestroyCard(Player *, QString))); - connect(player, SIGNAL(logAttachCard(Player *, QString, Player *, QString)), this, SLOT(logAttachCard(Player *, QString, Player *, QString))); - connect(player, SIGNAL(logUnattachCard(Player *, QString)), this, SLOT(logUnattachCard(Player *, QString))); - connect(player, SIGNAL(logDumpZone(Player *, CardZone *, int)), this, SLOT(logDumpZone(Player *, CardZone *, int))); - connect(player, SIGNAL(logStopDumpZone(Player *, CardZone *)), this, SLOT(logStopDumpZone(Player *, CardZone *))); - connect(player, SIGNAL(logDrawCards(Player *, int)), this, SLOT(logDrawCards(Player *, int))); - connect(player, SIGNAL(logUndoDraw(Player *, QString)), this, SLOT(logUndoDraw(Player *, QString))); - connect(player, SIGNAL(logRevealCards(Player *, CardZone *, int, QString, Player *, bool)), this, SLOT(logRevealCards(Player *, CardZone *, int, QString, Player *, bool))); - connect(player, SIGNAL(logAlwaysRevealTopCard(Player *, CardZone *, bool)), this, SLOT(logAlwaysRevealTopCard(Player *, CardZone *, bool))); + connect(player, SIGNAL(logSay(Player *, QString)), this, SLOT(logSay(Player *, QString))); + connect(player, SIGNAL(logShuffle(Player *, CardZone *)), this, SLOT(logShuffle(Player *, CardZone *))); + connect(player, SIGNAL(logRollDie(Player *, int, int)), this, SLOT(logRollDie(Player *, int, int))); + connect(player, SIGNAL(logCreateArrow(Player *, Player *, QString, Player *, QString, bool)), this, SLOT(logCreateArrow(Player *, Player *, QString, Player *, QString, bool))); + connect(player, SIGNAL(logCreateToken(Player *, QString, QString)), this, SLOT(logCreateToken(Player *, QString, QString))); + connect(player, SIGNAL(logSetCounter(Player *, QString, int, int)), this, SLOT(logSetCounter(Player *, QString, int, int))); + connect(player, SIGNAL(logSetCardCounter(Player *, QString, int, int, int)), this, SLOT(logSetCardCounter(Player *, QString, int, int, int))); + connect(player, SIGNAL(logSetTapped(Player *, CardItem *, bool)), this, SLOT(logSetTapped(Player *, CardItem *, bool))); + connect(player, SIGNAL(logSetDoesntUntap(Player *, CardItem *, bool)), this, SLOT(logSetDoesntUntap(Player *, CardItem *, bool))); + connect(player, SIGNAL(logSetPT(Player *, CardItem *, QString)), this, SLOT(logSetPT(Player *, CardItem *, QString))); + connect(player, SIGNAL(logSetAnnotation(Player *, CardItem *, QString)), this, SLOT(logSetAnnotation(Player *, CardItem *, QString))); + connect(player, SIGNAL(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int)), this, SLOT(logMoveCard(Player *, CardItem *, CardZone *, int, CardZone *, int))); + connect(player, SIGNAL(logFlipCard(Player *, QString, bool)), this, SLOT(logFlipCard(Player *, QString, bool))); + connect(player, SIGNAL(logDestroyCard(Player *, QString)), this, SLOT(logDestroyCard(Player *, QString))); + connect(player, SIGNAL(logAttachCard(Player *, QString, Player *, QString)), this, SLOT(logAttachCard(Player *, QString, Player *, QString))); + connect(player, SIGNAL(logUnattachCard(Player *, QString)), this, SLOT(logUnattachCard(Player *, QString))); + connect(player, SIGNAL(logDumpZone(Player *, CardZone *, int)), this, SLOT(logDumpZone(Player *, CardZone *, int))); + connect(player, SIGNAL(logStopDumpZone(Player *, CardZone *)), this, SLOT(logStopDumpZone(Player *, CardZone *))); + connect(player, SIGNAL(logDrawCards(Player *, int)), this, SLOT(logDrawCards(Player *, int))); + connect(player, SIGNAL(logUndoDraw(Player *, QString)), this, SLOT(logUndoDraw(Player *, QString))); + connect(player, SIGNAL(logRevealCards(Player *, CardZone *, int, QString, Player *, bool)), this, SLOT(logRevealCards(Player *, CardZone *, int, QString, Player *, bool))); + connect(player, SIGNAL(logAlwaysRevealTopCard(Player *, CardZone *, bool)), this, SLOT(logAlwaysRevealTopCard(Player *, CardZone *, bool))); } MessageLogWidget::MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent) - : ChatView(_tabSupervisor, _game, false, parent) + : ChatView(_tabSupervisor, _game, false, parent) { } diff --git a/cockatrice/src/messagelogwidget.h b/cockatrice/src/messagelogwidget.h index d1c1d6f7..1747a338 100644 --- a/cockatrice/src/messagelogwidget.h +++ b/cockatrice/src/messagelogwidget.h @@ -12,81 +12,81 @@ class GameEventContext; class CardItem; struct LogMoveCard { - Player *player; - CardItem *card; - QString cardName; - CardZone *startZone; - int oldX; - CardZone *targetZone; - int newX; + Player *player; + CardItem *card; + QString cardName; + CardZone *startZone; + int oldX; + CardZone *targetZone; + int newX; }; class MessageLogWidget : public ChatView { - Q_OBJECT + Q_OBJECT private: - enum MessageContext { MessageContext_None, MessageContext_MoveCard, MessageContext_Mulligan }; - - QString sanitizeHtml(QString dirty) const; - QString cardLink(const QString &cardName) const; - bool isFemale(Player *player) const; - bool userIsFemale() const; - QPair getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const; - MessageContext currentContext; - - QList moveCardQueue; - QMap moveCardPT; - QMap moveCardTapped; - - Player *mulliganPlayer; - int mulliganNumber; + enum MessageContext { MessageContext_None, MessageContext_MoveCard, MessageContext_Mulligan }; + + QString sanitizeHtml(QString dirty) const; + QString cardLink(const QString &cardName) const; + bool isFemale(Player *player) const; + bool userIsFemale() const; + QPair getFromStr(CardZone *zone, QString cardName, int position, bool ownerChange) const; + MessageContext currentContext; + + QList moveCardQueue; + QMap moveCardPT; + QMap moveCardTapped; + + Player *mulliganPlayer; + int mulliganNumber; public slots: - void logGameJoined(int gameId); - void logReplayStarted(int gameId); - void logJoin(Player *player); - void logLeave(Player *player); - void logGameClosed(); - void logKicked(); - void logJoinSpectator(QString name); - void logLeaveSpectator(QString name); - void logDeckSelect(Player *player, QString deckHash); - void logReadyStart(Player *player); - void logNotReadyStart(Player *player); - void logSetSideboardLock(Player *player, bool locked); - void logConcede(Player *player); - void logGameStart(); - void logConnectionStateChanged(Player *player, bool connectionState); - void logSay(Player *player, QString message); - void logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message); - void logShuffle(Player *player, CardZone *zone); - void logRollDie(Player *player, int sides, int roll); - void logDrawCards(Player *player, int number); - void logUndoDraw(Player *player, QString cardName); - void doMoveCard(LogMoveCard &attributes); - void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); - void logMulligan(Player *player, int number); - void logFlipCard(Player *player, QString cardName, bool faceDown); - void logDestroyCard(Player *player, QString cardName); - void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); - void logUnattachCard(Player *player, QString cardName); - void logCreateToken(Player *player, QString cardName, QString pt); - void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget); - void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); - void logSetTapped(Player *player, CardItem *card, bool tapped); - void logSetCounter(Player *player, QString counterName, int value, int oldValue); - void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); - void logSetPT(Player *player, CardItem *card, QString newPT); - void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); - void logDumpZone(Player *player, CardZone *zone, int numberCards); - void logStopDumpZone(Player *player, CardZone *zone); - void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); - void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); - void logSetActivePlayer(Player *player); - void logSetActivePhase(int phase); - void containerProcessingStarted(const GameEventContext &context); - void containerProcessingDone(); + void logGameJoined(int gameId); + void logReplayStarted(int gameId); + void logJoin(Player *player); + void logLeave(Player *player); + void logGameClosed(); + void logKicked(); + void logJoinSpectator(QString name); + void logLeaveSpectator(QString name); + void logDeckSelect(Player *player, QString deckHash); + void logReadyStart(Player *player); + void logNotReadyStart(Player *player); + void logSetSideboardLock(Player *player, bool locked); + void logConcede(Player *player); + void logGameStart(); + void logConnectionStateChanged(Player *player, bool connectionState); + void logSay(Player *player, QString message); + void logSpectatorSay(QString spectatorName, UserLevelFlags spectatorUserLevel, QString message); + void logShuffle(Player *player, CardZone *zone); + void logRollDie(Player *player, int sides, int roll); + void logDrawCards(Player *player, int number); + void logUndoDraw(Player *player, QString cardName); + void doMoveCard(LogMoveCard &attributes); + void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); + void logMulligan(Player *player, int number); + void logFlipCard(Player *player, QString cardName, bool faceDown); + void logDestroyCard(Player *player, QString cardName); + void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); + void logUnattachCard(Player *player, QString cardName); + void logCreateToken(Player *player, QString cardName, QString pt); + void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool playerTarget); + void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); + void logSetTapped(Player *player, CardItem *card, bool tapped); + void logSetCounter(Player *player, QString counterName, int value, int oldValue); + void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); + void logSetPT(Player *player, CardItem *card, QString newPT); + void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); + void logDumpZone(Player *player, CardZone *zone, int numberCards); + void logStopDumpZone(Player *player, CardZone *zone); + void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); + void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); + void logSetActivePlayer(Player *player); + void logSetActivePhase(int phase); + void containerProcessingStarted(const GameEventContext &context); + void containerProcessingDone(); public: - void connectToPlayer(Player *player); - MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent = 0); + void connectToPlayer(Player *player); + MessageLogWidget(const TabSupervisor *_tabSupervisor, TabGame *_game, QWidget *parent = 0); }; #endif diff --git a/cockatrice/src/pending_command.h b/cockatrice/src/pending_command.h index 2e2a2bf2..9b092dcd 100644 --- a/cockatrice/src/pending_command.h +++ b/cockatrice/src/pending_command.h @@ -6,26 +6,26 @@ #include class PendingCommand : public QObject { - Q_OBJECT + Q_OBJECT signals: - void finished(const Response &response, const CommandContainer &commandContainer, const QVariant &extraData); - void finished(Response::ResponseCode respCode); + void finished(const Response &response, const CommandContainer &commandContainer, const QVariant &extraData); + void finished(Response::ResponseCode respCode); private: - CommandContainer commandContainer; - QVariant extraData; - int ticks; + CommandContainer commandContainer; + QVariant extraData; + int ticks; public: - PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant()) - : commandContainer(_commandContainer), extraData(_extraData), ticks(0) { } - CommandContainer &getCommandContainer() { return commandContainer; } - void setExtraData(const QVariant &_extraData) { extraData = _extraData; } - QVariant getExtraData() const { return extraData; } - void processResponse(const Response &response) - { - emit finished(response, commandContainer, extraData); - emit finished(response.response_code()); - } - int tick() { return ++ticks; } + PendingCommand(const CommandContainer &_commandContainer, QVariant _extraData = QVariant()) + : commandContainer(_commandContainer), extraData(_extraData), ticks(0) { } + CommandContainer &getCommandContainer() { return commandContainer; } + void setExtraData(const QVariant &_extraData) { extraData = _extraData; } + QVariant getExtraData() const { return extraData; } + void processResponse(const Response &response) + { + emit finished(response, commandContainer, extraData); + emit finished(response.response_code()); + } + int tick() { return ++ticks; } }; #endif diff --git a/cockatrice/src/phasestoolbar.cpp b/cockatrice/src/phasestoolbar.cpp index 3ea9ad91..98f27404 100644 --- a/cockatrice/src/phasestoolbar.cpp +++ b/cockatrice/src/phasestoolbar.cpp @@ -13,239 +13,239 @@ #include "pb/command_draw_cards.pb.h" PhaseButton::PhaseButton(const QString &_name, QGraphicsItem *parent, QAction *_doubleClickAction, bool _highlightable) - : QObject(), QGraphicsItem(parent), name(_name), active(false), highlightable(_highlightable), activeAnimationCounter(0), doubleClickAction(_doubleClickAction), width(50) + : QObject(), QGraphicsItem(parent), name(_name), active(false), highlightable(_highlightable), activeAnimationCounter(0), doubleClickAction(_doubleClickAction), width(50) { - if (highlightable) { - activeAnimationTimer = new QTimer(this); - connect(activeAnimationTimer, SIGNAL(timeout()), this, SLOT(updateAnimation())); - activeAnimationTimer->setSingleShot(false); - } else - activeAnimationCounter = 9.0; - - setCacheMode(DeviceCoordinateCache); + if (highlightable) { + activeAnimationTimer = new QTimer(this); + connect(activeAnimationTimer, SIGNAL(timeout()), this, SLOT(updateAnimation())); + activeAnimationTimer->setSingleShot(false); + } else + activeAnimationCounter = 9.0; + + setCacheMode(DeviceCoordinateCache); } QRectF PhaseButton::boundingRect() const { - return QRectF(0, 0, width, width); + return QRectF(0, 0, width, width); } void PhaseButton::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QRectF iconRect = boundingRect().adjusted(3, 3, -3, -3); - QRectF translatedIconRect = painter->combinedTransform().mapRect(iconRect); - qreal scaleFactor = translatedIconRect.width() / iconRect.width(); - QPixmap iconPixmap = PhasePixmapGenerator::generatePixmap(round(translatedIconRect.height()), name); - - painter->setBrush(QColor(220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0))); - painter->setPen(Qt::gray); - painter->drawRect(0, 0, width - 1, width - 1); - painter->save(); - painter->resetTransform(); - painter->drawPixmap(iconPixmap.rect().translated(round(3 * scaleFactor), round(3 * scaleFactor)), iconPixmap, iconPixmap.rect()); - painter->restore(); - - painter->setBrush(QColor(0, 0, 0, 255 * ((10 - activeAnimationCounter) / 15.0))); - painter->setPen(Qt::gray); - painter->drawRect(0, 0, width - 1, width - 1); + QRectF iconRect = boundingRect().adjusted(3, 3, -3, -3); + QRectF translatedIconRect = painter->combinedTransform().mapRect(iconRect); + qreal scaleFactor = translatedIconRect.width() / iconRect.width(); + QPixmap iconPixmap = PhasePixmapGenerator::generatePixmap(round(translatedIconRect.height()), name); + + painter->setBrush(QColor(220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0), 220 * (activeAnimationCounter / 10.0))); + painter->setPen(Qt::gray); + painter->drawRect(0, 0, width - 1, width - 1); + painter->save(); + painter->resetTransform(); + painter->drawPixmap(iconPixmap.rect().translated(round(3 * scaleFactor), round(3 * scaleFactor)), iconPixmap, iconPixmap.rect()); + painter->restore(); + + painter->setBrush(QColor(0, 0, 0, 255 * ((10 - activeAnimationCounter) / 15.0))); + painter->setPen(Qt::gray); + painter->drawRect(0, 0, width - 1, width - 1); } void PhaseButton::setWidth(double _width) { - prepareGeometryChange(); - width = _width; + prepareGeometryChange(); + width = _width; } void PhaseButton::setActive(bool _active) { - if ((active == _active) || !highlightable) - return; - - active = _active; - activeAnimationTimer->start(50); + if ((active == _active) || !highlightable) + return; + + active = _active; + activeAnimationTimer->start(50); } void PhaseButton::updateAnimation() { - if (!highlightable) - return; - - if (active) { - if (++activeAnimationCounter >= 10) - activeAnimationTimer->stop(); - } else { - if (--activeAnimationCounter <= 0) - activeAnimationTimer->stop(); - } - update(); + if (!highlightable) + return; + + if (active) { + if (++activeAnimationCounter >= 10) + activeAnimationTimer->stop(); + } else { + if (--activeAnimationCounter <= 0) + activeAnimationTimer->stop(); + } + update(); } void PhaseButton::mousePressEvent(QGraphicsSceneMouseEvent * /*event*/) { - emit clicked(); + emit clicked(); } void PhaseButton::mouseDoubleClickEvent(QGraphicsSceneMouseEvent */*event*/) { - triggerDoubleClickAction(); + triggerDoubleClickAction(); } void PhaseButton::triggerDoubleClickAction() { - if (doubleClickAction) - doubleClickAction->trigger(); + if (doubleClickAction) + doubleClickAction->trigger(); } PhasesToolbar::PhasesToolbar(QGraphicsItem *parent) - : QGraphicsItem(parent), width(100), height(100) + : QGraphicsItem(parent), width(100), height(100) { - QAction *aUntapAll = new QAction(this); - connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); - QAction *aDrawCard = new QAction(this); - connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); - - PhaseButton *untapButton = new PhaseButton("untap", this, aUntapAll); - PhaseButton *upkeepButton = new PhaseButton("upkeep", this); - PhaseButton *drawButton = new PhaseButton("draw", this, aDrawCard); - PhaseButton *main1Button = new PhaseButton("main1", this); - PhaseButton *combatStartButton = new PhaseButton("combat_start", this); - PhaseButton *combatAttackersButton = new PhaseButton("combat_attackers", this); - PhaseButton *combatBlockersButton = new PhaseButton("combat_blockers", this); - PhaseButton *combatDamageButton = new PhaseButton("combat_damage", this); - PhaseButton *combatEndButton = new PhaseButton("combat_end", this); - PhaseButton *main2Button = new PhaseButton("main2", this); - PhaseButton *cleanupButton = new PhaseButton("cleanup", this); - - buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton - << combatAttackersButton << combatBlockersButton << combatDamageButton << combatEndButton - << main2Button << cleanupButton; - - for (int i = 0; i < buttonList.size(); ++i) - connect(buttonList[i], SIGNAL(clicked()), this, SLOT(phaseButtonClicked())); - - nextTurnButton = new PhaseButton("nextturn", this, 0, false); - connect(nextTurnButton, SIGNAL(clicked()), this, SLOT(actNextTurn())); - - rearrangeButtons(); - - retranslateUi(); + QAction *aUntapAll = new QAction(this); + connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); + QAction *aDrawCard = new QAction(this); + connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); + + PhaseButton *untapButton = new PhaseButton("untap", this, aUntapAll); + PhaseButton *upkeepButton = new PhaseButton("upkeep", this); + PhaseButton *drawButton = new PhaseButton("draw", this, aDrawCard); + PhaseButton *main1Button = new PhaseButton("main1", this); + PhaseButton *combatStartButton = new PhaseButton("combat_start", this); + PhaseButton *combatAttackersButton = new PhaseButton("combat_attackers", this); + PhaseButton *combatBlockersButton = new PhaseButton("combat_blockers", this); + PhaseButton *combatDamageButton = new PhaseButton("combat_damage", this); + PhaseButton *combatEndButton = new PhaseButton("combat_end", this); + PhaseButton *main2Button = new PhaseButton("main2", this); + PhaseButton *cleanupButton = new PhaseButton("cleanup", this); + + buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton + << combatAttackersButton << combatBlockersButton << combatDamageButton << combatEndButton + << main2Button << cleanupButton; + + for (int i = 0; i < buttonList.size(); ++i) + connect(buttonList[i], SIGNAL(clicked()), this, SLOT(phaseButtonClicked())); + + nextTurnButton = new PhaseButton("nextturn", this, 0, false); + connect(nextTurnButton, SIGNAL(clicked()), this, SLOT(actNextTurn())); + + rearrangeButtons(); + + retranslateUi(); } QRectF PhasesToolbar::boundingRect() const { - return QRectF(0, 0, width, height); + return QRectF(0, 0, width, height); } void PhasesToolbar::retranslateUi() { - for (int i = 0; i < buttonList.size(); ++i) - buttonList[i]->setToolTip(getLongPhaseName(i)); + for (int i = 0; i < buttonList.size(); ++i) + buttonList[i]->setToolTip(getLongPhaseName(i)); } QString PhasesToolbar::getLongPhaseName(int phase) const { - switch (phase) { - case 0: return tr("Untap step"); - case 1: return tr("Upkeep step"); - case 2: return tr("Draw step"); - case 3: return tr("First main phase"); - case 4: return tr("Beginning of combat step"); - case 5: return tr("Declare attackers step"); - case 6: return tr("Declare blockers step"); - case 7: return tr("Combat damage step"); - case 8: return tr("End of combat step"); - case 9: return tr("Second main phase"); - case 10: return tr("End of turn step"); - default: return QString(); - } + switch (phase) { + case 0: return tr("Untap step"); + case 1: return tr("Upkeep step"); + case 2: return tr("Draw step"); + case 3: return tr("First main phase"); + case 4: return tr("Beginning of combat step"); + case 5: return tr("Declare attackers step"); + case 6: return tr("Declare blockers step"); + case 7: return tr("Combat damage step"); + case 8: return tr("End of combat step"); + case 9: return tr("Second main phase"); + case 10: return tr("End of turn step"); + default: return QString(); + } } void PhasesToolbar::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - painter->fillRect(boundingRect(), QColor(50, 50, 50)); + painter->fillRect(boundingRect(), QColor(50, 50, 50)); } const double PhasesToolbar::marginSize = 3; void PhasesToolbar::rearrangeButtons() { - for (int i = 0; i < buttonList.size(); ++i) - buttonList[i]->setWidth(symbolSize); - nextTurnButton->setWidth(symbolSize); - - double y = marginSize; - buttonList[0]->setPos(marginSize, y); - buttonList[1]->setPos(marginSize, y += symbolSize); - buttonList[2]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[3]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[4]->setPos(marginSize, y += symbolSize); - buttonList[5]->setPos(marginSize, y += symbolSize); - buttonList[6]->setPos(marginSize, y += symbolSize); - buttonList[7]->setPos(marginSize, y += symbolSize); - buttonList[8]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[9]->setPos(marginSize, y += symbolSize); - y += ySpacing; - buttonList[10]->setPos(marginSize, y += symbolSize); - y += ySpacing; - y += ySpacing; - nextTurnButton->setPos(marginSize, y += symbolSize); + for (int i = 0; i < buttonList.size(); ++i) + buttonList[i]->setWidth(symbolSize); + nextTurnButton->setWidth(symbolSize); + + double y = marginSize; + buttonList[0]->setPos(marginSize, y); + buttonList[1]->setPos(marginSize, y += symbolSize); + buttonList[2]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[3]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[4]->setPos(marginSize, y += symbolSize); + buttonList[5]->setPos(marginSize, y += symbolSize); + buttonList[6]->setPos(marginSize, y += symbolSize); + buttonList[7]->setPos(marginSize, y += symbolSize); + buttonList[8]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[9]->setPos(marginSize, y += symbolSize); + y += ySpacing; + buttonList[10]->setPos(marginSize, y += symbolSize); + y += ySpacing; + y += ySpacing; + nextTurnButton->setPos(marginSize, y += symbolSize); } void PhasesToolbar::setHeight(double _height) { - prepareGeometryChange(); - - height = _height; - ySpacing = (height - 2 * marginSize) / (buttonCount * 5 + spaceCount); - symbolSize = ySpacing * 5; - width = symbolSize + 2 * marginSize; - - rearrangeButtons(); + prepareGeometryChange(); + + height = _height; + ySpacing = (height - 2 * marginSize) / (buttonCount * 5 + spaceCount); + symbolSize = ySpacing * 5; + width = symbolSize + 2 * marginSize; + + rearrangeButtons(); } void PhasesToolbar::setActivePhase(int phase) { - if (phase >= buttonList.size()) - return; - - for (int i = 0; i < buttonList.size(); ++i) - buttonList[i]->setActive(i == phase); + if (phase >= buttonList.size()) + return; + + for (int i = 0; i < buttonList.size(); ++i) + buttonList[i]->setActive(i == phase); } void PhasesToolbar::phaseButtonClicked() { - PhaseButton *button = qobject_cast(sender()); - if (button->getActive()) - button->triggerDoubleClickAction(); - - Command_SetActivePhase cmd; - cmd.set_phase(buttonList.indexOf(button)); - - emit sendGameCommand(cmd, -1); + PhaseButton *button = qobject_cast(sender()); + if (button->getActive()) + button->triggerDoubleClickAction(); + + Command_SetActivePhase cmd; + cmd.set_phase(buttonList.indexOf(button)); + + emit sendGameCommand(cmd, -1); } void PhasesToolbar::actNextTurn() { - emit sendGameCommand(Command_NextTurn(), -1); + emit sendGameCommand(Command_NextTurn(), -1); } void PhasesToolbar::actUntapAll() { - Command_SetCardAttr cmd; - cmd.set_zone("table"); - cmd.set_attribute(AttrTapped); - cmd.set_attr_value("0"); - - emit sendGameCommand(cmd, -1); + Command_SetCardAttr cmd; + cmd.set_zone("table"); + cmd.set_attribute(AttrTapped); + cmd.set_attr_value("0"); + + emit sendGameCommand(cmd, -1); } void PhasesToolbar::actDrawCard() { - Command_DrawCards cmd; - cmd.set_number(1); - - emit sendGameCommand(cmd, -1); + Command_DrawCards cmd; + cmd.set_number(1); + + emit sendGameCommand(cmd, -1); } diff --git a/cockatrice/src/phasestoolbar.h b/cockatrice/src/phasestoolbar.h index 3a39a950..852f4f58 100644 --- a/cockatrice/src/phasestoolbar.h +++ b/cockatrice/src/phasestoolbar.h @@ -10,62 +10,62 @@ class Player; class GameCommand; class PhaseButton : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT private: - QString name; - bool active, highlightable; - int activeAnimationCounter; - QTimer *activeAnimationTimer; - QAction *doubleClickAction; - double width; - - void updatePixmap(QPixmap &pixmap); + QString name; + bool active, highlightable; + int activeAnimationCounter; + QTimer *activeAnimationTimer; + QAction *doubleClickAction; + double width; + + void updatePixmap(QPixmap &pixmap); private slots: - void updateAnimation(); + void updateAnimation(); public: - PhaseButton(const QString &_name, QGraphicsItem *parent = 0, QAction *_doubleClickAction = 0, bool _highlightable = true); - QRectF boundingRect() const; - void setWidth(double _width); - void setActive(bool _active); - bool getActive() const { return active; } - void triggerDoubleClickAction(); + PhaseButton(const QString &_name, QGraphicsItem *parent = 0, QAction *_doubleClickAction = 0, bool _highlightable = true); + QRectF boundingRect() const; + void setWidth(double _width); + void setActive(bool _active); + bool getActive() const { return active; } + void triggerDoubleClickAction(); signals: - void clicked(); + void clicked(); protected: - void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); }; class PhasesToolbar : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT private: - QList buttonList; - PhaseButton *nextTurnButton; - double width, height, ySpacing, symbolSize; - static const int buttonCount = 12; - static const int spaceCount = 6; - static const double marginSize; - void rearrangeButtons(); + QList buttonList; + PhaseButton *nextTurnButton; + double width, height, ySpacing, symbolSize; + static const int buttonCount = 12; + static const int spaceCount = 6; + static const double marginSize; + void rearrangeButtons(); public: - PhasesToolbar(QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void retranslateUi(); - void setHeight(double _height); - double getWidth() const { return width; } - int phaseCount() const { return buttonList.size(); } - QString getLongPhaseName(int phase) const; + PhasesToolbar(QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void retranslateUi(); + void setHeight(double _height); + double getWidth() const { return width; } + int phaseCount() const { return buttonList.size(); } + QString getLongPhaseName(int phase) const; public slots: - void setActivePhase(int phase); + void setActivePhase(int phase); private slots: - void phaseButtonClicked(); - void actNextTurn(); - void actUntapAll(); - void actDrawCard(); + void phaseButtonClicked(); + void actNextTurn(); + void actUntapAll(); + void actDrawCard(); signals: - void sendGameCommand(const ::google::protobuf::Message &command, int playerId); + void sendGameCommand(const ::google::protobuf::Message &command, int playerId); protected: - void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); + void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); }; #endif diff --git a/cockatrice/src/pilezone.cpp b/cockatrice/src/pilezone.cpp index 97d32902..d34d4c06 100644 --- a/cockatrice/src/pilezone.cpp +++ b/cockatrice/src/pilezone.cpp @@ -10,109 +10,109 @@ #include "pb/command_move_card.pb.h" PileZone::PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent) - : CardZone(_p, _name, false, _isShufflable, _contentsKnown, parent) + : CardZone(_p, _name, false, _isShufflable, _contentsKnown, parent) { - setCacheMode(DeviceCoordinateCache); // Do not move this line to the parent constructor! - setAcceptsHoverEvents(true); - setCursor(Qt::OpenHandCursor); - - setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); + setCacheMode(DeviceCoordinateCache); // Do not move this line to the parent constructor! + setAcceptsHoverEvents(true); + setCursor(Qt::OpenHandCursor); + + setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(90).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2)); } QRectF PileZone::boundingRect() const { - return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); + return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT); } void PileZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - if (!cards.isEmpty()) - cards.at(0)->paintPicture(painter, cards.at(0)->getTranslatedSize(painter), 90); + if (!cards.isEmpty()) + cards.at(0)->paintPicture(painter, cards.at(0)->getTranslatedSize(painter), 90); - painter->drawRect(QRectF(0.5, 0.5, CARD_WIDTH - 1, CARD_HEIGHT - 1)); - - painter->translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2); - painter->rotate(-90); - painter->translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2); - paintNumberEllipse(cards.size(), 28, Qt::white, -1, -1, painter); + painter->drawRect(QRectF(0.5, 0.5, CARD_WIDTH - 1, CARD_HEIGHT - 1)); + + painter->translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2); + painter->rotate(-90); + painter->translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2); + paintNumberEllipse(cards.size(), 28, Qt::white, -1, -1, painter); } void PileZone::addCardImpl(CardItem *card, int x, int /*y*/) { - connect(card, SIGNAL(sigPixmapUpdated()), this, SLOT(callUpdate())); - cards.insert(x, card); - card->setPos(0, 0); - if (!contentsKnown()) { - card->setName(QString()); - card->setId(-1); - // If we obscure a previously revealed card, its name has to be forgotten - if (cards.size() > x + 1) - cards.at(x + 1)->setName(QString()); - } - card->setVisible(false); - card->resetState(); - card->setParentItem(this); + connect(card, SIGNAL(sigPixmapUpdated()), this, SLOT(callUpdate())); + cards.insert(x, card); + card->setPos(0, 0); + if (!contentsKnown()) { + card->setName(QString()); + card->setId(-1); + // If we obscure a previously revealed card, its name has to be forgotten + if (cards.size() > x + 1) + cards.at(x + 1)->setName(QString()); + } + card->setVisible(false); + card->resetState(); + card->setParentItem(this); } void PileZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) { - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(0); - cmd.set_y(0); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(0); + cmd.set_y(0); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - player->sendGameCommand(cmd); + player->sendGameCommand(cmd); } void PileZone::reorganizeCards() { - update(); + update(); } void PileZone::mousePressEvent(QGraphicsSceneMouseEvent *event) { - CardZone::mousePressEvent(event); - if (event->isAccepted()) - return; + CardZone::mousePressEvent(event); + if (event->isAccepted()) + return; - if (event->button() == Qt::LeftButton) { - setCursor(Qt::ClosedHandCursor); - event->accept(); - } else - event->ignore(); + if (event->button() == Qt::LeftButton) { + setCursor(Qt::ClosedHandCursor); + event->accept(); + } else + event->ignore(); } void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < QApplication::startDragDistance()) - return; + if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < QApplication::startDragDistance()) + return; - if (cards.isEmpty()) - return; + if (cards.isEmpty()) + return; - bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier); - bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); - CardItem *card = bottomCard ? cards.last() : cards.first(); - const int cardid = contentsKnown() ? card->getId() : (bottomCard ? cards.size() - 1 : 0); - CardDragItem *drag = card->createDragItem(cardid, event->pos(), event->scenePos(), faceDown); - drag->grabMouse(); - setCursor(Qt::OpenHandCursor); + bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier); + bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); + CardItem *card = bottomCard ? cards.last() : cards.first(); + const int cardid = contentsKnown() ? card->getId() : (bottomCard ? cards.size() - 1 : 0); + CardDragItem *drag = card->createDragItem(cardid, event->pos(), event->scenePos(), faceDown); + drag->grabMouse(); + setCursor(Qt::OpenHandCursor); } void PileZone::mouseReleaseEvent(QGraphicsSceneMouseEvent */*event*/) { - setCursor(Qt::OpenHandCursor); + setCursor(Qt::OpenHandCursor); } void PileZone::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - if (!cards.isEmpty()) - cards[0]->processHoverEvent(); - QGraphicsItem::hoverEnterEvent(event); + if (!cards.isEmpty()) + cards[0]->processHoverEvent(); + QGraphicsItem::hoverEnterEvent(event); } diff --git a/cockatrice/src/pilezone.h b/cockatrice/src/pilezone.h index 8675c99b..2469eb1e 100644 --- a/cockatrice/src/pilezone.h +++ b/cockatrice/src/pilezone.h @@ -4,21 +4,21 @@ #include "cardzone.h" class PileZone : public CardZone { - Q_OBJECT + Q_OBJECT private slots: - void callUpdate() { update(); } + void callUpdate() { update(); } public: - PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + PileZone(Player *_p, const QString &_name, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - void hoverEnterEvent(QGraphicsSceneHoverEvent *event); - void addCardImpl(CardItem *card, int x, int y); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/pixmapgenerator.cpp b/cockatrice/src/pixmapgenerator.cpp index e5b4a7dc..7ff7ca98 100644 --- a/cockatrice/src/pixmapgenerator.cpp +++ b/cockatrice/src/pixmapgenerator.cpp @@ -9,152 +9,152 @@ QMap PhasePixmapGenerator::pmCache; QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name) { - QString key = name + QString::number(height); - if (pmCache.contains(key)) - return pmCache.value(key); - - QSvgRenderer svg(QString(":/resources/phases/icon_phase_" + name + ".svg")); - - QPixmap pixmap(height, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, height, height)); - pmCache.insert(key, pixmap); - return pixmap; + QString key = name + QString::number(height); + if (pmCache.contains(key)) + return pmCache.value(key); + + QSvgRenderer svg(QString(":/resources/phases/icon_phase_" + name + ".svg")); + + QPixmap pixmap(height, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, height, height)); + pmCache.insert(key, pixmap); + return pixmap; } QMap CounterPixmapGenerator::pmCache; QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool highlight) { - if (highlight) - name.append("_highlight"); - QString key = name + QString::number(height); - if (pmCache.contains(key)) - return pmCache.value(key); - - QSvgRenderer svg(QString(":/resources/counters/" + name + ".svg")); - - if (!svg.isValid()) { - name = "general"; - if (highlight) - name.append("_highlight"); - svg.load(QString(":/resources/counters/" + name + ".svg")); - } - - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - pmCache.insert(key, pixmap); - return pixmap; + if (highlight) + name.append("_highlight"); + QString key = name + QString::number(height); + if (pmCache.contains(key)) + return pmCache.value(key); + + QSvgRenderer svg(QString(":/resources/counters/" + name + ".svg")); + + if (!svg.isValid()) { + name = "general"; + if (highlight) + name.append("_highlight"); + svg.load(QString(":/resources/counters/" + name + ".svg")); + } + + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + pmCache.insert(key, pixmap); + return pixmap; } QPixmap PingPixmapGenerator::generatePixmap(int size, int value, int max) { - int key = size * 1000000 + max * 1000 + value; - if (pmCache.contains(key)) - return pmCache.value(key); - - QPixmap pixmap(size, size); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - QColor color; - if ((max == -1) || (value == -1)) - color = Qt::black; - else - color.setHsv(120 * (1.0 - ((double) value / max)), 255, 255); - - QRadialGradient g(QPointF((double) pixmap.width() / 2, (double) pixmap.height() / 2), qMin(pixmap.width(), pixmap.height()) / 2.0); - g.setColorAt(0, color); - g.setColorAt(1, Qt::transparent); - painter.fillRect(0, 0, pixmap.width(), pixmap.height(), QBrush(g)); - - pmCache.insert(key, pixmap); + int key = size * 1000000 + max * 1000 + value; + if (pmCache.contains(key)) + return pmCache.value(key); + + QPixmap pixmap(size, size); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + QColor color; + if ((max == -1) || (value == -1)) + color = Qt::black; + else + color.setHsv(120 * (1.0 - ((double) value / max)), 255, 255); + + QRadialGradient g(QPointF((double) pixmap.width() / 2, (double) pixmap.height() / 2), qMin(pixmap.width(), pixmap.height()) / 2.0); + g.setColorAt(0, color); + g.setColorAt(1, Qt::transparent); + painter.fillRect(0, 0, pixmap.width(), pixmap.height(), QBrush(g)); + + pmCache.insert(key, pixmap); - return pixmap; + return pixmap; } QMap PingPixmapGenerator::pmCache; QPixmap GenderPixmapGenerator::generatePixmap(int height, int _gender) { - ServerInfo_User::Gender gender = static_cast(_gender); - if ((gender != ServerInfo_User::Male) && (gender != ServerInfo_User::Female)) - gender = ServerInfo_User::GenderUnknown; - - int key = gender * 100000 + height; - if (pmCache.contains(key)) - return pmCache.value(key); - - QString genderStr; - switch (gender) { - case ServerInfo_User::Male: genderStr = "male"; break; - case ServerInfo_User::Female: genderStr = "female"; break; - default: genderStr = "unknown"; - }; - - QSvgRenderer svg(QString(":/resources/genders/" + genderStr + ".svg")); - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - - pmCache.insert(key, pixmap); - return pixmap; + ServerInfo_User::Gender gender = static_cast(_gender); + if ((gender != ServerInfo_User::Male) && (gender != ServerInfo_User::Female)) + gender = ServerInfo_User::GenderUnknown; + + int key = gender * 100000 + height; + if (pmCache.contains(key)) + return pmCache.value(key); + + QString genderStr; + switch (gender) { + case ServerInfo_User::Male: genderStr = "male"; break; + case ServerInfo_User::Female: genderStr = "female"; break; + default: genderStr = "unknown"; + }; + + QSvgRenderer svg(QString(":/resources/genders/" + genderStr + ".svg")); + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + + pmCache.insert(key, pixmap); + return pixmap; } QMap GenderPixmapGenerator::pmCache; QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countryCode) { - if (countryCode.size() != 2) - return QPixmap(); - QString key = countryCode + QString::number(height); - if (pmCache.contains(key)) - return pmCache.value(key); - - QSvgRenderer svg(QString(":/resources/countries/" + countryCode + ".svg")); - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - painter.setPen(Qt::black); - painter.drawRect(0, 0, width - 1, height - 1); - - pmCache.insert(key, pixmap); - return pixmap; + if (countryCode.size() != 2) + return QPixmap(); + QString key = countryCode + QString::number(height); + if (pmCache.contains(key)) + return pmCache.value(key); + + QSvgRenderer svg(QString(":/resources/countries/" + countryCode + ".svg")); + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + painter.setPen(Qt::black); + painter.drawRect(0, 0, width - 1, height - 1); + + pmCache.insert(key, pixmap); + return pixmap; } QMap CountryPixmapGenerator::pmCache; QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel) { - int key = height * 10000 + (int) userLevel; - if (pmCache.contains(key)) - return pmCache.value(key); - - QString levelString; - if (userLevel.testFlag(ServerInfo_User::IsAdmin)) - levelString = "admin"; - else if (userLevel.testFlag(ServerInfo_User::IsModerator)) - levelString = "moderator"; - else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) - levelString = "registered"; - else - levelString = "normal"; - QSvgRenderer svg(QString(":/resources/userlevels/" + levelString + ".svg")); - int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); - QPixmap pixmap(width, height); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - svg.render(&painter, QRectF(0, 0, width, height)); - - pmCache.insert(key, pixmap); - return pixmap; + int key = height * 10000 + (int) userLevel; + if (pmCache.contains(key)) + return pmCache.value(key); + + QString levelString; + if (userLevel.testFlag(ServerInfo_User::IsAdmin)) + levelString = "admin"; + else if (userLevel.testFlag(ServerInfo_User::IsModerator)) + levelString = "moderator"; + else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) + levelString = "registered"; + else + levelString = "normal"; + QSvgRenderer svg(QString(":/resources/userlevels/" + levelString + ".svg")); + int width = (int) round(height * (double) svg.defaultSize().width() / (double) svg.defaultSize().height()); + QPixmap pixmap(width, height); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + svg.render(&painter, QRectF(0, 0, width, height)); + + pmCache.insert(key, pixmap); + return pixmap; } QMap UserLevelPixmapGenerator::pmCache; diff --git a/cockatrice/src/pixmapgenerator.h b/cockatrice/src/pixmapgenerator.h index b371bd91..67a8b2b2 100644 --- a/cockatrice/src/pixmapgenerator.h +++ b/cockatrice/src/pixmapgenerator.h @@ -8,50 +8,50 @@ class PhasePixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int size, QString name); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int size, QString name); + static void clear() { pmCache.clear(); } }; class CounterPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int size, QString name, bool highlight); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int size, QString name, bool highlight); + static void clear() { pmCache.clear(); } }; class PingPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int size, int value, int max); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int size, int value, int max); + static void clear() { pmCache.clear(); } }; class GenderPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int height, int gender); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int height, int gender); + static void clear() { pmCache.clear(); } }; class CountryPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int height, const QString &countryCode); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int height, const QString &countryCode); + static void clear() { pmCache.clear(); } }; class UserLevelPixmapGenerator { private: - static QMap pmCache; + static QMap pmCache; public: - static QPixmap generatePixmap(int height, UserLevelFlags userLevel); - static void clear() { pmCache.clear(); } + static QPixmap generatePixmap(int height, UserLevelFlags userLevel); + static void clear() { pmCache.clear(); } }; #endif diff --git a/cockatrice/src/player.cpp b/cockatrice/src/player.cpp index 7a31a08c..35d5bea9 100644 --- a/cockatrice/src/player.cpp +++ b/cockatrice/src/player.cpp @@ -66,1368 +66,1368 @@ #include "pb/event_change_zone_properties.pb.h" PlayerArea::PlayerArea(QGraphicsItem *parentItem) - : QObject(), QGraphicsItem(parentItem) + : QObject(), QGraphicsItem(parentItem) { - setCacheMode(DeviceCoordinateCache); - connect(settingsCache, SIGNAL(playerBgPathChanged()), this, SLOT(updateBgPixmap())); - updateBgPixmap(); + setCacheMode(DeviceCoordinateCache); + connect(settingsCache, SIGNAL(playerBgPathChanged()), this, SLOT(updateBgPixmap())); + updateBgPixmap(); } void PlayerArea::updateBgPixmap() { - QString bgPath = settingsCache->getPlayerBgPath(); - if (bgPath.isEmpty()) - bgPixmapBrush = QBrush(QColor(200, 200, 200)); - else { - qDebug() << "loading" << bgPath; - bgPixmapBrush = QBrush(QPixmap(bgPath)); - } - update(); + QString bgPath = settingsCache->getPlayerBgPath(); + if (bgPath.isEmpty()) + bgPixmapBrush = QBrush(QColor(200, 200, 200)); + else { + qDebug() << "loading" << bgPath; + bgPixmapBrush = QBrush(QPixmap(bgPath)); + } + update(); } void PlayerArea::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - painter->fillRect(bRect, bgPixmapBrush); + painter->fillRect(bRect, bgPixmapBrush); } void PlayerArea::setSize(qreal width, qreal height) { - prepareGeometryChange(); - bRect = QRectF(0, 0, width, height); + prepareGeometryChange(); + bRect = QRectF(0, 0, width, height); } Player::Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent) - : QObject(_parent), - game(_parent), - shortcutsActive(false), - defaultNumberTopCards(3), - lastTokenDestroy(true), - id(_id), - active(false), - local(_local), - mirrored(false), - handVisible(false), - conceded(false), - dialogSemaphore(false), - deck(0) + : QObject(_parent), + game(_parent), + shortcutsActive(false), + defaultNumberTopCards(3), + lastTokenDestroy(true), + id(_id), + active(false), + local(_local), + mirrored(false), + handVisible(false), + conceded(false), + dialogSemaphore(false), + deck(0) { - userInfo = new ServerInfo_User; - userInfo->CopyFrom(info); - - connect(settingsCache, SIGNAL(horizontalHandChanged()), this, SLOT(rearrangeZones())); - - playerArea = new PlayerArea(this); - - playerTarget = new PlayerTarget(this, playerArea); - qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0; - playerTarget->setPos(QPointF(avatarMargin, avatarMargin)); + userInfo = new ServerInfo_User; + userInfo->CopyFrom(info); + + connect(settingsCache, SIGNAL(horizontalHandChanged()), this, SLOT(rearrangeZones())); + + playerArea = new PlayerArea(this); + + playerTarget = new PlayerTarget(this, playerArea); + qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0; + playerTarget->setPos(QPointF(avatarMargin, avatarMargin)); - PileZone *deck = new PileZone(this, "deck", true, false, playerArea); - QPointF base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0, 10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0); - deck->setPos(base); + PileZone *deck = new PileZone(this, "deck", true, false, playerArea); + QPointF base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0, 10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0); + deck->setPos(base); - qreal h = deck->boundingRect().width() + 5; + qreal h = deck->boundingRect().width() + 5; - HandCounter *handCounter = new HandCounter(playerArea); - handCounter->setPos(base + QPointF(0, h + 10)); - qreal h2 = handCounter->boundingRect().height(); - - PileZone *grave = new PileZone(this, "grave", false, true, playerArea); - grave->setPos(base + QPointF(0, h + h2 + 10)); + HandCounter *handCounter = new HandCounter(playerArea); + handCounter->setPos(base + QPointF(0, h + 10)); + qreal h2 = handCounter->boundingRect().height(); + + PileZone *grave = new PileZone(this, "grave", false, true, playerArea); + grave->setPos(base + QPointF(0, h + h2 + 10)); - PileZone *rfg = new PileZone(this, "rfg", false, true, playerArea); - rfg->setPos(base + QPointF(0, 2 * h + h2 + 10)); + PileZone *rfg = new PileZone(this, "rfg", false, true, playerArea); + rfg->setPos(base + QPointF(0, 2 * h + h2 + 10)); - PileZone *sb = new PileZone(this, "sb", false, false, playerArea); - sb->setVisible(false); + PileZone *sb = new PileZone(this, "sb", false, false, playerArea); + sb->setVisible(false); - table = new TableZone(this, this); - connect(table, SIGNAL(sizeChanged()), this, SLOT(updateBoundingRect())); - - stack = new StackZone(this, (int) table->boundingRect().height(), this); - - hand = new HandZone(this, _local || (_parent->getSpectator() && _parent->getSpectatorsSeeEverything()), (int) table->boundingRect().height(), this); - connect(hand, SIGNAL(cardCountChanged()), handCounter, SLOT(updateNumber())); - connect(handCounter, SIGNAL(showContextMenu(const QPoint &)), hand, SLOT(showContextMenu(const QPoint &))); - - updateBoundingRect(); + table = new TableZone(this, this); + connect(table, SIGNAL(sizeChanged()), this, SLOT(updateBoundingRect())); + + stack = new StackZone(this, (int) table->boundingRect().height(), this); + + hand = new HandZone(this, _local || (_parent->getSpectator() && _parent->getSpectatorsSeeEverything()), (int) table->boundingRect().height(), this); + connect(hand, SIGNAL(cardCountChanged()), handCounter, SLOT(updateNumber())); + connect(handCounter, SIGNAL(showContextMenu(const QPoint &)), hand, SLOT(showContextMenu(const QPoint &))); + + updateBoundingRect(); - if (local) { - connect(_parent, SIGNAL(playerAdded(Player *)), this, SLOT(addPlayer(Player *))); - connect(_parent, SIGNAL(playerRemoved(Player *)), this, SLOT(removePlayer(Player *))); - - aMoveHandToTopLibrary = new QAction(this); - aMoveHandToTopLibrary->setData(QList() << "deck" << 0); - aMoveHandToBottomLibrary = new QAction(this); - aMoveHandToBottomLibrary->setData(QList() << "deck" << -1); - aMoveHandToGrave = new QAction(this); - aMoveHandToGrave->setData(QList() << "grave" << 0); - aMoveHandToRfg = new QAction(this); - aMoveHandToRfg->setData(QList() << "rfg" << 0); - - connect(aMoveHandToTopLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - connect(aMoveHandToBottomLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - connect(aMoveHandToGrave, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - connect(aMoveHandToRfg, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + if (local) { + connect(_parent, SIGNAL(playerAdded(Player *)), this, SLOT(addPlayer(Player *))); + connect(_parent, SIGNAL(playerRemoved(Player *)), this, SLOT(removePlayer(Player *))); + + aMoveHandToTopLibrary = new QAction(this); + aMoveHandToTopLibrary->setData(QList() << "deck" << 0); + aMoveHandToBottomLibrary = new QAction(this); + aMoveHandToBottomLibrary->setData(QList() << "deck" << -1); + aMoveHandToGrave = new QAction(this); + aMoveHandToGrave->setData(QList() << "grave" << 0); + aMoveHandToRfg = new QAction(this); + aMoveHandToRfg->setData(QList() << "rfg" << 0); + + connect(aMoveHandToTopLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + connect(aMoveHandToBottomLibrary, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + connect(aMoveHandToGrave, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); + connect(aMoveHandToRfg, SIGNAL(triggered()), hand, SLOT(moveAllToZone())); - aMoveGraveToTopLibrary = new QAction(this); - aMoveGraveToTopLibrary->setData(QList() << "deck" << 0); - aMoveGraveToBottomLibrary = new QAction(this); - aMoveGraveToBottomLibrary->setData(QList() << "deck" << -1); - aMoveGraveToHand = new QAction(this); - aMoveGraveToHand->setData(QList() << "hand" << 0); - aMoveGraveToRfg = new QAction(this); - aMoveGraveToRfg->setData(QList() << "rfg" << 0); - - connect(aMoveGraveToTopLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - connect(aMoveGraveToBottomLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - connect(aMoveGraveToHand, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - connect(aMoveGraveToRfg, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + aMoveGraveToTopLibrary = new QAction(this); + aMoveGraveToTopLibrary->setData(QList() << "deck" << 0); + aMoveGraveToBottomLibrary = new QAction(this); + aMoveGraveToBottomLibrary->setData(QList() << "deck" << -1); + aMoveGraveToHand = new QAction(this); + aMoveGraveToHand->setData(QList() << "hand" << 0); + aMoveGraveToRfg = new QAction(this); + aMoveGraveToRfg->setData(QList() << "rfg" << 0); + + connect(aMoveGraveToTopLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + connect(aMoveGraveToBottomLibrary, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + connect(aMoveGraveToHand, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); + connect(aMoveGraveToRfg, SIGNAL(triggered()), grave, SLOT(moveAllToZone())); - aMoveRfgToTopLibrary = new QAction(this); - aMoveRfgToTopLibrary->setData(QList() << "deck" << 0); - aMoveRfgToBottomLibrary = new QAction(this); - aMoveRfgToBottomLibrary->setData(QList() << "deck" << -1); - aMoveRfgToHand = new QAction(this); - aMoveRfgToHand->setData(QList() << "hand" << 0); - aMoveRfgToGrave = new QAction(this); - aMoveRfgToGrave->setData(QList() << "grave" << 0); - - connect(aMoveRfgToTopLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - connect(aMoveRfgToBottomLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - connect(aMoveRfgToHand, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - connect(aMoveRfgToGrave, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + aMoveRfgToTopLibrary = new QAction(this); + aMoveRfgToTopLibrary->setData(QList() << "deck" << 0); + aMoveRfgToBottomLibrary = new QAction(this); + aMoveRfgToBottomLibrary->setData(QList() << "deck" << -1); + aMoveRfgToHand = new QAction(this); + aMoveRfgToHand->setData(QList() << "hand" << 0); + aMoveRfgToGrave = new QAction(this); + aMoveRfgToGrave->setData(QList() << "grave" << 0); + + connect(aMoveRfgToTopLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + connect(aMoveRfgToBottomLibrary, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + connect(aMoveRfgToHand, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); + connect(aMoveRfgToGrave, SIGNAL(triggered()), rfg, SLOT(moveAllToZone())); - aViewLibrary = new QAction(this); - connect(aViewLibrary, SIGNAL(triggered()), this, SLOT(actViewLibrary())); - aViewTopCards = new QAction(this); - connect(aViewTopCards, SIGNAL(triggered()), this, SLOT(actViewTopCards())); - aAlwaysRevealTopCard = new QAction(this); - aAlwaysRevealTopCard->setCheckable(true); - connect(aAlwaysRevealTopCard, SIGNAL(triggered()), this, SLOT(actAlwaysRevealTopCard())); - aOpenDeckInDeckEditor = new QAction(this); - aOpenDeckInDeckEditor->setEnabled(false); - connect(aOpenDeckInDeckEditor, SIGNAL(triggered()), this, SLOT(actOpenDeckInDeckEditor())); - } + aViewLibrary = new QAction(this); + connect(aViewLibrary, SIGNAL(triggered()), this, SLOT(actViewLibrary())); + aViewTopCards = new QAction(this); + connect(aViewTopCards, SIGNAL(triggered()), this, SLOT(actViewTopCards())); + aAlwaysRevealTopCard = new QAction(this); + aAlwaysRevealTopCard->setCheckable(true); + connect(aAlwaysRevealTopCard, SIGNAL(triggered()), this, SLOT(actAlwaysRevealTopCard())); + aOpenDeckInDeckEditor = new QAction(this); + aOpenDeckInDeckEditor->setEnabled(false); + connect(aOpenDeckInDeckEditor, SIGNAL(triggered()), this, SLOT(actOpenDeckInDeckEditor())); + } - aViewGraveyard = new QAction(this); - connect(aViewGraveyard, SIGNAL(triggered()), this, SLOT(actViewGraveyard())); + aViewGraveyard = new QAction(this); + connect(aViewGraveyard, SIGNAL(triggered()), this, SLOT(actViewGraveyard())); - aViewRfg = new QAction(this); - connect(aViewRfg, SIGNAL(triggered()), this, SLOT(actViewRfg())); + aViewRfg = new QAction(this); + connect(aViewRfg, SIGNAL(triggered()), this, SLOT(actViewRfg())); - if (local) { - aViewSideboard = new QAction(this); - connect(aViewSideboard, SIGNAL(triggered()), this, SLOT(actViewSideboard())); - - aDrawCard = new QAction(this); - connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); - aDrawCards = new QAction(this); - connect(aDrawCards, SIGNAL(triggered()), this, SLOT(actDrawCards())); - aUndoDraw = new QAction(this); - connect(aUndoDraw, SIGNAL(triggered()), this, SLOT(actUndoDraw())); - aShuffle = new QAction(this); - connect(aShuffle, SIGNAL(triggered()), this, SLOT(actShuffle())); + if (local) { + aViewSideboard = new QAction(this); + connect(aViewSideboard, SIGNAL(triggered()), this, SLOT(actViewSideboard())); + + aDrawCard = new QAction(this); + connect(aDrawCard, SIGNAL(triggered()), this, SLOT(actDrawCard())); + aDrawCards = new QAction(this); + connect(aDrawCards, SIGNAL(triggered()), this, SLOT(actDrawCards())); + aUndoDraw = new QAction(this); + connect(aUndoDraw, SIGNAL(triggered()), this, SLOT(actUndoDraw())); + aShuffle = new QAction(this); + connect(aShuffle, SIGNAL(triggered()), this, SLOT(actShuffle())); aMulligan = new QAction(this); connect(aMulligan, SIGNAL(triggered()), this, SLOT(actMulligan())); - aMoveTopCardsToGrave = new QAction(this); - connect(aMoveTopCardsToGrave, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToGrave())); - aMoveTopCardsToExile = new QAction(this); - connect(aMoveTopCardsToExile, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToExile())); - aMoveTopCardToBottom = new QAction(this); - connect(aMoveTopCardToBottom, SIGNAL(triggered()), this, SLOT(actMoveTopCardToBottom())); - } + aMoveTopCardsToGrave = new QAction(this); + connect(aMoveTopCardsToGrave, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToGrave())); + aMoveTopCardsToExile = new QAction(this); + connect(aMoveTopCardsToExile, SIGNAL(triggered()), this, SLOT(actMoveTopCardsToExile())); + aMoveTopCardToBottom = new QAction(this); + connect(aMoveTopCardToBottom, SIGNAL(triggered()), this, SLOT(actMoveTopCardToBottom())); + } - playerMenu = new QMenu(QString()); - table->setMenu(playerMenu); + playerMenu = new QMenu(QString()); + table->setMenu(playerMenu); - if (local) { - handMenu = playerMenu->addMenu(QString()); + if (local) { + handMenu = playerMenu->addMenu(QString()); handMenu->addAction(aMulligan); - handMenu->addAction(aMoveHandToTopLibrary); - handMenu->addAction(aMoveHandToBottomLibrary); - handMenu->addAction(aMoveHandToGrave); - handMenu->addAction(aMoveHandToRfg); - handMenu->addSeparator(); - playerLists.append(mRevealHand = handMenu->addMenu(QString())); - playerLists.append(mRevealRandomHandCard = handMenu->addMenu(QString())); - hand->setMenu(handMenu); + handMenu->addAction(aMoveHandToTopLibrary); + handMenu->addAction(aMoveHandToBottomLibrary); + handMenu->addAction(aMoveHandToGrave); + handMenu->addAction(aMoveHandToRfg); + handMenu->addSeparator(); + playerLists.append(mRevealHand = handMenu->addMenu(QString())); + playerLists.append(mRevealRandomHandCard = handMenu->addMenu(QString())); + hand->setMenu(handMenu); - libraryMenu = playerMenu->addMenu(QString()); - libraryMenu->addAction(aDrawCard); - libraryMenu->addAction(aDrawCards); - libraryMenu->addAction(aUndoDraw); - libraryMenu->addSeparator(); - libraryMenu->addAction(aShuffle); - libraryMenu->addSeparator(); - libraryMenu->addAction(aViewLibrary); - libraryMenu->addAction(aViewTopCards); - libraryMenu->addSeparator(); - playerLists.append(mRevealLibrary = libraryMenu->addMenu(QString())); - playerLists.append(mRevealTopCard = libraryMenu->addMenu(QString())); - libraryMenu->addAction(aAlwaysRevealTopCard); - libraryMenu->addAction(aOpenDeckInDeckEditor); - libraryMenu->addSeparator(); - libraryMenu->addAction(aMoveTopCardsToGrave); - libraryMenu->addAction(aMoveTopCardsToExile); - libraryMenu->addAction(aMoveTopCardToBottom); - deck->setMenu(libraryMenu, aDrawCard); - } else { - handMenu = 0; - libraryMenu = 0; - } + libraryMenu = playerMenu->addMenu(QString()); + libraryMenu->addAction(aDrawCard); + libraryMenu->addAction(aDrawCards); + libraryMenu->addAction(aUndoDraw); + libraryMenu->addSeparator(); + libraryMenu->addAction(aShuffle); + libraryMenu->addSeparator(); + libraryMenu->addAction(aViewLibrary); + libraryMenu->addAction(aViewTopCards); + libraryMenu->addSeparator(); + playerLists.append(mRevealLibrary = libraryMenu->addMenu(QString())); + playerLists.append(mRevealTopCard = libraryMenu->addMenu(QString())); + libraryMenu->addAction(aAlwaysRevealTopCard); + libraryMenu->addAction(aOpenDeckInDeckEditor); + libraryMenu->addSeparator(); + libraryMenu->addAction(aMoveTopCardsToGrave); + libraryMenu->addAction(aMoveTopCardsToExile); + libraryMenu->addAction(aMoveTopCardToBottom); + deck->setMenu(libraryMenu, aDrawCard); + } else { + handMenu = 0; + libraryMenu = 0; + } - graveMenu = playerMenu->addMenu(QString()); - graveMenu->addAction(aViewGraveyard); - grave->setMenu(graveMenu, aViewGraveyard); + graveMenu = playerMenu->addMenu(QString()); + graveMenu->addAction(aViewGraveyard); + grave->setMenu(graveMenu, aViewGraveyard); - rfgMenu = playerMenu->addMenu(QString()); - rfgMenu->addAction(aViewRfg); - rfg->setMenu(rfgMenu, aViewRfg); + rfgMenu = playerMenu->addMenu(QString()); + rfgMenu->addAction(aViewRfg); + rfg->setMenu(rfgMenu, aViewRfg); - if (local) { - graveMenu->addSeparator(); - graveMenu->addAction(aMoveGraveToTopLibrary); - graveMenu->addAction(aMoveGraveToBottomLibrary); - graveMenu->addAction(aMoveGraveToHand); - graveMenu->addAction(aMoveGraveToRfg); + if (local) { + graveMenu->addSeparator(); + graveMenu->addAction(aMoveGraveToTopLibrary); + graveMenu->addAction(aMoveGraveToBottomLibrary); + graveMenu->addAction(aMoveGraveToHand); + graveMenu->addAction(aMoveGraveToRfg); - rfgMenu->addSeparator(); - rfgMenu->addAction(aMoveRfgToTopLibrary); - rfgMenu->addAction(aMoveRfgToBottomLibrary); - rfgMenu->addAction(aMoveRfgToHand); - rfgMenu->addAction(aMoveRfgToGrave); + rfgMenu->addSeparator(); + rfgMenu->addAction(aMoveRfgToTopLibrary); + rfgMenu->addAction(aMoveRfgToBottomLibrary); + rfgMenu->addAction(aMoveRfgToHand); + rfgMenu->addAction(aMoveRfgToGrave); - sbMenu = playerMenu->addMenu(QString()); - sbMenu->addAction(aViewSideboard); - sb->setMenu(sbMenu, aViewSideboard); + sbMenu = playerMenu->addMenu(QString()); + sbMenu->addAction(aViewSideboard); + sb->setMenu(sbMenu, aViewSideboard); - aUntapAll = new QAction(this); - connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); + aUntapAll = new QAction(this); + connect(aUntapAll, SIGNAL(triggered()), this, SLOT(actUntapAll())); - aRollDie = new QAction(this); - connect(aRollDie, SIGNAL(triggered()), this, SLOT(actRollDie())); - - aCreateToken = new QAction(this); - connect(aCreateToken, SIGNAL(triggered()), this, SLOT(actCreateToken())); - - aCreateAnotherToken = new QAction(this); - connect(aCreateAnotherToken, SIGNAL(triggered()), this, SLOT(actCreateAnotherToken())); - aCreateAnotherToken->setEnabled(false); - - createPredefinedTokenMenu = new QMenu(QString()); + aRollDie = new QAction(this); + connect(aRollDie, SIGNAL(triggered()), this, SLOT(actRollDie())); + + aCreateToken = new QAction(this); + connect(aCreateToken, SIGNAL(triggered()), this, SLOT(actCreateToken())); + + aCreateAnotherToken = new QAction(this); + connect(aCreateAnotherToken, SIGNAL(triggered()), this, SLOT(actCreateAnotherToken())); + aCreateAnotherToken->setEnabled(false); + + createPredefinedTokenMenu = new QMenu(QString()); - playerMenu->addSeparator(); - countersMenu = playerMenu->addMenu(QString()); - playerMenu->addSeparator(); - playerMenu->addAction(aUntapAll); - playerMenu->addSeparator(); - playerMenu->addAction(aRollDie); - playerMenu->addSeparator(); - playerMenu->addAction(aCreateToken); - playerMenu->addAction(aCreateAnotherToken); - playerMenu->addMenu(createPredefinedTokenMenu); - playerMenu->addSeparator(); - sayMenu = playerMenu->addMenu(QString()); - initSayMenu(); - - aCardMenu = new QAction(this); - playerMenu->addSeparator(); - playerMenu->addAction(aCardMenu); + playerMenu->addSeparator(); + countersMenu = playerMenu->addMenu(QString()); + playerMenu->addSeparator(); + playerMenu->addAction(aUntapAll); + playerMenu->addSeparator(); + playerMenu->addAction(aRollDie); + playerMenu->addSeparator(); + playerMenu->addAction(aCreateToken); + playerMenu->addAction(aCreateAnotherToken); + playerMenu->addMenu(createPredefinedTokenMenu); + playerMenu->addSeparator(); + sayMenu = playerMenu->addMenu(QString()); + initSayMenu(); + + aCardMenu = new QAction(this); + playerMenu->addSeparator(); + playerMenu->addAction(aCardMenu); - for (int i = 0; i < playerLists.size(); ++i) { - QAction *newAction = playerLists[i]->addAction(QString()); - newAction->setData(-1); - connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); - allPlayersActions.append(newAction); - playerLists[i]->addSeparator(); - } - } else { - countersMenu = 0; - sbMenu = 0; - aCreateAnotherToken = 0; - createPredefinedTokenMenu = 0; - aCardMenu = 0; - } - - aTap = new QAction(this); - aTap->setData(cmTap); - connect(aTap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aUntap = new QAction(this); - aUntap->setData(cmUntap); - connect(aUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aDoesntUntap = new QAction(this); - aDoesntUntap->setData(cmDoesntUntap); - connect(aDoesntUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aAttach = new QAction(this); - connect(aAttach, SIGNAL(triggered()), this, SLOT(actAttach())); - aUnattach = new QAction(this); - connect(aUnattach, SIGNAL(triggered()), this, SLOT(actUnattach())); - aDrawArrow = new QAction(this); - connect(aDrawArrow, SIGNAL(triggered()), this, SLOT(actDrawArrow())); - aIncP = new QAction(this); - connect(aIncP, SIGNAL(triggered()), this, SLOT(actIncP())); - aDecP = new QAction(this); - connect(aDecP, SIGNAL(triggered()), this, SLOT(actDecP())); - aIncT = new QAction(this); - connect(aIncT, SIGNAL(triggered()), this, SLOT(actIncT())); - aDecT = new QAction(this); - connect(aDecT, SIGNAL(triggered()), this, SLOT(actDecT())); - aIncPT = new QAction(this); - connect(aIncPT, SIGNAL(triggered()), this, SLOT(actIncPT())); - aDecPT = new QAction(this); - connect(aDecPT, SIGNAL(triggered()), this, SLOT(actDecPT())); - aSetPT = new QAction(this); - connect(aSetPT, SIGNAL(triggered()), this, SLOT(actSetPT())); - aSetAnnotation = new QAction(this); - connect(aSetAnnotation, SIGNAL(triggered()), this, SLOT(actSetAnnotation())); - aFlip = new QAction(this); - aFlip->setData(cmFlip); - connect(aFlip, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aPeek = new QAction(this); - aPeek->setData(cmPeek); - connect(aPeek, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aClone = new QAction(this); - aClone->setData(cmClone); - connect(aClone, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - aMoveToTopLibrary = new QAction(this); - aMoveToTopLibrary->setData(cmMoveToTopLibrary); - aMoveToBottomLibrary = new QAction(this); - aMoveToBottomLibrary->setData(cmMoveToBottomLibrary); - aMoveToGraveyard = new QAction(this); - aMoveToGraveyard->setData(cmMoveToGraveyard); - aMoveToExile = new QAction(this); - aMoveToExile->setData(cmMoveToExile); - connect(aMoveToTopLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - connect(aMoveToBottomLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - connect(aMoveToGraveyard, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - connect(aMoveToExile, SIGNAL(triggered()), this, SLOT(cardMenuAction())); - - aPlay = new QAction(this); - connect(aPlay, SIGNAL(triggered()), this, SLOT(actPlay())); - aHide = new QAction(this); - connect(aHide, SIGNAL(triggered()), this, SLOT(actHide())); - - for (int i = 0; i < 3; ++i) { - QAction *tempAddCounter = new QAction(this); - tempAddCounter->setData(9 + i * 1000); - QAction *tempRemoveCounter = new QAction(this); - tempRemoveCounter->setData(10 + i * 1000); - QAction *tempSetCounter = new QAction(this); - tempSetCounter->setData(11 + i * 1000); - aAddCounter.append(tempAddCounter); - aRemoveCounter.append(tempRemoveCounter); - aSetCounter.append(tempSetCounter); - connect(tempAddCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); - connect(tempRemoveCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); - connect(tempSetCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); - } + for (int i = 0; i < playerLists.size(); ++i) { + QAction *newAction = playerLists[i]->addAction(QString()); + newAction->setData(-1); + connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); + allPlayersActions.append(newAction); + playerLists[i]->addSeparator(); + } + } else { + countersMenu = 0; + sbMenu = 0; + aCreateAnotherToken = 0; + createPredefinedTokenMenu = 0; + aCardMenu = 0; + } + + aTap = new QAction(this); + aTap->setData(cmTap); + connect(aTap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aUntap = new QAction(this); + aUntap->setData(cmUntap); + connect(aUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aDoesntUntap = new QAction(this); + aDoesntUntap->setData(cmDoesntUntap); + connect(aDoesntUntap, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aAttach = new QAction(this); + connect(aAttach, SIGNAL(triggered()), this, SLOT(actAttach())); + aUnattach = new QAction(this); + connect(aUnattach, SIGNAL(triggered()), this, SLOT(actUnattach())); + aDrawArrow = new QAction(this); + connect(aDrawArrow, SIGNAL(triggered()), this, SLOT(actDrawArrow())); + aIncP = new QAction(this); + connect(aIncP, SIGNAL(triggered()), this, SLOT(actIncP())); + aDecP = new QAction(this); + connect(aDecP, SIGNAL(triggered()), this, SLOT(actDecP())); + aIncT = new QAction(this); + connect(aIncT, SIGNAL(triggered()), this, SLOT(actIncT())); + aDecT = new QAction(this); + connect(aDecT, SIGNAL(triggered()), this, SLOT(actDecT())); + aIncPT = new QAction(this); + connect(aIncPT, SIGNAL(triggered()), this, SLOT(actIncPT())); + aDecPT = new QAction(this); + connect(aDecPT, SIGNAL(triggered()), this, SLOT(actDecPT())); + aSetPT = new QAction(this); + connect(aSetPT, SIGNAL(triggered()), this, SLOT(actSetPT())); + aSetAnnotation = new QAction(this); + connect(aSetAnnotation, SIGNAL(triggered()), this, SLOT(actSetAnnotation())); + aFlip = new QAction(this); + aFlip->setData(cmFlip); + connect(aFlip, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aPeek = new QAction(this); + aPeek->setData(cmPeek); + connect(aPeek, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aClone = new QAction(this); + aClone->setData(cmClone); + connect(aClone, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + aMoveToTopLibrary = new QAction(this); + aMoveToTopLibrary->setData(cmMoveToTopLibrary); + aMoveToBottomLibrary = new QAction(this); + aMoveToBottomLibrary->setData(cmMoveToBottomLibrary); + aMoveToGraveyard = new QAction(this); + aMoveToGraveyard->setData(cmMoveToGraveyard); + aMoveToExile = new QAction(this); + aMoveToExile->setData(cmMoveToExile); + connect(aMoveToTopLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + connect(aMoveToBottomLibrary, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + connect(aMoveToGraveyard, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + connect(aMoveToExile, SIGNAL(triggered()), this, SLOT(cardMenuAction())); + + aPlay = new QAction(this); + connect(aPlay, SIGNAL(triggered()), this, SLOT(actPlay())); + aHide = new QAction(this); + connect(aHide, SIGNAL(triggered()), this, SLOT(actHide())); + + for (int i = 0; i < 3; ++i) { + QAction *tempAddCounter = new QAction(this); + tempAddCounter->setData(9 + i * 1000); + QAction *tempRemoveCounter = new QAction(this); + tempRemoveCounter->setData(10 + i * 1000); + QAction *tempSetCounter = new QAction(this); + tempSetCounter->setData(11 + i * 1000); + aAddCounter.append(tempAddCounter); + aRemoveCounter.append(tempRemoveCounter); + aSetCounter.append(tempSetCounter); + connect(tempAddCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); + connect(tempRemoveCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); + connect(tempSetCounter, SIGNAL(triggered()), this, SLOT(actCardCounterTrigger())); + } - const QList &players = game->getPlayers().values(); - for (int i = 0; i < players.size(); ++i) - addPlayer(players[i]); - - rearrangeZones(); - retranslateUi(); + const QList &players = game->getPlayers().values(); + for (int i = 0; i < players.size(); ++i) + addPlayer(players[i]); + + rearrangeZones(); + retranslateUi(); } Player::~Player() { - qDebug() << "Player destructor:" << getName(); + qDebug() << "Player destructor:" << getName(); - static_cast(scene())->removePlayer(this); - - clear(); - QMapIterator i(zones); - while (i.hasNext()) - delete i.next().value(); - zones.clear(); - - delete playerMenu; - delete userInfo; + static_cast(scene())->removePlayer(this); + + clear(); + QMapIterator i(zones); + while (i.hasNext()) + delete i.next().value(); + zones.clear(); + + delete playerMenu; + delete userInfo; } void Player::clear() { - clearArrows(); - - QMapIterator i(zones); - while (i.hasNext()) - i.next().value()->clearContents(); - - clearCounters(); + clearArrows(); + + QMapIterator i(zones); + while (i.hasNext()) + i.next().value()->clearContents(); + + clearCounters(); } void Player::addPlayer(Player *player) { - if (player == this) - return; - for (int i = 0; i < playerLists.size(); ++i) { - QAction *newAction = playerLists[i]->addAction(player->getName()); - newAction->setData(player->getId()); - connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); - } + if (player == this) + return; + for (int i = 0; i < playerLists.size(); ++i) { + QAction *newAction = playerLists[i]->addAction(player->getName()); + newAction->setData(player->getId()); + connect(newAction, SIGNAL(triggered()), this, SLOT(playerListActionTriggered())); + } } void Player::removePlayer(Player *player) { - for (int i = 0; i < playerLists.size(); ++i) { - QList actionList = playerLists[i]->actions(); - for (int j = 0; j < actionList.size(); ++j) - if (actionList[j]->data().toInt() == player->getId()) { - playerLists[i]->removeAction(actionList[j]); - actionList[j]->deleteLater(); - } - } + for (int i = 0; i < playerLists.size(); ++i) { + QList actionList = playerLists[i]->actions(); + for (int j = 0; j < actionList.size(); ++j) + if (actionList[j]->data().toInt() == player->getId()) { + playerLists[i]->removeAction(actionList[j]); + actionList[j]->deleteLater(); + } + } } void Player::playerListActionTriggered() { - QAction *action = static_cast(sender()); - QMenu *menu = static_cast(action->parentWidget()); - - Command_RevealCards cmd; - const int otherPlayerId = action->data().toInt(); - if (otherPlayerId != -1) - cmd.set_player_id(otherPlayerId); - - if (menu == mRevealLibrary) { - cmd.set_zone_name("deck"); - cmd.set_grant_write_access(true); - } else if (menu == mRevealTopCard) { - cmd.set_zone_name("deck"); - cmd.set_card_id(0); - } else if (menu == mRevealHand) - cmd.set_zone_name("hand"); - else if (menu == mRevealRandomHandCard) { - cmd.set_zone_name("hand"); - cmd.set_card_id(-2); - } else - return; - - sendGameCommand(cmd); + QAction *action = static_cast(sender()); + QMenu *menu = static_cast(action->parentWidget()); + + Command_RevealCards cmd; + const int otherPlayerId = action->data().toInt(); + if (otherPlayerId != -1) + cmd.set_player_id(otherPlayerId); + + if (menu == mRevealLibrary) { + cmd.set_zone_name("deck"); + cmd.set_grant_write_access(true); + } else if (menu == mRevealTopCard) { + cmd.set_zone_name("deck"); + cmd.set_card_id(0); + } else if (menu == mRevealHand) + cmd.set_zone_name("hand"); + else if (menu == mRevealRandomHandCard) { + cmd.set_zone_name("hand"); + cmd.set_card_id(-2); + } else + return; + + sendGameCommand(cmd); } void Player::rearrangeZones() { - QPointF base = QPointF(CARD_HEIGHT + counterAreaWidth + 15, 0); - if (settingsCache->getHorizontalHand()) { - if (mirrored) { - if (hand->contentsKnown()) { - handVisible = true; - hand->setPos(base); - base += QPointF(0, hand->boundingRect().height()); - } else - handVisible = false; - - stack->setPos(base); - base += QPointF(stack->boundingRect().width(), 0); - - table->setPos(base); - } else { - stack->setPos(base); - - table->setPos(base.x() + stack->boundingRect().width(), 0); - base += QPointF(0, table->boundingRect().height()); - - if (hand->contentsKnown()) { - handVisible = true; - hand->setPos(base); - } else - handVisible = false; - } - hand->setWidth(table->getWidth() + stack->boundingRect().width()); - } else { - handVisible = true; - - hand->setPos(base); - base += QPointF(hand->boundingRect().width(), 0); - - stack->setPos(base); - base += QPointF(stack->boundingRect().width(), 0); - - table->setPos(base); - } - hand->setVisible(handVisible); - hand->updateOrientation(); - table->reorganizeCards(); - updateBoundingRect(); - rearrangeCounters(); + QPointF base = QPointF(CARD_HEIGHT + counterAreaWidth + 15, 0); + if (settingsCache->getHorizontalHand()) { + if (mirrored) { + if (hand->contentsKnown()) { + handVisible = true; + hand->setPos(base); + base += QPointF(0, hand->boundingRect().height()); + } else + handVisible = false; + + stack->setPos(base); + base += QPointF(stack->boundingRect().width(), 0); + + table->setPos(base); + } else { + stack->setPos(base); + + table->setPos(base.x() + stack->boundingRect().width(), 0); + base += QPointF(0, table->boundingRect().height()); + + if (hand->contentsKnown()) { + handVisible = true; + hand->setPos(base); + } else + handVisible = false; + } + hand->setWidth(table->getWidth() + stack->boundingRect().width()); + } else { + handVisible = true; + + hand->setPos(base); + base += QPointF(hand->boundingRect().width(), 0); + + stack->setPos(base); + base += QPointF(stack->boundingRect().width(), 0); + + table->setPos(base); + } + hand->setVisible(handVisible); + hand->updateOrientation(); + table->reorganizeCards(); + updateBoundingRect(); + rearrangeCounters(); } void Player::updateZones() { - table->reorganizeCards(); + table->reorganizeCards(); } void Player::updateBoundingRect() { - prepareGeometryChange(); - qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); - if (settingsCache->getHorizontalHand()) { - qreal handHeight = handVisible ? hand->boundingRect().height() : 0; - bRect = QRectF(0, 0, width + table->boundingRect().width(), table->boundingRect().height() + handHeight); - } else - bRect = QRectF(0, 0, width + hand->boundingRect().width() + table->boundingRect().width(), table->boundingRect().height()); - playerArea->setSize(CARD_HEIGHT + counterAreaWidth + 15, bRect.height()); - - emit sizeChanged(); + prepareGeometryChange(); + qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); + if (settingsCache->getHorizontalHand()) { + qreal handHeight = handVisible ? hand->boundingRect().height() : 0; + bRect = QRectF(0, 0, width + table->boundingRect().width(), table->boundingRect().height() + handHeight); + } else + bRect = QRectF(0, 0, width + hand->boundingRect().width() + table->boundingRect().width(), table->boundingRect().height()); + playerArea->setSize(CARD_HEIGHT + counterAreaWidth + 15, bRect.height()); + + emit sizeChanged(); } void Player::retranslateUi() { - aViewGraveyard->setText(tr("&View graveyard")); - aViewRfg->setText(tr("&View exile")); - playerMenu->setTitle(tr("Player \"%1\"").arg(QString::fromStdString(userInfo->name()))); - graveMenu->setTitle(tr("&Graveyard")); - rfgMenu->setTitle(tr("&Exile")); - - if (local) { - aMoveHandToTopLibrary->setText(tr("Move to &top of library")); - aMoveHandToBottomLibrary->setText(tr("Move to &bottom of library")); - aMoveHandToGrave->setText(tr("Move to &graveyard")); - aMoveHandToRfg->setText(tr("Move to &exile")); - aMoveGraveToTopLibrary->setText(tr("Move to &top of library")); - aMoveGraveToBottomLibrary->setText(tr("Move to &bottom of library")); - aMoveGraveToHand->setText(tr("Move to &hand")); - aMoveGraveToRfg->setText(tr("Move to &exile")); - aMoveRfgToTopLibrary->setText(tr("Move to &top of library")); - aMoveRfgToBottomLibrary->setText(tr("Move to &bottom of library")); - aMoveRfgToHand->setText(tr("Move to &hand")); - aMoveRfgToGrave->setText(tr("Move to &graveyard")); - aViewLibrary->setText(tr("&View library")); - aViewTopCards->setText(tr("View &top cards of library...")); - mRevealLibrary->setTitle(tr("Reveal &library to")); - mRevealTopCard->setTitle(tr("Reveal t&op card to")); - aAlwaysRevealTopCard->setText(tr("&Always reveal top card")); - aOpenDeckInDeckEditor->setText(tr("O&pen deck in deck editor")); - aViewSideboard->setText(tr("&View sideboard")); - aDrawCard->setText(tr("&Draw card")); - aDrawCards->setText(tr("D&raw cards...")); - aUndoDraw->setText(tr("&Undo last draw")); - aMulligan->setText(tr("Take &mulligan")); - aShuffle->setText(tr("&Shuffle")); - aMoveTopCardsToGrave->setText(tr("Move top cards to &graveyard...")); - aMoveTopCardsToExile->setText(tr("Move top cards to &exile...")); - aMoveTopCardToBottom->setText(tr("Put top card on &bottom")); - - handMenu->setTitle(tr("&Hand")); - mRevealHand->setTitle(tr("&Reveal to")); - mRevealRandomHandCard->setTitle(tr("Reveal r&andom card to")); - sbMenu->setTitle(tr("&Sideboard")); - libraryMenu->setTitle(tr("&Library")); - countersMenu->setTitle(tr("&Counters")); + aViewGraveyard->setText(tr("&View graveyard")); + aViewRfg->setText(tr("&View exile")); + playerMenu->setTitle(tr("Player \"%1\"").arg(QString::fromStdString(userInfo->name()))); + graveMenu->setTitle(tr("&Graveyard")); + rfgMenu->setTitle(tr("&Exile")); + + if (local) { + aMoveHandToTopLibrary->setText(tr("Move to &top of library")); + aMoveHandToBottomLibrary->setText(tr("Move to &bottom of library")); + aMoveHandToGrave->setText(tr("Move to &graveyard")); + aMoveHandToRfg->setText(tr("Move to &exile")); + aMoveGraveToTopLibrary->setText(tr("Move to &top of library")); + aMoveGraveToBottomLibrary->setText(tr("Move to &bottom of library")); + aMoveGraveToHand->setText(tr("Move to &hand")); + aMoveGraveToRfg->setText(tr("Move to &exile")); + aMoveRfgToTopLibrary->setText(tr("Move to &top of library")); + aMoveRfgToBottomLibrary->setText(tr("Move to &bottom of library")); + aMoveRfgToHand->setText(tr("Move to &hand")); + aMoveRfgToGrave->setText(tr("Move to &graveyard")); + aViewLibrary->setText(tr("&View library")); + aViewTopCards->setText(tr("View &top cards of library...")); + mRevealLibrary->setTitle(tr("Reveal &library to")); + mRevealTopCard->setTitle(tr("Reveal t&op card to")); + aAlwaysRevealTopCard->setText(tr("&Always reveal top card")); + aOpenDeckInDeckEditor->setText(tr("O&pen deck in deck editor")); + aViewSideboard->setText(tr("&View sideboard")); + aDrawCard->setText(tr("&Draw card")); + aDrawCards->setText(tr("D&raw cards...")); + aUndoDraw->setText(tr("&Undo last draw")); + aMulligan->setText(tr("Take &mulligan")); + aShuffle->setText(tr("&Shuffle")); + aMoveTopCardsToGrave->setText(tr("Move top cards to &graveyard...")); + aMoveTopCardsToExile->setText(tr("Move top cards to &exile...")); + aMoveTopCardToBottom->setText(tr("Put top card on &bottom")); + + handMenu->setTitle(tr("&Hand")); + mRevealHand->setTitle(tr("&Reveal to")); + mRevealRandomHandCard->setTitle(tr("Reveal r&andom card to")); + sbMenu->setTitle(tr("&Sideboard")); + libraryMenu->setTitle(tr("&Library")); + countersMenu->setTitle(tr("&Counters")); - aUntapAll->setText(tr("&Untap all permanents")); - aRollDie->setText(tr("R&oll die...")); - aCreateToken->setText(tr("&Create token...")); - aCreateAnotherToken->setText(tr("C&reate another token")); - createPredefinedTokenMenu->setTitle(tr("Cr&eate predefined token")); - sayMenu->setTitle(tr("S&ay")); - - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->retranslateUi(); + aUntapAll->setText(tr("&Untap all permanents")); + aRollDie->setText(tr("R&oll die...")); + aCreateToken->setText(tr("&Create token...")); + aCreateAnotherToken->setText(tr("C&reate another token")); + createPredefinedTokenMenu->setTitle(tr("Cr&eate predefined token")); + sayMenu->setTitle(tr("S&ay")); + + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->retranslateUi(); - aCardMenu->setText(tr("C&ard")); - - for (int i = 0; i < allPlayersActions.size(); ++i) - allPlayersActions[i]->setText(tr("&All players")); - } - - aPlay->setText(tr("&Play")); - aHide->setText(tr("&Hide")); - - aTap->setText(tr("&Tap")); - aUntap->setText(tr("&Untap")); - aDoesntUntap->setText(tr("Toggle &normal untapping")); - aFlip->setText(tr("&Flip")); - aPeek->setText(tr("&Peek at card face")); - aClone->setText(tr("&Clone")); - aClone->setShortcut(tr("Ctrl+J")); - aAttach->setText(tr("Attac&h to card...")); - aAttach->setShortcut(tr("Ctrl+A")); - aUnattach->setText(tr("Unattac&h")); - aDrawArrow->setText(tr("&Draw arrow...")); - aIncP->setText(tr("&Increase power")); - aIncP->setShortcut(tr("Ctrl++")); - aDecP->setText(tr("&Decrease power")); - aDecP->setShortcut(tr("Ctrl+-")); - aIncT->setText(tr("I&ncrease toughness")); - aIncT->setShortcut(tr("Alt++")); - aDecT->setText(tr("D&ecrease toughness")); - aDecT->setShortcut(tr("Alt+-")); - aIncPT->setText(tr("In&crease power and toughness")); - aIncPT->setShortcut(tr("Ctrl+Alt++")); - aDecPT->setText(tr("Dec&rease power and toughness")); - aDecPT->setShortcut(tr("Ctrl+Alt+-")); - aSetPT->setText(tr("Set &power and toughness...")); - aSetPT->setShortcut(tr("Ctrl+P")); - aSetAnnotation->setText(tr("&Set annotation...")); - QStringList counterColors; - counterColors.append(tr("red")); - counterColors.append(tr("yellow")); - counterColors.append(tr("green")); - for (int i = 0; i < aAddCounter.size(); ++i) - aAddCounter[i]->setText(tr("&Add counter (%1)").arg(counterColors[i])); - for (int i = 0; i < aRemoveCounter.size(); ++i) - aRemoveCounter[i]->setText(tr("&Remove counter (%1)").arg(counterColors[i])); - for (int i = 0; i < aSetCounter.size(); ++i) - aSetCounter[i]->setText(tr("&Set counters (%1)...").arg(counterColors[i])); - aMoveToTopLibrary->setText(tr("&top of library")); - aMoveToBottomLibrary->setText(tr("&bottom of library")); - aMoveToGraveyard->setText(tr("&graveyard")); - aMoveToGraveyard->setShortcut(tr("Ctrl+Del")); - aMoveToExile->setText(tr("&exile")); - - QMapIterator zoneIterator(zones); - while (zoneIterator.hasNext()) - zoneIterator.next().value()->retranslateUi(); + aCardMenu->setText(tr("C&ard")); + + for (int i = 0; i < allPlayersActions.size(); ++i) + allPlayersActions[i]->setText(tr("&All players")); + } + + aPlay->setText(tr("&Play")); + aHide->setText(tr("&Hide")); + + aTap->setText(tr("&Tap")); + aUntap->setText(tr("&Untap")); + aDoesntUntap->setText(tr("Toggle &normal untapping")); + aFlip->setText(tr("&Flip")); + aPeek->setText(tr("&Peek at card face")); + aClone->setText(tr("&Clone")); + aClone->setShortcut(tr("Ctrl+J")); + aAttach->setText(tr("Attac&h to card...")); + aAttach->setShortcut(tr("Ctrl+A")); + aUnattach->setText(tr("Unattac&h")); + aDrawArrow->setText(tr("&Draw arrow...")); + aIncP->setText(tr("&Increase power")); + aIncP->setShortcut(tr("Ctrl++")); + aDecP->setText(tr("&Decrease power")); + aDecP->setShortcut(tr("Ctrl+-")); + aIncT->setText(tr("I&ncrease toughness")); + aIncT->setShortcut(tr("Alt++")); + aDecT->setText(tr("D&ecrease toughness")); + aDecT->setShortcut(tr("Alt+-")); + aIncPT->setText(tr("In&crease power and toughness")); + aIncPT->setShortcut(tr("Ctrl+Alt++")); + aDecPT->setText(tr("Dec&rease power and toughness")); + aDecPT->setShortcut(tr("Ctrl+Alt+-")); + aSetPT->setText(tr("Set &power and toughness...")); + aSetPT->setShortcut(tr("Ctrl+P")); + aSetAnnotation->setText(tr("&Set annotation...")); + QStringList counterColors; + counterColors.append(tr("red")); + counterColors.append(tr("yellow")); + counterColors.append(tr("green")); + for (int i = 0; i < aAddCounter.size(); ++i) + aAddCounter[i]->setText(tr("&Add counter (%1)").arg(counterColors[i])); + for (int i = 0; i < aRemoveCounter.size(); ++i) + aRemoveCounter[i]->setText(tr("&Remove counter (%1)").arg(counterColors[i])); + for (int i = 0; i < aSetCounter.size(); ++i) + aSetCounter[i]->setText(tr("&Set counters (%1)...").arg(counterColors[i])); + aMoveToTopLibrary->setText(tr("&top of library")); + aMoveToBottomLibrary->setText(tr("&bottom of library")); + aMoveToGraveyard->setText(tr("&graveyard")); + aMoveToGraveyard->setShortcut(tr("Ctrl+Del")); + aMoveToExile->setText(tr("&exile")); + + QMapIterator zoneIterator(zones); + while (zoneIterator.hasNext()) + zoneIterator.next().value()->retranslateUi(); } void Player::setShortcutsActive() { - shortcutsActive = true; - - aViewSideboard->setShortcut(tr("Ctrl+F3")); - aViewLibrary->setShortcut(tr("F3")); - aViewTopCards->setShortcut(tr("Ctrl+W")); - aViewGraveyard->setShortcut(tr("F4")); - aDrawCard->setShortcut(tr("Ctrl+D")); - aDrawCards->setShortcut(tr("Ctrl+E")); - aUndoDraw->setShortcut(tr("Ctrl+Shift+D")); - aMulligan->setShortcut(tr("Ctrl+M")); - aShuffle->setShortcut(tr("Ctrl+S")); - aUntapAll->setShortcut(tr("Ctrl+U")); - aRollDie->setShortcut(tr("Ctrl+I")); - aCreateToken->setShortcut(tr("Ctrl+T")); - aCreateAnotherToken->setShortcut(tr("Ctrl+G")); + shortcutsActive = true; + + aViewSideboard->setShortcut(tr("Ctrl+F3")); + aViewLibrary->setShortcut(tr("F3")); + aViewTopCards->setShortcut(tr("Ctrl+W")); + aViewGraveyard->setShortcut(tr("F4")); + aDrawCard->setShortcut(tr("Ctrl+D")); + aDrawCards->setShortcut(tr("Ctrl+E")); + aUndoDraw->setShortcut(tr("Ctrl+Shift+D")); + aMulligan->setShortcut(tr("Ctrl+M")); + aShuffle->setShortcut(tr("Ctrl+S")); + aUntapAll->setShortcut(tr("Ctrl+U")); + aRollDie->setShortcut(tr("Ctrl+I")); + aCreateToken->setShortcut(tr("Ctrl+T")); + aCreateAnotherToken->setShortcut(tr("Ctrl+G")); - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->setShortcutsActive(); + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->setShortcutsActive(); } void Player::setShortcutsInactive() { - shortcutsActive = false; - - aViewSideboard->setShortcut(QKeySequence()); - aViewLibrary->setShortcut(QKeySequence()); - aViewTopCards->setShortcut(QKeySequence()); - aViewGraveyard->setShortcut(QKeySequence()); - aDrawCard->setShortcut(QKeySequence()); - aDrawCards->setShortcut(QKeySequence()); - aUndoDraw->setShortcut(QKeySequence()); - aMulligan->setShortcut(QKeySequence()); - aShuffle->setShortcut(QKeySequence()); - aUntapAll->setShortcut(QKeySequence()); - aRollDie->setShortcut(QKeySequence()); - aCreateToken->setShortcut(QKeySequence()); - aCreateAnotherToken->setShortcut(QKeySequence()); + shortcutsActive = false; + + aViewSideboard->setShortcut(QKeySequence()); + aViewLibrary->setShortcut(QKeySequence()); + aViewTopCards->setShortcut(QKeySequence()); + aViewGraveyard->setShortcut(QKeySequence()); + aDrawCard->setShortcut(QKeySequence()); + aDrawCards->setShortcut(QKeySequence()); + aUndoDraw->setShortcut(QKeySequence()); + aMulligan->setShortcut(QKeySequence()); + aShuffle->setShortcut(QKeySequence()); + aUntapAll->setShortcut(QKeySequence()); + aRollDie->setShortcut(QKeySequence()); + aCreateToken->setShortcut(QKeySequence()); + aCreateAnotherToken->setShortcut(QKeySequence()); - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->setShortcutsInactive(); + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->setShortcutsInactive(); } void Player::initSayMenu() { - sayMenu->clear(); + sayMenu->clear(); - QSettings settings; - settings.beginGroup("messages"); - int count = settings.value("count", 0).toInt(); - for (int i = 0; i < count; i++) { - QAction *newAction = new QAction(settings.value(QString("msg%1").arg(i)).toString(), this); - if (i <= 10) - newAction->setShortcut(QString("Ctrl+%1").arg((i + 1) % 10)); - connect(newAction, SIGNAL(triggered()), this, SLOT(actSayMessage())); - sayMenu->addAction(newAction); - } + QSettings settings; + settings.beginGroup("messages"); + int count = settings.value("count", 0).toInt(); + for (int i = 0; i < count; i++) { + QAction *newAction = new QAction(settings.value(QString("msg%1").arg(i)).toString(), this); + if (i <= 10) + newAction->setShortcut(QString("Ctrl+%1").arg((i + 1) % 10)); + connect(newAction, SIGNAL(triggered()), this, SLOT(actSayMessage())); + sayMenu->addAction(newAction); + } } void Player::setDeck(const DeckLoader &_deck) { - deck = new DeckLoader(_deck); - aOpenDeckInDeckEditor->setEnabled(deck); - - createPredefinedTokenMenu->clear(); - predefinedTokens.clear(); - InnerDecklistNode *tokenZone = dynamic_cast(deck->getRoot()->findChild("tokens")); - if (tokenZone) - for (int i = 0; i < tokenZone->size(); ++i) { - const QString tokenName = tokenZone->at(i)->getName(); - predefinedTokens.append(tokenName); - QAction *a = createPredefinedTokenMenu->addAction(tokenName); - if (i < 10) - a->setShortcut("Alt+" + QString::number((i + 1) % 10)); - connect(a, SIGNAL(triggered()), this, SLOT(actCreatePredefinedToken())); - } + deck = new DeckLoader(_deck); + aOpenDeckInDeckEditor->setEnabled(deck); + + createPredefinedTokenMenu->clear(); + predefinedTokens.clear(); + InnerDecklistNode *tokenZone = dynamic_cast(deck->getRoot()->findChild("tokens")); + if (tokenZone) + for (int i = 0; i < tokenZone->size(); ++i) { + const QString tokenName = tokenZone->at(i)->getName(); + predefinedTokens.append(tokenName); + QAction *a = createPredefinedTokenMenu->addAction(tokenName); + if (i < 10) + a->setShortcut("Alt+" + QString::number((i + 1) % 10)); + connect(a, SIGNAL(triggered()), this, SLOT(actCreatePredefinedToken())); + } } void Player::actViewLibrary() { - static_cast(scene())->toggleZoneView(this, "deck", -1); + static_cast(scene())->toggleZoneView(this, "deck", -1); } void Player::actViewTopCards() { - bool ok; - int number = QInputDialog::getInteger(0, tr("View top cards of library"), tr("Number of cards:"), defaultNumberTopCards, 1, 2000000000, 1, &ok); - if (ok) { - defaultNumberTopCards = number; - static_cast(scene())->toggleZoneView(this, "deck", number); - } + bool ok; + int number = QInputDialog::getInteger(0, tr("View top cards of library"), tr("Number of cards:"), defaultNumberTopCards, 1, 2000000000, 1, &ok); + if (ok) { + defaultNumberTopCards = number; + static_cast(scene())->toggleZoneView(this, "deck", number); + } } void Player::actAlwaysRevealTopCard() { - Command_ChangeZoneProperties cmd; - cmd.set_zone_name("deck"); - cmd.set_always_reveal_top_card(aAlwaysRevealTopCard->isChecked()); - - sendGameCommand(cmd); + Command_ChangeZoneProperties cmd; + cmd.set_zone_name("deck"); + cmd.set_always_reveal_top_card(aAlwaysRevealTopCard->isChecked()); + + sendGameCommand(cmd); } void Player::actOpenDeckInDeckEditor() { - emit openDeckEditor(deck); + emit openDeckEditor(deck); } void Player::actViewGraveyard() { - static_cast(scene())->toggleZoneView(this, "grave", -1); + static_cast(scene())->toggleZoneView(this, "grave", -1); } void Player::actViewRfg() { - static_cast(scene())->toggleZoneView(this, "rfg", -1); + static_cast(scene())->toggleZoneView(this, "rfg", -1); } void Player::actViewSideboard() { - static_cast(scene())->toggleZoneView(this, "sb", -1); + static_cast(scene())->toggleZoneView(this, "sb", -1); } void Player::actShuffle() { - sendGameCommand(Command_Shuffle()); + sendGameCommand(Command_Shuffle()); } void Player::actDrawCard() { - Command_DrawCards cmd; - cmd.set_number(1); - sendGameCommand(cmd); + Command_DrawCards cmd; + cmd.set_number(1); + sendGameCommand(cmd); } void Player::actMulligan() { - sendGameCommand(Command_Mulligan()); + sendGameCommand(Command_Mulligan()); } void Player::actDrawCards() { - int number = QInputDialog::getInteger(0, tr("Draw cards"), tr("Number:")); + int number = QInputDialog::getInteger(0, tr("Draw cards"), tr("Number:")); if (number) { - Command_DrawCards cmd; - cmd.set_number(number); - sendGameCommand(cmd); - } + Command_DrawCards cmd; + cmd.set_number(number); + sendGameCommand(cmd); + } } void Player::actUndoDraw() { - sendGameCommand(Command_UndoDraw()); + sendGameCommand(Command_UndoDraw()); } void Player::actMoveTopCardsToGrave() { - int number = QInputDialog::getInteger(0, tr("Move top cards to grave"), tr("Number:")); + int number = QInputDialog::getInteger(0, tr("Move top cards to grave"), tr("Number:")); if (!number) - return; + return; - const int maxCards = zones.value("deck")->getCards().size(); - if (number > maxCards) - number = maxCards; + const int maxCards = zones.value("deck")->getCards().size(); + if (number > maxCards) + number = maxCards; - Command_MoveCard cmd; - cmd.set_start_zone("deck"); - cmd.set_target_player_id(getId()); - cmd.set_target_zone("grave"); - cmd.set_x(0); - cmd.set_y(0); + Command_MoveCard cmd; + cmd.set_start_zone("deck"); + cmd.set_target_player_id(getId()); + cmd.set_target_zone("grave"); + cmd.set_x(0); + cmd.set_y(0); - for (int i = 0; i < number; ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(i); - - sendGameCommand(cmd); + for (int i = 0; i < number; ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(i); + + sendGameCommand(cmd); } void Player::actMoveTopCardsToExile() { - int number = QInputDialog::getInteger(0, tr("Move top cards to exile"), tr("Number:")); + int number = QInputDialog::getInteger(0, tr("Move top cards to exile"), tr("Number:")); if (!number) - return; + return; - const int maxCards = zones.value("deck")->getCards().size(); - if (number > maxCards) - number = maxCards; - - Command_MoveCard cmd; - cmd.set_start_zone("deck"); - cmd.set_target_player_id(getId()); - cmd.set_target_zone("rfg"); - cmd.set_x(0); - cmd.set_y(0); + const int maxCards = zones.value("deck")->getCards().size(); + if (number > maxCards) + number = maxCards; + + Command_MoveCard cmd; + cmd.set_start_zone("deck"); + cmd.set_target_player_id(getId()); + cmd.set_target_zone("rfg"); + cmd.set_x(0); + cmd.set_y(0); - for (int i = 0; i < number; ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(i); - - sendGameCommand(cmd); + for (int i = 0; i < number; ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(i); + + sendGameCommand(cmd); } void Player::actMoveTopCardToBottom() { - Command_MoveCard cmd; - cmd.set_start_zone("deck"); - cmd.mutable_cards_to_move()->add_card()->set_card_id(0); - cmd.set_target_player_id(getId()); - cmd.set_target_zone("deck"); - cmd.set_x(-1); - cmd.set_y(0); - - sendGameCommand(cmd); + Command_MoveCard cmd; + cmd.set_start_zone("deck"); + cmd.mutable_cards_to_move()->add_card()->set_card_id(0); + cmd.set_target_player_id(getId()); + cmd.set_target_zone("deck"); + cmd.set_x(-1); + cmd.set_y(0); + + sendGameCommand(cmd); } void Player::actUntapAll() { - Command_SetCardAttr cmd; - cmd.set_zone("table"); - cmd.set_attribute(AttrTapped); - cmd.set_attr_value("0"); - - sendGameCommand(cmd); + Command_SetCardAttr cmd; + cmd.set_zone("table"); + cmd.set_attribute(AttrTapped); + cmd.set_attr_value("0"); + + sendGameCommand(cmd); } void Player::actRollDie() { - bool ok; - int sides = QInputDialog::getInteger(0, tr("Roll die"), tr("Number of sides:"), 20, 2, 1000, 1, &ok); - if (ok) { - Command_RollDie cmd; - cmd.set_sides(sides); - sendGameCommand(cmd); - } + bool ok; + int sides = QInputDialog::getInteger(0, tr("Roll die"), tr("Number of sides:"), 20, 2, 1000, 1, &ok); + if (ok) { + Command_RollDie cmd; + cmd.set_sides(sides); + sendGameCommand(cmd); + } } void Player::actCreateToken() { - DlgCreateToken dlg(predefinedTokens); - if (!dlg.exec()) - return; - - lastTokenName = dlg.getName(); - lastTokenColor = dlg.getColor(); - lastTokenPT = dlg.getPT(); - lastTokenAnnotation = dlg.getAnnotation(); - lastTokenDestroy = dlg.getDestroy(); - aCreateAnotherToken->setEnabled(true); - - actCreateAnotherToken(); + DlgCreateToken dlg(predefinedTokens); + if (!dlg.exec()) + return; + + lastTokenName = dlg.getName(); + lastTokenColor = dlg.getColor(); + lastTokenPT = dlg.getPT(); + lastTokenAnnotation = dlg.getAnnotation(); + lastTokenDestroy = dlg.getDestroy(); + aCreateAnotherToken->setEnabled(true); + + actCreateAnotherToken(); } void Player::actCreateAnotherToken() { - Command_CreateToken cmd; - cmd.set_zone("table"); - cmd.set_card_name(lastTokenName.toStdString()); - cmd.set_color(lastTokenColor.toStdString()); - cmd.set_pt(lastTokenPT.toStdString()); - cmd.set_annotation(lastTokenAnnotation.toStdString()); - cmd.set_destroy_on_zone_change(lastTokenDestroy); - cmd.set_x(-1); - cmd.set_y(0); - - sendGameCommand(cmd); + Command_CreateToken cmd; + cmd.set_zone("table"); + cmd.set_card_name(lastTokenName.toStdString()); + cmd.set_color(lastTokenColor.toStdString()); + cmd.set_pt(lastTokenPT.toStdString()); + cmd.set_annotation(lastTokenAnnotation.toStdString()); + cmd.set_destroy_on_zone_change(lastTokenDestroy); + cmd.set_x(-1); + cmd.set_y(0); + + sendGameCommand(cmd); } void Player::actCreatePredefinedToken() { - QAction *action = static_cast(sender()); - CardInfo *cardInfo = db->getCard(action->text()); - - lastTokenName = cardInfo->getName(); - lastTokenColor = cardInfo->getColors().isEmpty() ? QString() : cardInfo->getColors().first().toLower(); - lastTokenPT = cardInfo->getPowTough(); - lastTokenAnnotation = cardInfo->getText(); - lastTokenDestroy = true; - aCreateAnotherToken->setEnabled(true); - - actCreateAnotherToken(); + QAction *action = static_cast(sender()); + CardInfo *cardInfo = db->getCard(action->text()); + + lastTokenName = cardInfo->getName(); + lastTokenColor = cardInfo->getColors().isEmpty() ? QString() : cardInfo->getColors().first().toLower(); + lastTokenPT = cardInfo->getPowTough(); + lastTokenAnnotation = cardInfo->getText(); + lastTokenDestroy = true; + aCreateAnotherToken->setEnabled(true); + + actCreateAnotherToken(); } void Player::actSayMessage() { - QAction *a = qobject_cast(sender()); - Command_GameSay cmd; - cmd.set_message(a->text().toStdString()); - sendGameCommand(cmd); + QAction *a = qobject_cast(sender()); + Command_GameSay cmd; + cmd.set_message(a->text().toStdString()); + sendGameCommand(cmd); } void Player::setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards) { - bool moveCardContext = context.HasExtension(Context_MoveCard::ext); - switch (attribute) { - case AttrTapped: { - bool tapped = avalue == "1"; - if (!(!tapped && card->getDoesntUntap() && allCards)) { - if (!allCards) - emit logSetTapped(this, card, tapped); - card->setTapped(tapped, !moveCardContext); - } - break; - } - case AttrAttacking: card->setAttacking(avalue == "1"); break; - case AttrFaceDown: card->setFaceDown(avalue == "1"); break; - case AttrColor: card->setColor(avalue); break; - case AttrAnnotation: { - emit logSetAnnotation(this, card, avalue); - card->setAnnotation(avalue); - break; - } - case AttrDoesntUntap: { - bool value = (avalue == "1"); - emit logSetDoesntUntap(this, card, value); - card->setDoesntUntap(value); - break; - } - case AttrPT: { - emit logSetPT(this, card, avalue); - card->setPT(avalue); - break; - } - } + bool moveCardContext = context.HasExtension(Context_MoveCard::ext); + switch (attribute) { + case AttrTapped: { + bool tapped = avalue == "1"; + if (!(!tapped && card->getDoesntUntap() && allCards)) { + if (!allCards) + emit logSetTapped(this, card, tapped); + card->setTapped(tapped, !moveCardContext); + } + break; + } + case AttrAttacking: card->setAttacking(avalue == "1"); break; + case AttrFaceDown: card->setFaceDown(avalue == "1"); break; + case AttrColor: card->setColor(avalue); break; + case AttrAnnotation: { + emit logSetAnnotation(this, card, avalue); + card->setAnnotation(avalue); + break; + } + case AttrDoesntUntap: { + bool value = (avalue == "1"); + emit logSetDoesntUntap(this, card, value); + card->setDoesntUntap(value); + break; + } + case AttrPT: { + emit logSetPT(this, card, avalue); + card->setPT(avalue); + break; + } + } } void Player::eventGameSay(const Event_GameSay &event) { - emit logSay(this, QString::fromStdString(event.message())); + emit logSay(this, QString::fromStdString(event.message())); } void Player::eventShuffle(const Event_Shuffle &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); - if (!zone) - return; - if (zone->getView()) - if (zone->getView()->getRevealZone()) - zone->getView()->setWriteableRevealZone(false); - emit logShuffle(this, zone); + CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); + if (!zone) + return; + if (zone->getView()) + if (zone->getView()->getRevealZone()) + zone->getView()->setWriteableRevealZone(false); + emit logShuffle(this, zone); } void Player::eventRollDie(const Event_RollDie &event) { - emit logRollDie(this, event.sides(), event.value()); + emit logRollDie(this, event.sides(), event.value()); } void Player::eventCreateArrow(const Event_CreateArrow &event) { - ArrowItem *arrow = addArrow(event.arrow_info()); - if (!arrow) - return; - - CardItem *startCard = static_cast(arrow->getStartItem()); - CardItem *targetCard = qgraphicsitem_cast(arrow->getTargetItem()); - if (targetCard) - emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), targetCard->getOwner(), targetCard->getName(), false); - else - emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), arrow->getTargetItem()->getOwner(), QString(), true); + ArrowItem *arrow = addArrow(event.arrow_info()); + if (!arrow) + return; + + CardItem *startCard = static_cast(arrow->getStartItem()); + CardItem *targetCard = qgraphicsitem_cast(arrow->getTargetItem()); + if (targetCard) + emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), targetCard->getOwner(), targetCard->getName(), false); + else + emit logCreateArrow(this, startCard->getOwner(), startCard->getName(), arrow->getTargetItem()->getOwner(), QString(), true); } void Player::eventDeleteArrow(const Event_DeleteArrow &event) { - delArrow(event.arrow_id()); + delArrow(event.arrow_id()); } void Player::eventCreateToken(const Event_CreateToken &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; - CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id()); - card->setColor(QString::fromStdString(event.color())); - card->setPT(QString::fromStdString(event.pt())); - card->setAnnotation(QString::fromStdString(event.annotation())); - card->setDestroyOnZoneChange(event.destroy_on_zone_change()); + CardItem *card = new CardItem(this, QString::fromStdString(event.card_name()), event.card_id()); + card->setColor(QString::fromStdString(event.color())); + card->setPT(QString::fromStdString(event.pt())); + card->setAnnotation(QString::fromStdString(event.annotation())); + card->setDestroyOnZoneChange(event.destroy_on_zone_change()); - emit logCreateToken(this, card->getName(), card->getPT()); - zone->addCard(card, true, event.x(), event.y()); + emit logCreateToken(this, card->getName(), card->getPT()); + zone->addCard(card, true, event.x(), event.y()); } void Player::eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; - if (!event.has_card_id()) { - const CardList &cards = zone->getCards(); - for (int i = 0; i < cards.size(); i++) - setCardAttrHelper(context, cards.at(i), event.attribute(), QString::fromStdString(event.attr_value()), true); - if (event.attribute() == AttrTapped) - emit logSetTapped(this, 0, event.attr_value() == "1"); - } else { - CardItem *card = zone->getCard(event.card_id(), QString()); - if (!card) { - qDebug() << "Player::eventSetCardAttr: card id=" << event.card_id() << "not found"; - return; - } - setCardAttrHelper(context, card, event.attribute(), QString::fromStdString(event.attr_value()), false); - } + if (!event.has_card_id()) { + const CardList &cards = zone->getCards(); + for (int i = 0; i < cards.size(); i++) + setCardAttrHelper(context, cards.at(i), event.attribute(), QString::fromStdString(event.attr_value()), true); + if (event.attribute() == AttrTapped) + emit logSetTapped(this, 0, event.attr_value() == "1"); + } else { + CardItem *card = zone->getCard(event.card_id(), QString()); + if (!card) { + qDebug() << "Player::eventSetCardAttr: card id=" << event.card_id() << "not found"; + return; + } + setCardAttrHelper(context, card, event.attribute(), QString::fromStdString(event.attr_value()), false); + } } void Player::eventSetCardCounter(const Event_SetCardCounter &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; - CardItem *card = zone->getCard(event.card_id(), QString()); - if (!card) - return; - - int oldValue = card->getCounters().value(event.counter_id(), 0); - card->setCounter(event.counter_id(), event.counter_value()); - emit logSetCardCounter(this, card->getName(), event.counter_id(), event.counter_value(), oldValue); + CardItem *card = zone->getCard(event.card_id(), QString()); + if (!card) + return; + + int oldValue = card->getCounters().value(event.counter_id(), 0); + card->setCounter(event.counter_id(), event.counter_value()); + emit logSetCardCounter(this, card->getName(), event.counter_id(), event.counter_value(), oldValue); } void Player::eventCreateCounter(const Event_CreateCounter &event) { - addCounter(event.counter_info()); + addCounter(event.counter_info()); } void Player::eventSetCounter(const Event_SetCounter &event) { - AbstractCounter *c = counters.value(event.counter_id(), 0); - if (!c) - return; - int oldValue = c->getValue(); - c->setValue(event.value()); - emit logSetCounter(this, c->getName(), event.value(), oldValue); + AbstractCounter *c = counters.value(event.counter_id(), 0); + if (!c) + return; + int oldValue = c->getValue(); + c->setValue(event.value()); + emit logSetCounter(this, c->getName(), event.value(), oldValue); } void Player::eventDelCounter(const Event_DelCounter &event) { - delCounter(event.counter_id()); + delCounter(event.counter_id()); } void Player::eventDumpZone(const Event_DumpZone &event) { - Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); - if (!zoneOwner) - return; - CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - emit logDumpZone(this, zone, event.number_cards()); + Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); + if (!zoneOwner) + return; + CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + emit logDumpZone(this, zone, event.number_cards()); } void Player::eventStopDumpZone(const Event_StopDumpZone &event) { - Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); - if (!zoneOwner) - return; - CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - emit logStopDumpZone(this, zone); + Player *zoneOwner = game->getPlayers().value(event.zone_owner_id(), 0); + if (!zoneOwner) + return; + CardZone *zone = zoneOwner->getZones().value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + emit logStopDumpZone(this, zone); } void Player::eventMoveCard(const Event_MoveCard &event, const GameEventContext &context) { - Player *startPlayer = game->getPlayers().value(event.start_player_id()); - if (!startPlayer) - return; - CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(event.start_zone()), 0); - Player *targetPlayer = game->getPlayers().value(event.target_player_id()); - if (!targetPlayer) - return; - CardZone *targetZone; - if (event.has_target_zone()) - targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); - else - targetZone = startZone; - if (!startZone || !targetZone) - return; - - int position = event.position(); - int x = event.x(); - int y = event.y(); + Player *startPlayer = game->getPlayers().value(event.start_player_id()); + if (!startPlayer) + return; + CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(event.start_zone()), 0); + Player *targetPlayer = game->getPlayers().value(event.target_player_id()); + if (!targetPlayer) + return; + CardZone *targetZone; + if (event.has_target_zone()) + targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); + else + targetZone = startZone; + if (!startZone || !targetZone) + return; + + int position = event.position(); + int x = event.x(); + int y = event.y(); - int logPosition = position; - int logX = x; - if (x == -1) - x = 0; - CardItem *card = startZone->takeCard(position, event.card_id(), startZone != targetZone); - if (!card) - return; - if (startZone != targetZone) - card->deleteCardInfoPopup(); - if (event.has_card_name()) - card->setName(QString::fromStdString(event.card_name())); - - if (card->getAttachedTo() && (startZone != targetZone)) { - CardItem *parentCard = card->getAttachedTo(); - card->setAttachedTo(0); - parentCard->getZone()->reorganizeCards(); - } + int logPosition = position; + int logX = x; + if (x == -1) + x = 0; + CardItem *card = startZone->takeCard(position, event.card_id(), startZone != targetZone); + if (!card) + return; + if (startZone != targetZone) + card->deleteCardInfoPopup(); + if (event.has_card_name()) + card->setName(QString::fromStdString(event.card_name())); + + if (card->getAttachedTo() && (startZone != targetZone)) { + CardItem *parentCard = card->getAttachedTo(); + card->setAttachedTo(0); + parentCard->getZone()->reorganizeCards(); + } - card->deleteDragItem(); + card->deleteDragItem(); - card->setId(event.new_card_id()); - card->setFaceDown(event.face_down()); - if (startZone != targetZone) { - card->setBeingPointedAt(false); - card->setHovered(false); - - const QList &attachedCards = card->getAttachedCards(); - for (int i = 0; i < attachedCards.size(); ++i) - attachedCards[i]->setParentItem(targetZone); - - if (startZone->getPlayer() != targetZone->getPlayer()) - card->setOwner(targetZone->getPlayer()); - } + card->setId(event.new_card_id()); + card->setFaceDown(event.face_down()); + if (startZone != targetZone) { + card->setBeingPointedAt(false); + card->setHovered(false); + + const QList &attachedCards = card->getAttachedCards(); + for (int i = 0; i < attachedCards.size(); ++i) + attachedCards[i]->setParentItem(targetZone); + + if (startZone->getPlayer() != targetZone->getPlayer()) + card->setOwner(targetZone->getPlayer()); + } - // The log event has to be sent before the card is added to the target zone - // because the addCard function can modify the card object. - if (context.HasExtension(Context_UndoDraw::ext)) - emit logUndoDraw(this, card->getName()); - else - emit logMoveCard(this, card, startZone, logPosition, targetZone, logX); + // The log event has to be sent before the card is added to the target zone + // because the addCard function can modify the card object. + if (context.HasExtension(Context_UndoDraw::ext)) + emit logUndoDraw(this, card->getName()); + else + emit logMoveCard(this, card, startZone, logPosition, targetZone, logX); - targetZone->addCard(card, true, x, y); + targetZone->addCard(card, true, x, y); - // Look at all arrows from and to the card. - // If the card was moved to another zone, delete the arrows, otherwise update them. - QMapIterator playerIterator(game->getPlayers()); - while (playerIterator.hasNext()) { - Player *p = playerIterator.next().value(); + // Look at all arrows from and to the card. + // If the card was moved to another zone, delete the arrows, otherwise update them. + QMapIterator playerIterator(game->getPlayers()); + while (playerIterator.hasNext()) { + Player *p = playerIterator.next().value(); - QList arrowsToDelete; - QMapIterator arrowIterator(p->getArrows()); - while (arrowIterator.hasNext()) { - ArrowItem *arrow = arrowIterator.next().value(); - if ((arrow->getStartItem() == card) || (arrow->getTargetItem() == card)) { - if (startZone == targetZone) - arrow->updatePath(); - else - arrowsToDelete.append(arrow); - } - } - for (int i = 0; i < arrowsToDelete.size(); ++i) - arrowsToDelete[i]->delArrow(); - } + QList arrowsToDelete; + QMapIterator arrowIterator(p->getArrows()); + while (arrowIterator.hasNext()) { + ArrowItem *arrow = arrowIterator.next().value(); + if ((arrow->getStartItem() == card) || (arrow->getTargetItem() == card)) { + if (startZone == targetZone) + arrow->updatePath(); + else + arrowsToDelete.append(arrow); + } + } + for (int i = 0; i < arrowsToDelete.size(); ++i) + arrowsToDelete[i]->delArrow(); + } } void Player::eventFlipCard(const Event_FlipCard &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - CardItem *card = zone->getCard(event.card_id(), QString::fromStdString(event.card_name())); - if (!card) - return; - emit logFlipCard(this, card->getName(), event.face_down()); - card->setFaceDown(event.face_down()); + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + CardItem *card = zone->getCard(event.card_id(), QString::fromStdString(event.card_name())); + if (!card) + return; + emit logFlipCard(this, card->getName(), event.face_down()); + card->setFaceDown(event.face_down()); } void Player::eventDestroyCard(const Event_DestroyCard &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); - if (!zone) - return; - - CardItem *card = zone->getCard(event.card_id(), QString()); - if (!card) - return; - - QList attachedCards = card->getAttachedCards(); - // This list is always empty except for buggy server implementations. - for (int i = 0; i < attachedCards.size(); ++i) - attachedCards[i]->setAttachedTo(0); - - emit logDestroyCard(this, card->getName()); - zone->takeCard(-1, event.card_id(), true); - card->deleteLater(); + CardZone *zone = zones.value(QString::fromStdString(event.zone_name()), 0); + if (!zone) + return; + + CardItem *card = zone->getCard(event.card_id(), QString()); + if (!card) + return; + + QList attachedCards = card->getAttachedCards(); + // This list is always empty except for buggy server implementations. + for (int i = 0; i < attachedCards.size(); ++i) + attachedCards[i]->setAttachedTo(0); + + emit logDestroyCard(this, card->getName()); + zone->takeCard(-1, event.card_id(), true); + card->deleteLater(); } void Player::eventAttachCard(const Event_AttachCard &event) { - const QMap &playerList = game->getPlayers(); - Player *targetPlayer = 0; - CardZone *targetZone = 0; - CardItem *targetCard = 0; - if (event.has_target_player_id()) { - targetPlayer = playerList.value(event.target_player_id(), 0); - if (targetPlayer) { - targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); - if (targetZone) - targetCard = targetZone->getCard(event.target_card_id(), QString()); - } - } - - CardZone *startZone = getZones().value(QString::fromStdString(event.start_zone()), 0); - if (!startZone) - return; - - CardItem *startCard = startZone->getCard(event.card_id(), QString()); - if (!startCard) - return; - - CardItem *oldParent = startCard->getAttachedTo(); - - startCard->setAttachedTo(targetCard); - - startZone->reorganizeCards(); - if ((startZone != targetZone) && targetZone) - targetZone->reorganizeCards(); - if (oldParent) - oldParent->getZone()->reorganizeCards(); - - if (targetCard) - emit logAttachCard(this, startCard->getName(), targetPlayer, targetCard->getName()); - else - emit logUnattachCard(this, startCard->getName()); + const QMap &playerList = game->getPlayers(); + Player *targetPlayer = 0; + CardZone *targetZone = 0; + CardItem *targetCard = 0; + if (event.has_target_player_id()) { + targetPlayer = playerList.value(event.target_player_id(), 0); + if (targetPlayer) { + targetZone = targetPlayer->getZones().value(QString::fromStdString(event.target_zone()), 0); + if (targetZone) + targetCard = targetZone->getCard(event.target_card_id(), QString()); + } + } + + CardZone *startZone = getZones().value(QString::fromStdString(event.start_zone()), 0); + if (!startZone) + return; + + CardItem *startCard = startZone->getCard(event.card_id(), QString()); + if (!startCard) + return; + + CardItem *oldParent = startCard->getAttachedTo(); + + startCard->setAttachedTo(targetCard); + + startZone->reorganizeCards(); + if ((startZone != targetZone) && targetZone) + targetZone->reorganizeCards(); + if (oldParent) + oldParent->getZone()->reorganizeCards(); + + if (targetCard) + emit logAttachCard(this, startCard->getName(), targetPlayer, targetCard->getName()); + else + emit logUnattachCard(this, startCard->getName()); } void Player::eventDrawCards(const Event_DrawCards &event) { - CardZone *deck = zones.value("deck"); - CardZone *hand = zones.value("hand"); - - const int listSize = event.cards_size(); - if (listSize) { - for (int i = 0; i < listSize; ++i) { - const ServerInfo_Card &cardInfo = event.cards(i); - CardItem *card = deck->takeCard(0, cardInfo.id()); - card->setName(QString::fromStdString(cardInfo.name())); - hand->addCard(card, false, -1); - } - } else { - const int number = event.number(); - for (int i = 0; i < number; ++i) - hand->addCard(deck->takeCard(0, -1), false, -1); - } - - hand->reorganizeCards(); - deck->reorganizeCards(); - emit logDrawCards(this, event.number()); + CardZone *deck = zones.value("deck"); + CardZone *hand = zones.value("hand"); + + const int listSize = event.cards_size(); + if (listSize) { + for (int i = 0; i < listSize; ++i) { + const ServerInfo_Card &cardInfo = event.cards(i); + CardItem *card = deck->takeCard(0, cardInfo.id()); + card->setName(QString::fromStdString(cardInfo.name())); + hand->addCard(card, false, -1); + } + } else { + const int number = event.number(); + for (int i = 0; i < number; ++i) + hand->addCard(deck->takeCard(0, -1), false, -1); + } + + hand->reorganizeCards(); + deck->reorganizeCards(); + emit logDrawCards(this, event.number()); } void Player::eventRevealCards(const Event_RevealCards &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); - if (!zone) - return; - Player *otherPlayer = 0; - if (event.has_other_player_id()) { - otherPlayer = game->getPlayers().value(event.other_player_id()); - if (!otherPlayer) - return; - } - - bool peeking = false; - QList cardList; - const int cardListSize = event.cards_size(); - for (int i = 0; i < cardListSize; ++i) { - const ServerInfo_Card *temp = &event.cards(i); - if (temp->face_down()) - peeking = true; - cardList.append(temp); - } - - if (peeking) { - for (int i = 0; i < cardList.size(); ++i) { - QString cardName = QString::fromStdString(cardList.at(i)->name()); - CardItem *card = zone->getCard(cardList.at(i)->id(), QString()); - if (!card) - continue; - card->setName(cardName); - emit logRevealCards(this, zone, cardList.at(i)->id(), cardName, this, true); - } - } else { - bool showZoneView = true; - QString cardName; - if (cardList.size() == 1) { - cardName = QString::fromStdString(cardList.first()->name()); - if ((event.card_id() == 0) && dynamic_cast(zone)) { - zone->getCards().first()->setName(cardName); - zone->update(); - showZoneView = false; - } - } - if (showZoneView && !cardList.isEmpty()) - static_cast(scene())->addRevealedZoneView(this, zone, cardList, event.grant_write_access()); - - emit logRevealCards(this, zone, event.card_id(), cardName, otherPlayer, false); - } + CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); + if (!zone) + return; + Player *otherPlayer = 0; + if (event.has_other_player_id()) { + otherPlayer = game->getPlayers().value(event.other_player_id()); + if (!otherPlayer) + return; + } + + bool peeking = false; + QList cardList; + const int cardListSize = event.cards_size(); + for (int i = 0; i < cardListSize; ++i) { + const ServerInfo_Card *temp = &event.cards(i); + if (temp->face_down()) + peeking = true; + cardList.append(temp); + } + + if (peeking) { + for (int i = 0; i < cardList.size(); ++i) { + QString cardName = QString::fromStdString(cardList.at(i)->name()); + CardItem *card = zone->getCard(cardList.at(i)->id(), QString()); + if (!card) + continue; + card->setName(cardName); + emit logRevealCards(this, zone, cardList.at(i)->id(), cardName, this, true); + } + } else { + bool showZoneView = true; + QString cardName; + if (cardList.size() == 1) { + cardName = QString::fromStdString(cardList.first()->name()); + if ((event.card_id() == 0) && dynamic_cast(zone)) { + zone->getCards().first()->setName(cardName); + zone->update(); + showZoneView = false; + } + } + if (showZoneView && !cardList.isEmpty()) + static_cast(scene())->addRevealedZoneView(this, zone, cardList, event.grant_write_access()); + + emit logRevealCards(this, zone, event.card_id(), cardName, otherPlayer, false); + } } void Player::eventChangeZoneProperties(const Event_ChangeZoneProperties &event) { - CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); - if (!zone) - return; - - if (event.has_always_reveal_top_card()) { - zone->setAlwaysRevealTopCard(event.always_reveal_top_card()); - emit logAlwaysRevealTopCard(this, zone, event.always_reveal_top_card()); - } + CardZone *zone = zones.value(QString::fromStdString(event.zone_name())); + if (!zone) + return; + + if (event.has_always_reveal_top_card()) { + zone->setAlwaysRevealTopCard(event.always_reveal_top_card()); + emit logAlwaysRevealTopCard(this, zone, event.always_reveal_top_card()); + } } void Player::processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context) { - switch (type) { - case GameEvent::GAME_SAY: eventGameSay(event.GetExtension(Event_GameSay::ext)); break; - case GameEvent::SHUFFLE: eventShuffle(event.GetExtension(Event_Shuffle::ext)); break; - case GameEvent::ROLL_DIE: eventRollDie(event.GetExtension(Event_RollDie::ext)); break; - case GameEvent::CREATE_ARROW: eventCreateArrow(event.GetExtension(Event_CreateArrow::ext)); break; - case GameEvent::DELETE_ARROW: eventDeleteArrow(event.GetExtension(Event_DeleteArrow::ext)); break; - case GameEvent::CREATE_TOKEN: eventCreateToken(event.GetExtension(Event_CreateToken::ext)); break; - case GameEvent::SET_CARD_ATTR: eventSetCardAttr(event.GetExtension(Event_SetCardAttr::ext), context); break; - case GameEvent::SET_CARD_COUNTER: eventSetCardCounter(event.GetExtension(Event_SetCardCounter::ext)); break; - case GameEvent::CREATE_COUNTER: eventCreateCounter(event.GetExtension(Event_CreateCounter::ext)); break; - case GameEvent::SET_COUNTER: eventSetCounter(event.GetExtension(Event_SetCounter::ext)); break; - case GameEvent::DEL_COUNTER: eventDelCounter(event.GetExtension(Event_DelCounter::ext)); break; - case GameEvent::DUMP_ZONE: eventDumpZone(event.GetExtension(Event_DumpZone::ext)); break; - case GameEvent::STOP_DUMP_ZONE: eventStopDumpZone(event.GetExtension(Event_StopDumpZone::ext)); break; - case GameEvent::MOVE_CARD: eventMoveCard(event.GetExtension(Event_MoveCard::ext), context); break; - case GameEvent::FLIP_CARD: eventFlipCard(event.GetExtension(Event_FlipCard::ext)); break; - case GameEvent::DESTROY_CARD: eventDestroyCard(event.GetExtension(Event_DestroyCard::ext)); break; - case GameEvent::ATTACH_CARD: eventAttachCard(event.GetExtension(Event_AttachCard::ext)); break; - case GameEvent::DRAW_CARDS: eventDrawCards(event.GetExtension(Event_DrawCards::ext)); break; - case GameEvent::REVEAL_CARDS: eventRevealCards(event.GetExtension(Event_RevealCards::ext)); break; - case GameEvent::CHANGE_ZONE_PROPERTIES: eventChangeZoneProperties(event.GetExtension(Event_ChangeZoneProperties::ext)); break; - default: { - qDebug() << "unhandled game event"; - } - } + switch (type) { + case GameEvent::GAME_SAY: eventGameSay(event.GetExtension(Event_GameSay::ext)); break; + case GameEvent::SHUFFLE: eventShuffle(event.GetExtension(Event_Shuffle::ext)); break; + case GameEvent::ROLL_DIE: eventRollDie(event.GetExtension(Event_RollDie::ext)); break; + case GameEvent::CREATE_ARROW: eventCreateArrow(event.GetExtension(Event_CreateArrow::ext)); break; + case GameEvent::DELETE_ARROW: eventDeleteArrow(event.GetExtension(Event_DeleteArrow::ext)); break; + case GameEvent::CREATE_TOKEN: eventCreateToken(event.GetExtension(Event_CreateToken::ext)); break; + case GameEvent::SET_CARD_ATTR: eventSetCardAttr(event.GetExtension(Event_SetCardAttr::ext), context); break; + case GameEvent::SET_CARD_COUNTER: eventSetCardCounter(event.GetExtension(Event_SetCardCounter::ext)); break; + case GameEvent::CREATE_COUNTER: eventCreateCounter(event.GetExtension(Event_CreateCounter::ext)); break; + case GameEvent::SET_COUNTER: eventSetCounter(event.GetExtension(Event_SetCounter::ext)); break; + case GameEvent::DEL_COUNTER: eventDelCounter(event.GetExtension(Event_DelCounter::ext)); break; + case GameEvent::DUMP_ZONE: eventDumpZone(event.GetExtension(Event_DumpZone::ext)); break; + case GameEvent::STOP_DUMP_ZONE: eventStopDumpZone(event.GetExtension(Event_StopDumpZone::ext)); break; + case GameEvent::MOVE_CARD: eventMoveCard(event.GetExtension(Event_MoveCard::ext), context); break; + case GameEvent::FLIP_CARD: eventFlipCard(event.GetExtension(Event_FlipCard::ext)); break; + case GameEvent::DESTROY_CARD: eventDestroyCard(event.GetExtension(Event_DestroyCard::ext)); break; + case GameEvent::ATTACH_CARD: eventAttachCard(event.GetExtension(Event_AttachCard::ext)); break; + case GameEvent::DRAW_CARDS: eventDrawCards(event.GetExtension(Event_DrawCards::ext)); break; + case GameEvent::REVEAL_CARDS: eventRevealCards(event.GetExtension(Event_RevealCards::ext)); break; + case GameEvent::CHANGE_ZONE_PROPERTIES: eventChangeZoneProperties(event.GetExtension(Event_ChangeZoneProperties::ext)); break; + default: { + qDebug() << "unhandled game event"; + } + } } void Player::setActive(bool _active) { - active = _active; - table->setActive(active); - update(); + active = _active; + table->setActive(active); + update(); } QRectF Player::boundingRect() const { - return bRect; + return bRect; } void Player::paint(QPainter * /*painter*/, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) @@ -1436,758 +1436,759 @@ void Player::paint(QPainter * /*painter*/, const QStyleOptionGraphicsItem */*opt void Player::processPlayerInfo(const ServerInfo_Player &info) { - clearCounters(); - clearArrows(); - - QMapIterator zoneIt(zones); - while (zoneIt.hasNext()) - zoneIt.next().value()->clearContents(); - - const int zoneListSize = info.zone_list_size(); - for (int i = 0; i < zoneListSize; ++i) { - const ServerInfo_Zone &zoneInfo = info.zone_list(i); - CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); - if (!zone) - continue; - - const int cardListSize = zoneInfo.card_list_size(); - if (!cardListSize) { - for (int j = 0; j < zoneInfo.card_count(); ++j) - zone->addCard(new CardItem(this), false, -1); - } else { - for (int j = 0; j < cardListSize; ++j) { - const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); - CardItem *card = new CardItem(this); - card->processCardInfo(cardInfo); - zone->addCard(card, false, cardInfo.x(), cardInfo.y()); - } - } - if (zoneInfo.has_always_reveal_top_card()) - zone->setAlwaysRevealTopCard(zoneInfo.always_reveal_top_card()); - - zone->reorganizeCards(); - } - - const int counterListSize = info.counter_list_size(); - for (int i = 0; i < counterListSize; ++i) - addCounter(info.counter_list(i)); - - setConceded(info.properties().conceded()); + clearCounters(); + clearArrows(); + + QMapIterator zoneIt(zones); + while (zoneIt.hasNext()) + zoneIt.next().value()->clearContents(); + + const int zoneListSize = info.zone_list_size(); + for (int i = 0; i < zoneListSize; ++i) { + const ServerInfo_Zone &zoneInfo = info.zone_list(i); + CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); + if (!zone) + continue; + + const int cardListSize = zoneInfo.card_list_size(); + if (!cardListSize) { + for (int j = 0; j < zoneInfo.card_count(); ++j) + zone->addCard(new CardItem(this), false, -1); + } else { + for (int j = 0; j < cardListSize; ++j) { + const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); + CardItem *card = new CardItem(this); + card->processCardInfo(cardInfo); + zone->addCard(card, false, cardInfo.x(), cardInfo.y()); + } + } + if (zoneInfo.has_always_reveal_top_card()) + zone->setAlwaysRevealTopCard(zoneInfo.always_reveal_top_card()); + + zone->reorganizeCards(); + } + + const int counterListSize = info.counter_list_size(); + for (int i = 0; i < counterListSize; ++i) + addCounter(info.counter_list(i)); + + setConceded(info.properties().conceded()); } void Player::processCardAttachment(const ServerInfo_Player &info) { - const int zoneListSize = info.zone_list_size(); - for (int i = 0; i < zoneListSize; ++i) { - const ServerInfo_Zone &zoneInfo = info.zone_list(i); - CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); - if (!zone) - continue; - - const int cardListSize = zoneInfo.card_list_size(); - for (int j = 0; j < cardListSize; ++j) { - const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); - if (cardInfo.has_attach_player_id()) { - CardItem *startCard = zone->getCard(cardInfo.id(), QString()); - CardItem *targetCard = game->getCard(cardInfo.attach_player_id(), QString::fromStdString(cardInfo.attach_zone()), cardInfo.attach_card_id()); - if (!targetCard) - continue; - - startCard->setAttachedTo(targetCard); - } - } - } - - const int arrowListSize = info.arrow_list_size(); - for (int i = 0; i < arrowListSize; ++i) - addArrow(info.arrow_list(i)); + const int zoneListSize = info.zone_list_size(); + for (int i = 0; i < zoneListSize; ++i) { + const ServerInfo_Zone &zoneInfo = info.zone_list(i); + CardZone *zone = zones.value(QString::fromStdString(zoneInfo.name()), 0); + if (!zone) + continue; + + const int cardListSize = zoneInfo.card_list_size(); + for (int j = 0; j < cardListSize; ++j) { + const ServerInfo_Card &cardInfo = zoneInfo.card_list(j); + if (cardInfo.has_attach_player_id()) { + CardItem *startCard = zone->getCard(cardInfo.id(), QString()); + CardItem *targetCard = game->getCard(cardInfo.attach_player_id(), QString::fromStdString(cardInfo.attach_zone()), cardInfo.attach_card_id()); + if (!targetCard) + continue; + + startCard->setAttachedTo(targetCard); + } + } + } + + const int arrowListSize = info.arrow_list_size(); + for (int i = 0; i < arrowListSize; ++i) + addArrow(info.arrow_list(i)); } void Player::playCard(CardItem *c, bool faceDown, bool tapped) { - Command_MoveCard cmd; - cmd.set_start_player_id(c->getZone()->getPlayer()->getId()); - cmd.set_start_zone(c->getZone()->getName().toStdString()); - cmd.set_target_player_id(getId()); - CardToMove *cardToMove = cmd.mutable_cards_to_move()->add_card(); - cardToMove->set_card_id(c->getId()); - - CardInfo *ci = c->getInfo(); - if ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || - (settingsCache->getPlayToStack() && ci->getTableRow() != 0) && - c->getZone()->getName().toStdString() != "stack") { - cmd.set_target_zone("stack"); - cmd.set_x(0); - cmd.set_y(0); - } else { - QPoint gridPoint = QPoint(-1, 2 - ci->getTableRow()); - cardToMove->set_face_down(faceDown); - cardToMove->set_pt(ci->getPowTough().toStdString()); - cardToMove->set_tapped(tapped); - if(ci->getTableRow() != 3) - cmd.set_target_zone("table"); - cmd.set_x(gridPoint.x()); - cmd.set_y(gridPoint.y()); - } - sendGameCommand(cmd); + Command_MoveCard cmd; + cmd.set_start_player_id(c->getZone()->getPlayer()->getId()); + cmd.set_start_zone(c->getZone()->getName().toStdString()); + cmd.set_target_player_id(getId()); + CardToMove *cardToMove = cmd.mutable_cards_to_move()->add_card(); + cardToMove->set_card_id(c->getId()); + + CardInfo *ci = c->getInfo(); + if ((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) || + ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) && + c->getZone()->getName().toStdString() != "stack")) { + cmd.set_target_zone("stack"); + cmd.set_x(0); + cmd.set_y(0); + } else { + QPoint gridPoint = QPoint(-1, 2 - ci->getTableRow()); + cardToMove->set_face_down(faceDown); + cardToMove->set_pt(ci->getPowTough().toStdString()); + cardToMove->set_tapped(tapped); + if(ci->getTableRow() != 3) + cmd.set_target_zone("table"); + cmd.set_x(gridPoint.x()); + cmd.set_y(gridPoint.y()); + } + sendGameCommand(cmd); } void Player::addCard(CardItem *c) { - emit newCardAdded(c); + emit newCardAdded(c); } void Player::deleteCard(CardItem *c) { - if (dialogSemaphore) - cardsToDelete.append(c); - else - c->deleteLater(); + if (dialogSemaphore) + cardsToDelete.append(c); + else + c->deleteLater(); } void Player::addZone(CardZone *z) { - zones.insert(z->getName(), z); + zones.insert(z->getName(), z); } AbstractCounter *Player::addCounter(const ServerInfo_Counter &counter) { - return addCounter(counter.id(), QString::fromStdString(counter.name()), convertColorToQColor(counter.counter_color()), counter.radius(), counter.count()); + return addCounter(counter.id(), QString::fromStdString(counter.name()), convertColorToQColor(counter.counter_color()), counter.radius(), counter.count()); } AbstractCounter *Player::addCounter(int counterId, const QString &name, QColor color, int radius, int value) { - qDebug() << "addCounter:" << getName() << counterId << name; - if (counters.contains(counterId)) - return 0; - - AbstractCounter *c; - if (name == "life") - c = playerTarget->addCounter(counterId, name, value); - else - c = new GeneralCounter(this, counterId, name, color, radius, value, this); - counters.insert(counterId, c); - if (countersMenu) - countersMenu->addMenu(c->getMenu()); - if (shortcutsActive) - c->setShortcutsActive(); - rearrangeCounters(); - return c; + qDebug() << "addCounter:" << getName() << counterId << name; + if (counters.contains(counterId)) + return 0; + + AbstractCounter *c; + if (name == "life") + c = playerTarget->addCounter(counterId, name, value); + else + c = new GeneralCounter(this, counterId, name, color, radius, value, this); + counters.insert(counterId, c); + if (countersMenu) + countersMenu->addMenu(c->getMenu()); + if (shortcutsActive) + c->setShortcutsActive(); + rearrangeCounters(); + return c; } void Player::delCounter(int counterId) { - AbstractCounter *c = counters.value(counterId, 0); - if (!c) - return; - - c->delCounter(); - counters.remove(counterId); - rearrangeCounters(); + AbstractCounter *c = counters.value(counterId, 0); + if (!c) + return; + + c->delCounter(); + counters.remove(counterId); + rearrangeCounters(); } void Player::clearCounters() { - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) - counterIterator.next().value()->delCounter(); - counters.clear(); + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) + counterIterator.next().value()->delCounter(); + counters.clear(); } ArrowItem *Player::addArrow(const ServerInfo_Arrow &arrow) { - const QMap &playerList = game->getPlayers(); - Player *startPlayer = playerList.value(arrow.start_player_id(), 0); - Player *targetPlayer = playerList.value(arrow.target_player_id(), 0); - if (!startPlayer || !targetPlayer) - return 0; - - CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(arrow.start_zone()), 0); - CardZone *targetZone = 0; - if (arrow.has_target_zone()) - targetZone = targetPlayer->getZones().value(QString::fromStdString(arrow.target_zone()), 0); - if (!startZone || (!targetZone && arrow.has_target_zone())) - return 0; - - CardItem *startCard = startZone->getCard(arrow.start_card_id(), QString()); - CardItem *targetCard = 0; - if (targetZone) - targetCard = targetZone->getCard(arrow.target_card_id(), QString()); - if (!startCard || (!targetCard && arrow.has_target_card_id())) - return 0; - - if (targetCard) - return addArrow(arrow.id(), startCard, targetCard, convertColorToQColor(arrow.arrow_color())); - else - return addArrow(arrow.id(), startCard, targetPlayer->getPlayerTarget(), convertColorToQColor(arrow.arrow_color())); + const QMap &playerList = game->getPlayers(); + Player *startPlayer = playerList.value(arrow.start_player_id(), 0); + Player *targetPlayer = playerList.value(arrow.target_player_id(), 0); + if (!startPlayer || !targetPlayer) + return 0; + + CardZone *startZone = startPlayer->getZones().value(QString::fromStdString(arrow.start_zone()), 0); + CardZone *targetZone = 0; + if (arrow.has_target_zone()) + targetZone = targetPlayer->getZones().value(QString::fromStdString(arrow.target_zone()), 0); + if (!startZone || (!targetZone && arrow.has_target_zone())) + return 0; + + CardItem *startCard = startZone->getCard(arrow.start_card_id(), QString()); + CardItem *targetCard = 0; + if (targetZone) + targetCard = targetZone->getCard(arrow.target_card_id(), QString()); + if (!startCard || (!targetCard && arrow.has_target_card_id())) + return 0; + + if (targetCard) + return addArrow(arrow.id(), startCard, targetCard, convertColorToQColor(arrow.arrow_color())); + else + return addArrow(arrow.id(), startCard, targetPlayer->getPlayerTarget(), convertColorToQColor(arrow.arrow_color())); } ArrowItem *Player::addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color) { - ArrowItem *arrow = new ArrowItem(this, arrowId, startCard, targetItem, color); - arrows.insert(arrowId, arrow); - scene()->addItem(arrow); - return arrow; + ArrowItem *arrow = new ArrowItem(this, arrowId, startCard, targetItem, color); + arrows.insert(arrowId, arrow); + scene()->addItem(arrow); + return arrow; } void Player::delArrow(int arrowId) { - ArrowItem *a = arrows.value(arrowId, 0); - if (!a) - return; - a->delArrow(); + ArrowItem *a = arrows.value(arrowId, 0); + if (!a) + return; + a->delArrow(); } void Player::removeArrow(ArrowItem *arrow) { - if (arrow->getId() != -1) - arrows.remove(arrow->getId()); + if (arrow->getId() != -1) + arrows.remove(arrow->getId()); } void Player::clearArrows() { - QMapIterator arrowIterator(arrows); - while (arrowIterator.hasNext()) - arrowIterator.next().value()->delArrow(); - arrows.clear(); + QMapIterator arrowIterator(arrows); + while (arrowIterator.hasNext()) + arrowIterator.next().value()->delArrow(); + arrows.clear(); } void Player::rearrangeCounters() { - qreal marginTop = 80; - - // Determine total height of bounding rectangles - qreal totalHeight = 0; - QMapIterator counterIterator(counters); - while (counterIterator.hasNext()) { - counterIterator.next(); - if (counterIterator.value()->getShownInCounterArea()) - totalHeight += counterIterator.value()->boundingRect().height(); - } - - const qreal padding = 5; - qreal y = boundingRect().y() + marginTop; - - // Place objects - for (counterIterator.toFront(); counterIterator.hasNext(); ) { - AbstractCounter *c = counterIterator.next().value(); + qreal marginTop = 80; + + // Determine total height of bounding rectangles + qreal totalHeight = 0; + QMapIterator counterIterator(counters); + while (counterIterator.hasNext()) { + counterIterator.next(); + if (counterIterator.value()->getShownInCounterArea()) + totalHeight += counterIterator.value()->boundingRect().height(); + } + + const qreal padding = 5; + qreal y = boundingRect().y() + marginTop; + + // Place objects + for (counterIterator.toFront(); counterIterator.hasNext(); ) { + AbstractCounter *c = counterIterator.next().value(); - if (!c->getShownInCounterArea()) - continue; - - QRectF br = c->boundingRect(); - c->setPos((counterAreaWidth - br.width()) / 2, y); - y += br.height() + padding; - } + if (!c->getShownInCounterArea()) + continue; + + QRectF br = c->boundingRect(); + c->setPos((counterAreaWidth - br.width()) / 2, y); + y += br.height() + padding; + } } PendingCommand * Player::prepareGameCommand(const google::protobuf::Message &cmd) { - return game->prepareGameCommand(cmd); + return game->prepareGameCommand(cmd); } PendingCommand * Player::prepareGameCommand(const QList &cmdList) { - return game->prepareGameCommand(cmdList); + return game->prepareGameCommand(cmdList); } void Player::sendGameCommand(const google::protobuf::Message &command) { - game->sendGameCommand(command, id); + game->sendGameCommand(command, id); } void Player::sendGameCommand(PendingCommand *pend) { - game->sendGameCommand(pend, id); + game->sendGameCommand(pend, id); } bool Player::clearCardsToDelete() { - if (cardsToDelete.isEmpty()) - return false; - - for (int i = 0; i < cardsToDelete.size(); ++i) - cardsToDelete[i]->deleteLater(); - cardsToDelete.clear(); - - return true; + if (cardsToDelete.isEmpty()) + return false; + + for (int i = 0; i < cardsToDelete.size(); ++i) + cardsToDelete[i]->deleteLater(); + cardsToDelete.clear(); + + return true; } void Player::cardMenuAction() { - QAction *a = static_cast(sender()); - QList sel = scene()->selectedItems(); - QList cardList; - while (!sel.isEmpty()) - cardList.append(qgraphicsitem_cast(sel.takeFirst())); - - QList< const ::google::protobuf::Message * > commandList; - if (a->data().toInt() <= (int) cmClone) - for (int i = 0; i < cardList.size(); ++i) { - CardItem *card = cardList[i]; - switch (static_cast(a->data().toInt())) { - case cmTap: - if (!card->getTapped()) { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrTapped); - cmd->set_attr_value("1"); - commandList.append(cmd); - } - break; - case cmUntap: - if (card->getTapped()) { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrTapped); - cmd->set_attr_value("0"); - commandList.append(cmd); - } - break; - case cmDoesntUntap: { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrDoesntUntap); - cmd->set_attr_value(card->getDoesntUntap() ? "0" : "1"); - commandList.append(cmd); - break; - } - case cmFlip: { - Command_FlipCard *cmd = new Command_FlipCard; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_face_down(!card->getFaceDown()); - commandList.append(cmd); - break; - } - case cmPeek: { - Command_RevealCards *cmd = new Command_RevealCards; - cmd->set_zone_name(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_player_id(id); - commandList.append(cmd); - break; - } - case cmClone: { - Command_CreateToken *cmd = new Command_CreateToken; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_name(card->getName().toStdString()); - cmd->set_color(card->getColor().toStdString()); - cmd->set_pt(card->getPT().toStdString()); - cmd->set_annotation(card->getAnnotation().toStdString()); - cmd->set_destroy_on_zone_change(true); - cmd->set_x(-1); - cmd->set_y(card->getGridPoint().y()); - commandList.append(cmd); - break; - } - } - } - else { - ListOfCardsToMove idList; - for (int i = 0; i < cardList.size(); ++i) - idList.add_card()->set_card_id(cardList[i]->getId()); - int startPlayerId = cardList[0]->getZone()->getPlayer()->getId(); - QString startZone = cardList[0]->getZone()->getName(); - - switch (static_cast(a->data().toInt())) { - case cmMoveToTopLibrary: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("deck"); - cmd->set_x(0); - cmd->set_y(0); - commandList.append(cmd); - break; - } - case cmMoveToBottomLibrary: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("deck"); - cmd->set_x(-1); - cmd->set_y(0); - commandList.append(cmd); - break; - } - case cmMoveToGraveyard: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("grave"); - cmd->set_x(0); - cmd->set_y(0); - commandList.append(cmd); - break; - } - case cmMoveToExile: { - Command_MoveCard *cmd = new Command_MoveCard; - cmd->set_start_player_id(startPlayerId); - cmd->set_start_zone(startZone.toStdString()); - cmd->mutable_cards_to_move()->CopyFrom(idList); - cmd->set_target_player_id(getId()); - cmd->set_target_zone("rfg"); - cmd->set_x(0); - cmd->set_y(0); - commandList.append(cmd); - break; - } - default: ; - } - } - game->sendGameCommand(prepareGameCommand(commandList)); + QAction *a = static_cast(sender()); + QList sel = scene()->selectedItems(); + QList cardList; + while (!sel.isEmpty()) + cardList.append(qgraphicsitem_cast(sel.takeFirst())); + + QList< const ::google::protobuf::Message * > commandList; + if (a->data().toInt() <= (int) cmClone) + for (int i = 0; i < cardList.size(); ++i) { + CardItem *card = cardList[i]; + switch (static_cast(a->data().toInt())) { + case cmTap: + if (!card->getTapped()) { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrTapped); + cmd->set_attr_value("1"); + commandList.append(cmd); + } + break; + case cmUntap: + if (card->getTapped()) { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrTapped); + cmd->set_attr_value("0"); + commandList.append(cmd); + } + break; + case cmDoesntUntap: { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrDoesntUntap); + cmd->set_attr_value(card->getDoesntUntap() ? "0" : "1"); + commandList.append(cmd); + break; + } + case cmFlip: { + Command_FlipCard *cmd = new Command_FlipCard; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_face_down(!card->getFaceDown()); + commandList.append(cmd); + break; + } + case cmPeek: { + Command_RevealCards *cmd = new Command_RevealCards; + cmd->set_zone_name(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_player_id(id); + commandList.append(cmd); + break; + } + case cmClone: { + Command_CreateToken *cmd = new Command_CreateToken; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_name(card->getName().toStdString()); + cmd->set_color(card->getColor().toStdString()); + cmd->set_pt(card->getPT().toStdString()); + cmd->set_annotation(card->getAnnotation().toStdString()); + cmd->set_destroy_on_zone_change(true); + cmd->set_x(-1); + cmd->set_y(card->getGridPoint().y()); + commandList.append(cmd); + break; + } + default: break; + } + } + else { + ListOfCardsToMove idList; + for (int i = 0; i < cardList.size(); ++i) + idList.add_card()->set_card_id(cardList[i]->getId()); + int startPlayerId = cardList[0]->getZone()->getPlayer()->getId(); + QString startZone = cardList[0]->getZone()->getName(); + + switch (static_cast(a->data().toInt())) { + case cmMoveToTopLibrary: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("deck"); + cmd->set_x(0); + cmd->set_y(0); + commandList.append(cmd); + break; + } + case cmMoveToBottomLibrary: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("deck"); + cmd->set_x(-1); + cmd->set_y(0); + commandList.append(cmd); + break; + } + case cmMoveToGraveyard: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("grave"); + cmd->set_x(0); + cmd->set_y(0); + commandList.append(cmd); + break; + } + case cmMoveToExile: { + Command_MoveCard *cmd = new Command_MoveCard; + cmd->set_start_player_id(startPlayerId); + cmd->set_start_zone(startZone.toStdString()); + cmd->mutable_cards_to_move()->CopyFrom(idList); + cmd->set_target_player_id(getId()); + cmd->set_target_zone("rfg"); + cmd->set_x(0); + cmd->set_y(0); + commandList.append(cmd); + break; + } + default: ; + } + } + game->sendGameCommand(prepareGameCommand(commandList)); } void Player::actIncPT(int deltaP, int deltaT) { - QString ptString = "+" + QString::number(deltaP) + "/+" + QString::number(deltaT); - - QList< const ::google::protobuf::Message * > commandList; - QListIterator j(scene()->selectedItems()); - while (j.hasNext()) { - CardItem *card = static_cast(j.next()); - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrPT); - cmd->set_attr_value(ptString.toStdString()); - commandList.append(cmd); - } - sendGameCommand(prepareGameCommand(commandList)); + QString ptString = "+" + QString::number(deltaP) + "/+" + QString::number(deltaT); + + QList< const ::google::protobuf::Message * > commandList; + QListIterator j(scene()->selectedItems()); + while (j.hasNext()) { + CardItem *card = static_cast(j.next()); + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrPT); + cmd->set_attr_value(ptString.toStdString()); + commandList.append(cmd); + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actSetPT() { - QString oldPT; - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (!card->getPT().isEmpty()) - oldPT = card->getPT(); - } - bool ok; - dialogSemaphore = true; - QString pt = QInputDialog::getText(0, tr("Set power/toughness"), tr("Please enter the new PT:"), QLineEdit::Normal, oldPT, &ok); - dialogSemaphore = false; - if (clearCardsToDelete()) - return; - if (!ok) - return; - - QList< const ::google::protobuf::Message * > commandList; - QListIterator j(scene()->selectedItems()); - while (j.hasNext()) { - CardItem *card = static_cast(j.next()); - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrPT); - cmd->set_attr_value(pt.toStdString()); - commandList.append(cmd); - } - sendGameCommand(prepareGameCommand(commandList)); + QString oldPT; + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (!card->getPT().isEmpty()) + oldPT = card->getPT(); + } + bool ok; + dialogSemaphore = true; + QString pt = QInputDialog::getText(0, tr("Set power/toughness"), tr("Please enter the new PT:"), QLineEdit::Normal, oldPT, &ok); + dialogSemaphore = false; + if (clearCardsToDelete()) + return; + if (!ok) + return; + + QList< const ::google::protobuf::Message * > commandList; + QListIterator j(scene()->selectedItems()); + while (j.hasNext()) { + CardItem *card = static_cast(j.next()); + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrPT); + cmd->set_attr_value(pt.toStdString()); + commandList.append(cmd); + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actDrawArrow() { - game->getActiveCard()->drawArrow(Qt::red); + game->getActiveCard()->drawArrow(Qt::red); } void Player::actIncP() { - actIncPT(1, 0); + actIncPT(1, 0); } void Player::actDecP() { - actIncPT(-1, 0); + actIncPT(-1, 0); } void Player::actIncT() { - actIncPT(0, 1); + actIncPT(0, 1); } void Player::actDecT() { - actIncPT(0, -1); + actIncPT(0, -1); } void Player::actIncPT() { - actIncPT(1, 1); + actIncPT(1, 1); } void Player::actDecPT() { - actIncPT(-1, -1); + actIncPT(-1, -1); } void Player::actSetAnnotation() { - QString oldAnnotation; - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (!card->getAnnotation().isEmpty()) - oldAnnotation = card->getAnnotation(); - } - - bool ok; - dialogSemaphore = true; - QString annotation = QInputDialog::getText(0, tr("Set annotation"), tr("Please enter the new annotation:"), QLineEdit::Normal, oldAnnotation, &ok); - dialogSemaphore = false; - if (clearCardsToDelete()) - return; - if (!ok) - return; - - QList< const ::google::protobuf::Message * > commandList; - i.toFront(); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_attribute(AttrAnnotation); - cmd->set_attr_value(annotation.toStdString()); - commandList.append(cmd); - } - sendGameCommand(prepareGameCommand(commandList)); + QString oldAnnotation; + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (!card->getAnnotation().isEmpty()) + oldAnnotation = card->getAnnotation(); + } + + bool ok; + dialogSemaphore = true; + QString annotation = QInputDialog::getText(0, tr("Set annotation"), tr("Please enter the new annotation:"), QLineEdit::Normal, oldAnnotation, &ok); + dialogSemaphore = false; + if (clearCardsToDelete()) + return; + if (!ok) + return; + + QList< const ::google::protobuf::Message * > commandList; + i.toFront(); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_attribute(AttrAnnotation); + cmd->set_attr_value(annotation.toStdString()); + commandList.append(cmd); + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actAttach() { - ArrowAttachItem *arrow = new ArrowAttachItem(game->getActiveCard()); - scene()->addItem(arrow); - arrow->grabMouse(); + ArrowAttachItem *arrow = new ArrowAttachItem(game->getActiveCard()); + scene()->addItem(arrow); + arrow->grabMouse(); } void Player::actUnattach() { - Command_AttachCard cmd; - cmd.set_start_zone(game->getActiveCard()->getZone()->getName().toStdString()); - cmd.set_card_id(game->getActiveCard()->getId()); - sendGameCommand(cmd); + Command_AttachCard cmd; + cmd.set_start_zone(game->getActiveCard()->getZone()->getName().toStdString()); + cmd.set_card_id(game->getActiveCard()->getId()); + sendGameCommand(cmd); } void Player::actCardCounterTrigger() { - QAction *a = static_cast(sender()); - int counterId = a->data().toInt() / 1000; - int action = a->data().toInt() % 1000; - QList< const ::google::protobuf::Message * > commandList; - switch (action) { - case 9: { - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (card->getCounters().value(counterId, 0) < MAX_COUNTERS_ON_CARD) { - Command_SetCardCounter *cmd = new Command_SetCardCounter; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_counter_id(counterId); - cmd->set_counter_value(card->getCounters().value(counterId, 0) + 1); - commandList.append(cmd); - } - } - break; - } - case 10: { - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - if (card->getCounters().value(counterId, 0)) { - Command_SetCardCounter *cmd = new Command_SetCardCounter; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_counter_id(counterId); - cmd->set_counter_value(card->getCounters().value(counterId, 0) - 1); - commandList.append(cmd); - } - } - break; - } - case 11: { - bool ok; - dialogSemaphore = true; - int number = QInputDialog::getInteger(0, tr("Set counters"), tr("Number:"), 0, 0, MAX_COUNTERS_ON_CARD, 1, &ok); - dialogSemaphore = false; - if (clearCardsToDelete()) - return; - if (!ok) - return; - - QListIterator i(scene()->selectedItems()); - while (i.hasNext()) { - CardItem *card = static_cast(i.next()); - Command_SetCardCounter *cmd = new Command_SetCardCounter; - cmd->set_zone(card->getZone()->getName().toStdString()); - cmd->set_card_id(card->getId()); - cmd->set_counter_id(counterId); - cmd->set_counter_value(number); - commandList.append(cmd); - } - break; - } - default: ; - } - sendGameCommand(prepareGameCommand(commandList)); + QAction *a = static_cast(sender()); + int counterId = a->data().toInt() / 1000; + int action = a->data().toInt() % 1000; + QList< const ::google::protobuf::Message * > commandList; + switch (action) { + case 9: { + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (card->getCounters().value(counterId, 0) < MAX_COUNTERS_ON_CARD) { + Command_SetCardCounter *cmd = new Command_SetCardCounter; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_counter_id(counterId); + cmd->set_counter_value(card->getCounters().value(counterId, 0) + 1); + commandList.append(cmd); + } + } + break; + } + case 10: { + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + if (card->getCounters().value(counterId, 0)) { + Command_SetCardCounter *cmd = new Command_SetCardCounter; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_counter_id(counterId); + cmd->set_counter_value(card->getCounters().value(counterId, 0) - 1); + commandList.append(cmd); + } + } + break; + } + case 11: { + bool ok; + dialogSemaphore = true; + int number = QInputDialog::getInteger(0, tr("Set counters"), tr("Number:"), 0, 0, MAX_COUNTERS_ON_CARD, 1, &ok); + dialogSemaphore = false; + if (clearCardsToDelete()) + return; + if (!ok) + return; + + QListIterator i(scene()->selectedItems()); + while (i.hasNext()) { + CardItem *card = static_cast(i.next()); + Command_SetCardCounter *cmd = new Command_SetCardCounter; + cmd->set_zone(card->getZone()->getName().toStdString()); + cmd->set_card_id(card->getId()); + cmd->set_counter_id(counterId); + cmd->set_counter_value(number); + commandList.append(cmd); + } + break; + } + default: ; + } + sendGameCommand(prepareGameCommand(commandList)); } void Player::actPlay() { - playCard(game->getActiveCard(), false, game->getActiveCard()->getInfo()->getCipt()); + playCard(game->getActiveCard(), false, game->getActiveCard()->getInfo()->getCipt()); } void Player::actHide() { - game->getActiveCard()->getZone()->removeCard(game->getActiveCard()); + game->getActiveCard()->getZone()->removeCard(game->getActiveCard()); } void Player::updateCardMenu(CardItem *card) { - QMenu *cardMenu = card->getCardMenu(); - QMenu *ptMenu = card->getPTMenu(); - QMenu *moveMenu = card->getMoveMenu(); - - cardMenu->clear(); - - bool revealedCard = false; - bool writeableCard = getLocal(); - if (card->getZone()) - if (card->getZone()->getIsView()) { - ZoneViewZone *view = static_cast(card->getZone()); - if (view->getRevealZone()) { - if (view->getWriteableRevealZone()) - writeableCard = true; - else - revealedCard = true; - } - } - - if (revealedCard) - cardMenu->addAction(aHide); - else if (writeableCard) { - if (moveMenu->isEmpty()) { - moveMenu->addAction(aMoveToTopLibrary); - moveMenu->addAction(aMoveToBottomLibrary); - moveMenu->addAction(aMoveToGraveyard); - moveMenu->addAction(aMoveToExile); - } - - if (card->getZone()) { - if (card->getZone()->getName() == "table") { - if (ptMenu->isEmpty()) { - ptMenu->addAction(aIncP); - ptMenu->addAction(aDecP); - ptMenu->addSeparator(); - ptMenu->addAction(aIncT); - ptMenu->addAction(aDecT); - ptMenu->addSeparator(); - ptMenu->addAction(aIncPT); - ptMenu->addAction(aDecPT); - ptMenu->addSeparator(); - ptMenu->addAction(aSetPT); - } - - cardMenu->addAction(aTap); - cardMenu->addAction(aUntap); - cardMenu->addAction(aDoesntUntap); - cardMenu->addAction(aFlip); - if (card->getFaceDown()) - cardMenu->addAction(aPeek); - cardMenu->addSeparator(); - cardMenu->addAction(aAttach); - if (card->getAttachedTo()) - cardMenu->addAction(aUnattach); - cardMenu->addAction(aDrawArrow); - cardMenu->addSeparator(); - cardMenu->addMenu(ptMenu); - cardMenu->addAction(aSetAnnotation); - cardMenu->addSeparator(); - cardMenu->addAction(aClone); - cardMenu->addMenu(moveMenu); - - for (int i = 0; i < aAddCounter.size(); ++i) { - cardMenu->addSeparator(); - cardMenu->addAction(aAddCounter[i]); - cardMenu->addAction(aRemoveCounter[i]); - cardMenu->addAction(aSetCounter[i]); - } - cardMenu->addSeparator(); - } else if (card->getZone()->getName() == "stack") { - cardMenu->addAction(aDrawArrow); - cardMenu->addMenu(moveMenu); - } else { - cardMenu->addAction(aPlay); - cardMenu->addMenu(moveMenu); - } - } else - cardMenu->addMenu(moveMenu); - } + QMenu *cardMenu = card->getCardMenu(); + QMenu *ptMenu = card->getPTMenu(); + QMenu *moveMenu = card->getMoveMenu(); + + cardMenu->clear(); + + bool revealedCard = false; + bool writeableCard = getLocal(); + if (card->getZone()) + if (card->getZone()->getIsView()) { + ZoneViewZone *view = static_cast(card->getZone()); + if (view->getRevealZone()) { + if (view->getWriteableRevealZone()) + writeableCard = true; + else + revealedCard = true; + } + } + + if (revealedCard) + cardMenu->addAction(aHide); + else if (writeableCard) { + if (moveMenu->isEmpty()) { + moveMenu->addAction(aMoveToTopLibrary); + moveMenu->addAction(aMoveToBottomLibrary); + moveMenu->addAction(aMoveToGraveyard); + moveMenu->addAction(aMoveToExile); + } + + if (card->getZone()) { + if (card->getZone()->getName() == "table") { + if (ptMenu->isEmpty()) { + ptMenu->addAction(aIncP); + ptMenu->addAction(aDecP); + ptMenu->addSeparator(); + ptMenu->addAction(aIncT); + ptMenu->addAction(aDecT); + ptMenu->addSeparator(); + ptMenu->addAction(aIncPT); + ptMenu->addAction(aDecPT); + ptMenu->addSeparator(); + ptMenu->addAction(aSetPT); + } + + cardMenu->addAction(aTap); + cardMenu->addAction(aUntap); + cardMenu->addAction(aDoesntUntap); + cardMenu->addAction(aFlip); + if (card->getFaceDown()) + cardMenu->addAction(aPeek); + cardMenu->addSeparator(); + cardMenu->addAction(aAttach); + if (card->getAttachedTo()) + cardMenu->addAction(aUnattach); + cardMenu->addAction(aDrawArrow); + cardMenu->addSeparator(); + cardMenu->addMenu(ptMenu); + cardMenu->addAction(aSetAnnotation); + cardMenu->addSeparator(); + cardMenu->addAction(aClone); + cardMenu->addMenu(moveMenu); + + for (int i = 0; i < aAddCounter.size(); ++i) { + cardMenu->addSeparator(); + cardMenu->addAction(aAddCounter[i]); + cardMenu->addAction(aRemoveCounter[i]); + cardMenu->addAction(aSetCounter[i]); + } + cardMenu->addSeparator(); + } else if (card->getZone()->getName() == "stack") { + cardMenu->addAction(aDrawArrow); + cardMenu->addMenu(moveMenu); + } else { + cardMenu->addAction(aPlay); + cardMenu->addMenu(moveMenu); + } + } else + cardMenu->addMenu(moveMenu); + } } void Player::setCardMenu(QMenu *menu) { - if (aCardMenu) - aCardMenu->setMenu(menu); + if (aCardMenu) + aCardMenu->setMenu(menu); } QMenu *Player::getCardMenu() const { - if (aCardMenu) - return aCardMenu->menu(); - return 0; + if (aCardMenu) + return aCardMenu->menu(); + return 0; } QString Player::getName() const { - return QString::fromStdString(userInfo->name()); + return QString::fromStdString(userInfo->name()); } qreal Player::getMinimumWidth() const { - qreal result = table->getMinimumWidth() + CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); - if (!settingsCache->getHorizontalHand()) - result += hand->boundingRect().width(); - return result; + qreal result = table->getMinimumWidth() + CARD_HEIGHT + 15 + counterAreaWidth + stack->boundingRect().width(); + if (!settingsCache->getHorizontalHand()) + result += hand->boundingRect().width(); + return result; } void Player::setConceded(bool _conceded) { - conceded = _conceded; - setVisible(!conceded); - if (conceded) { - clear(); - emit gameConceded(); - } + conceded = _conceded; + setVisible(!conceded); + if (conceded) { + clear(); + emit gameConceded(); + } } void Player::setMirrored(bool _mirrored) { - if (mirrored != _mirrored) { - mirrored = _mirrored; - rearrangeZones(); - } + if (mirrored != _mirrored) { + mirrored = _mirrored; + rearrangeZones(); + } } void Player::processSceneSizeChange(int newPlayerWidth) { - qreal tableWidth = newPlayerWidth - CARD_HEIGHT - 15 - counterAreaWidth - stack->boundingRect().width(); - if (!settingsCache->getHorizontalHand()) - tableWidth -= hand->boundingRect().width(); - - table->setWidth(tableWidth); - hand->setWidth(tableWidth + stack->boundingRect().width()); + qreal tableWidth = newPlayerWidth - CARD_HEIGHT - 15 - counterAreaWidth - stack->boundingRect().width(); + if (!settingsCache->getHorizontalHand()) + tableWidth -= hand->boundingRect().width(); + + table->setWidth(tableWidth); + hand->setWidth(tableWidth + stack->boundingRect().width()); } diff --git a/cockatrice/src/player.h b/cockatrice/src/player.h index f55d0fd7..9eed7c07 100644 --- a/cockatrice/src/player.h +++ b/cockatrice/src/player.h @@ -57,246 +57,246 @@ class Event_ChangeZoneProperties; class PendingCommand; class PlayerArea : public QObject, public QGraphicsItem { - Q_OBJECT -private: - QBrush bgPixmapBrush; - QRectF bRect; + Q_OBJECT +private: + QBrush bgPixmapBrush; + QRectF bRect; private slots: - void updateBgPixmap(); + void updateBgPixmap(); public: - enum { Type = typeOther }; - int type() const { return Type; } - - PlayerArea(QGraphicsItem *parent = 0); - QRectF boundingRect() const { return bRect; } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - - void setSize(qreal width, qreal height); + enum { Type = typeOther }; + int type() const { return Type; } + + PlayerArea(QGraphicsItem *parent = 0); + QRectF boundingRect() const { return bRect; } + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + + void setSize(qreal width, qreal height); }; class Player : public QObject, public QGraphicsItem { - Q_OBJECT + Q_OBJECT signals: - void openDeckEditor(const DeckLoader *deck); - void newCardAdded(AbstractCardItem *card); - // Log events - void logSay(Player *player, QString message); - void logShuffle(Player *player, CardZone *zone); - void logRollDie(Player *player, int sides, int roll); - void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool _playerTarget); - void logCreateToken(Player *player, QString cardName, QString pt); - void logDrawCards(Player *player, int number); - void logUndoDraw(Player *player, QString cardName); - void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); - void logFlipCard(Player *player, QString cardName, bool faceDown); - void logDestroyCard(Player *player, QString cardName); - void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); - void logUnattachCard(Player *player, QString cardName); - void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); - void logSetTapped(Player *player, CardItem *card, bool tapped); - void logSetCounter(Player *player, QString counterName, int value, int oldValue); - void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); - void logSetPT(Player *player, CardItem *card, QString newPT); - void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); - void logDumpZone(Player *player, CardZone *zone, int numberCards); - void logStopDumpZone(Player *player, CardZone *zone); - void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); - void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); - - void sizeChanged(); - void gameConceded(); + void openDeckEditor(const DeckLoader *deck); + void newCardAdded(AbstractCardItem *card); + // Log events + void logSay(Player *player, QString message); + void logShuffle(Player *player, CardZone *zone); + void logRollDie(Player *player, int sides, int roll); + void logCreateArrow(Player *player, Player *startPlayer, QString startCard, Player *targetPlayer, QString targetCard, bool _playerTarget); + void logCreateToken(Player *player, QString cardName, QString pt); + void logDrawCards(Player *player, int number); + void logUndoDraw(Player *player, QString cardName); + void logMoveCard(Player *player, CardItem *card, CardZone *startZone, int oldX, CardZone *targetZone, int newX); + void logFlipCard(Player *player, QString cardName, bool faceDown); + void logDestroyCard(Player *player, QString cardName); + void logAttachCard(Player *player, QString cardName, Player *targetPlayer, QString targetCardName); + void logUnattachCard(Player *player, QString cardName); + void logSetCardCounter(Player *player, QString cardName, int counterId, int value, int oldValue); + void logSetTapped(Player *player, CardItem *card, bool tapped); + void logSetCounter(Player *player, QString counterName, int value, int oldValue); + void logSetDoesntUntap(Player *player, CardItem *card, bool doesntUntap); + void logSetPT(Player *player, CardItem *card, QString newPT); + void logSetAnnotation(Player *player, CardItem *card, QString newAnnotation); + void logDumpZone(Player *player, CardZone *zone, int numberCards); + void logStopDumpZone(Player *player, CardZone *zone); + void logRevealCards(Player *player, CardZone *zone, int cardId, QString cardName, Player *otherPlayer, bool faceDown); + void logAlwaysRevealTopCard(Player *player, CardZone *zone, bool reveal); + + void sizeChanged(); + void gameConceded(); public slots: - void actUntapAll(); - void actRollDie(); - void actCreateToken(); - void actCreateAnotherToken(); - void actShuffle(); - void actDrawCard(); - void actDrawCards(); - void actUndoDraw(); + void actUntapAll(); + void actRollDie(); + void actCreateToken(); + void actCreateAnotherToken(); + void actShuffle(); + void actDrawCard(); + void actDrawCards(); + void actUndoDraw(); void actMulligan(); - void actMoveTopCardsToGrave(); - void actMoveTopCardsToExile(); - void actMoveTopCardToBottom(); + void actMoveTopCardsToGrave(); + void actMoveTopCardsToExile(); + void actMoveTopCardToBottom(); - void actViewLibrary(); - void actViewTopCards(); - void actAlwaysRevealTopCard(); - void actViewGraveyard(); - void actViewRfg(); - void actViewSideboard(); - - void actSayMessage(); + void actViewLibrary(); + void actViewTopCards(); + void actAlwaysRevealTopCard(); + void actViewGraveyard(); + void actViewRfg(); + void actViewSideboard(); + + void actSayMessage(); private slots: - void addPlayer(Player *player); - void removePlayer(Player *player); - void playerListActionTriggered(); - - void updateBoundingRect(); - void rearrangeZones(); - - void actOpenDeckInDeckEditor(); - void actCreatePredefinedToken(); - void cardMenuAction(); - void actCardCounterTrigger(); - void actAttach(); - void actUnattach(); - void actDrawArrow(); - void actIncPT(int deltaP, int deltaT); - void actSetPT(); - void actIncP(); - void actDecP(); - void actIncT(); - void actDecT(); - void actIncPT(); - void actDecPT(); - void actSetAnnotation(); - void actPlay(); - void actHide(); + void addPlayer(Player *player); + void removePlayer(Player *player); + void playerListActionTriggered(); + + void updateBoundingRect(); + void rearrangeZones(); + + void actOpenDeckInDeckEditor(); + void actCreatePredefinedToken(); + void cardMenuAction(); + void actCardCounterTrigger(); + void actAttach(); + void actUnattach(); + void actDrawArrow(); + void actIncPT(int deltaP, int deltaT); + void actSetPT(); + void actIncP(); + void actDecP(); + void actIncT(); + void actDecT(); + void actIncPT(); + void actDecPT(); + void actSetAnnotation(); + void actPlay(); + void actHide(); private: - TabGame *game; - QMenu *playerMenu, *handMenu, *graveMenu, *rfgMenu, *libraryMenu, *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu, - *mRevealLibrary, *mRevealTopCard, *mRevealHand, *mRevealRandomHandCard; - QList playerLists; - QList allPlayersActions; - QAction *aMoveHandToTopLibrary, *aMoveHandToBottomLibrary, *aMoveHandToGrave, *aMoveHandToRfg, - *aMoveGraveToTopLibrary, *aMoveGraveToBottomLibrary, *aMoveGraveToHand, *aMoveGraveToRfg, - *aMoveRfgToTopLibrary, *aMoveRfgToBottomLibrary, *aMoveRfgToHand, *aMoveRfgToGrave, - *aViewLibrary, *aViewTopCards, *aAlwaysRevealTopCard, *aOpenDeckInDeckEditor, *aMoveTopCardsToGrave, *aMoveTopCardsToExile, *aMoveTopCardToBottom, - *aViewGraveyard, *aViewRfg, *aViewSideboard, + TabGame *game; + QMenu *playerMenu, *handMenu, *graveMenu, *rfgMenu, *libraryMenu, *sbMenu, *countersMenu, *sayMenu, *createPredefinedTokenMenu, + *mRevealLibrary, *mRevealTopCard, *mRevealHand, *mRevealRandomHandCard; + QList playerLists; + QList allPlayersActions; + QAction *aMoveHandToTopLibrary, *aMoveHandToBottomLibrary, *aMoveHandToGrave, *aMoveHandToRfg, + *aMoveGraveToTopLibrary, *aMoveGraveToBottomLibrary, *aMoveGraveToHand, *aMoveGraveToRfg, + *aMoveRfgToTopLibrary, *aMoveRfgToBottomLibrary, *aMoveRfgToHand, *aMoveRfgToGrave, + *aViewLibrary, *aViewTopCards, *aAlwaysRevealTopCard, *aOpenDeckInDeckEditor, *aMoveTopCardsToGrave, *aMoveTopCardsToExile, *aMoveTopCardToBottom, + *aViewGraveyard, *aViewRfg, *aViewSideboard, *aDrawCard, *aDrawCards, *aUndoDraw, *aMulligan, *aShuffle, - *aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken, - *aCardMenu; - - QList aAddCounter, aSetCounter, aRemoveCounter; - QAction *aPlay, - *aHide, - *aTap, *aUntap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone, - *aMoveToTopLibrary, *aMoveToBottomLibrary, *aMoveToGraveyard, *aMoveToExile; + *aUntapAll, *aRollDie, *aCreateToken, *aCreateAnotherToken, + *aCardMenu; + + QList aAddCounter, aSetCounter, aRemoveCounter; + QAction *aPlay, + *aHide, + *aTap, *aUntap, *aDoesntUntap, *aAttach, *aUnattach, *aDrawArrow, *aSetPT, *aIncP, *aDecP, *aIncT, *aDecT, *aIncPT, *aDecPT, *aSetAnnotation, *aFlip, *aPeek, *aClone, + *aMoveToTopLibrary, *aMoveToBottomLibrary, *aMoveToGraveyard, *aMoveToExile; - bool shortcutsActive; - int defaultNumberTopCards; - QString lastTokenName, lastTokenColor, lastTokenPT, lastTokenAnnotation; - bool lastTokenDestroy; - ServerInfo_User *userInfo; - int id; - bool active; - bool local; - bool mirrored; - bool handVisible; - bool conceded; - - bool dialogSemaphore; - bool clearCardsToDelete(); - QList cardsToDelete; - - DeckLoader *deck; - QStringList predefinedTokens; - - PlayerArea *playerArea; - QMap zones; - StackZone *stack; - TableZone *table; - HandZone *hand; - PlayerTarget *playerTarget; - - void setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards); + bool shortcutsActive; + int defaultNumberTopCards; + QString lastTokenName, lastTokenColor, lastTokenPT, lastTokenAnnotation; + bool lastTokenDestroy; + ServerInfo_User *userInfo; + int id; + bool active; + bool local; + bool mirrored; + bool handVisible; + bool conceded; + + bool dialogSemaphore; + bool clearCardsToDelete(); + QList cardsToDelete; + + DeckLoader *deck; + QStringList predefinedTokens; + + PlayerArea *playerArea; + QMap zones; + StackZone *stack; + TableZone *table; + HandZone *hand; + PlayerTarget *playerTarget; + + void setCardAttrHelper(const GameEventContext &context, CardItem *card, CardAttribute attribute, const QString &avalue, bool allCards); - QRectF bRect; + QRectF bRect; - QMap counters; - QMap arrows; - void rearrangeCounters(); - - void initSayMenu(); - - void eventConnectionStateChanged(const Event_ConnectionStateChanged &event); - void eventGameSay(const Event_GameSay &event); - void eventShuffle(const Event_Shuffle &event); - void eventRollDie(const Event_RollDie &event); - void eventCreateArrow(const Event_CreateArrow &event); - void eventDeleteArrow(const Event_DeleteArrow &event); - void eventCreateToken(const Event_CreateToken &event); - void eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context); - void eventSetCardCounter(const Event_SetCardCounter &event); - void eventCreateCounter(const Event_CreateCounter &event); - void eventSetCounter(const Event_SetCounter &event); - void eventDelCounter(const Event_DelCounter &event); - void eventDumpZone(const Event_DumpZone &event); - void eventStopDumpZone(const Event_StopDumpZone &event); - void eventMoveCard(const Event_MoveCard &event, const GameEventContext &context); - void eventFlipCard(const Event_FlipCard &event); - void eventDestroyCard(const Event_DestroyCard &event); - void eventAttachCard(const Event_AttachCard &event); - void eventDrawCards(const Event_DrawCards &event); - void eventRevealCards(const Event_RevealCards &event); - void eventChangeZoneProperties(const Event_ChangeZoneProperties &event); + QMap counters; + QMap arrows; + void rearrangeCounters(); + + void initSayMenu(); + + void eventConnectionStateChanged(const Event_ConnectionStateChanged &event); + void eventGameSay(const Event_GameSay &event); + void eventShuffle(const Event_Shuffle &event); + void eventRollDie(const Event_RollDie &event); + void eventCreateArrow(const Event_CreateArrow &event); + void eventDeleteArrow(const Event_DeleteArrow &event); + void eventCreateToken(const Event_CreateToken &event); + void eventSetCardAttr(const Event_SetCardAttr &event, const GameEventContext &context); + void eventSetCardCounter(const Event_SetCardCounter &event); + void eventCreateCounter(const Event_CreateCounter &event); + void eventSetCounter(const Event_SetCounter &event); + void eventDelCounter(const Event_DelCounter &event); + void eventDumpZone(const Event_DumpZone &event); + void eventStopDumpZone(const Event_StopDumpZone &event); + void eventMoveCard(const Event_MoveCard &event, const GameEventContext &context); + void eventFlipCard(const Event_FlipCard &event); + void eventDestroyCard(const Event_DestroyCard &event); + void eventAttachCard(const Event_AttachCard &event); + void eventDrawCards(const Event_DrawCards &event); + void eventRevealCards(const Event_RevealCards &event); + void eventChangeZoneProperties(const Event_ChangeZoneProperties &event); public: - static const int counterAreaWidth = 55; - enum CardMenuActionType { cmTap, cmUntap, cmDoesntUntap, cmFlip, cmPeek, cmClone, cmMoveToTopLibrary, cmMoveToBottomLibrary, cmMoveToGraveyard, cmMoveToExile }; - - enum { Type = typeOther }; - int type() const { return Type; } - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - - void playCard(CardItem *c, bool faceDown, bool tapped); - void addCard(CardItem *c); - void deleteCard(CardItem *c); - void addZone(CardZone *z); + static const int counterAreaWidth = 55; + enum CardMenuActionType { cmTap, cmUntap, cmDoesntUntap, cmFlip, cmPeek, cmClone, cmMoveToTopLibrary, cmMoveToBottomLibrary, cmMoveToGraveyard, cmMoveToExile }; + + enum { Type = typeOther }; + int type() const { return Type; } + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + + void playCard(CardItem *c, bool faceDown, bool tapped); + void addCard(CardItem *c); + void deleteCard(CardItem *c); + void addZone(CardZone *z); - AbstractCounter *addCounter(const ServerInfo_Counter &counter); - AbstractCounter *addCounter(int counterId, const QString &name, QColor color, int radius, int value); - void delCounter(int counterId); - void clearCounters(); - - ArrowItem *addArrow(const ServerInfo_Arrow &arrow); - ArrowItem *addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color); - void delArrow(int arrowId); - void removeArrow(ArrowItem *arrow); - void clearArrows(); - PlayerTarget *getPlayerTarget() const { return playerTarget; } + AbstractCounter *addCounter(const ServerInfo_Counter &counter); + AbstractCounter *addCounter(int counterId, const QString &name, QColor color, int radius, int value); + void delCounter(int counterId); + void clearCounters(); + + ArrowItem *addArrow(const ServerInfo_Arrow &arrow); + ArrowItem *addArrow(int arrowId, CardItem *startCard, ArrowTarget *targetItem, const QColor &color); + void delArrow(int arrowId); + void removeArrow(ArrowItem *arrow); + void clearArrows(); + PlayerTarget *getPlayerTarget() const { return playerTarget; } - Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent); - ~Player(); - void retranslateUi(); - void clear(); - TabGame *getGame() const { return game; } - void setDeck(const DeckLoader &_deck); - QMenu *getPlayerMenu() const { return playerMenu; } - int getId() const { return id; } - QString getName() const; - ServerInfo_User *getUserInfo() const { return userInfo; } - bool getLocal() const { return local; } - bool getMirrored() const { return mirrored; } - const QMap &getZones() const { return zones; } - const QMap &getArrows() const { return arrows; } - void setCardMenu(QMenu *menu); - QMenu *getCardMenu() const; - void updateCardMenu(CardItem *card); - bool getActive() const { return active; } - void setActive(bool _active); - void setShortcutsActive(); - void setShortcutsInactive(); - void updateZones(); - - void setConceded(bool _conceded); - bool getConceded() const { return conceded; } - - qreal getMinimumWidth() const; - void setMirrored(bool _mirrored); - void processSceneSizeChange(int newPlayerWidth); - - void processPlayerInfo(const ServerInfo_Player &info); - void processCardAttachment(const ServerInfo_Player &info); - - void processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context); + Player(const ServerInfo_User &info, int _id, bool _local, TabGame *_parent); + ~Player(); + void retranslateUi(); + void clear(); + TabGame *getGame() const { return game; } + void setDeck(const DeckLoader &_deck); + QMenu *getPlayerMenu() const { return playerMenu; } + int getId() const { return id; } + QString getName() const; + ServerInfo_User *getUserInfo() const { return userInfo; } + bool getLocal() const { return local; } + bool getMirrored() const { return mirrored; } + const QMap &getZones() const { return zones; } + const QMap &getArrows() const { return arrows; } + void setCardMenu(QMenu *menu); + QMenu *getCardMenu() const; + void updateCardMenu(CardItem *card); + bool getActive() const { return active; } + void setActive(bool _active); + void setShortcutsActive(); + void setShortcutsInactive(); + void updateZones(); + + void setConceded(bool _conceded); + bool getConceded() const { return conceded; } + + qreal getMinimumWidth() const; + void setMirrored(bool _mirrored); + void processSceneSizeChange(int newPlayerWidth); + + void processPlayerInfo(const ServerInfo_Player &info); + void processCardAttachment(const ServerInfo_Player &info); + + void processGameEvent(GameEvent::GameEventType type, const GameEvent &event, const GameEventContext &context); - PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); - PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); - void sendGameCommand(PendingCommand *pend); - void sendGameCommand(const google::protobuf::Message &command); + PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); + PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); + void sendGameCommand(PendingCommand *pend); + void sendGameCommand(const google::protobuf::Message &command); }; #endif diff --git a/cockatrice/src/playerlistwidget.cpp b/cockatrice/src/playerlistwidget.cpp index 9c706ac9..f299cda9 100644 --- a/cockatrice/src/playerlistwidget.cpp +++ b/cockatrice/src/playerlistwidget.cpp @@ -17,63 +17,63 @@ #include "pb/serverinfo_playerproperties.pb.h" PlayerListItemDelegate::PlayerListItemDelegate(QObject *const parent) - : QStyledItemDelegate(parent) + : QStyledItemDelegate(parent) { } bool PlayerListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { - if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { - QMouseEvent *const mouseEvent = static_cast(event); - if (mouseEvent->button() == Qt::RightButton) { - static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); - return true; - } - } - return QStyledItemDelegate::editorEvent(event, model, option, index); + if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { + QMouseEvent *const mouseEvent = static_cast(event); + if (mouseEvent->button() == Qt::RightButton) { + static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); + return true; + } + } + return QStyledItemDelegate::editorEvent(event, model, option, index); } PlayerListTWI::PlayerListTWI() - : QTreeWidgetItem(Type) + : QTreeWidgetItem(Type) { } bool PlayerListTWI::operator<(const QTreeWidgetItem &other) const { - // Sort by spectator/player - if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole)) - return data(1, Qt::UserRole).toBool(); - - // Sort by player ID - return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt(); + // Sort by spectator/player + if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole)) + return data(1, Qt::UserRole).toBool(); + + // Sort by player ID + return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt(); } PlayerListWidget::PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent) - : QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false) + : QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false) { - readyIcon = QIcon(":/resources/icon_ready_start.svg"); - notReadyIcon = QIcon(":/resources/icon_not_ready_start.svg"); - concededIcon = QIcon(":/resources/icon_conceded.svg"); - playerIcon = QIcon(":/resources/icon_player.svg"); - spectatorIcon = QIcon(":/resources/icon_spectator.svg"); - lockIcon = QIcon(":/resources/lock.svg"); - - if (tabSupervisor) { - itemDelegate = new PlayerListItemDelegate(this); - setItemDelegate(itemDelegate); - - userContextMenu = new UserContextMenu(tabSupervisor, this, game); - connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - } else - userContextMenu = 0; - - setMinimumHeight(60); - setIconSize(QSize(20, 15)); - setColumnCount(6); - setHeaderHidden(true); - setRootIsDecorated(false); - header()->setResizeMode(QHeaderView::ResizeToContents); - retranslateUi(); + readyIcon = QIcon(":/resources/icon_ready_start.svg"); + notReadyIcon = QIcon(":/resources/icon_not_ready_start.svg"); + concededIcon = QIcon(":/resources/icon_conceded.svg"); + playerIcon = QIcon(":/resources/icon_player.svg"); + spectatorIcon = QIcon(":/resources/icon_spectator.svg"); + lockIcon = QIcon(":/resources/lock.svg"); + + if (tabSupervisor) { + itemDelegate = new PlayerListItemDelegate(this); + setItemDelegate(itemDelegate); + + userContextMenu = new UserContextMenu(tabSupervisor, this, game); + connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + } else + userContextMenu = 0; + + setMinimumHeight(60); + setIconSize(QSize(20, 15)); + setColumnCount(6); + setHeaderHidden(true); + setRootIsDecorated(false); + header()->setResizeMode(QHeaderView::ResizeToContents); + retranslateUi(); } void PlayerListWidget::retranslateUi() @@ -82,97 +82,97 @@ void PlayerListWidget::retranslateUi() void PlayerListWidget::addPlayer(const ServerInfo_PlayerProperties &player) { - QTreeWidgetItem *newPlayer = new PlayerListTWI; - players.insert(player.player_id(), newPlayer); - updatePlayerProperties(player); - addTopLevelItem(newPlayer); - sortItems(1, Qt::AscendingOrder); + QTreeWidgetItem *newPlayer = new PlayerListTWI; + players.insert(player.player_id(), newPlayer); + updatePlayerProperties(player); + addTopLevelItem(newPlayer); + sortItems(1, Qt::AscendingOrder); } void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId) { - if (playerId == -1) - playerId = prop.player_id(); - - QTreeWidgetItem *player = players.value(playerId, 0); - if (!player) - return; - - if (prop.has_spectator()) { - player->setIcon(1, prop.spectator() ? spectatorIcon : playerIcon); - player->setData(1, Qt::UserRole, !prop.spectator()); - } - if (prop.has_conceded()) - player->setData(2, Qt::UserRole, prop.conceded()); - if (prop.has_ready_start()) - player->setData(2, Qt::UserRole + 1, prop.ready_start()); - if (prop.has_conceded() || prop.has_ready_start()) - player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon()) : (prop.ready_start() ? readyIcon : notReadyIcon)); - if (prop.has_user_info()) { - player->setData(3, Qt::UserRole, prop.user_info().user_level()); - player->setIcon(3, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(prop.user_info().user_level())))); - player->setText(4, QString::fromStdString(prop.user_info().name())); - const QString country = QString::fromStdString(prop.user_info().country()); - if (!country.isEmpty()) - player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country))); - player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name())); - } - if (prop.has_player_id()) - player->setData(4, Qt::UserRole + 1, prop.player_id()); - if (prop.has_deck_hash()) - player->setText(5, QString::fromStdString(prop.deck_hash())); - if (prop.has_sideboard_locked()) - player->setIcon(5, prop.sideboard_locked() ? lockIcon : QIcon()); - if (prop.has_ping_seconds()) - player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10))); + if (playerId == -1) + playerId = prop.player_id(); + + QTreeWidgetItem *player = players.value(playerId, 0); + if (!player) + return; + + if (prop.has_spectator()) { + player->setIcon(1, prop.spectator() ? spectatorIcon : playerIcon); + player->setData(1, Qt::UserRole, !prop.spectator()); + } + if (prop.has_conceded()) + player->setData(2, Qt::UserRole, prop.conceded()); + if (prop.has_ready_start()) + player->setData(2, Qt::UserRole + 1, prop.ready_start()); + if (prop.has_conceded() || prop.has_ready_start()) + player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon()) : (prop.ready_start() ? readyIcon : notReadyIcon)); + if (prop.has_user_info()) { + player->setData(3, Qt::UserRole, prop.user_info().user_level()); + player->setIcon(3, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(prop.user_info().user_level())))); + player->setText(4, QString::fromStdString(prop.user_info().name())); + const QString country = QString::fromStdString(prop.user_info().country()); + if (!country.isEmpty()) + player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country))); + player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name())); + } + if (prop.has_player_id()) + player->setData(4, Qt::UserRole + 1, prop.player_id()); + if (prop.has_deck_hash()) + player->setText(5, QString::fromStdString(prop.deck_hash())); + if (prop.has_sideboard_locked()) + player->setIcon(5, prop.sideboard_locked() ? lockIcon : QIcon()); + if (prop.has_ping_seconds()) + player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10))); } void PlayerListWidget::removePlayer(int playerId) { - QTreeWidgetItem *player = players.value(playerId, 0); - if (!player) - return; - players.remove(playerId); - delete takeTopLevelItem(indexOfTopLevelItem(player)); + QTreeWidgetItem *player = players.value(playerId, 0); + if (!player) + return; + players.remove(playerId); + delete takeTopLevelItem(indexOfTopLevelItem(player)); } void PlayerListWidget::setActivePlayer(int playerId) { - QMapIterator i(players); - while (i.hasNext()) { - i.next(); - QTreeWidgetItem *twi = i.value(); - QColor c = i.key() == playerId ? QColor(150, 255, 150) : Qt::white; - twi->setBackground(4, c); - } + QMapIterator i(players); + while (i.hasNext()) { + i.next(); + QTreeWidgetItem *twi = i.value(); + QColor c = i.key() == playerId ? QColor(150, 255, 150) : Qt::white; + twi->setBackground(4, c); + } } void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming) { - gameStarted = _gameStarted; - QMapIterator i(players); - while (i.hasNext()) { - QTreeWidgetItem *twi = i.next().value(); - if (gameStarted) { - if (resuming) - twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon()); - else { - twi->setData(2, Qt::UserRole, false); - twi->setIcon(2, QIcon()); - } - } else - twi->setIcon(2, notReadyIcon); - } + gameStarted = _gameStarted; + QMapIterator i(players); + while (i.hasNext()) { + QTreeWidgetItem *twi = i.next().value(); + if (gameStarted) { + if (resuming) + twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon()); + else { + twi->setData(2, Qt::UserRole, false); + twi->setIcon(2, QIcon()); + } + } else + twi->setIcon(2, notReadyIcon); + } } void PlayerListWidget::showContextMenu(const QPoint &pos, const QModelIndex &index) { - if (!userContextMenu) - return; - - const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString(); - int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt(); - UserLevelFlags userLevel(index.sibling(index.row(), 3).data(Qt::UserRole).toInt()); - - userContextMenu->showContextMenu(pos, userName, userLevel, playerId); + if (!userContextMenu) + return; + + const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString(); + int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt(); + UserLevelFlags userLevel(index.sibling(index.row(), 3).data(Qt::UserRole).toInt()); + + userContextMenu->showContextMenu(pos, userName, userLevel, playerId); } diff --git a/cockatrice/src/playerlistwidget.h b/cockatrice/src/playerlistwidget.h index c07799af..ff932ce7 100644 --- a/cockatrice/src/playerlistwidget.h +++ b/cockatrice/src/playerlistwidget.h @@ -14,38 +14,38 @@ class UserContextMenu; class PlayerListItemDelegate : public QStyledItemDelegate { public: - PlayerListItemDelegate(QObject *const parent); - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); + PlayerListItemDelegate(QObject *const parent); + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); }; class PlayerListTWI : public QTreeWidgetItem { public: - PlayerListTWI(); - bool operator<(const QTreeWidgetItem &other) const; + PlayerListTWI(); + bool operator<(const QTreeWidgetItem &other) const; }; class PlayerListWidget : public QTreeWidget { - Q_OBJECT + Q_OBJECT private: - PlayerListItemDelegate *itemDelegate; - QMap players; - TabSupervisor *tabSupervisor; - AbstractClient *client; - TabGame *game; - UserContextMenu *userContextMenu; - QIcon readyIcon, notReadyIcon, concededIcon, playerIcon, spectatorIcon, lockIcon; - bool gameStarted; + PlayerListItemDelegate *itemDelegate; + QMap players; + TabSupervisor *tabSupervisor; + AbstractClient *client; + TabGame *game; + UserContextMenu *userContextMenu; + QIcon readyIcon, notReadyIcon, concededIcon, playerIcon, spectatorIcon, lockIcon; + bool gameStarted; signals: - void openMessageDialog(const QString &userName, bool focus); + void openMessageDialog(const QString &userName, bool focus); public: - PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent = 0); - void retranslateUi(); - void addPlayer(const ServerInfo_PlayerProperties &player); - void removePlayer(int playerId); - void setActivePlayer(int playerId); - void updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId = -1); - void setGameStarted(bool _gameStarted, bool resuming); - void showContextMenu(const QPoint &pos, const QModelIndex &index); + PlayerListWidget(TabSupervisor *_tabSupervisor, AbstractClient *_client, TabGame *_game, QWidget *parent = 0); + void retranslateUi(); + void addPlayer(const ServerInfo_PlayerProperties &player); + void removePlayer(int playerId); + void setActivePlayer(int playerId); + void updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId = -1); + void setGameStarted(bool _gameStarted, bool resuming); + void showContextMenu(const QPoint &pos, const QModelIndex &index); }; #endif diff --git a/cockatrice/src/playertarget.cpp b/cockatrice/src/playertarget.cpp index 6e21fa65..eb18a332 100644 --- a/cockatrice/src/playertarget.cpp +++ b/cockatrice/src/playertarget.cpp @@ -8,149 +8,149 @@ #include PlayerCounter::PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent) - : AbstractCounter(_player, _id, _name, false, _value, parent) + : AbstractCounter(_player, _id, _name, false, _value, parent) { } QRectF PlayerCounter::boundingRect() const { - return QRectF(0, 0, 50, 30); + return QRectF(0, 0, 50, 30); } void PlayerCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - const int radius = 8; - const qreal border = 1; - QPainterPath path(QPointF(50 - border / 2, border / 2)); - path.lineTo(radius, border / 2); - path.arcTo(border / 2, border / 2, 2 * radius, 2 * radius, 90, 90); - path.lineTo(border / 2, 30 - border / 2); - path.lineTo(50 - border / 2, 30 - border / 2); - path.closeSubpath(); - - QPen pen(QColor(100, 100, 100)); - pen.setWidth(border); - painter->setPen(pen); - painter->setBrush(hovered ? QColor(50, 50, 50, 160) : QColor(0, 0, 0, 160)); - - painter->drawPath(path); + const int radius = 8; + const qreal border = 1; + QPainterPath path(QPointF(50 - border / 2, border / 2)); + path.lineTo(radius, border / 2); + path.arcTo(border / 2, border / 2, 2 * radius, 2 * radius, 90, 90); + path.lineTo(border / 2, 30 - border / 2); + path.lineTo(50 - border / 2, 30 - border / 2); + path.closeSubpath(); + + QPen pen(QColor(100, 100, 100)); + pen.setWidth(border); + painter->setPen(pen); + painter->setBrush(hovered ? QColor(50, 50, 50, 160) : QColor(0, 0, 0, 160)); + + painter->drawPath(path); - QRectF translatedRect = painter->combinedTransform().mapRect(boundingRect()); - QSize translatedSize = translatedRect.size().toSize(); - painter->resetTransform(); - QFont font("Serif"); - font.setWeight(QFont::Bold); - font.setPixelSize(qMax((int) round(translatedSize.height() / 1.3), 9)); - painter->setFont(font); - painter->setPen(Qt::white); - painter->drawText(translatedRect, Qt::AlignCenter, QString::number(value)); + QRectF translatedRect = painter->combinedTransform().mapRect(boundingRect()); + QSize translatedSize = translatedRect.size().toSize(); + painter->resetTransform(); + QFont font("Serif"); + font.setWeight(QFont::Bold); + font.setPixelSize(qMax((int) round(translatedSize.height() / 1.3), 9)); + painter->setFont(font); + painter->setPen(Qt::white); + painter->drawText(translatedRect, Qt::AlignCenter, QString::number(value)); } PlayerTarget::PlayerTarget(Player *_owner, QGraphicsItem *parentItem) - : ArrowTarget(_owner, parentItem), playerCounter(0) + : ArrowTarget(_owner, parentItem), playerCounter(0) { - setCacheMode(DeviceCoordinateCache); - - const std::string &bmp = _owner->getUserInfo()->avatar_bmp(); - if (!fullPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) - fullPixmap = QPixmap(); + setCacheMode(DeviceCoordinateCache); + + const std::string &bmp = _owner->getUserInfo()->avatar_bmp(); + if (!fullPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) + fullPixmap = QPixmap(); } PlayerTarget::~PlayerTarget() { - // Explicit deletion is necessary in spite of parent/child relationship - // as we need this object to be alive to receive the destroyed() signal. - delete playerCounter; + // Explicit deletion is necessary in spite of parent/child relationship + // as we need this object to be alive to receive the destroyed() signal. + delete playerCounter; } QRectF PlayerTarget::boundingRect() const { - return QRectF(0, 0, 160, 64); + return QRectF(0, 0, 160, 64); } void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - const ServerInfo_User *const info = owner->getUserInfo(); + const ServerInfo_User *const info = owner->getUserInfo(); - const qreal border = 2; + const qreal border = 2; - QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border); - QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect); - QSize translatedSize = translatedRect.size().toSize(); - QPixmap cachedPixmap; - const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey()); + QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border); + QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect); + QSize translatedSize = translatedRect.size().toSize(); + QPixmap cachedPixmap; + const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey()); #if QT_VERSION >= 0x040600 - if (!QPixmapCache::find(cacheKey, &cachedPixmap)) { + if (!QPixmapCache::find(cacheKey, &cachedPixmap)) { #else - if (!QPixmapCache::find(cacheKey, cachedPixmap)) { + if (!QPixmapCache::find(cacheKey, cachedPixmap)) { #endif - cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height()); - - QPainter tempPainter(&cachedPixmap); - QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2); - grad.setColorAt(1, Qt::black); - grad.setColorAt(0, QColor(180, 180, 180)); - tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad); - - QPixmap tempPixmap; - if (fullPixmap.isNull()) - tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), UserLevelFlags(info->user_level())); - else - tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap); - QPixmapCache::insert(cacheKey, cachedPixmap); - } - - painter->save(); - painter->resetTransform(); - painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0); - painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect()); - painter->restore(); + cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height()); + + QPainter tempPainter(&cachedPixmap); + QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2); + grad.setColorAt(1, Qt::black); + grad.setColorAt(0, QColor(180, 180, 180)); + tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad); + + QPixmap tempPixmap; + if (fullPixmap.isNull()) + tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), UserLevelFlags(info->user_level())); + else + tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); + + tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap); + QPixmapCache::insert(cacheKey, cachedPixmap); + } + + painter->save(); + painter->resetTransform(); + painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0); + painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect()); + painter->restore(); - QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20); - painter->fillRect(nameRect, QColor(0, 0, 0, 160)); - QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect); - - painter->save(); - painter->resetTransform(); - - QString name = QString::fromStdString(info->name()); - if (name.size() > 13) - name = name.mid(0, 10) + "..."; - - QFont font; - font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9)); - painter->setFont(font); - painter->setPen(Qt::white); - painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name); - painter->restore(); + QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20); + painter->fillRect(nameRect, QColor(0, 0, 0, 160)); + QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect); + + painter->save(); + painter->resetTransform(); + + QString name = QString::fromStdString(info->name()); + if (name.size() > 13) + name = name.mid(0, 10) + "..."; + + QFont font; + font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9)); + painter->setFont(font); + painter->setPen(Qt::white); + painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name); + painter->restore(); - QPen pen(QColor(100, 100, 100)); - pen.setWidth(border); - pen.setJoinStyle(Qt::RoundJoin); - painter->setPen(pen); - painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2)); - - if (getBeingPointedAt()) - painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); + QPen pen(QColor(100, 100, 100)); + pen.setWidth(border); + pen.setJoinStyle(Qt::RoundJoin); + painter->setPen(pen); + painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2)); + + if (getBeingPointedAt()) + painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); } AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value) { - if (playerCounter) { - disconnect(playerCounter, 0, this, 0); - playerCounter->delCounter(); - } + if (playerCounter) { + disconnect(playerCounter, 0, this, 0); + playerCounter->delCounter(); + } - playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this); - playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height()); - connect(playerCounter, SIGNAL(destroyed()), this, SLOT(counterDeleted())); - - return playerCounter; + playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this); + playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height()); + connect(playerCounter, SIGNAL(destroyed()), this, SLOT(counterDeleted())); + + return playerCounter; } void PlayerTarget::counterDeleted() { - playerCounter = 0; + playerCounter = 0; } diff --git a/cockatrice/src/playertarget.h b/cockatrice/src/playertarget.h index fa3c3e01..8d36084c 100644 --- a/cockatrice/src/playertarget.h +++ b/cockatrice/src/playertarget.h @@ -9,30 +9,30 @@ class Player; class PlayerCounter : public AbstractCounter { - Q_OBJECT + Q_OBJECT public: - PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + PlayerCounter(Player *_player, int _id, const QString &_name, int _value, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; class PlayerTarget : public ArrowTarget { - Q_OBJECT + Q_OBJECT private: - QPixmap fullPixmap; - PlayerCounter *playerCounter; + QPixmap fullPixmap; + PlayerCounter *playerCounter; public slots: - void counterDeleted(); + void counterDeleted(); public: - enum { Type = typePlayerTarget }; - int type() const { return Type; } - - PlayerTarget(Player *_player = 0, QGraphicsItem *parentItem = 0); - ~PlayerTarget(); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - - AbstractCounter *addCounter(int _counterId, const QString &_name, int _value); + enum { Type = typePlayerTarget }; + int type() const { return Type; } + + PlayerTarget(Player *_player = 0, QGraphicsItem *parentItem = 0); + ~PlayerTarget(); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + + AbstractCounter *addCounter(int _counterId, const QString &_name, int _value); }; #endif diff --git a/cockatrice/src/qt-json/json.cpp b/cockatrice/src/qt-json/json.cpp index 6c20a8eb..1cda4453 100644 --- a/cockatrice/src/qt-json/json.cpp +++ b/cockatrice/src/qt-json/json.cpp @@ -131,30 +131,30 @@ QByteArray Json::serialize(const QVariant &data, bool &success) str = "[ " + join( values, ", " ) + " ]"; } - else if(data.type() == QVariant::Hash) // variant is a hash? - { - const QVariantHash vhash = data.toHash(); - QHashIterator it( vhash ); - str = "{ "; - QList pairs; + else if(data.type() == QVariant::Hash) // variant is a hash? + { + const QVariantHash vhash = data.toHash(); + QHashIterator it( vhash ); + str = "{ "; + QList pairs; - while(it.hasNext()) - { - it.next(); - QByteArray serializedValue = serialize(it.value()); + while(it.hasNext()) + { + it.next(); + QByteArray serializedValue = serialize(it.value()); - if(serializedValue.isNull()) - { - success = false; - break; - } + if(serializedValue.isNull()) + { + success = false; + break; + } - pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue; - } + pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue; + } - str += join(pairs, ", "); - str += " }"; - } + str += join(pairs, ", "); + str += " }"; + } else if(data.type() == QVariant::Map) // variant is a map? { const QVariantMap vmap = data.toMap(); diff --git a/cockatrice/src/remoteclient.cpp b/cockatrice/src/remoteclient.cpp index 3ef2c658..0eae13ab 100644 --- a/cockatrice/src/remoteclient.cpp +++ b/cockatrice/src/remoteclient.cpp @@ -12,220 +12,220 @@ static const unsigned int protocolVersion = 14; RemoteClient::RemoteClient(QObject *parent) - : AbstractClient(parent), timeRunning(0), lastDataReceived(0), messageInProgress(false), handshakeStarted(false), messageLength(0) + : AbstractClient(parent), timeRunning(0), lastDataReceived(0), messageInProgress(false), handshakeStarted(false), messageLength(0) { - timer = new QTimer(this); - timer->setInterval(1000); - connect(timer, SIGNAL(timeout()), this, SLOT(ping())); + timer = new QTimer(this); + timer->setInterval(1000); + connect(timer, SIGNAL(timeout()), this, SLOT(ping())); - socket = new QTcpSocket(this); - socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); - connect(socket, SIGNAL(connected()), this, SLOT(slotConnected())); - connect(socket, SIGNAL(readyRead()), this, SLOT(readData())); - connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotSocketError(QAbstractSocket::SocketError))); - - connect(this, SIGNAL(serverIdentificationEventReceived(const Event_ServerIdentification &)), this, SLOT(processServerIdentificationEvent(const Event_ServerIdentification &))); - connect(this, SIGNAL(connectionClosedEventReceived(Event_ConnectionClosed)), this, SLOT(processConnectionClosedEvent(Event_ConnectionClosed))); - connect(this, SIGNAL(sigConnectToServer(QString, unsigned int, QString, QString)), this, SLOT(doConnectToServer(QString, unsigned int, QString, QString))); - connect(this, SIGNAL(sigDisconnectFromServer()), this, SLOT(doDisconnectFromServer())); + socket = new QTcpSocket(this); + socket->setSocketOption(QAbstractSocket::LowDelayOption, 1); + connect(socket, SIGNAL(connected()), this, SLOT(slotConnected())); + connect(socket, SIGNAL(readyRead()), this, SLOT(readData())); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotSocketError(QAbstractSocket::SocketError))); + + connect(this, SIGNAL(serverIdentificationEventReceived(const Event_ServerIdentification &)), this, SLOT(processServerIdentificationEvent(const Event_ServerIdentification &))); + connect(this, SIGNAL(connectionClosedEventReceived(Event_ConnectionClosed)), this, SLOT(processConnectionClosedEvent(Event_ConnectionClosed))); + connect(this, SIGNAL(sigConnectToServer(QString, unsigned int, QString, QString)), this, SLOT(doConnectToServer(QString, unsigned int, QString, QString))); + connect(this, SIGNAL(sigDisconnectFromServer()), this, SLOT(doDisconnectFromServer())); } RemoteClient::~RemoteClient() { - doDisconnectFromServer(); - thread()->quit(); + doDisconnectFromServer(); + thread()->quit(); } void RemoteClient::slotSocketError(QAbstractSocket::SocketError /*error*/) { - QString errorString = socket->errorString(); - doDisconnectFromServer(); - emit socketError(errorString); + QString errorString = socket->errorString(); + doDisconnectFromServer(); + emit socketError(errorString); } void RemoteClient::slotConnected() { - timeRunning = lastDataReceived = 0; - timer->start(); - - // dirty hack to be compatible with v14 server - sendCommandContainer(CommandContainer()); - getNewCmdId(); - // end of hack - - setStatus(StatusAwaitingWelcome); + timeRunning = lastDataReceived = 0; + timer->start(); + + // dirty hack to be compatible with v14 server + sendCommandContainer(CommandContainer()); + getNewCmdId(); + // end of hack + + setStatus(StatusAwaitingWelcome); } void RemoteClient::processServerIdentificationEvent(const Event_ServerIdentification &event) { - if (event.protocol_version() != protocolVersion) { - emit protocolVersionMismatch(protocolVersion, event.protocol_version()); - setStatus(StatusDisconnecting); - return; - } - setStatus(StatusLoggingIn); - - Command_Login cmdLogin; - cmdLogin.set_user_name(userName.toStdString()); - cmdLogin.set_password(password.toStdString()); - - PendingCommand *pend = prepareSessionCommand(cmdLogin); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(loginResponse(Response))); - sendCommand(pend); + if (event.protocol_version() != protocolVersion) { + emit protocolVersionMismatch(protocolVersion, event.protocol_version()); + setStatus(StatusDisconnecting); + return; + } + setStatus(StatusLoggingIn); + + Command_Login cmdLogin; + cmdLogin.set_user_name(userName.toStdString()); + cmdLogin.set_password(password.toStdString()); + + PendingCommand *pend = prepareSessionCommand(cmdLogin); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(loginResponse(Response))); + sendCommand(pend); } void RemoteClient::processConnectionClosedEvent(const Event_ConnectionClosed & /*event*/) { - doDisconnectFromServer(); + doDisconnectFromServer(); } void RemoteClient::loginResponse(const Response &response) { - const Response_Login &resp = response.GetExtension(Response_Login::ext); - if (response.response_code() == Response::RespOk) { - setStatus(StatusLoggedIn); - emit userInfoChanged(resp.user_info()); - - QList buddyList; - for (int i = resp.buddy_list_size() - 1; i >= 0; --i) - buddyList.append(resp.buddy_list(i)); - emit buddyListReceived(buddyList); - - QList ignoreList; - for (int i = resp.ignore_list_size() - 1; i >= 0; --i) - ignoreList.append(resp.ignore_list(i)); - emit ignoreListReceived(ignoreList); - } else { - emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time()); - setStatus(StatusDisconnecting); - } + const Response_Login &resp = response.GetExtension(Response_Login::ext); + if (response.response_code() == Response::RespOk) { + setStatus(StatusLoggedIn); + emit userInfoChanged(resp.user_info()); + + QList buddyList; + for (int i = resp.buddy_list_size() - 1; i >= 0; --i) + buddyList.append(resp.buddy_list(i)); + emit buddyListReceived(buddyList); + + QList ignoreList; + for (int i = resp.ignore_list_size() - 1; i >= 0; --i) + ignoreList.append(resp.ignore_list(i)); + emit ignoreListReceived(ignoreList); + } else { + emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()), resp.denied_end_time()); + setStatus(StatusDisconnecting); + } } void RemoteClient::readData() { - lastDataReceived = timeRunning; - QByteArray data = socket->readAll(); + lastDataReceived = timeRunning; + QByteArray data = socket->readAll(); - inputBuffer.append(data); - - do { - if (!messageInProgress) { - if (inputBuffer.size() >= 4) { - // dirty hack to be compatible with v14 server that sends 60 bytes of garbage at the beginning - if (!handshakeStarted) { - handshakeStarted = true; - if (inputBuffer.startsWith("= 4) { + // dirty hack to be compatible with v14 server that sends 60 bytes of garbage at the beginning + if (!handshakeStarted) { + handshakeStarted = true; + if (inputBuffer.startsWith("> 8); - buf.data()[1] = (unsigned char) (size >> 16); - buf.data()[0] = (unsigned char) (size >> 24); - - socket->write(buf); + buf.resize(size + 4); + cont.SerializeToArray(buf.data() + 4, size); + buf.data()[3] = (unsigned char) size; + buf.data()[2] = (unsigned char) (size >> 8); + buf.data()[1] = (unsigned char) (size >> 16); + buf.data()[0] = (unsigned char) (size >> 24); + + socket->write(buf); } void RemoteClient::doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password) { - doDisconnectFromServer(); - - userName = _userName; - password = _password; - socket->connectToHost(hostname, port); - setStatus(StatusConnecting); + doDisconnectFromServer(); + + userName = _userName; + password = _password; + socket->connectToHost(hostname, port); + setStatus(StatusConnecting); } void RemoteClient::doDisconnectFromServer() { - timer->stop(); - - messageInProgress = false; - handshakeStarted = false; - messageLength = 0; + timer->stop(); + + messageInProgress = false; + handshakeStarted = false; + messageLength = 0; - QList pc = pendingCommands.values(); - for (int i = 0; i < pc.size(); i++) { - Response response; - response.set_response_code(Response::RespNotConnected); - response.set_cmd_id(pc[i]->getCommandContainer().cmd_id()); - pc[i]->processResponse(response); - - delete pc[i]; - } - pendingCommands.clear(); + QList pc = pendingCommands.values(); + for (int i = 0; i < pc.size(); i++) { + Response response; + response.set_response_code(Response::RespNotConnected); + response.set_cmd_id(pc[i]->getCommandContainer().cmd_id()); + pc[i]->processResponse(response); + + delete pc[i]; + } + pendingCommands.clear(); - setStatus(StatusDisconnected); - socket->close(); + setStatus(StatusDisconnected); + socket->close(); } void RemoteClient::ping() { - QMutableMapIterator i(pendingCommands); - while (i.hasNext()) { - PendingCommand *pend = i.next().value(); - if (pend->tick() > maxTimeout) { - i.remove(); - pend->deleteLater(); - } - } - - int maxTime = timeRunning - lastDataReceived; - emit maxPingTime(maxTime, maxTimeout); - if (maxTime >= maxTimeout) { - disconnectFromServer(); - emit serverTimeout(); - } else { - sendCommand(prepareSessionCommand(Command_Ping())); - ++timeRunning; - } + QMutableMapIterator i(pendingCommands); + while (i.hasNext()) { + PendingCommand *pend = i.next().value(); + if (pend->tick() > maxTimeout) { + i.remove(); + pend->deleteLater(); + } + } + + int maxTime = timeRunning - lastDataReceived; + emit maxPingTime(maxTime, maxTimeout); + if (maxTime >= maxTimeout) { + disconnectFromServer(); + emit serverTimeout(); + } else { + sendCommand(prepareSessionCommand(Command_Ping())); + ++timeRunning; + } } void RemoteClient::connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password) { - emit sigConnectToServer(hostname, port, _userName, _password); + emit sigConnectToServer(hostname, port, _userName, _password); } void RemoteClient::disconnectFromServer() { - emit sigDisconnectFromServer(); + emit sigDisconnectFromServer(); } diff --git a/cockatrice/src/remoteclient.h b/cockatrice/src/remoteclient.h index 19ca26f4..2cb84e90 100644 --- a/cockatrice/src/remoteclient.h +++ b/cockatrice/src/remoteclient.h @@ -7,45 +7,45 @@ class QTimer; class RemoteClient : public AbstractClient { - Q_OBJECT + Q_OBJECT signals: - void maxPingTime(int seconds, int maxSeconds); - void serverTimeout(); - void loginError(Response::ResponseCode resp, QString reasonStr, quint32 endTime); - void socketError(const QString &errorString); - void protocolVersionMismatch(int clientVersion, int serverVersion); - void protocolError(); - void sigConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); - void sigDisconnectFromServer(); + void maxPingTime(int seconds, int maxSeconds); + void serverTimeout(); + void loginError(Response::ResponseCode resp, QString reasonStr, quint32 endTime); + void socketError(const QString &errorString); + void protocolVersionMismatch(int clientVersion, int serverVersion); + void protocolError(); + void sigConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void sigDisconnectFromServer(); private slots: - void slotConnected(); - void readData(); - void slotSocketError(QAbstractSocket::SocketError error); - void ping(); - void processServerIdentificationEvent(const Event_ServerIdentification &event); - void processConnectionClosedEvent(const Event_ConnectionClosed &event); - void loginResponse(const Response &response); - void doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); - void doDisconnectFromServer(); + void slotConnected(); + void readData(); + void slotSocketError(QAbstractSocket::SocketError error); + void ping(); + void processServerIdentificationEvent(const Event_ServerIdentification &event); + void processConnectionClosedEvent(const Event_ConnectionClosed &event); + void loginResponse(const Response &response); + void doConnectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void doDisconnectFromServer(); private: - static const int maxTimeout = 10; - int timeRunning, lastDataReceived; + static const int maxTimeout = 10; + int timeRunning, lastDataReceived; - QByteArray inputBuffer; - bool messageInProgress; - bool handshakeStarted; - int messageLength; - - QTimer *timer; - QTcpSocket *socket; -protected slots: - void sendCommandContainer(const CommandContainer &cont); + QByteArray inputBuffer; + bool messageInProgress; + bool handshakeStarted; + int messageLength; + + QTimer *timer; + QTcpSocket *socket; +protected slots: + void sendCommandContainer(const CommandContainer &cont); public: - RemoteClient(QObject *parent = 0); - ~RemoteClient(); - QString peerName() const { return socket->peerName(); } - void connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); - void disconnectFromServer(); + RemoteClient(QObject *parent = 0); + ~RemoteClient(); + QString peerName() const { return socket->peerName(); } + void connectToServer(const QString &hostname, unsigned int port, const QString &_userName, const QString &_password); + void disconnectFromServer(); }; #endif diff --git a/cockatrice/src/remotedecklist_treewidget.cpp b/cockatrice/src/remotedecklist_treewidget.cpp index ae1aa294..b72df671 100644 --- a/cockatrice/src/remotedecklist_treewidget.cpp +++ b/cockatrice/src/remotedecklist_treewidget.cpp @@ -10,324 +10,324 @@ #include "pb/serverinfo_deckstorage.pb.h" RemoteDeckList_TreeModel::DirectoryNode::DirectoryNode(const QString &_name, RemoteDeckList_TreeModel::DirectoryNode *_parent) - : RemoteDeckList_TreeModel::Node(_name, _parent) + : RemoteDeckList_TreeModel::Node(_name, _parent) { } RemoteDeckList_TreeModel::DirectoryNode::~DirectoryNode() { - clearTree(); + clearTree(); } void RemoteDeckList_TreeModel::DirectoryNode::clearTree() { - for (int i = 0; i < size(); ++i) - delete at(i); - clear(); + for (int i = 0; i < size(); ++i) + delete at(i); + clear(); } QString RemoteDeckList_TreeModel::DirectoryNode::getPath() const { - if (parent) { - QString parentPath = parent->getPath(); - if (parentPath.isEmpty()) - return name; - else - return parentPath + "/" + name; - } else - return name; + if (parent) { + QString parentPath = parent->getPath(); + if (parentPath.isEmpty()) + return name; + else + return parentPath + "/" + name; + } else + return name; } RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeByPath(QStringList path) { - QString pathItem; - if (parent) { - if (path.isEmpty()) - return this; - pathItem = path.takeFirst(); - if (pathItem.isEmpty() && name.isEmpty()) - return this; - } - - for (int i = 0; i < size(); ++i) { - DirectoryNode *node = dynamic_cast(at(i)); - if (!node) - continue; - if (node->getName() == pathItem) - return node->getNodeByPath(path); - } - return 0; + QString pathItem; + if (parent) { + if (path.isEmpty()) + return this; + pathItem = path.takeFirst(); + if (pathItem.isEmpty() && name.isEmpty()) + return this; + } + + for (int i = 0; i < size(); ++i) { + DirectoryNode *node = dynamic_cast(at(i)); + if (!node) + continue; + if (node->getName() == pathItem) + return node->getNodeByPath(path); + } + return 0; } RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeById(int id) const { - for (int i = 0; i < size(); ++i) { - DirectoryNode *node = dynamic_cast(at(i)); - if (node) { - FileNode *result = node->getNodeById(id); - if (result) - return result; - } else { - FileNode *file = dynamic_cast(at(i)); - if (file->getId() == id) - return file; - } - } - return 0; + for (int i = 0; i < size(); ++i) { + DirectoryNode *node = dynamic_cast(at(i)); + if (node) { + FileNode *result = node->getNodeById(id); + if (result) + return result; + } else { + FileNode *file = dynamic_cast(at(i)); + if (file->getId() == id) + return file; + } + } + return 0; } RemoteDeckList_TreeModel::RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent) - : QAbstractItemModel(parent), client(_client) + : QAbstractItemModel(parent), client(_client) { - QFileIconProvider fip; - dirIcon = fip.icon(QFileIconProvider::Folder); - fileIcon = fip.icon(QFileIconProvider::File); + QFileIconProvider fip; + dirIcon = fip.icon(QFileIconProvider::Folder); + fileIcon = fip.icon(QFileIconProvider::File); - root = new DirectoryNode; - refreshTree(); + root = new DirectoryNode; + refreshTree(); } RemoteDeckList_TreeModel::~RemoteDeckList_TreeModel() { - delete root; + delete root; } int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const { - DirectoryNode *node = getNode(parent); - if (node) - return node->size(); - else - return 0; + DirectoryNode *node = getNode(parent); + if (node) + return node->size(); + else + return 0; } int RemoteDeckList_TreeModel::columnCount(const QModelIndex &/*parent*/) const { - return 3; + return 3; } QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if (index.column() >= 3) - return QVariant(); + if (!index.isValid()) + return QVariant(); + if (index.column() >= 3) + return QVariant(); - Node *temp = static_cast(index.internalPointer()); - FileNode *file = dynamic_cast(temp); - if (!file) { - DirectoryNode *node = dynamic_cast(temp); - switch (role) { - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return node->getName(); - default: - return QVariant(); - } - } - case Qt::DecorationRole: - return index.column() == 0 ? dirIcon : QVariant(); - default: return QVariant(); - } - } else { - switch (role) { - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return file->getName(); - case 1: return file->getId(); - case 2: return file->getUploadTime(); - default: - return QVariant(); - } - } - case Qt::DecorationRole: - return index.column() == 0 ? fileIcon : QVariant(); - case Qt::TextAlignmentRole: - return index.column() == 1 ? Qt::AlignRight : Qt::AlignLeft; - default: return QVariant(); - } - } + Node *temp = static_cast(index.internalPointer()); + FileNode *file = dynamic_cast(temp); + if (!file) { + DirectoryNode *node = dynamic_cast(temp); + switch (role) { + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return node->getName(); + default: + return QVariant(); + } + } + case Qt::DecorationRole: + return index.column() == 0 ? dirIcon : QVariant(); + default: return QVariant(); + } + } else { + switch (role) { + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return file->getName(); + case 1: return file->getId(); + case 2: return file->getUploadTime(); + default: + return QVariant(); + } + } + case Qt::DecorationRole: + return index.column() == 0 ? fileIcon : QVariant(); + case Qt::TextAlignmentRole: + return index.column() == 1 ? Qt::AlignRight : Qt::AlignLeft; + default: return QVariant(); + } + } } QVariant RemoteDeckList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (orientation != Qt::Horizontal) - return QVariant(); - switch (role) { - case Qt::TextAlignmentRole: - return section == 1 ? Qt::AlignRight : Qt::AlignLeft; - case Qt::DisplayRole: { - switch (section) { - case 0: return tr("Name"); - case 1: return tr("ID"); - case 2: return tr("Upload time"); - default: return QVariant(); - } - } - default: return QVariant(); - } + if (orientation != Qt::Horizontal) + return QVariant(); + switch (role) { + case Qt::TextAlignmentRole: + return section == 1 ? Qt::AlignRight : Qt::AlignLeft; + case Qt::DisplayRole: { + switch (section) { + case 0: return tr("Name"); + case 1: return tr("ID"); + case 2: return tr("Upload time"); + default: return QVariant(); + } + } + default: return QVariant(); + } } QModelIndex RemoteDeckList_TreeModel::index(int row, int column, const QModelIndex &parent) const { - if (!hasIndex(row, column, parent)) - return QModelIndex(); + if (!hasIndex(row, column, parent)) + return QModelIndex(); - DirectoryNode *parentNode = getNode(parent); - if (row >= parentNode->size()) - return QModelIndex(); + DirectoryNode *parentNode = getNode(parent); + if (row >= parentNode->size()) + return QModelIndex(); - return createIndex(row, column, parentNode->at(row)); + return createIndex(row, column, parentNode->at(row)); } QModelIndex RemoteDeckList_TreeModel::parent(const QModelIndex &ind) const { - if (!ind.isValid()) - return QModelIndex(); + if (!ind.isValid()) + return QModelIndex(); - return nodeToIndex(static_cast(ind.internalPointer())->getParent()); + return nodeToIndex(static_cast(ind.internalPointer())->getParent()); } Qt::ItemFlags RemoteDeckList_TreeModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } QModelIndex RemoteDeckList_TreeModel::nodeToIndex(Node *node) const { - if (node == root) - return QModelIndex(); - return createIndex(node->getParent()->indexOf(node), 0, node); + if (node == root) + return QModelIndex(); + return createIndex(node->getParent()->indexOf(node), 0, node); } void RemoteDeckList_TreeModel::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent) { - const ServerInfo_DeckStorage_File &fileInfo = file.file(); - QDateTime time; - time.setTime_t(fileInfo.creation_time()); - - beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); - parent->append(new FileNode(QString::fromStdString(file.name()), file.id(), time, parent)); - endInsertRows(); + const ServerInfo_DeckStorage_File &fileInfo = file.file(); + QDateTime time; + time.setTime_t(fileInfo.creation_time()); + + beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); + parent->append(new FileNode(QString::fromStdString(file.name()), file.id(), time, parent)); + endInsertRows(); } void RemoteDeckList_TreeModel::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent) { - DirectoryNode *newItem = addNamedFolderToTree(QString::fromStdString(folder.name()), parent); - const ServerInfo_DeckStorage_Folder &folderInfo = folder.folder(); - const int folderItemsSize = folderInfo.items_size(); - for (int i = 0; i < folderItemsSize; ++i) { - const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i); - if (subItem.has_folder()) - addFolderToTree(subItem, newItem); - else - addFileToTree(subItem, newItem); - } + DirectoryNode *newItem = addNamedFolderToTree(QString::fromStdString(folder.name()), parent); + const ServerInfo_DeckStorage_Folder &folderInfo = folder.folder(); + const int folderItemsSize = folderInfo.items_size(); + for (int i = 0; i < folderItemsSize; ++i) { + const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i); + if (subItem.has_folder()) + addFolderToTree(subItem, newItem); + else + addFileToTree(subItem, newItem); + } } RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::addNamedFolderToTree(const QString &name, DirectoryNode *parent) { - DirectoryNode *newItem = new DirectoryNode(name, parent); - beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); - parent->append(newItem); - endInsertRows(); - return newItem; + DirectoryNode *newItem = new DirectoryNode(name, parent); + beginInsertRows(nodeToIndex(parent), parent->size(), parent->size()); + parent->append(newItem); + endInsertRows(); + return newItem; } void RemoteDeckList_TreeModel::removeNode(RemoteDeckList_TreeModel::Node *node) { - int ind = node->getParent()->indexOf(node); - beginRemoveRows(nodeToIndex(node->getParent()), ind, ind); - node->getParent()->removeAt(ind); - endRemoveRows(); - delete node; + int ind = node->getParent()->indexOf(node); + beginRemoveRows(nodeToIndex(node->getParent()), ind, ind); + node->getParent()->removeAt(ind); + endRemoveRows(); + delete node; } void RemoteDeckList_TreeModel::refreshTree() { - PendingCommand *pend = client->prepareSessionCommand(Command_DeckList()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckListFinished(const Response &))); - - client->sendCommand(pend); + PendingCommand *pend = client->prepareSessionCommand(Command_DeckList()); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckListFinished(const Response &))); + + client->sendCommand(pend); } void RemoteDeckList_TreeModel::deckListFinished(const Response &r) { - const Response_DeckList &resp = r.GetExtension(Response_DeckList::ext); + const Response_DeckList &resp = r.GetExtension(Response_DeckList::ext); - root->clearTree(); - reset(); - - ServerInfo_DeckStorage_TreeItem tempRoot; - tempRoot.set_id(0); - tempRoot.mutable_folder()->CopyFrom(resp.root()); - addFolderToTree(tempRoot, root); - - emit treeRefreshed(); + root->clearTree(); + reset(); + + ServerInfo_DeckStorage_TreeItem tempRoot; + tempRoot.set_id(0); + tempRoot.mutable_folder()->CopyFrom(resp.root()); + addFolderToTree(tempRoot, root); + + emit treeRefreshed(); } RemoteDeckList_TreeWidget::RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent) - : QTreeView(parent) + : QTreeView(parent) { - treeModel = new RemoteDeckList_TreeModel(_client, this); - proxyModel = new QSortFilterProxyModel(this); - proxyModel->setSourceModel(treeModel); - proxyModel->setDynamicSortFilter(true); - proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); - setModel(proxyModel); - connect(treeModel, SIGNAL(treeRefreshed()), this, SLOT(expandAll())); + treeModel = new RemoteDeckList_TreeModel(_client, this); + proxyModel = new QSortFilterProxyModel(this); + proxyModel->setSourceModel(treeModel); + proxyModel->setDynamicSortFilter(true); + proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + setModel(proxyModel); + connect(treeModel, SIGNAL(treeRefreshed()), this, SLOT(expandAll())); - header()->setResizeMode(QHeaderView::ResizeToContents); - setUniformRowHeights(true); - setSortingEnabled(true); - proxyModel->sort(0, Qt::AscendingOrder); - header()->setSortIndicator(0, Qt::AscendingOrder); + header()->setResizeMode(QHeaderView::ResizeToContents); + setUniformRowHeights(true); + setSortingEnabled(true); + proxyModel->sort(0, Qt::AscendingOrder); + header()->setSortIndicator(0, Qt::AscendingOrder); } RemoteDeckList_TreeModel::Node *RemoteDeckList_TreeWidget::getNode(const QModelIndex &ind) const { - return treeModel->getNode(proxyModel->mapToSource(ind)); + return treeModel->getNode(proxyModel->mapToSource(ind)); } RemoteDeckList_TreeModel::Node *RemoteDeckList_TreeWidget::getCurrentItem() const { - return getNode(selectionModel()->currentIndex()); + return getNode(selectionModel()->currentIndex()); } RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeWidget::getNodeByPath(const QString &path) const { - return treeModel->getRoot()->getNodeByPath(path.split("/")); + return treeModel->getRoot()->getNodeByPath(path.split("/")); } RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeWidget::getNodeById(int id) const { - return treeModel->getRoot()->getNodeById(id); + return treeModel->getRoot()->getNodeById(id); } void RemoteDeckList_TreeWidget::addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent) { - treeModel->addFileToTree(file, parent); + treeModel->addFileToTree(file, parent); } void RemoteDeckList_TreeWidget::addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent) { - treeModel->addFolderToTree(folder, parent); + treeModel->addFolderToTree(folder, parent); } void RemoteDeckList_TreeWidget::addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent) { - treeModel->addNamedFolderToTree(name, parent); + treeModel->addNamedFolderToTree(name, parent); } void RemoteDeckList_TreeWidget::removeNode(RemoteDeckList_TreeModel::Node *node) { - treeModel->removeNode(node); + treeModel->removeNode(node); } void RemoteDeckList_TreeWidget::refreshTree() { - treeModel->refreshTree(); + treeModel->refreshTree(); } diff --git a/cockatrice/src/remotedecklist_treewidget.h b/cockatrice/src/remotedecklist_treewidget.h index 717ffa0c..ecb2ca18 100644 --- a/cockatrice/src/remotedecklist_treewidget.h +++ b/cockatrice/src/remotedecklist_treewidget.h @@ -11,92 +11,92 @@ class QSortFilterProxyModel; class ServerInfo_DeckStorage_TreeItem; class RemoteDeckList_TreeModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT public: - class DirectoryNode; - class FileNode; - class Node { - protected: - DirectoryNode *parent; - QString name; - public: - Node(const QString &_name, DirectoryNode *_parent = 0) - : parent(_parent), name(_name) { } - virtual ~Node() { }; - DirectoryNode *getParent() const { return parent; } - QString getName() const { return name; } - }; - class DirectoryNode : public Node, public QList { - public: - DirectoryNode(const QString &_name = QString(), DirectoryNode *_parent = 0); - ~DirectoryNode(); - void clearTree(); - QString getPath() const; - DirectoryNode *getNodeByPath(QStringList path); - FileNode *getNodeById(int id) const; - }; - class FileNode : public Node { - private: - int id; - QDateTime uploadTime; - public: - FileNode(const QString &_name, int _id, const QDateTime &_uploadTime, DirectoryNode *_parent = 0) - : Node(_name, _parent), id(_id), uploadTime(_uploadTime) { } - int getId() const { return id; } - QDateTime getUploadTime() const { return uploadTime; } - }; - - template T getNode(const QModelIndex &index) const - { - if (!index.isValid()) - return dynamic_cast(root); - return dynamic_cast(static_cast(index.internalPointer())); - } + class DirectoryNode; + class FileNode; + class Node { + protected: + DirectoryNode *parent; + QString name; + public: + Node(const QString &_name, DirectoryNode *_parent = 0) + : parent(_parent), name(_name) { } + virtual ~Node() { }; + DirectoryNode *getParent() const { return parent; } + QString getName() const { return name; } + }; + class DirectoryNode : public Node, public QList { + public: + DirectoryNode(const QString &_name = QString(), DirectoryNode *_parent = 0); + ~DirectoryNode(); + void clearTree(); + QString getPath() const; + DirectoryNode *getNodeByPath(QStringList path); + FileNode *getNodeById(int id) const; + }; + class FileNode : public Node { + private: + int id; + QDateTime uploadTime; + public: + FileNode(const QString &_name, int _id, const QDateTime &_uploadTime, DirectoryNode *_parent = 0) + : Node(_name, _parent), id(_id), uploadTime(_uploadTime) { } + int getId() const { return id; } + QDateTime getUploadTime() const { return uploadTime; } + }; + + template T getNode(const QModelIndex &index) const + { + if (!index.isValid()) + return dynamic_cast(root); + return dynamic_cast(static_cast(index.internalPointer())); + } private: - AbstractClient *client; - DirectoryNode *root; - - QIcon fileIcon, dirIcon; - - QModelIndex nodeToIndex(Node *node) const; + AbstractClient *client; + DirectoryNode *root; + + QIcon fileIcon, dirIcon; + + QModelIndex nodeToIndex(Node *node) const; signals: - void treeRefreshed(); + void treeRefreshed(); private slots: - void deckListFinished(const Response &r); + void deckListFinished(const Response &r); public: - RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent = 0); - ~RemoteDeckList_TreeModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index) const; - Qt::ItemFlags flags(const QModelIndex &index) const; + RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent = 0); + ~RemoteDeckList_TreeModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + Qt::ItemFlags flags(const QModelIndex &index) const; - DirectoryNode *getRoot() const { return root; } - void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent); - void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent); - DirectoryNode *addNamedFolderToTree(const QString &name, DirectoryNode *parent); - void removeNode(Node *node); - void refreshTree(); + DirectoryNode *getRoot() const { return root; } + void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, DirectoryNode *parent); + void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, DirectoryNode *parent); + DirectoryNode *addNamedFolderToTree(const QString &name, DirectoryNode *parent); + void removeNode(Node *node); + void refreshTree(); }; class RemoteDeckList_TreeWidget : public QTreeView { private: - RemoteDeckList_TreeModel *treeModel; - QSortFilterProxyModel *proxyModel; + RemoteDeckList_TreeModel *treeModel; + QSortFilterProxyModel *proxyModel; public: - RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); - RemoteDeckList_TreeModel::Node *getNode(const QModelIndex &ind) const; - RemoteDeckList_TreeModel::Node *getCurrentItem() const; - RemoteDeckList_TreeModel::DirectoryNode *getNodeByPath(const QString &path) const; - RemoteDeckList_TreeModel::FileNode *getNodeById(int id) const; - void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent); - void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent); - void addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent); - void removeNode(RemoteDeckList_TreeModel::Node *node); - void refreshTree(); + RemoteDeckList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); + RemoteDeckList_TreeModel::Node *getNode(const QModelIndex &ind) const; + RemoteDeckList_TreeModel::Node *getCurrentItem() const; + RemoteDeckList_TreeModel::DirectoryNode *getNodeByPath(const QString &path) const; + RemoteDeckList_TreeModel::FileNode *getNodeById(int id) const; + void addFileToTree(const ServerInfo_DeckStorage_TreeItem &file, RemoteDeckList_TreeModel::DirectoryNode *parent); + void addFolderToTree(const ServerInfo_DeckStorage_TreeItem &folder, RemoteDeckList_TreeModel::DirectoryNode *parent); + void addFolderToTree(const QString &name, RemoteDeckList_TreeModel::DirectoryNode *parent); + void removeNode(RemoteDeckList_TreeModel::Node *node); + void refreshTree(); }; #endif diff --git a/cockatrice/src/remotereplaylist_treewidget.cpp b/cockatrice/src/remotereplaylist_treewidget.cpp index ed2d823d..6184049e 100644 --- a/cockatrice/src/remotereplaylist_treewidget.cpp +++ b/cockatrice/src/remotereplaylist_treewidget.cpp @@ -12,286 +12,286 @@ const int RemoteReplayList_TreeModel::numberOfColumns = 6; RemoteReplayList_TreeModel::MatchNode::MatchNode(const ServerInfo_ReplayMatch &_matchInfo) - : RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo) + : RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo) { - for (int i = 0; i < matchInfo.replay_list_size(); ++i) - append(new ReplayNode(matchInfo.replay_list(i), this)); + for (int i = 0; i < matchInfo.replay_list_size(); ++i) + append(new ReplayNode(matchInfo.replay_list(i), this)); } RemoteReplayList_TreeModel::MatchNode::~MatchNode() { - for (int i = 0; i < size(); ++i) - delete at(i); + for (int i = 0; i < size(); ++i) + delete at(i); } void RemoteReplayList_TreeModel::MatchNode::updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo) { - matchInfo.MergeFrom(_matchInfo); + matchInfo.MergeFrom(_matchInfo); } RemoteReplayList_TreeModel::RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent) - : QAbstractItemModel(parent), client(_client) + : QAbstractItemModel(parent), client(_client) { - QFileIconProvider fip; - dirIcon = fip.icon(QFileIconProvider::Folder); - fileIcon = fip.icon(QFileIconProvider::File); - lockIcon = QIcon(":/resources/lock.svg"); + QFileIconProvider fip; + dirIcon = fip.icon(QFileIconProvider::Folder); + fileIcon = fip.icon(QFileIconProvider::File); + lockIcon = QIcon(":/resources/lock.svg"); - refreshTree(); + refreshTree(); } RemoteReplayList_TreeModel::~RemoteReplayList_TreeModel() { - clearTree(); + clearTree(); } int RemoteReplayList_TreeModel::rowCount(const QModelIndex &parent) const { - if (!parent.isValid()) - return replayMatches.size(); - - MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); - if (matchNode) - return matchNode->size(); - else - return 0; + if (!parent.isValid()) + return replayMatches.size(); + + MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); + if (matchNode) + return matchNode->size(); + else + return 0; } QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) const { - if (!index.isValid()) - return QVariant(); - if (index.column() >= numberOfColumns) - return QVariant(); - - ReplayNode *replayNode = dynamic_cast(static_cast(index.internalPointer())); - if (replayNode) { - const ServerInfo_Replay &replayInfo = replayNode->getReplayInfo(); - switch (role) { - case Qt::TextAlignmentRole: - return index.column() == 0 ? Qt::AlignRight : Qt::AlignLeft; - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return replayInfo.replay_id(); - case 1: return QString::fromStdString(replayInfo.replay_name()); - case 5: return replayInfo.duration(); - default: return QVariant(); - } - } - case Qt::DecorationRole: - return index.column() == 0 ? fileIcon : QVariant(); - } - } else { - MatchNode *matchNode = dynamic_cast(static_cast(index.internalPointer())); - const ServerInfo_ReplayMatch &matchInfo = matchNode->getMatchInfo(); - switch (role) { - case Qt::TextAlignmentRole: - switch (index.column()) { - case 0: - case 5: - return Qt::AlignRight; - default: - return Qt::AlignLeft; - } - case Qt::DisplayRole: { - switch (index.column()) { - case 0: return matchInfo.game_id(); - case 1: return QString::fromStdString(matchInfo.game_name()); - case 2: { - QStringList playerList; - for (int i = 0; i < matchInfo.player_names_size(); ++i) - playerList.append(QString::fromStdString(matchInfo.player_names(i))); - return playerList.join(", "); - } - case 4: return QDateTime::fromTime_t(matchInfo.time_started()); - case 5: return matchInfo.length(); - default: return QVariant(); - } - } - case Qt::DecorationRole: - switch (index.column()) { - case 0: return dirIcon; - case 3: return matchInfo.do_not_hide() ? lockIcon : QVariant(); - default: return QVariant(); - } - } - } - return QVariant(); + if (!index.isValid()) + return QVariant(); + if (index.column() >= numberOfColumns) + return QVariant(); + + ReplayNode *replayNode = dynamic_cast(static_cast(index.internalPointer())); + if (replayNode) { + const ServerInfo_Replay &replayInfo = replayNode->getReplayInfo(); + switch (role) { + case Qt::TextAlignmentRole: + return index.column() == 0 ? Qt::AlignRight : Qt::AlignLeft; + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return replayInfo.replay_id(); + case 1: return QString::fromStdString(replayInfo.replay_name()); + case 5: return replayInfo.duration(); + default: return QVariant(); + } + } + case Qt::DecorationRole: + return index.column() == 0 ? fileIcon : QVariant(); + } + } else { + MatchNode *matchNode = dynamic_cast(static_cast(index.internalPointer())); + const ServerInfo_ReplayMatch &matchInfo = matchNode->getMatchInfo(); + switch (role) { + case Qt::TextAlignmentRole: + switch (index.column()) { + case 0: + case 5: + return Qt::AlignRight; + default: + return Qt::AlignLeft; + } + case Qt::DisplayRole: { + switch (index.column()) { + case 0: return matchInfo.game_id(); + case 1: return QString::fromStdString(matchInfo.game_name()); + case 2: { + QStringList playerList; + for (int i = 0; i < matchInfo.player_names_size(); ++i) + playerList.append(QString::fromStdString(matchInfo.player_names(i))); + return playerList.join(", "); + } + case 4: return QDateTime::fromTime_t(matchInfo.time_started()); + case 5: return matchInfo.length(); + default: return QVariant(); + } + } + case Qt::DecorationRole: + switch (index.column()) { + case 0: return dirIcon; + case 3: return matchInfo.do_not_hide() ? lockIcon : QVariant(); + default: return QVariant(); + } + } + } + return QVariant(); } QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (orientation != Qt::Horizontal) - return QVariant(); - switch (role) { - case Qt::TextAlignmentRole: - switch (section) { - case 0: - case 5: - return Qt::AlignRight; - default: - return Qt::AlignLeft; - } - case Qt::DisplayRole: { - switch (section) { - case 0: return tr("ID"); - case 1: return tr("Name"); - case 2: return tr("Players"); - case 3: return tr("Keep"); - case 4: return tr("Time started"); - case 5: return tr("Duration (sec)"); - default: return QVariant(); - } - } - default: return QVariant(); - } + if (orientation != Qt::Horizontal) + return QVariant(); + switch (role) { + case Qt::TextAlignmentRole: + switch (section) { + case 0: + case 5: + return Qt::AlignRight; + default: + return Qt::AlignLeft; + } + case Qt::DisplayRole: { + switch (section) { + case 0: return tr("ID"); + case 1: return tr("Name"); + case 2: return tr("Players"); + case 3: return tr("Keep"); + case 4: return tr("Time started"); + case 5: return tr("Duration (sec)"); + default: return QVariant(); + } + } + default: return QVariant(); + } } QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelIndex &parent) const { - if (!hasIndex(row, column, parent)) - return QModelIndex(); - - MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); - if (matchNode) { - if (row >= matchNode->size()) - return QModelIndex(); - return createIndex(row, column, (void *) matchNode->at(row)); - } else { - if (row >= replayMatches.size()) - return QModelIndex(); - return createIndex(row, column, (void *) replayMatches[row]); - } + if (!hasIndex(row, column, parent)) + return QModelIndex(); + + MatchNode *matchNode = dynamic_cast(static_cast(parent.internalPointer())); + if (matchNode) { + if (row >= matchNode->size()) + return QModelIndex(); + return createIndex(row, column, (void *) matchNode->at(row)); + } else { + if (row >= replayMatches.size()) + return QModelIndex(); + return createIndex(row, column, (void *) replayMatches[row]); + } } QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const { - MatchNode const *matchNode = dynamic_cast(static_cast(ind.internalPointer())); - if (matchNode) - return QModelIndex(); - else { - ReplayNode *replayNode = dynamic_cast(static_cast(ind.internalPointer())); - return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode); - } + MatchNode const *matchNode = dynamic_cast(static_cast(ind.internalPointer())); + if (matchNode) + return QModelIndex(); + else { + ReplayNode *replayNode = dynamic_cast(static_cast(ind.internalPointer())); + return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode); + } } Qt::ItemFlags RemoteReplayList_TreeModel::flags(const QModelIndex &index) const { - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } ServerInfo_Replay const* RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const { - if (!index.isValid()) - return 0; - - ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); - if (!node) - return 0; - return &node->getReplayInfo(); + if (!index.isValid()) + return 0; + + ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); + if (!node) + return 0; + return &node->getReplayInfo(); } ServerInfo_ReplayMatch const* RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const { - if (!index.isValid()) - return 0; - - MatchNode *node = dynamic_cast(static_cast(index.internalPointer())); - if (!node) { - ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); - if (!node) - return 0; - return &node->getParent()->getMatchInfo(); - } else - return &node->getMatchInfo(); + if (!index.isValid()) + return 0; + + MatchNode *node = dynamic_cast(static_cast(index.internalPointer())); + if (!node) { + ReplayNode *node = dynamic_cast(static_cast(index.internalPointer())); + if (!node) + return 0; + return &node->getParent()->getMatchInfo(); + } else + return &node->getMatchInfo(); } void RemoteReplayList_TreeModel::clearTree() { - for (int i = 0; i < replayMatches.size(); ++i) - delete replayMatches[i]; - replayMatches.clear(); + for (int i = 0; i < replayMatches.size(); ++i) + delete replayMatches[i]; + replayMatches.clear(); } void RemoteReplayList_TreeModel::refreshTree() { - PendingCommand *pend = client->prepareSessionCommand(Command_ReplayList()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(replayListFinished(const Response &))); - - client->sendCommand(pend); + PendingCommand *pend = client->prepareSessionCommand(Command_ReplayList()); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(replayListFinished(const Response &))); + + client->sendCommand(pend); } void RemoteReplayList_TreeModel::addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { - beginInsertRows(QModelIndex(), replayMatches.size(), replayMatches.size()); - replayMatches.append(new MatchNode(matchInfo)); - endInsertRows(); - - emit treeRefreshed(); + beginInsertRows(QModelIndex(), replayMatches.size(), replayMatches.size()); + replayMatches.append(new MatchNode(matchInfo)); + endInsertRows(); + + emit treeRefreshed(); } void RemoteReplayList_TreeModel::updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { - for (int i = 0; i < replayMatches.size(); ++i) - if (replayMatches[i]->getMatchInfo().game_id() == gameId) { - replayMatches[i]->updateMatchInfo(matchInfo); - emit dataChanged(createIndex(i, 0, (void *) replayMatches[i]), createIndex(i, numberOfColumns - 1, (void *) replayMatches[i])); - break; - } + for (int i = 0; i < replayMatches.size(); ++i) + if (replayMatches[i]->getMatchInfo().game_id() == gameId) { + replayMatches[i]->updateMatchInfo(matchInfo); + emit dataChanged(createIndex(i, 0, (void *) replayMatches[i]), createIndex(i, numberOfColumns - 1, (void *) replayMatches[i])); + break; + } } void RemoteReplayList_TreeModel::removeMatchInfo(int gameId) { - for (int i = 0; i < replayMatches.size(); ++i) - if (replayMatches[i]->getMatchInfo().game_id() == gameId) { - beginRemoveRows(QModelIndex(), i, i); - replayMatches.removeAt(i); - endRemoveRows(); - break; - } + for (int i = 0; i < replayMatches.size(); ++i) + if (replayMatches[i]->getMatchInfo().game_id() == gameId) { + beginRemoveRows(QModelIndex(), i, i); + replayMatches.removeAt(i); + endRemoveRows(); + break; + } } void RemoteReplayList_TreeModel::replayListFinished(const Response &r) { - const Response_ReplayList &resp = r.GetExtension(Response_ReplayList::ext); - - beginResetModel(); - clearTree(); - - for (int i = 0; i < resp.match_list_size(); ++i) - replayMatches.append(new MatchNode(resp.match_list(i))); - - endResetModel(); - emit treeRefreshed(); + const Response_ReplayList &resp = r.GetExtension(Response_ReplayList::ext); + + beginResetModel(); + clearTree(); + + for (int i = 0; i < resp.match_list_size(); ++i) + replayMatches.append(new MatchNode(resp.match_list(i))); + + endResetModel(); + emit treeRefreshed(); } RemoteReplayList_TreeWidget::RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent) - : QTreeView(parent) + : QTreeView(parent) { - treeModel = new RemoteReplayList_TreeModel(_client, this); - proxyModel = new QSortFilterProxyModel(this); - proxyModel->setSourceModel(treeModel); - proxyModel->setDynamicSortFilter(true); - proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); - setModel(proxyModel); + treeModel = new RemoteReplayList_TreeModel(_client, this); + proxyModel = new QSortFilterProxyModel(this); + proxyModel->setSourceModel(treeModel); + proxyModel->setDynamicSortFilter(true); + proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + setModel(proxyModel); - header()->setResizeMode(QHeaderView::ResizeToContents); - header()->setStretchLastSection(false); - setUniformRowHeights(true); - setSortingEnabled(true); - proxyModel->sort(0, Qt::AscendingOrder); - header()->setSortIndicator(0, Qt::AscendingOrder); + header()->setResizeMode(QHeaderView::ResizeToContents); + header()->setStretchLastSection(false); + setUniformRowHeights(true); + setSortingEnabled(true); + proxyModel->sort(0, Qt::AscendingOrder); + header()->setSortIndicator(0, Qt::AscendingOrder); } ServerInfo_Replay const *RemoteReplayList_TreeWidget::getCurrentReplay() const { - return treeModel->getReplay(proxyModel->mapToSource(selectionModel()->currentIndex())); + return treeModel->getReplay(proxyModel->mapToSource(selectionModel()->currentIndex())); } ServerInfo_ReplayMatch const *RemoteReplayList_TreeWidget::getCurrentReplayMatch() const { - return treeModel->getReplayMatch(proxyModel->mapToSource(selectionModel()->currentIndex())); + return treeModel->getReplayMatch(proxyModel->mapToSource(selectionModel()->currentIndex())); } diff --git a/cockatrice/src/remotereplaylist_treewidget.h b/cockatrice/src/remotereplaylist_treewidget.h index 7397d21d..986e2fa4 100644 --- a/cockatrice/src/remotereplaylist_treewidget.h +++ b/cockatrice/src/remotereplaylist_treewidget.h @@ -12,82 +12,82 @@ class AbstractClient; class QSortFilterProxyModel; class RemoteReplayList_TreeModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT private: - class MatchNode; - class ReplayNode; - class Node { - protected: - QString name; - public: - Node(const QString &_name) - : name(_name) { } - virtual ~Node() { }; - QString getName() const { return name; } - }; - class MatchNode : public Node, public QList { - private: - ServerInfo_ReplayMatch matchInfo; - public: - MatchNode(const ServerInfo_ReplayMatch &_matchInfo); - ~MatchNode(); - void clearTree(); - const ServerInfo_ReplayMatch &getMatchInfo() { return matchInfo; } - void updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo); - }; - class ReplayNode : public Node { - private: - MatchNode *parent; - ServerInfo_Replay replayInfo; - public: - ReplayNode(const ServerInfo_Replay &_replayInfo, MatchNode *_parent) - : Node(QString::fromStdString(_replayInfo.replay_name())), parent(_parent), replayInfo(_replayInfo) { } - MatchNode *getParent() const { return parent; } - const ServerInfo_Replay &getReplayInfo() { return replayInfo; } - }; - - AbstractClient *client; - QList replayMatches; - - QIcon dirIcon, fileIcon, lockIcon; - void clearTree(); - - static const int numberOfColumns; + class MatchNode; + class ReplayNode; + class Node { + protected: + QString name; + public: + Node(const QString &_name) + : name(_name) { } + virtual ~Node() { }; + QString getName() const { return name; } + }; + class MatchNode : public Node, public QList { + private: + ServerInfo_ReplayMatch matchInfo; + public: + MatchNode(const ServerInfo_ReplayMatch &_matchInfo); + ~MatchNode(); + void clearTree(); + const ServerInfo_ReplayMatch &getMatchInfo() { return matchInfo; } + void updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo); + }; + class ReplayNode : public Node { + private: + MatchNode *parent; + ServerInfo_Replay replayInfo; + public: + ReplayNode(const ServerInfo_Replay &_replayInfo, MatchNode *_parent) + : Node(QString::fromStdString(_replayInfo.replay_name())), parent(_parent), replayInfo(_replayInfo) { } + MatchNode *getParent() const { return parent; } + const ServerInfo_Replay &getReplayInfo() { return replayInfo; } + }; + + AbstractClient *client; + QList replayMatches; + + QIcon dirIcon, fileIcon, lockIcon; + void clearTree(); + + static const int numberOfColumns; signals: - void treeRefreshed(); + void treeRefreshed(); private slots: - void replayListFinished(const Response &r); + void replayListFinished(const Response &r); public: - RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent = 0); - ~RemoteReplayList_TreeModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return numberOfColumns; } - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex &index) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - void refreshTree(); - ServerInfo_Replay const* getReplay(const QModelIndex &index) const; - ServerInfo_ReplayMatch const* getReplayMatch(const QModelIndex &index) const; - void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo); - void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo); - void removeMatchInfo(int gameId); + RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent = 0); + ~RemoteReplayList_TreeModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/ = QModelIndex()) const { return numberOfColumns; } + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + void refreshTree(); + ServerInfo_Replay const* getReplay(const QModelIndex &index) const; + ServerInfo_ReplayMatch const* getReplayMatch(const QModelIndex &index) const; + void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo); + void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo); + void removeMatchInfo(int gameId); }; class RemoteReplayList_TreeWidget : public QTreeView { private: - RemoteReplayList_TreeModel *treeModel; - QSortFilterProxyModel *proxyModel; - ServerInfo_Replay const *getNode(const QModelIndex &ind) const; + RemoteReplayList_TreeModel *treeModel; + QSortFilterProxyModel *proxyModel; + ServerInfo_Replay const *getNode(const QModelIndex &ind) const; public: - RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); - ServerInfo_Replay const *getCurrentReplay() const; - ServerInfo_ReplayMatch const *getCurrentReplayMatch() const; - void refreshTree(); - void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { treeModel->addMatchInfo(matchInfo); } - void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { treeModel->updateMatchInfo(gameId, matchInfo); } - void removeMatchInfo(int gameId) { treeModel->removeMatchInfo(gameId); } + RemoteReplayList_TreeWidget(AbstractClient *_client, QWidget *parent = 0); + ServerInfo_Replay const *getCurrentReplay() const; + ServerInfo_ReplayMatch const *getCurrentReplayMatch() const; + void refreshTree(); + void addMatchInfo(const ServerInfo_ReplayMatch &matchInfo) { treeModel->addMatchInfo(matchInfo); } + void updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) { treeModel->updateMatchInfo(gameId, matchInfo); } + void removeMatchInfo(int gameId) { treeModel->removeMatchInfo(gameId); } }; #endif diff --git a/cockatrice/src/replay_timeline_widget.cpp b/cockatrice/src/replay_timeline_widget.cpp index 071cb7b6..7934fb0e 100644 --- a/cockatrice/src/replay_timeline_widget.cpp +++ b/cockatrice/src/replay_timeline_widget.cpp @@ -5,97 +5,97 @@ #include ReplayTimelineWidget::ReplayTimelineWidget(QWidget *parent) - : QWidget(parent), maxBinValue(1), maxTime(1), timeScaleFactor(1.0), currentTime(0), currentEvent(0) + : QWidget(parent), maxBinValue(1), maxTime(1), timeScaleFactor(1.0), currentTime(0), currentEvent(0) { - replayTimer = new QTimer(this); - connect(replayTimer, SIGNAL(timeout()), this, SLOT(replayTimerTimeout())); + replayTimer = new QTimer(this); + connect(replayTimer, SIGNAL(timeout()), this, SLOT(replayTimerTimeout())); } const int ReplayTimelineWidget::binLength = 5000; void ReplayTimelineWidget::setTimeline(const QList &_replayTimeline) { - replayTimeline = _replayTimeline; - histogram.clear(); - int binEndTime = binLength - 1; - int binValue = 0; - for (int i = 0; i < replayTimeline.size(); ++i) { - if (replayTimeline[i] > binEndTime) { - histogram.append(binValue); - if (binValue > maxBinValue) - maxBinValue = binValue; - while (replayTimeline[i] > binEndTime + binLength) { - histogram.append(0); - binEndTime += binLength; - } - binValue = 1; - binEndTime += binLength; - } else - ++binValue; - } - histogram.append(binValue); - if (!replayTimeline.isEmpty()) - maxTime = replayTimeline.last(); - - update(); + replayTimeline = _replayTimeline; + histogram.clear(); + int binEndTime = binLength - 1; + int binValue = 0; + for (int i = 0; i < replayTimeline.size(); ++i) { + if (replayTimeline[i] > binEndTime) { + histogram.append(binValue); + if (binValue > maxBinValue) + maxBinValue = binValue; + while (replayTimeline[i] > binEndTime + binLength) { + histogram.append(0); + binEndTime += binLength; + } + binValue = 1; + binEndTime += binLength; + } else + ++binValue; + } + histogram.append(binValue); + if (!replayTimeline.isEmpty()) + maxTime = replayTimeline.last(); + + update(); } void ReplayTimelineWidget::paintEvent(QPaintEvent *event) { - QPainter painter(this); - painter.drawRect(0, 0, width() - 1, height() - 1); - - qreal binWidth = (qreal) width() / histogram.size(); - QPainterPath path; - path.moveTo(0, height() - 1); - for (int i = 0; i < histogram.size(); ++i) - path.lineTo(round(i * binWidth), (height() - 1) * (1.0 - (qreal) histogram[i] / maxBinValue)); - path.lineTo(width() - 1, height() - 1); - path.lineTo(0, height() - 1); - painter.fillPath(path, Qt::black); - - const QColor barColor = QColor::fromHsv(120, 255, 255, 100); - painter.fillRect(0, 0, (width() - 1) * currentTime / maxTime, height() - 1, barColor); + QPainter painter(this); + painter.drawRect(0, 0, width() - 1, height() - 1); + + qreal binWidth = (qreal) width() / histogram.size(); + QPainterPath path; + path.moveTo(0, height() - 1); + for (int i = 0; i < histogram.size(); ++i) + path.lineTo(round(i * binWidth), (height() - 1) * (1.0 - (qreal) histogram[i] / maxBinValue)); + path.lineTo(width() - 1, height() - 1); + path.lineTo(0, height() - 1); + painter.fillPath(path, Qt::black); + + const QColor barColor = QColor::fromHsv(120, 255, 255, 100); + painter.fillRect(0, 0, (width() - 1) * currentTime / maxTime, height() - 1, barColor); } QSize ReplayTimelineWidget::sizeHint() const { - return QSize(-1, 50); + return QSize(-1, 50); } QSize ReplayTimelineWidget::minimumSizeHint() const { - return QSize(400, 50); + return QSize(400, 50); } void ReplayTimelineWidget::replayTimerTimeout() { - currentTime += 200; - while ((currentEvent < replayTimeline.size()) && (replayTimeline[currentEvent] < currentTime)) { - emit processNextEvent(); - ++currentEvent; - } - if (currentEvent == replayTimeline.size()) { - emit replayFinished(); - replayTimer->stop(); - } - - if (!(currentTime % 1000)) - update(); + currentTime += 200; + while ((currentEvent < replayTimeline.size()) && (replayTimeline[currentEvent] < currentTime)) { + emit processNextEvent(); + ++currentEvent; + } + if (currentEvent == replayTimeline.size()) { + emit replayFinished(); + replayTimer->stop(); + } + + if (!(currentTime % 1000)) + update(); } void ReplayTimelineWidget::setTimeScaleFactor(qreal _timeScaleFactor) { - timeScaleFactor = _timeScaleFactor; - replayTimer->setInterval(200 / timeScaleFactor); + timeScaleFactor = _timeScaleFactor; + replayTimer->setInterval(200 / timeScaleFactor); } void ReplayTimelineWidget::startReplay() { - replayTimer->start(200 / timeScaleFactor); + replayTimer->start(200 / timeScaleFactor); } void ReplayTimelineWidget::stopReplay() { - replayTimer->stop(); + replayTimer->stop(); } diff --git a/cockatrice/src/replay_timeline_widget.h b/cockatrice/src/replay_timeline_widget.h index 3a1b6712..8c668393 100644 --- a/cockatrice/src/replay_timeline_widget.h +++ b/cockatrice/src/replay_timeline_widget.h @@ -8,33 +8,33 @@ class QPaintEvent; class QTimer; class ReplayTimelineWidget : public QWidget { - Q_OBJECT + Q_OBJECT signals: - void processNextEvent(); - void replayFinished(); + void processNextEvent(); + void replayFinished(); private: - QTimer *replayTimer; - QList replayTimeline; - QList histogram; - static const int binLength; - int maxBinValue, maxTime; - qreal timeScaleFactor; - int currentTime; - int currentEvent; + QTimer *replayTimer; + QList replayTimeline; + QList histogram; + static const int binLength; + int maxBinValue, maxTime; + qreal timeScaleFactor; + int currentTime; + int currentEvent; private slots: - void replayTimerTimeout(); + void replayTimerTimeout(); public: - ReplayTimelineWidget(QWidget *parent = 0); - void setTimeline(const QList &_replayTimeline); - QSize sizeHint() const; - QSize minimumSizeHint() const; - void setTimeScaleFactor(qreal _timeScaleFactor); - int getCurrentEvent() const { return currentEvent; } + ReplayTimelineWidget(QWidget *parent = 0); + void setTimeline(const QList &_replayTimeline); + QSize sizeHint() const; + QSize minimumSizeHint() const; + void setTimeScaleFactor(qreal _timeScaleFactor); + int getCurrentEvent() const { return currentEvent; } public slots: - void startReplay(); - void stopReplay(); + void startReplay(); + void stopReplay(); protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent *event); }; #endif diff --git a/cockatrice/src/selectzone.cpp b/cockatrice/src/selectzone.cpp index f7168b2e..be966352 100644 --- a/cockatrice/src/selectzone.cpp +++ b/cockatrice/src/selectzone.cpp @@ -5,52 +5,52 @@ #include SelectZone::SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent, bool isView) - : CardZone(_player, _name, _hasCardAttr, _isShufflable, _contentsKnown, parent, isView) + : CardZone(_player, _name, _hasCardAttr, _isShufflable, _contentsKnown, parent, isView) { } void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (event->buttons().testFlag(Qt::LeftButton)) { - QPointF pos = event->pos(); - if (pos.x() < 0) - pos.setX(0); - QRectF br = boundingRect(); - if (pos.x() > br.width()) - pos.setX(br.width()); - if (pos.y() < 0) - pos.setY(0); - if (pos.y() > br.height()) - pos.setY(br.height()); - - QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); - for (int i = 0; i < cards.size(); ++i) { - if (cards[i]->getAttachedTo()) - if (cards[i]->getAttachedTo()->getZone() != this) - continue; - cards[i]->setSelected(selectionRect.intersects(cards[i]->mapRectToParent(cards[i]->boundingRect()))); - } - static_cast(scene())->resizeRubberBand(deviceTransform(static_cast(scene())->getViewportTransform()).map(pos)); - event->accept(); - } + if (event->buttons().testFlag(Qt::LeftButton)) { + QPointF pos = event->pos(); + if (pos.x() < 0) + pos.setX(0); + QRectF br = boundingRect(); + if (pos.x() > br.width()) + pos.setX(br.width()); + if (pos.y() < 0) + pos.setY(0); + if (pos.y() > br.height()) + pos.setY(br.height()); + + QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); + for (int i = 0; i < cards.size(); ++i) { + if (cards[i]->getAttachedTo()) + if (cards[i]->getAttachedTo()->getZone() != this) + continue; + cards[i]->setSelected(selectionRect.intersects(cards[i]->mapRectToParent(cards[i]->boundingRect()))); + } + static_cast(scene())->resizeRubberBand(deviceTransform(static_cast(scene())->getViewportTransform()).map(pos)); + event->accept(); + } } void SelectZone::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - scene()->clearSelection(); - - selectionOrigin = event->pos(); - static_cast(scene())->startRubberBand(event->scenePos()); - event->accept(); - } else - CardZone::mousePressEvent(event); + if (event->button() == Qt::LeftButton) { + scene()->clearSelection(); + + selectionOrigin = event->pos(); + static_cast(scene())->startRubberBand(event->scenePos()); + event->accept(); + } else + CardZone::mousePressEvent(event); } void SelectZone::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { - selectionOrigin = QPoint(); - static_cast(scene())->stopRubberBand(); - event->accept(); + selectionOrigin = QPoint(); + static_cast(scene())->stopRubberBand(); + event->accept(); } diff --git a/cockatrice/src/selectzone.h b/cockatrice/src/selectzone.h index 23e82d1c..347e9a52 100644 --- a/cockatrice/src/selectzone.h +++ b/cockatrice/src/selectzone.h @@ -4,15 +4,15 @@ #include "cardzone.h" class SelectZone : public CardZone { - Q_OBJECT + Q_OBJECT private: - QPointF selectionOrigin; + QPointF selectionOrigin; protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); public: - SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool isView = false); + SelectZone(Player *_player, const QString &_name, bool _hasCardAttr, bool _isShufflable, bool _contentsKnown, QGraphicsItem *parent = 0, bool isView = false); }; #endif diff --git a/cockatrice/src/setsmodel.cpp b/cockatrice/src/setsmodel.cpp index f0ca77e7..f11d73c4 100644 --- a/cockatrice/src/setsmodel.cpp +++ b/cockatrice/src/setsmodel.cpp @@ -1,9 +1,9 @@ #include "setsmodel.h" SetsModel::SetsModel(CardDatabase *_db, QObject *parent) - : QAbstractTableModel(parent), sets(_db->getSetList()) + : QAbstractTableModel(parent), sets(_db->getSetList()) { - sets.sortByKey(); + sets.sortByKey(); } SetsModel::~SetsModel() @@ -12,82 +12,82 @@ SetsModel::~SetsModel() int SetsModel::rowCount(const QModelIndex &parent) const { - if (parent.isValid()) - return 0; - else - return sets.size(); + if (parent.isValid()) + return 0; + else + return sets.size(); } QVariant SetsModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || (index.column() >= 2) || (index.row() >= rowCount()) || (role != Qt::DisplayRole)) - return QVariant(); + if (!index.isValid() || (index.column() >= 2) || (index.row() >= rowCount()) || (role != Qt::DisplayRole)) + return QVariant(); - CardSet *set = sets[index.row()]; - switch (index.column()) { - case 0: return set->getShortName(); - case 1: return set->getLongName(); - default: return QVariant(); - } + CardSet *set = sets[index.row()]; + switch (index.column()) { + case 0: return set->getShortName(); + case 1: return set->getLongName(); + default: return QVariant(); + } } QVariant SetsModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) - return QVariant(); - switch (section) { - case 0: return tr("Short name"); - case 1: return tr("Long name"); - default: return QVariant(); - } + if ((role != Qt::DisplayRole) || (orientation != Qt::Horizontal)) + return QVariant(); + switch (section) { + case 0: return tr("Short name"); + case 1: return tr("Long name"); + default: return QVariant(); + } } Qt::ItemFlags SetsModel::flags(const QModelIndex &index) const { - Qt::ItemFlags result = QAbstractTableModel::flags(index); - return result | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; + Qt::ItemFlags result = QAbstractTableModel::flags(index); + return result | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; } Qt::DropActions SetsModel::supportedDropActions() const { - return Qt::MoveAction; + return Qt::MoveAction; } QMimeData *SetsModel::mimeData(const QModelIndexList &indexes) const { - if (indexes.isEmpty()) - return 0; + if (indexes.isEmpty()) + return 0; - SetsMimeData *result = new SetsMimeData(indexes[0].row()); - return qobject_cast(result); + SetsMimeData *result = new SetsMimeData(indexes[0].row()); + return qobject_cast(result); } bool SetsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int /*column*/, const QModelIndex &parent) { - if (action != Qt::MoveAction) - return false; - if (row == -1) { - if (!parent.isValid()) - return false; - row = parent.row(); - } - int oldRow = qobject_cast(data)->getOldRow(); - beginRemoveRows(QModelIndex(), oldRow, oldRow); - CardSet *temp = sets.takeAt(oldRow); - endRemoveRows(); - if (oldRow < row) - row--; - beginInsertRows(QModelIndex(), row, row); - sets.insert(row, temp); - endInsertRows(); + if (action != Qt::MoveAction) + return false; + if (row == -1) { + if (!parent.isValid()) + return false; + row = parent.row(); + } + int oldRow = qobject_cast(data)->getOldRow(); + beginRemoveRows(QModelIndex(), oldRow, oldRow); + CardSet *temp = sets.takeAt(oldRow); + endRemoveRows(); + if (oldRow < row) + row--; + beginInsertRows(QModelIndex(), row, row); + sets.insert(row, temp); + endInsertRows(); - for (int i = 0; i < sets.size(); i++) - sets[i]->setSortKey(i); + for (int i = 0; i < sets.size(); i++) + sets[i]->setSortKey(i); - return true; + return true; } QStringList SetsModel::mimeTypes() const { - return QStringList() << "application/x-cockatricecardset"; + return QStringList() << "application/x-cockatricecardset"; } diff --git a/cockatrice/src/setsmodel.h b/cockatrice/src/setsmodel.h index 5d61b57c..74d29443 100644 --- a/cockatrice/src/setsmodel.h +++ b/cockatrice/src/setsmodel.h @@ -6,32 +6,32 @@ #include "carddatabase.h" class SetsMimeData : public QMimeData { - Q_OBJECT + Q_OBJECT private: - int oldRow; + int oldRow; public: - SetsMimeData(int _oldRow) : oldRow(_oldRow) { } - int getOldRow() const { return oldRow; } - QStringList formats() const { return QStringList() << "application/x-cockatricecardset"; } + SetsMimeData(int _oldRow) : oldRow(_oldRow) { } + int getOldRow() const { return oldRow; } + QStringList formats() const { return QStringList() << "application/x-cockatricecardset"; } }; class SetsModel : public QAbstractTableModel { - Q_OBJECT + Q_OBJECT public: - SetsModel(CardDatabase *_db, QObject *parent = 0); - ~SetsModel(); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - int columnCount(const QModelIndex &/*parent*/) const { return 2; } - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - Qt::DropActions supportedDropActions() const; + SetsModel(CardDatabase *_db, QObject *parent = 0); + ~SetsModel(); + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &/*parent*/) const { return 2; } + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + Qt::DropActions supportedDropActions() const; - QMimeData *mimeData(const QModelIndexList &indexes) const; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); - QStringList mimeTypes() const; + QMimeData *mimeData(const QModelIndexList &indexes) const; + bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); + QStringList mimeTypes() const; private: - SetList sets; + SetList sets; }; #endif diff --git a/cockatrice/src/settingscache.cpp b/cockatrice/src/settingscache.cpp index 1c2e9b34..b73d6d86 100644 --- a/cockatrice/src/settingscache.cpp +++ b/cockatrice/src/settingscache.cpp @@ -3,233 +3,233 @@ SettingsCache::SettingsCache() { - settings = new QSettings(this); - - lang = settings->value("personal/lang").toString(); - - deckPath = settings->value("paths/decks").toString(); - replaysPath = settings->value("paths/replays").toString(); - picsPath = settings->value("paths/pics").toString(); - cardDatabasePath = settings->value("paths/carddatabase").toString(); - tokenDatabasePath = settings->value("paths/tokendatabase").toString(); - - handBgPath = settings->value("zonebg/hand").toString(); - stackBgPath = settings->value("zonebg/stack").toString(); - tableBgPath = settings->value("zonebg/table").toString(); - playerBgPath = settings->value("zonebg/playerarea").toString(); - cardBackPicturePath = settings->value("paths/cardbackpicture").toString(); - - mainWindowGeometry = settings->value("interface/main_window_geometry").toByteArray(); - picDownload = settings->value("personal/picturedownload", true).toBool(); - notificationsEnabled = settings->value("interface/notificationsenabled", true).toBool(); - doubleClickToPlay = settings->value("interface/doubleclicktoplay", true).toBool(); - playToStack = settings->value("interface/playtostack", false).toBool(); - cardInfoMinimized = settings->value("interface/cardinfominimized", 0).toInt(); - tabGameSplitterSizes = settings->value("interface/tabgame_splittersizes").toByteArray(); - displayCardNames = settings->value("cards/displaycardnames", true).toBool(); - horizontalHand = settings->value("hand/horizontal", true).toBool(); - invertVerticalCoordinate = settings->value("table/invert_vertical", false).toBool(); - minPlayersForMultiColumnLayout = settings->value("interface/min_players_multicolumn", 5).toInt(); - tapAnimation = settings->value("cards/tapanimation", true).toBool(); - - zoneViewSortByName = settings->value("zoneview/sortbyname", true).toBool(); - zoneViewSortByType = settings->value("zoneview/sortbytype", true).toBool(); - - soundEnabled = settings->value("sound/enabled", false).toBool(); - soundPath = settings->value("sound/path").toString(); - - priceTagFeature = settings->value("deckeditor/pricetags", false).toBool(); - - ignoreUnregisteredUsers = settings->value("chat/ignore_unregistered", false).toBool(); + settings = new QSettings(this); + + lang = settings->value("personal/lang").toString(); + + deckPath = settings->value("paths/decks").toString(); + replaysPath = settings->value("paths/replays").toString(); + picsPath = settings->value("paths/pics").toString(); + cardDatabasePath = settings->value("paths/carddatabase").toString(); + tokenDatabasePath = settings->value("paths/tokendatabase").toString(); + + handBgPath = settings->value("zonebg/hand").toString(); + stackBgPath = settings->value("zonebg/stack").toString(); + tableBgPath = settings->value("zonebg/table").toString(); + playerBgPath = settings->value("zonebg/playerarea").toString(); + cardBackPicturePath = settings->value("paths/cardbackpicture").toString(); + + mainWindowGeometry = settings->value("interface/main_window_geometry").toByteArray(); + picDownload = settings->value("personal/picturedownload", true).toBool(); + notificationsEnabled = settings->value("interface/notificationsenabled", true).toBool(); + doubleClickToPlay = settings->value("interface/doubleclicktoplay", true).toBool(); + playToStack = settings->value("interface/playtostack", false).toBool(); + cardInfoMinimized = settings->value("interface/cardinfominimized", 0).toInt(); + tabGameSplitterSizes = settings->value("interface/tabgame_splittersizes").toByteArray(); + displayCardNames = settings->value("cards/displaycardnames", true).toBool(); + horizontalHand = settings->value("hand/horizontal", true).toBool(); + invertVerticalCoordinate = settings->value("table/invert_vertical", false).toBool(); + minPlayersForMultiColumnLayout = settings->value("interface/min_players_multicolumn", 5).toInt(); + tapAnimation = settings->value("cards/tapanimation", true).toBool(); + + zoneViewSortByName = settings->value("zoneview/sortbyname", true).toBool(); + zoneViewSortByType = settings->value("zoneview/sortbytype", true).toBool(); + + soundEnabled = settings->value("sound/enabled", false).toBool(); + soundPath = settings->value("sound/path").toString(); + + priceTagFeature = settings->value("deckeditor/pricetags", false).toBool(); + + ignoreUnregisteredUsers = settings->value("chat/ignore_unregistered", false).toBool(); } void SettingsCache::setLang(const QString &_lang) { - lang = _lang; - settings->setValue("personal/lang", lang); - emit langChanged(); + lang = _lang; + settings->setValue("personal/lang", lang); + emit langChanged(); } void SettingsCache::setDeckPath(const QString &_deckPath) { - deckPath = _deckPath; - settings->setValue("paths/decks", deckPath); + deckPath = _deckPath; + settings->setValue("paths/decks", deckPath); } void SettingsCache::setReplaysPath(const QString &_replaysPath) { - replaysPath = _replaysPath; - settings->setValue("paths/replays", replaysPath); + replaysPath = _replaysPath; + settings->setValue("paths/replays", replaysPath); } void SettingsCache::setPicsPath(const QString &_picsPath) { - picsPath = _picsPath; - settings->setValue("paths/pics", picsPath); - emit picsPathChanged(); + picsPath = _picsPath; + settings->setValue("paths/pics", picsPath); + emit picsPathChanged(); } void SettingsCache::setCardDatabasePath(const QString &_cardDatabasePath) { - cardDatabasePath = _cardDatabasePath; - settings->setValue("paths/carddatabase", cardDatabasePath); - emit cardDatabasePathChanged(); + cardDatabasePath = _cardDatabasePath; + settings->setValue("paths/carddatabase", cardDatabasePath); + emit cardDatabasePathChanged(); } void SettingsCache::setTokenDatabasePath(const QString &_tokenDatabasePath) { - tokenDatabasePath = _tokenDatabasePath; - settings->setValue("paths/tokendatabase", tokenDatabasePath); - emit tokenDatabasePathChanged(); + tokenDatabasePath = _tokenDatabasePath; + settings->setValue("paths/tokendatabase", tokenDatabasePath); + emit tokenDatabasePathChanged(); } void SettingsCache::setHandBgPath(const QString &_handBgPath) { - handBgPath = _handBgPath; - settings->setValue("zonebg/hand", handBgPath); - emit handBgPathChanged(); + handBgPath = _handBgPath; + settings->setValue("zonebg/hand", handBgPath); + emit handBgPathChanged(); } void SettingsCache::setStackBgPath(const QString &_stackBgPath) { - stackBgPath = _stackBgPath; - settings->setValue("zonebg/stack", stackBgPath); - emit stackBgPathChanged(); + stackBgPath = _stackBgPath; + settings->setValue("zonebg/stack", stackBgPath); + emit stackBgPathChanged(); } void SettingsCache::setTableBgPath(const QString &_tableBgPath) { - tableBgPath = _tableBgPath; - settings->setValue("zonebg/table", tableBgPath); - emit tableBgPathChanged(); + tableBgPath = _tableBgPath; + settings->setValue("zonebg/table", tableBgPath); + emit tableBgPathChanged(); } void SettingsCache::setPlayerBgPath(const QString &_playerBgPath) { - playerBgPath = _playerBgPath; - settings->setValue("zonebg/playerarea", playerBgPath); - emit playerBgPathChanged(); + playerBgPath = _playerBgPath; + settings->setValue("zonebg/playerarea", playerBgPath); + emit playerBgPathChanged(); } void SettingsCache::setCardBackPicturePath(const QString &_cardBackPicturePath) { - cardBackPicturePath = _cardBackPicturePath; - settings->setValue("paths/cardbackpicture", cardBackPicturePath); - emit cardBackPicturePathChanged(); + cardBackPicturePath = _cardBackPicturePath; + settings->setValue("paths/cardbackpicture", cardBackPicturePath); + emit cardBackPicturePathChanged(); } void SettingsCache::setPicDownload(int _picDownload) { - picDownload = _picDownload; - settings->setValue("personal/picturedownload", picDownload); - emit picDownloadChanged(); + picDownload = _picDownload; + settings->setValue("personal/picturedownload", picDownload); + emit picDownloadChanged(); } void SettingsCache::setNotificationsEnabled(int _notificationsEnabled) { - notificationsEnabled = _notificationsEnabled; - settings->setValue("interface/notificationsenabled", notificationsEnabled); + notificationsEnabled = _notificationsEnabled; + settings->setValue("interface/notificationsenabled", notificationsEnabled); } void SettingsCache::setDoubleClickToPlay(int _doubleClickToPlay) { - doubleClickToPlay = _doubleClickToPlay; - settings->setValue("interface/doubleclicktoplay", doubleClickToPlay); + doubleClickToPlay = _doubleClickToPlay; + settings->setValue("interface/doubleclicktoplay", doubleClickToPlay); } void SettingsCache::setPlayToStack(int _playToStack) { - playToStack = _playToStack; - settings->setValue("interface/playtostack", playToStack); + playToStack = _playToStack; + settings->setValue("interface/playtostack", playToStack); } void SettingsCache::setCardInfoMinimized(int _cardInfoMinimized) { cardInfoMinimized = _cardInfoMinimized; - settings->setValue("interface/cardinfominimized", cardInfoMinimized); + settings->setValue("interface/cardinfominimized", cardInfoMinimized); } void SettingsCache::setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes) { - tabGameSplitterSizes = _tabGameSplitterSizes; - settings->setValue("interface/tabgame_splittersizes", tabGameSplitterSizes); + tabGameSplitterSizes = _tabGameSplitterSizes; + settings->setValue("interface/tabgame_splittersizes", tabGameSplitterSizes); } void SettingsCache::setDisplayCardNames(int _displayCardNames) { - displayCardNames = _displayCardNames; - settings->setValue("cards/displaycardnames", displayCardNames); - emit displayCardNamesChanged(); + displayCardNames = _displayCardNames; + settings->setValue("cards/displaycardnames", displayCardNames); + emit displayCardNamesChanged(); } void SettingsCache::setHorizontalHand(int _horizontalHand) { - horizontalHand = _horizontalHand; - settings->setValue("hand/horizontal", horizontalHand); - emit horizontalHandChanged(); + horizontalHand = _horizontalHand; + settings->setValue("hand/horizontal", horizontalHand); + emit horizontalHandChanged(); } void SettingsCache::setInvertVerticalCoordinate(int _invertVerticalCoordinate) { - invertVerticalCoordinate = _invertVerticalCoordinate; - settings->setValue("table/invert_vertical", invertVerticalCoordinate); - emit invertVerticalCoordinateChanged(); + invertVerticalCoordinate = _invertVerticalCoordinate; + settings->setValue("table/invert_vertical", invertVerticalCoordinate); + emit invertVerticalCoordinateChanged(); } void SettingsCache::setMinPlayersForMultiColumnLayout(int _minPlayersForMultiColumnLayout) { - minPlayersForMultiColumnLayout = _minPlayersForMultiColumnLayout; - settings->setValue("interface/min_players_multicolumn", minPlayersForMultiColumnLayout); - emit minPlayersForMultiColumnLayoutChanged(); + minPlayersForMultiColumnLayout = _minPlayersForMultiColumnLayout; + settings->setValue("interface/min_players_multicolumn", minPlayersForMultiColumnLayout); + emit minPlayersForMultiColumnLayoutChanged(); } void SettingsCache::setTapAnimation(int _tapAnimation) { - tapAnimation = _tapAnimation; - settings->setValue("cards/tapanimation", tapAnimation); + tapAnimation = _tapAnimation; + settings->setValue("cards/tapanimation", tapAnimation); } void SettingsCache::setZoneViewSortByName(int _zoneViewSortByName) { - zoneViewSortByName = _zoneViewSortByName; - settings->setValue("zoneview/sortbyname", zoneViewSortByName); + zoneViewSortByName = _zoneViewSortByName; + settings->setValue("zoneview/sortbyname", zoneViewSortByName); } void SettingsCache::setZoneViewSortByType(int _zoneViewSortByType) { - zoneViewSortByType = _zoneViewSortByType; - settings->setValue("zoneview/sortbytype", zoneViewSortByType); + zoneViewSortByType = _zoneViewSortByType; + settings->setValue("zoneview/sortbytype", zoneViewSortByType); } void SettingsCache::setSoundEnabled(int _soundEnabled) { - soundEnabled = _soundEnabled; - settings->setValue("sound/enabled", soundEnabled); - emit soundEnabledChanged(); + soundEnabled = _soundEnabled; + settings->setValue("sound/enabled", soundEnabled); + emit soundEnabledChanged(); } void SettingsCache::setSoundPath(const QString &_soundPath) { - soundPath = _soundPath; - settings->setValue("sound/path", soundPath); - emit soundPathChanged(); + soundPath = _soundPath; + settings->setValue("sound/path", soundPath); + emit soundPathChanged(); } void SettingsCache::setPriceTagFeature(int _priceTagFeature) { - priceTagFeature = _priceTagFeature; - settings->setValue("deckeditor/pricetags", priceTagFeature); + priceTagFeature = _priceTagFeature; + settings->setValue("deckeditor/pricetags", priceTagFeature); } void SettingsCache::setIgnoreUnregisteredUsers(bool _ignoreUnregisteredUsers) { - ignoreUnregisteredUsers = _ignoreUnregisteredUsers; - settings->setValue("chat/ignore_unregistered", ignoreUnregisteredUsers); - emit ignoreUnregisteredUsersChanged(); + ignoreUnregisteredUsers = _ignoreUnregisteredUsers; + settings->setValue("chat/ignore_unregistered", ignoreUnregisteredUsers); + emit ignoreUnregisteredUsersChanged(); } void SettingsCache::setMainWindowGeometry(const QByteArray &_mainWindowGeometry) { - mainWindowGeometry = _mainWindowGeometry; - settings->setValue("interface/main_window_geometry", mainWindowGeometry); + mainWindowGeometry = _mainWindowGeometry; + settings->setValue("interface/main_window_geometry", mainWindowGeometry); } diff --git a/cockatrice/src/settingscache.h b/cockatrice/src/settingscache.h index 72b60087..6c28227a 100644 --- a/cockatrice/src/settingscache.h +++ b/cockatrice/src/settingscache.h @@ -6,109 +6,109 @@ class QSettings; class SettingsCache : public QObject { - Q_OBJECT + Q_OBJECT signals: - void langChanged(); - void picsPathChanged(); - void cardDatabasePathChanged(); - void tokenDatabasePathChanged(); - void handBgPathChanged(); - void stackBgPathChanged(); - void tableBgPathChanged(); - void playerBgPathChanged(); - void cardBackPicturePathChanged(); - void picDownloadChanged(); - void displayCardNamesChanged(); - void horizontalHandChanged(); - void invertVerticalCoordinateChanged(); - void minPlayersForMultiColumnLayoutChanged(); - void soundEnabledChanged(); - void soundPathChanged(); - void ignoreUnregisteredUsersChanged(); + void langChanged(); + void picsPathChanged(); + void cardDatabasePathChanged(); + void tokenDatabasePathChanged(); + void handBgPathChanged(); + void stackBgPathChanged(); + void tableBgPathChanged(); + void playerBgPathChanged(); + void cardBackPicturePathChanged(); + void picDownloadChanged(); + void displayCardNamesChanged(); + void horizontalHandChanged(); + void invertVerticalCoordinateChanged(); + void minPlayersForMultiColumnLayoutChanged(); + void soundEnabledChanged(); + void soundPathChanged(); + void ignoreUnregisteredUsersChanged(); private: - QSettings *settings; - - QByteArray mainWindowGeometry; - QString lang; - QString deckPath, replaysPath, picsPath, cardDatabasePath, tokenDatabasePath; - QString handBgPath, stackBgPath, tableBgPath, playerBgPath, cardBackPicturePath; - bool picDownload; - bool notificationsEnabled; - bool doubleClickToPlay; - bool playToStack; - int cardInfoMinimized; - QByteArray tabGameSplitterSizes; - bool displayCardNames; - bool horizontalHand; - bool invertVerticalCoordinate; - int minPlayersForMultiColumnLayout; - bool tapAnimation; - bool zoneViewSortByName, zoneViewSortByType; - bool soundEnabled; - QString soundPath; - bool priceTagFeature; - bool ignoreUnregisteredUsers; + QSettings *settings; + + QByteArray mainWindowGeometry; + QString lang; + QString deckPath, replaysPath, picsPath, cardDatabasePath, tokenDatabasePath; + QString handBgPath, stackBgPath, tableBgPath, playerBgPath, cardBackPicturePath; + bool picDownload; + bool notificationsEnabled; + bool doubleClickToPlay; + bool playToStack; + int cardInfoMinimized; + QByteArray tabGameSplitterSizes; + bool displayCardNames; + bool horizontalHand; + bool invertVerticalCoordinate; + int minPlayersForMultiColumnLayout; + bool tapAnimation; + bool zoneViewSortByName, zoneViewSortByType; + bool soundEnabled; + QString soundPath; + bool priceTagFeature; + bool ignoreUnregisteredUsers; public: - SettingsCache(); - const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; } - QString getLang() const { return lang; } - QString getDeckPath() const { return deckPath; } - QString getReplaysPath() const { return replaysPath; } - QString getPicsPath() const { return picsPath; } - QString getCardDatabasePath() const { return cardDatabasePath; } - QString getTokenDatabasePath() const { return tokenDatabasePath; } - QString getHandBgPath() const { return handBgPath; } - QString getStackBgPath() const { return stackBgPath; } - QString getTableBgPath() const { return tableBgPath; } - QString getPlayerBgPath() const { return playerBgPath; } - QString getCardBackPicturePath() const { return cardBackPicturePath; } - bool getPicDownload() const { return picDownload; } - bool getNotificationsEnabled() const { return notificationsEnabled; } - bool getDoubleClickToPlay() const { return doubleClickToPlay; } - bool getPlayToStack() const { return playToStack; } - int getCardInfoMinimized() const { return cardInfoMinimized; } - QByteArray getTabGameSplitterSizes() const { return tabGameSplitterSizes; } - bool getDisplayCardNames() const { return displayCardNames; } - bool getHorizontalHand() const { return horizontalHand; } - bool getInvertVerticalCoordinate() const { return invertVerticalCoordinate; } - int getMinPlayersForMultiColumnLayout() const { return minPlayersForMultiColumnLayout; } - bool getTapAnimation() const { return tapAnimation; } - bool getZoneViewSortByName() const { return zoneViewSortByName; } - bool getZoneViewSortByType() const { return zoneViewSortByType; } - bool getSoundEnabled() const { return soundEnabled; } - QString getSoundPath() const { return soundPath; } - bool getPriceTagFeature() const { return priceTagFeature; } - bool getIgnoreUnregisteredUsers() const { return ignoreUnregisteredUsers; } + SettingsCache(); + const QByteArray &getMainWindowGeometry() const { return mainWindowGeometry; } + QString getLang() const { return lang; } + QString getDeckPath() const { return deckPath; } + QString getReplaysPath() const { return replaysPath; } + QString getPicsPath() const { return picsPath; } + QString getCardDatabasePath() const { return cardDatabasePath; } + QString getTokenDatabasePath() const { return tokenDatabasePath; } + QString getHandBgPath() const { return handBgPath; } + QString getStackBgPath() const { return stackBgPath; } + QString getTableBgPath() const { return tableBgPath; } + QString getPlayerBgPath() const { return playerBgPath; } + QString getCardBackPicturePath() const { return cardBackPicturePath; } + bool getPicDownload() const { return picDownload; } + bool getNotificationsEnabled() const { return notificationsEnabled; } + bool getDoubleClickToPlay() const { return doubleClickToPlay; } + bool getPlayToStack() const { return playToStack; } + int getCardInfoMinimized() const { return cardInfoMinimized; } + QByteArray getTabGameSplitterSizes() const { return tabGameSplitterSizes; } + bool getDisplayCardNames() const { return displayCardNames; } + bool getHorizontalHand() const { return horizontalHand; } + bool getInvertVerticalCoordinate() const { return invertVerticalCoordinate; } + int getMinPlayersForMultiColumnLayout() const { return minPlayersForMultiColumnLayout; } + bool getTapAnimation() const { return tapAnimation; } + bool getZoneViewSortByName() const { return zoneViewSortByName; } + bool getZoneViewSortByType() const { return zoneViewSortByType; } + bool getSoundEnabled() const { return soundEnabled; } + QString getSoundPath() const { return soundPath; } + bool getPriceTagFeature() const { return priceTagFeature; } + bool getIgnoreUnregisteredUsers() const { return ignoreUnregisteredUsers; } public slots: - void setMainWindowGeometry(const QByteArray &_mainWindowGeometry); - void setLang(const QString &_lang); - void setDeckPath(const QString &_deckPath); - void setReplaysPath(const QString &_replaysPath); - void setPicsPath(const QString &_picsPath); - void setCardDatabasePath(const QString &_cardDatabasePath); - void setTokenDatabasePath(const QString &_tokenDatabasePath); - void setHandBgPath(const QString &_handBgPath); - void setStackBgPath(const QString &_stackBgPath); - void setTableBgPath(const QString &_tableBgPath); - void setPlayerBgPath(const QString &_playerBgPath); - void setCardBackPicturePath(const QString &_cardBackPicturePath); - void setPicDownload(int _picDownload); - void setNotificationsEnabled(int _notificationsEnabled); - void setDoubleClickToPlay(int _doubleClickToPlay); - void setPlayToStack(int _playToStack); - void setCardInfoMinimized(int _cardInfoMinimized); - void setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes); - void setDisplayCardNames(int _displayCardNames); - void setHorizontalHand(int _horizontalHand); - void setInvertVerticalCoordinate(int _invertVerticalCoordinate); - void setMinPlayersForMultiColumnLayout(int _minPlayersForMultiColumnLayout); - void setTapAnimation(int _tapAnimation); - void setZoneViewSortByName(int _zoneViewSortByName); - void setZoneViewSortByType(int _zoneViewSortByType); - void setSoundEnabled(int _soundEnabled); - void setSoundPath(const QString &_soundPath); - void setPriceTagFeature(int _priceTagFeature); - void setIgnoreUnregisteredUsers(bool _ignoreUnregisteredUsers); + void setMainWindowGeometry(const QByteArray &_mainWindowGeometry); + void setLang(const QString &_lang); + void setDeckPath(const QString &_deckPath); + void setReplaysPath(const QString &_replaysPath); + void setPicsPath(const QString &_picsPath); + void setCardDatabasePath(const QString &_cardDatabasePath); + void setTokenDatabasePath(const QString &_tokenDatabasePath); + void setHandBgPath(const QString &_handBgPath); + void setStackBgPath(const QString &_stackBgPath); + void setTableBgPath(const QString &_tableBgPath); + void setPlayerBgPath(const QString &_playerBgPath); + void setCardBackPicturePath(const QString &_cardBackPicturePath); + void setPicDownload(int _picDownload); + void setNotificationsEnabled(int _notificationsEnabled); + void setDoubleClickToPlay(int _doubleClickToPlay); + void setPlayToStack(int _playToStack); + void setCardInfoMinimized(int _cardInfoMinimized); + void setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSizes); + void setDisplayCardNames(int _displayCardNames); + void setHorizontalHand(int _horizontalHand); + void setInvertVerticalCoordinate(int _invertVerticalCoordinate); + void setMinPlayersForMultiColumnLayout(int _minPlayersForMultiColumnLayout); + void setTapAnimation(int _tapAnimation); + void setZoneViewSortByName(int _zoneViewSortByName); + void setZoneViewSortByType(int _zoneViewSortByType); + void setSoundEnabled(int _soundEnabled); + void setSoundPath(const QString &_soundPath); + void setPriceTagFeature(int _priceTagFeature); + void setIgnoreUnregisteredUsers(bool _ignoreUnregisteredUsers); }; extern SettingsCache *settingsCache; diff --git a/cockatrice/src/soundengine.cpp b/cockatrice/src/soundengine.cpp index 35d179fd..5847c9ae 100644 --- a/cockatrice/src/soundengine.cpp +++ b/cockatrice/src/soundengine.cpp @@ -6,91 +6,91 @@ #include SoundEngine::SoundEngine(QObject *parent) - : QObject(parent), audio(0) + : QObject(parent), audio(0) { - inputBuffer = new QBuffer(this); - - connect(settingsCache, SIGNAL(soundPathChanged()), this, SLOT(cacheData())); - connect(settingsCache, SIGNAL(soundEnabledChanged()), this, SLOT(soundEnabledChanged())); - cacheData(); - soundEnabledChanged(); + inputBuffer = new QBuffer(this); + + connect(settingsCache, SIGNAL(soundPathChanged()), this, SLOT(cacheData())); + connect(settingsCache, SIGNAL(soundEnabledChanged()), this, SLOT(soundEnabledChanged())); + cacheData(); + soundEnabledChanged(); } void SoundEngine::cacheData() { - static const QStringList fileNames = QStringList() - << "notification" << "draw" << "playcard" << "shuffle" << "tap" << "untap" << "cuckoo"; - for (int i = 0; i < fileNames.size(); ++i) { - QFile file(settingsCache->getSoundPath() + "/" + fileNames[i] + ".raw"); - file.open(QIODevice::ReadOnly); - audioData.insert(fileNames[i], file.readAll()); - file.close(); - } + static const QStringList fileNames = QStringList() + << "notification" << "draw" << "playcard" << "shuffle" << "tap" << "untap" << "cuckoo"; + for (int i = 0; i < fileNames.size(); ++i) { + QFile file(settingsCache->getSoundPath() + "/" + fileNames[i] + ".raw"); + file.open(QIODevice::ReadOnly); + audioData.insert(fileNames[i], file.readAll()); + file.close(); + } } void SoundEngine::soundEnabledChanged() { - if (settingsCache->getSoundEnabled()) { - qDebug("SoundEngine: enabling sound"); - QAudioFormat format; - format.setFrequency(44100); - format.setChannels(1); - format.setSampleSize(16); - format.setCodec("audio/pcm"); - format.setByteOrder(QAudioFormat::LittleEndian); - format.setSampleType(QAudioFormat::SignedInt); - audio = new QAudioOutput(format, this); - } else if (audio) { - qDebug("SoundEngine: disabling sound"); - audio->stop(); - audio->deleteLater(); - audio = 0; - } + if (settingsCache->getSoundEnabled()) { + qDebug("SoundEngine: enabling sound"); + QAudioFormat format; + format.setFrequency(44100); + format.setChannels(1); + format.setSampleSize(16); + format.setCodec("audio/pcm"); + format.setByteOrder(QAudioFormat::LittleEndian); + format.setSampleType(QAudioFormat::SignedInt); + audio = new QAudioOutput(format, this); + } else if (audio) { + qDebug("SoundEngine: disabling sound"); + audio->stop(); + audio->deleteLater(); + audio = 0; + } } void SoundEngine::playSound(const QString &fileName) { - if (!audio) - return; - - audio->stop(); - inputBuffer->close(); - inputBuffer->setData(audioData[fileName]); - inputBuffer->open(QIODevice::ReadOnly); - audio->start(inputBuffer); + if (!audio) + return; + + audio->stop(); + inputBuffer->close(); + inputBuffer->setData(audioData[fileName]); + inputBuffer->open(QIODevice::ReadOnly); + audio->start(inputBuffer); } void SoundEngine::notification() { - playSound("notification"); + playSound("notification"); } void SoundEngine::draw() { - playSound("draw"); + playSound("draw"); } void SoundEngine::playCard() { - playSound("playcard"); + playSound("playcard"); } void SoundEngine::shuffle() { - playSound("shuffle"); + playSound("shuffle"); } void SoundEngine::tap() { - playSound("tap"); + playSound("tap"); } void SoundEngine::untap() { - playSound("untap"); + playSound("untap"); } void SoundEngine::cuckoo() { - playSound("cuckoo"); + playSound("cuckoo"); } diff --git a/cockatrice/src/soundengine.h b/cockatrice/src/soundengine.h index 89dd6751..a3071fda 100644 --- a/cockatrice/src/soundengine.h +++ b/cockatrice/src/soundengine.h @@ -8,25 +8,25 @@ class QAudioOutput; class QBuffer; class SoundEngine : public QObject { - Q_OBJECT + Q_OBJECT private: - void playSound(const QString &fileName); - QMap audioData; - QBuffer *inputBuffer; - QAudioOutput *audio; + void playSound(const QString &fileName); + QMap audioData; + QBuffer *inputBuffer; + QAudioOutput *audio; private slots: - void cacheData(); - void soundEnabledChanged(); + void cacheData(); + void soundEnabledChanged(); public: - SoundEngine(QObject *parent = 0); + SoundEngine(QObject *parent = 0); public slots: - void notification(); - void draw(); - void playCard(); - void shuffle(); - void tap(); - void untap(); - void cuckoo(); + void notification(); + void draw(); + void playCard(); + void shuffle(); + void tap(); + void untap(); + void cuckoo(); }; extern SoundEngine *soundEngine; diff --git a/cockatrice/src/stackzone.cpp b/cockatrice/src/stackzone.cpp index 216dac99..f3e4767c 100644 --- a/cockatrice/src/stackzone.cpp +++ b/cockatrice/src/stackzone.cpp @@ -10,100 +10,100 @@ #include "pb/command_move_card.pb.h" StackZone::StackZone(Player *_p, int _zoneHeight, QGraphicsItem *parent) - : SelectZone(_p, "stack", false, false, true, parent), zoneHeight(_zoneHeight) + : SelectZone(_p, "stack", false, false, true, parent), zoneHeight(_zoneHeight) { - connect(settingsCache, SIGNAL(stackBgPathChanged()), this, SLOT(updateBgPixmap())); - updateBgPixmap(); - setCacheMode(DeviceCoordinateCache); + connect(settingsCache, SIGNAL(stackBgPathChanged()), this, SLOT(updateBgPixmap())); + updateBgPixmap(); + setCacheMode(DeviceCoordinateCache); } void StackZone::updateBgPixmap() { - QString bgPath = settingsCache->getStackBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); - update(); + QString bgPath = settingsCache->getStackBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); + update(); } void StackZone::addCardImpl(CardItem *card, int x, int /*y*/) { - if (x == -1) - x = cards.size(); - cards.insert(x, card); + if (x == -1) + x = cards.size(); + cards.insert(x, card); - if (!cards.getContentsKnown()) { - card->setId(-1); - card->setName(); - } - card->setParentItem(this); - card->resetState(); - card->setVisible(true); - card->update(); + if (!cards.getContentsKnown()) { + card->setId(-1); + card->setName(); + } + card->setParentItem(this); + card->resetState(); + card->setVisible(true); + card->update(); } QRectF StackZone::boundingRect() const { - return QRectF(0, 0, 100, zoneHeight); + return QRectF(0, 0, 100, zoneHeight); } void StackZone::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), QColor(113, 43, 43)); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), QColor(113, 43, 43)); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); } void StackZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) { - if (startZone == this) - return; - - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(0); - cmd.set_y(0); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + if (startZone == this) + return; + + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(0); + cmd.set_y(0); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - player->sendGameCommand(cmd); + player->sendGameCommand(cmd); } void StackZone::reorganizeCards() { - if (!cards.isEmpty()) { - QList arrowsToUpdate; - - const int cardCount = cards.size(); - qreal totalWidth = boundingRect().width(); - qreal totalHeight = boundingRect().height(); - qreal cardWidth = cards.at(0)->boundingRect().width(); - qreal cardHeight = cards.at(0)->boundingRect().height(); - qreal xspace = 5; - qreal x1 = xspace; - qreal x2 = totalWidth - xspace - cardWidth; - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cards.at(i); - qreal x = i % 2 ? x2 : x1; - // If the total height of the cards is smaller than the available height, - // the cards do not need to overlap and are displayed in the center of the area. - if (cardHeight * cardCount > totalHeight) - c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); - else - c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); - c->setRealZValue(i); - - arrowsToUpdate.append(c->getArrowsFrom()); - arrowsToUpdate.append(c->getArrowsTo()); - } - QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); - while (arrowIterator.hasNext()) - arrowIterator.next()->updatePath(); - } - update(); + if (!cards.isEmpty()) { + QList arrowsToUpdate; + + const int cardCount = cards.size(); + qreal totalWidth = boundingRect().width(); + qreal totalHeight = boundingRect().height(); + qreal cardWidth = cards.at(0)->boundingRect().width(); + qreal cardHeight = cards.at(0)->boundingRect().height(); + qreal xspace = 5; + qreal x1 = xspace; + qreal x2 = totalWidth - xspace - cardWidth; + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cards.at(i); + qreal x = i % 2 ? x2 : x1; + // If the total height of the cards is smaller than the available height, + // the cards do not need to overlap and are displayed in the center of the area. + if (cardHeight * cardCount > totalHeight) + c->setPos(x, ((qreal) i) * (totalHeight - cardHeight) / (cardCount - 1)); + else + c->setPos(x, ((qreal) i) * cardHeight + (totalHeight - cardCount * cardHeight) / 2); + c->setRealZValue(i); + + arrowsToUpdate.append(c->getArrowsFrom()); + arrowsToUpdate.append(c->getArrowsTo()); + } + QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); + while (arrowIterator.hasNext()) + arrowIterator.next()->updatePath(); + } + update(); } diff --git a/cockatrice/src/stackzone.h b/cockatrice/src/stackzone.h index 5fb2878b..948d3bcb 100644 --- a/cockatrice/src/stackzone.h +++ b/cockatrice/src/stackzone.h @@ -4,20 +4,20 @@ #include "selectzone.h" class StackZone : public SelectZone { - Q_OBJECT + Q_OBJECT private: - qreal zoneHeight; - QPixmap bgPixmap; + qreal zoneHeight; + QPixmap bgPixmap; private slots: - void updateBgPixmap(); + void updateBgPixmap(); public: - StackZone(Player *_p, int _zoneHeight, QGraphicsItem *parent = 0); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); + StackZone(Player *_p, int _zoneHeight, QGraphicsItem *parent = 0); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); protected: - void addCardImpl(CardItem *card, int x, int y); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/tab.cpp b/cockatrice/src/tab.cpp index 0c20a821..28838ed2 100644 --- a/cockatrice/src/tab.cpp +++ b/cockatrice/src/tab.cpp @@ -4,28 +4,28 @@ #include #include Tab::Tab(TabSupervisor *_tabSupervisor, QWidget *parent) - : QWidget(parent), tabSupervisor(_tabSupervisor), contentsChanged(false), infoPopup(0) + : QWidget(parent), tabSupervisor(_tabSupervisor), contentsChanged(false), infoPopup(0) { } void Tab::showCardInfoPopup(const QPoint &pos, const QString &cardName) { - infoPopup = new CardInfoWidget(CardInfoWidget::ModePopUp, cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint); - infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents); - QRect screenRect = qApp->desktop()->screenGeometry(this); - infoPopup->move( - qMax(screenRect.left(), qMin(pos.x() - infoPopup->width() / 2, screenRect.left() + screenRect.width() - infoPopup->width())), - qMax(screenRect.top(), qMin(pos.y() - infoPopup->height() / 2, screenRect.top() + screenRect.height() - infoPopup->height())) - ); - infoPopup->show(); + infoPopup = new CardInfoWidget(CardInfoWidget::ModePopUp, cardName, 0, Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint); + infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents); + QRect screenRect = qApp->desktop()->screenGeometry(this); + infoPopup->move( + qMax(screenRect.left(), qMin(pos.x() - infoPopup->width() / 2, screenRect.left() + screenRect.width() - infoPopup->width())), + qMax(screenRect.top(), qMin(pos.y() - infoPopup->height() / 2, screenRect.top() + screenRect.height() - infoPopup->height())) + ); + infoPopup->show(); } void Tab::deleteCardInfoPopup(const QString &cardName) { - if (infoPopup) { - if ((infoPopup->getCardName() == cardName) || (cardName == "_")) { - infoPopup->deleteLater(); - infoPopup = 0; - } - } + if (infoPopup) { + if ((infoPopup->getCardName() == cardName) || (cardName == "_")) { + infoPopup->deleteLater(); + infoPopup = 0; + } + } } diff --git a/cockatrice/src/tab.h b/cockatrice/src/tab.h index 445180fd..65473121 100644 --- a/cockatrice/src/tab.h +++ b/cockatrice/src/tab.h @@ -8,29 +8,29 @@ class TabSupervisor; class CardInfoWidget; class Tab : public QWidget { - Q_OBJECT + Q_OBJECT signals: - void userEvent(bool globalEvent = true); - void tabTextChanged(Tab *tab, const QString &newTabText); + void userEvent(bool globalEvent = true); + void tabTextChanged(Tab *tab, const QString &newTabText); protected: - TabSupervisor *tabSupervisor; - void addTabMenu(QMenu *menu) { tabMenus.append(menu); } + TabSupervisor *tabSupervisor; + void addTabMenu(QMenu *menu) { tabMenus.append(menu); } protected slots: - void showCardInfoPopup(const QPoint &pos, const QString &cardName); - void deleteCardInfoPopup(const QString &cardName); + void showCardInfoPopup(const QPoint &pos, const QString &cardName); + void deleteCardInfoPopup(const QString &cardName); private: - bool contentsChanged; - CardInfoWidget *infoPopup; - QList tabMenus; + bool contentsChanged; + CardInfoWidget *infoPopup; + QList tabMenus; public: - Tab(TabSupervisor *_tabSupervisor, QWidget *parent = 0); - const QList &getTabMenus() const { return tabMenus; } - TabSupervisor *getTabSupervisor() const { return tabSupervisor; } - bool getContentsChanged() const { return contentsChanged; } - void setContentsChanged(bool _contentsChanged) { contentsChanged = _contentsChanged; } - virtual QString getTabText() const = 0; - virtual void retranslateUi() = 0; - virtual void closeRequest() { } + Tab(TabSupervisor *_tabSupervisor, QWidget *parent = 0); + const QList &getTabMenus() const { return tabMenus; } + TabSupervisor *getTabSupervisor() const { return tabSupervisor; } + bool getContentsChanged() const { return contentsChanged; } + void setContentsChanged(bool _contentsChanged) { contentsChanged = _contentsChanged; } + virtual QString getTabText() const = 0; + virtual void retranslateUi() = 0; + virtual void closeRequest() { } }; #endif diff --git a/cockatrice/src/tab_admin.cpp b/cockatrice/src/tab_admin.cpp index 53189707..71018186 100644 --- a/cockatrice/src/tab_admin.cpp +++ b/cockatrice/src/tab_admin.cpp @@ -14,119 +14,119 @@ #include "pb/admin_commands.pb.h" ShutdownDialog::ShutdownDialog(QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - QLabel *reasonLabel = new QLabel(tr("&Reason for shutdown:")); - reasonEdit = new QLineEdit; - reasonLabel->setBuddy(reasonEdit); - QLabel *minutesLabel = new QLabel(tr("&Time until shutdown (minutes):")); - minutesEdit = new QSpinBox; - minutesLabel->setBuddy(minutesEdit); - minutesEdit->setMinimum(0); - minutesEdit->setValue(5); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(reasonLabel, 0, 0); - mainLayout->addWidget(reasonEdit, 0, 1); - mainLayout->addWidget(minutesLabel, 1, 0); - mainLayout->addWidget(minutesEdit, 1, 1); - mainLayout->addWidget(buttonBox, 2, 0, 1, 2); - - setLayout(mainLayout); - setWindowTitle(tr("Shut down server")); + QLabel *reasonLabel = new QLabel(tr("&Reason for shutdown:")); + reasonEdit = new QLineEdit; + reasonLabel->setBuddy(reasonEdit); + QLabel *minutesLabel = new QLabel(tr("&Time until shutdown (minutes):")); + minutesEdit = new QSpinBox; + minutesLabel->setBuddy(minutesEdit); + minutesEdit->setMinimum(0); + minutesEdit->setValue(5); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QGridLayout *mainLayout = new QGridLayout; + mainLayout->addWidget(reasonLabel, 0, 0); + mainLayout->addWidget(reasonEdit, 0, 1); + mainLayout->addWidget(minutesLabel, 1, 0); + mainLayout->addWidget(minutesEdit, 1, 1); + mainLayout->addWidget(buttonBox, 2, 0, 1, 2); + + setLayout(mainLayout); + setWindowTitle(tr("Shut down server")); } QString ShutdownDialog::getReason() const { - return reasonEdit->text(); + return reasonEdit->text(); } int ShutdownDialog::getMinutes() const { - return minutesEdit->value(); + return minutesEdit->value(); } TabAdmin::TabAdmin(TabSupervisor *_tabSupervisor, AbstractClient *_client, bool _fullAdmin, QWidget *parent) - : Tab(_tabSupervisor, parent), locked(true), client(_client), fullAdmin(_fullAdmin) + : Tab(_tabSupervisor, parent), locked(true), client(_client), fullAdmin(_fullAdmin) { - updateServerMessageButton = new QPushButton; - connect(updateServerMessageButton, SIGNAL(clicked()), this, SLOT(actUpdateServerMessage())); - shutdownServerButton = new QPushButton; - connect(shutdownServerButton, SIGNAL(clicked()), this, SLOT(actShutdownServer())); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(updateServerMessageButton); - vbox->addWidget(shutdownServerButton); - vbox->addStretch(); - - adminGroupBox = new QGroupBox; - adminGroupBox->setLayout(vbox); - adminGroupBox->setEnabled(false); - - unlockButton = new QPushButton; - connect(unlockButton, SIGNAL(clicked()), this, SLOT(actUnlock())); - lockButton = new QPushButton; - lockButton->setEnabled(false); - connect(lockButton, SIGNAL(clicked()), this, SLOT(actLock())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(adminGroupBox); - mainLayout->addWidget(unlockButton); - mainLayout->addWidget(lockButton); - - retranslateUi(); - setLayout(mainLayout); + updateServerMessageButton = new QPushButton; + connect(updateServerMessageButton, SIGNAL(clicked()), this, SLOT(actUpdateServerMessage())); + shutdownServerButton = new QPushButton; + connect(shutdownServerButton, SIGNAL(clicked()), this, SLOT(actShutdownServer())); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(updateServerMessageButton); + vbox->addWidget(shutdownServerButton); + vbox->addStretch(); + + adminGroupBox = new QGroupBox; + adminGroupBox->setLayout(vbox); + adminGroupBox->setEnabled(false); + + unlockButton = new QPushButton; + connect(unlockButton, SIGNAL(clicked()), this, SLOT(actUnlock())); + lockButton = new QPushButton; + lockButton->setEnabled(false); + connect(lockButton, SIGNAL(clicked()), this, SLOT(actLock())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(adminGroupBox); + mainLayout->addWidget(unlockButton); + mainLayout->addWidget(lockButton); + + retranslateUi(); + setLayout(mainLayout); } void TabAdmin::retranslateUi() { - updateServerMessageButton->setText(tr("Update server &message")); - shutdownServerButton->setText(tr("&Shut down server")); - adminGroupBox->setTitle(tr("Server administration functions")); - - unlockButton->setText(tr("&Unlock functions")); - lockButton->setText(tr("&Lock functions")); + updateServerMessageButton->setText(tr("Update server &message")); + shutdownServerButton->setText(tr("&Shut down server")); + adminGroupBox->setTitle(tr("Server administration functions")); + + unlockButton->setText(tr("&Unlock functions")); + lockButton->setText(tr("&Lock functions")); } void TabAdmin::actUpdateServerMessage() { - client->sendCommand(client->prepareAdminCommand(Command_UpdateServerMessage())); + client->sendCommand(client->prepareAdminCommand(Command_UpdateServerMessage())); } void TabAdmin::actShutdownServer() { - ShutdownDialog dlg; - if (dlg.exec()) { - Command_ShutdownServer cmd; - cmd.set_reason(dlg.getReason().toStdString()); - cmd.set_minutes(dlg.getMinutes()); - - client->sendCommand(client->prepareAdminCommand(cmd)); - } + ShutdownDialog dlg; + if (dlg.exec()) { + Command_ShutdownServer cmd; + cmd.set_reason(dlg.getReason().toStdString()); + cmd.set_minutes(dlg.getMinutes()); + + client->sendCommand(client->prepareAdminCommand(cmd)); + } } void TabAdmin::actUnlock() { - if (QMessageBox::question(this, tr("Unlock administration functions"), tr("Do you really want to unlock the administration functions?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - if (fullAdmin) - adminGroupBox->setEnabled(true); - lockButton->setEnabled(true); - unlockButton->setEnabled(false); - locked = false; - emit adminLockChanged(false); - } + if (QMessageBox::question(this, tr("Unlock administration functions"), tr("Do you really want to unlock the administration functions?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + if (fullAdmin) + adminGroupBox->setEnabled(true); + lockButton->setEnabled(true); + unlockButton->setEnabled(false); + locked = false; + emit adminLockChanged(false); + } } void TabAdmin::actLock() { - if (fullAdmin) - adminGroupBox->setEnabled(false); - lockButton->setEnabled(false); - unlockButton->setEnabled(true); - locked = true; - emit adminLockChanged(true); + if (fullAdmin) + adminGroupBox->setEnabled(false); + lockButton->setEnabled(false); + unlockButton->setEnabled(true); + locked = true; + emit adminLockChanged(true); } diff --git a/cockatrice/src/tab_admin.h b/cockatrice/src/tab_admin.h index 7d5e9175..cc5ae6a9 100644 --- a/cockatrice/src/tab_admin.h +++ b/cockatrice/src/tab_admin.h @@ -12,38 +12,38 @@ class QSpinBox; class QLineEdit; class ShutdownDialog : public QDialog { - Q_OBJECT + Q_OBJECT private: - QLineEdit *reasonEdit; - QSpinBox *minutesEdit; + QLineEdit *reasonEdit; + QSpinBox *minutesEdit; public: - ShutdownDialog(QWidget *parent = 0); - QString getReason() const; - int getMinutes() const; + ShutdownDialog(QWidget *parent = 0); + QString getReason() const; + int getMinutes() const; }; class TabAdmin : public Tab { - Q_OBJECT + Q_OBJECT private: - bool locked; - AbstractClient *client; - bool fullAdmin; - QPushButton *updateServerMessageButton, *shutdownServerButton; - QGroupBox *adminGroupBox; - QPushButton *unlockButton, *lockButton; + bool locked; + AbstractClient *client; + bool fullAdmin; + QPushButton *updateServerMessageButton, *shutdownServerButton; + QGroupBox *adminGroupBox; + QPushButton *unlockButton, *lockButton; signals: - void adminLockChanged(bool lock); + void adminLockChanged(bool lock); private slots: - void actUpdateServerMessage(); - void actShutdownServer(); - - void actUnlock(); - void actLock(); + void actUpdateServerMessage(); + void actShutdownServer(); + + void actUnlock(); + void actLock(); public: - TabAdmin(TabSupervisor *_tabSupervisor, AbstractClient *_client, bool _fullAdmin, QWidget *parent = 0); - void retranslateUi(); - QString getTabText() const { return tr("Administration"); } - bool getLocked() const { return locked; } + TabAdmin(TabSupervisor *_tabSupervisor, AbstractClient *_client, bool _fullAdmin, QWidget *parent = 0); + void retranslateUi(); + QString getTabText() const { return tr("Administration"); } + bool getLocked() const { return locked; } }; #endif diff --git a/cockatrice/src/tab_deck_editor.cpp b/cockatrice/src/tab_deck_editor.cpp index ee5c240c..075ee918 100644 --- a/cockatrice/src/tab_deck_editor.cpp +++ b/cockatrice/src/tab_deck_editor.cpp @@ -54,6 +54,7 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) searchLabel = new QLabel(); searchEdit = new SearchLineEdit; searchLabel->setBuddy(searchEdit); + searchKeySignals.filterDelete(false); searchEdit->installEventFilter(&searchKeySignals); connect(searchEdit, SIGNAL(textChanged(const QString &)), this, SLOT(updateSearch(const QString &))); @@ -96,7 +97,6 @@ TabDeckEditor::TabDeckEditor(TabSupervisor *_tabSupervisor, QWidget *parent) connect(&dbViewKeySignals, SIGNAL(onLeft()), this, SLOT(actDecrementCard())); connect(&dbViewKeySignals, SIGNAL(onCtrlLeft()), this, SLOT(actDecrementCardFromSideboard())); connect(&dbViewKeySignals, SIGNAL(onCtrlEnter()), this, SLOT(actAddCardToSideboard())); - searchEdit->setTreeView(databaseView); QVBoxLayout *leftFrame = new QVBoxLayout; @@ -414,7 +414,7 @@ void TabDeckEditor::actLoadDeck() return; QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); DeckLoader *l = new DeckLoader; if (l->loadFromFile(fileName, fmt)) @@ -467,7 +467,7 @@ bool TabDeckEditor::actSaveDeckAs() return false; QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); if (!deckModel->getDeckList()->saveToFile(fileName, fmt)) { QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved.\nPlease check that the directory is writable and try again.")); @@ -561,7 +561,6 @@ void TabDeckEditor::addCardHelper(QString zoneName) QModelIndex newCardIndex = deckModel->addCard(info->getName(), zoneName); recursiveExpand(newCardIndex); deckView->setCurrentIndex(newCardIndex); - setModified(true); } diff --git a/cockatrice/src/tab_deck_editor.h b/cockatrice/src/tab_deck_editor.h index 349f28eb..bcdca8d3 100644 --- a/cockatrice/src/tab_deck_editor.h +++ b/cockatrice/src/tab_deck_editor.h @@ -61,9 +61,9 @@ private slots: void actDecrementCard(); void actDecrementCardFromSideboard(); - void actUpdatePrices(); + void actUpdatePrices(); - void finishedUpdatingPrices(); + void finishedUpdatingPrices(); void saveDeckRemoteFinished(const Response &r); void filterViewCustomContextMenu(const QPoint &point); void filterRemove(QAction *action); @@ -79,6 +79,7 @@ private: CardDatabaseDisplayModel *databaseDisplayModel; DeckListModel *deckModel; QTreeView *databaseView; + KeySignals dbViewKeySignals; QTreeView *deckView; KeySignals deckViewKeySignals; @@ -86,6 +87,7 @@ private: QLabel *searchLabel; SearchLineEdit *searchEdit; KeySignals searchKeySignals; + QLabel *nameLabel; QLineEdit *nameEdit; QLabel *commentsLabel; @@ -98,7 +100,7 @@ private: QMenu *deckMenu, *dbMenu; QAction *aNewDeck, *aLoadDeck, *aSaveDeck, *aSaveDeckAs, *aLoadDeckFromClipboard, *aSaveDeckToClipboard, *aPrintDeck, *aAnalyzeDeck, *aClose; QAction *aEditSets, *aEditTokens, *aClearSearch, *aCardTextOnly; - QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement, *aUpdatePrices; + QAction *aAddCard, *aAddCardToSideboard, *aRemoveCard, *aIncrement, *aDecrement, *aUpdatePrices; bool modified; public: diff --git a/cockatrice/src/tab_deck_storage.cpp b/cockatrice/src/tab_deck_storage.cpp index 10ddb354..7e7d30ed 100644 --- a/cockatrice/src/tab_deck_storage.cpp +++ b/cockatrice/src/tab_deck_storage.cpp @@ -27,323 +27,323 @@ #include "pb/command_deck_del.pb.h" TabDeckStorage::TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_client) - : Tab(_tabSupervisor), client(_client) + : Tab(_tabSupervisor), client(_client) { - localDirModel = new QFileSystemModel(this); - localDirModel->setRootPath(settingsCache->getDeckPath()); - localDirModel->sort(0, Qt::AscendingOrder); - - localDirView = new QTreeView; - localDirView->setModel(localDirModel); - localDirView->setColumnHidden(1, true); - localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); - localDirView->setSortingEnabled(true); - localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); - localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); - - leftToolBar = new QToolBar; - leftToolBar->setOrientation(Qt::Horizontal); - leftToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *leftToolBarLayout = new QHBoxLayout; - leftToolBarLayout->addStretch(); - leftToolBarLayout->addWidget(leftToolBar); - leftToolBarLayout->addStretch(); + localDirModel = new QFileSystemModel(this); + localDirModel->setRootPath(settingsCache->getDeckPath()); + localDirModel->sort(0, Qt::AscendingOrder); + + localDirView = new QTreeView; + localDirView->setModel(localDirModel); + localDirView->setColumnHidden(1, true); + localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); + localDirView->setSortingEnabled(true); + localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); + localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); + + leftToolBar = new QToolBar; + leftToolBar->setOrientation(Qt::Horizontal); + leftToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *leftToolBarLayout = new QHBoxLayout; + leftToolBarLayout->addStretch(); + leftToolBarLayout->addWidget(leftToolBar); + leftToolBarLayout->addStretch(); - QVBoxLayout *leftVbox = new QVBoxLayout; - leftVbox->addWidget(localDirView); - leftVbox->addLayout(leftToolBarLayout); - leftGroupBox = new QGroupBox; - leftGroupBox->setLayout(leftVbox); - - rightToolBar = new QToolBar; - rightToolBar->setOrientation(Qt::Horizontal); - rightToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *rightToolBarLayout = new QHBoxLayout; - rightToolBarLayout->addStretch(); - rightToolBarLayout->addWidget(rightToolBar); - rightToolBarLayout->addStretch(); + QVBoxLayout *leftVbox = new QVBoxLayout; + leftVbox->addWidget(localDirView); + leftVbox->addLayout(leftToolBarLayout); + leftGroupBox = new QGroupBox; + leftGroupBox->setLayout(leftVbox); + + rightToolBar = new QToolBar; + rightToolBar->setOrientation(Qt::Horizontal); + rightToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *rightToolBarLayout = new QHBoxLayout; + rightToolBarLayout->addStretch(); + rightToolBarLayout->addWidget(rightToolBar); + rightToolBarLayout->addStretch(); - serverDirView = new RemoteDeckList_TreeWidget(client); + serverDirView = new RemoteDeckList_TreeWidget(client); - QVBoxLayout *rightVbox = new QVBoxLayout; - rightVbox->addWidget(serverDirView); - rightVbox->addLayout(rightToolBarLayout); - rightGroupBox = new QGroupBox; - rightGroupBox->setLayout(rightVbox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addWidget(leftGroupBox); - hbox->addWidget(rightGroupBox); - - aOpenLocalDeck = new QAction(this); - aOpenLocalDeck->setIcon(QIcon(":/resources/pencil.svg")); - connect(aOpenLocalDeck, SIGNAL(triggered()), this, SLOT(actOpenLocalDeck())); - aUpload = new QAction(this); - aUpload->setIcon(QIcon(":/resources/arrow_right_green.svg")); - connect(aUpload, SIGNAL(triggered()), this, SLOT(actUpload())); - aDeleteLocalDeck = new QAction(this); - aDeleteLocalDeck->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteLocalDeck, SIGNAL(triggered()), this, SLOT(actDeleteLocalDeck())); - aOpenRemoteDeck = new QAction(this); - aOpenRemoteDeck->setIcon(QIcon(":/resources/pencil.svg")); - connect(aOpenRemoteDeck, SIGNAL(triggered()), this, SLOT(actOpenRemoteDeck())); - aDownload = new QAction(this); - aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); - connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); - aNewFolder = new QAction(this); - aNewFolder->setIcon(qApp->style()->standardIcon(QStyle::SP_FileDialogNewFolder)); - connect(aNewFolder, SIGNAL(triggered()), this, SLOT(actNewFolder())); - aDeleteRemoteDeck = new QAction(this); - aDeleteRemoteDeck->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteRemoteDeck, SIGNAL(triggered()), this, SLOT(actDeleteRemoteDeck())); - - leftToolBar->addAction(aOpenLocalDeck); - leftToolBar->addAction(aUpload); - leftToolBar->addAction(aDeleteLocalDeck); - rightToolBar->addAction(aOpenRemoteDeck); - rightToolBar->addAction(aDownload); - rightToolBar->addAction(aNewFolder); - rightToolBar->addAction(aDeleteRemoteDeck); - - retranslateUi(); - setLayout(hbox); + QVBoxLayout *rightVbox = new QVBoxLayout; + rightVbox->addWidget(serverDirView); + rightVbox->addLayout(rightToolBarLayout); + rightGroupBox = new QGroupBox; + rightGroupBox->setLayout(rightVbox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addWidget(leftGroupBox); + hbox->addWidget(rightGroupBox); + + aOpenLocalDeck = new QAction(this); + aOpenLocalDeck->setIcon(QIcon(":/resources/pencil.svg")); + connect(aOpenLocalDeck, SIGNAL(triggered()), this, SLOT(actOpenLocalDeck())); + aUpload = new QAction(this); + aUpload->setIcon(QIcon(":/resources/arrow_right_green.svg")); + connect(aUpload, SIGNAL(triggered()), this, SLOT(actUpload())); + aDeleteLocalDeck = new QAction(this); + aDeleteLocalDeck->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteLocalDeck, SIGNAL(triggered()), this, SLOT(actDeleteLocalDeck())); + aOpenRemoteDeck = new QAction(this); + aOpenRemoteDeck->setIcon(QIcon(":/resources/pencil.svg")); + connect(aOpenRemoteDeck, SIGNAL(triggered()), this, SLOT(actOpenRemoteDeck())); + aDownload = new QAction(this); + aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); + connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); + aNewFolder = new QAction(this); + aNewFolder->setIcon(qApp->style()->standardIcon(QStyle::SP_FileDialogNewFolder)); + connect(aNewFolder, SIGNAL(triggered()), this, SLOT(actNewFolder())); + aDeleteRemoteDeck = new QAction(this); + aDeleteRemoteDeck->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteRemoteDeck, SIGNAL(triggered()), this, SLOT(actDeleteRemoteDeck())); + + leftToolBar->addAction(aOpenLocalDeck); + leftToolBar->addAction(aUpload); + leftToolBar->addAction(aDeleteLocalDeck); + rightToolBar->addAction(aOpenRemoteDeck); + rightToolBar->addAction(aDownload); + rightToolBar->addAction(aNewFolder); + rightToolBar->addAction(aDeleteRemoteDeck); + + retranslateUi(); + setLayout(hbox); } void TabDeckStorage::retranslateUi() { - leftGroupBox->setTitle(tr("Local file system")); - rightGroupBox->setTitle(tr("Server deck storage")); - - aOpenLocalDeck->setText(tr("Open in deck editor")); - aUpload->setText(tr("Upload deck")); - aOpenRemoteDeck->setText(tr("Open in deck editor")); - aDownload->setText(tr("Download deck")); - aNewFolder->setText(tr("New folder")); - aDeleteLocalDeck->setText(tr("Delete")); - aDeleteRemoteDeck->setText(tr("Delete")); + leftGroupBox->setTitle(tr("Local file system")); + rightGroupBox->setTitle(tr("Server deck storage")); + + aOpenLocalDeck->setText(tr("Open in deck editor")); + aUpload->setText(tr("Upload deck")); + aOpenRemoteDeck->setText(tr("Open in deck editor")); + aDownload->setText(tr("Download deck")); + aNewFolder->setText(tr("New folder")); + aDeleteLocalDeck->setText(tr("Delete")); + aDeleteRemoteDeck->setText(tr("Delete")); } void TabDeckStorage::actOpenLocalDeck() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (localDirModel->isDir(curLeft)) - return; - QString filePath = localDirModel->filePath(curLeft); - - DeckLoader deckLoader; - if (!deckLoader.loadFromFile(filePath, DeckLoader::CockatriceFormat)) - return; - - emit openDeckEditor(&deckLoader); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (localDirModel->isDir(curLeft)) + return; + QString filePath = localDirModel->filePath(curLeft); + + DeckLoader deckLoader; + if (!deckLoader.loadFromFile(filePath, DeckLoader::CockatriceFormat)) + return; + + emit openDeckEditor(&deckLoader); } void TabDeckStorage::actUpload() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (localDirModel->isDir(curLeft)) - return; - QString filePath = localDirModel->filePath(curLeft); - QFile deckFile(filePath); - QFileInfo deckFileInfo(deckFile); - DeckLoader deck; - if (!deck.loadFromFile(filePath, DeckLoader::CockatriceFormat)) - return; - if (deck.getName().isEmpty()) { - bool ok; - QString deckName = QInputDialog::getText(this, tr("Enter deck name"), tr("This decklist does not have a name.\nPlease enter a name:"), QLineEdit::Normal, deckFileInfo.completeBaseName(), &ok); - if (!ok) - return; - if (deckName.isEmpty()) - deckName = tr("Unnamed deck"); - deck.setName(deckName); - } - - QString targetPath; - RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); - if (!curRight) - return; - if (!dynamic_cast(curRight)) - curRight = curRight->getParent(); - targetPath = dynamic_cast(curRight)->getPath(); - - Command_DeckUpload cmd; - cmd.set_path(targetPath.toStdString()); - cmd.set_deck_list(deck.writeToString_Native().toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(uploadFinished(Response, CommandContainer))); - client->sendCommand(pend); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (localDirModel->isDir(curLeft)) + return; + QString filePath = localDirModel->filePath(curLeft); + QFile deckFile(filePath); + QFileInfo deckFileInfo(deckFile); + DeckLoader deck; + if (!deck.loadFromFile(filePath, DeckLoader::CockatriceFormat)) + return; + if (deck.getName().isEmpty()) { + bool ok; + QString deckName = QInputDialog::getText(this, tr("Enter deck name"), tr("This decklist does not have a name.\nPlease enter a name:"), QLineEdit::Normal, deckFileInfo.completeBaseName(), &ok); + if (!ok) + return; + if (deckName.isEmpty()) + deckName = tr("Unnamed deck"); + deck.setName(deckName); + } + + QString targetPath; + RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); + if (!curRight) + return; + if (!dynamic_cast(curRight)) + curRight = curRight->getParent(); + targetPath = dynamic_cast(curRight)->getPath(); + + Command_DeckUpload cmd; + cmd.set_path(targetPath.toStdString()); + cmd.set_deck_list(deck.writeToString_Native().toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(uploadFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabDeckStorage::uploadFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Response_DeckUpload &resp = r.GetExtension(Response_DeckUpload::ext); - const Command_DeckUpload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckUpload::ext); - - serverDirView->addFileToTree(resp.new_file(), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); + if (r.response_code() != Response::RespOk) + return; + + const Response_DeckUpload &resp = r.GetExtension(Response_DeckUpload::ext); + const Command_DeckUpload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckUpload::ext); + + serverDirView->addFileToTree(resp.new_file(), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); } void TabDeckStorage::actDeleteLocalDeck() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - localDirModel->remove(curLeft); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + localDirModel->remove(curLeft); } void TabDeckStorage::actOpenRemoteDeck() { - RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); - if (!curRight) - return; - - Command_DeckDownload cmd; - cmd.set_deck_id(curRight->getId()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteDeckFinished(Response, CommandContainer))); - client->sendCommand(pend); + RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); + if (!curRight) + return; + + Command_DeckDownload cmd; + cmd.set_deck_id(curRight->getId()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteDeckFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabDeckStorage::openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); - const Command_DeckDownload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDownload::ext); - - DeckLoader loader; - if (!loader.loadFromRemote(QString::fromStdString(resp.deck()), cmd.deck_id())) - return; - - emit openDeckEditor(&loader); + if (r.response_code() != Response::RespOk) + return; + + const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); + const Command_DeckDownload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDownload::ext); + + DeckLoader loader; + if (!loader.loadFromRemote(QString::fromStdString(resp.deck()), cmd.deck_id())) + return; + + emit openDeckEditor(&loader); } void TabDeckStorage::actDownload() { - QString filePath; - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (!curLeft.isValid()) - filePath = localDirModel->rootPath(); - else { - while (!localDirModel->isDir(curLeft)) - curLeft = curLeft.parent(); - filePath = localDirModel->filePath(curLeft); - } + QString filePath; + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (!curLeft.isValid()) + filePath = localDirModel->rootPath(); + else { + while (!localDirModel->isDir(curLeft)) + curLeft = curLeft.parent(); + filePath = localDirModel->filePath(curLeft); + } - RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); - if (!curRight) - return; - filePath += QString("/deck_%1.cod").arg(curRight->getId()); - - Command_DeckDownload cmd; - cmd.set_deck_id(curRight->getId()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - pend->setExtraData(filePath); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); - client->sendCommand(pend); + RemoteDeckList_TreeModel::FileNode *curRight = dynamic_cast(serverDirView->getCurrentItem()); + if (!curRight) + return; + filePath += QString("/deck_%1.cod").arg(curRight->getId()); + + Command_DeckDownload cmd; + cmd.set_deck_id(curRight->getId()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + pend->setExtraData(filePath); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); + client->sendCommand(pend); } void TabDeckStorage::downloadFinished(const Response &r, const CommandContainer &/*commandContainer*/, const QVariant &extraData) { - if (r.response_code() != Response::RespOk) - return; - - const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); - QString filePath = extraData.toString(); - - DeckLoader deck(QString::fromStdString(resp.deck())); - deck.saveToFile(filePath, DeckLoader::CockatriceFormat); + if (r.response_code() != Response::RespOk) + return; + + const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); + QString filePath = extraData.toString(); + + DeckLoader deck(QString::fromStdString(resp.deck())); + deck.saveToFile(filePath, DeckLoader::CockatriceFormat); } void TabDeckStorage::actNewFolder() { - QString folderName = QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:")); - if (folderName.isEmpty()) - return; + QString folderName = QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:")); + if (folderName.isEmpty()) + return; - QString targetPath; - RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); - if (!curRight) - return; - if (!dynamic_cast(curRight)) - curRight = curRight->getParent(); - RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); - targetPath = dir->getPath(); - - Command_DeckNewDir cmd; - cmd.set_path(targetPath.toStdString()); - cmd.set_dir_name(folderName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(newFolderFinished(Response, CommandContainer))); - client->sendCommand(pend); + QString targetPath; + RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); + if (!curRight) + return; + if (!dynamic_cast(curRight)) + curRight = curRight->getParent(); + RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); + targetPath = dir->getPath(); + + Command_DeckNewDir cmd; + cmd.set_path(targetPath.toStdString()); + cmd.set_dir_name(folderName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(newFolderFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabDeckStorage::newFolderFinished(const Response &response, const CommandContainer &commandContainer) { - if (response.response_code() != Response::RespOk) - return; - - const Command_DeckNewDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckNewDir::ext); - serverDirView->addFolderToTree(QString::fromStdString(cmd.dir_name()), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); + if (response.response_code() != Response::RespOk) + return; + + const Command_DeckNewDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckNewDir::ext); + serverDirView->addFolderToTree(QString::fromStdString(cmd.dir_name()), serverDirView->getNodeByPath(QString::fromStdString(cmd.path()))); } void TabDeckStorage::actDeleteRemoteDeck() { - PendingCommand *pend; - RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); - if (!curRight) - return; - RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); - if (dir) { - QString path = dir->getPath(); - if (path.isEmpty()) - return; - if (QMessageBox::warning(this, tr("Delete remote folder"), tr("Are you sure you want to delete \"%1\"?").arg(path), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - Command_DeckDelDir cmd; - cmd.set_path(path.toStdString()); - pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteFolderFinished(Response, CommandContainer))); - } else { - RemoteDeckList_TreeModel::FileNode *deckNode = dynamic_cast(curRight); - if (QMessageBox::warning(this, tr("Delete remote deck"), tr("Are you sure you want to delete \"%1\"?").arg(deckNode->getName()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - Command_DeckDel cmd; - cmd.set_deck_id(deckNode->getId()); - pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteDeckFinished(Response, CommandContainer))); - } - - client->sendCommand(pend); + PendingCommand *pend; + RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem(); + if (!curRight) + return; + RemoteDeckList_TreeModel::DirectoryNode *dir = dynamic_cast(curRight); + if (dir) { + QString path = dir->getPath(); + if (path.isEmpty()) + return; + if (QMessageBox::warning(this, tr("Delete remote folder"), tr("Are you sure you want to delete \"%1\"?").arg(path), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + Command_DeckDelDir cmd; + cmd.set_path(path.toStdString()); + pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteFolderFinished(Response, CommandContainer))); + } else { + RemoteDeckList_TreeModel::FileNode *deckNode = dynamic_cast(curRight); + if (QMessageBox::warning(this, tr("Delete remote deck"), tr("Are you sure you want to delete \"%1\"?").arg(deckNode->getName()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + Command_DeckDel cmd; + cmd.set_deck_id(deckNode->getId()); + pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteDeckFinished(Response, CommandContainer))); + } + + client->sendCommand(pend); } void TabDeckStorage::deleteDeckFinished(const Response &response, const CommandContainer &commandContainer) { - if (response.response_code() != Response::RespOk) - return; - - const Command_DeckDel &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDel::ext); - RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeById(cmd.deck_id()); - if (toDelete) - serverDirView->removeNode(toDelete); + if (response.response_code() != Response::RespOk) + return; + + const Command_DeckDel &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDel::ext); + RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeById(cmd.deck_id()); + if (toDelete) + serverDirView->removeNode(toDelete); } void TabDeckStorage::deleteFolderFinished(const Response &response, const CommandContainer &commandContainer) { - if (response.response_code() != Response::RespOk) - return; - - const Command_DeckDelDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDelDir::ext); - RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeByPath(QString::fromStdString(cmd.path())); - if (toDelete) - serverDirView->removeNode(toDelete); + if (response.response_code() != Response::RespOk) + return; + + const Command_DeckDelDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDelDir::ext); + RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeByPath(QString::fromStdString(cmd.path())); + if (toDelete) + serverDirView->removeNode(toDelete); } diff --git a/cockatrice/src/tab_deck_storage.h b/cockatrice/src/tab_deck_storage.h index a3ef7fc4..c6567ff1 100644 --- a/cockatrice/src/tab_deck_storage.h +++ b/cockatrice/src/tab_deck_storage.h @@ -16,42 +16,42 @@ class Response; class DeckLoader; class TabDeckStorage : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - QTreeView *localDirView; - QFileSystemModel *localDirModel; - QToolBar *leftToolBar, *rightToolBar; - RemoteDeckList_TreeWidget *serverDirView; - QGroupBox *leftGroupBox, *rightGroupBox; - - QAction *aOpenLocalDeck, *aUpload, *aDeleteLocalDeck, *aOpenRemoteDeck, *aDownload, *aNewFolder, *aDeleteRemoteDeck; + AbstractClient *client; + QTreeView *localDirView; + QFileSystemModel *localDirModel; + QToolBar *leftToolBar, *rightToolBar; + RemoteDeckList_TreeWidget *serverDirView; + QGroupBox *leftGroupBox, *rightGroupBox; + + QAction *aOpenLocalDeck, *aUpload, *aDeleteLocalDeck, *aOpenRemoteDeck, *aDownload, *aNewFolder, *aDeleteRemoteDeck; private slots: - void actOpenLocalDeck(); - - void actUpload(); - void uploadFinished(const Response &r, const CommandContainer &commandContainer); - - void actDeleteLocalDeck(); - - void actOpenRemoteDeck(); - void openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer); - - void actDownload(); - void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); + void actOpenLocalDeck(); + + void actUpload(); + void uploadFinished(const Response &r, const CommandContainer &commandContainer); + + void actDeleteLocalDeck(); + + void actOpenRemoteDeck(); + void openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer); + + void actDownload(); + void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); - void actNewFolder(); - void newFolderFinished(const Response &response, const CommandContainer &commandContainer); + void actNewFolder(); + void newFolderFinished(const Response &response, const CommandContainer &commandContainer); - void actDeleteRemoteDeck(); - void deleteFolderFinished(const Response &response, const CommandContainer &commandContainer); - void deleteDeckFinished(const Response &response, const CommandContainer &commandContainer); + void actDeleteRemoteDeck(); + void deleteFolderFinished(const Response &response, const CommandContainer &commandContainer); + void deleteDeckFinished(const Response &response, const CommandContainer &commandContainer); public: - TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_client); - void retranslateUi(); - QString getTabText() const { return tr("Deck storage"); } + TabDeckStorage(TabSupervisor *_tabSupervisor, AbstractClient *_client); + void retranslateUi(); + QString getTabText() const { return tr("Deck storage"); } signals: - void openDeckEditor(const DeckLoader *deckLoader); + void openDeckEditor(const DeckLoader *deckLoader); }; #endif diff --git a/cockatrice/src/tab_game.cpp b/cockatrice/src/tab_game.cpp index 17d5d33c..f237589e 100644 --- a/cockatrice/src/tab_game.cpp +++ b/cockatrice/src/tab_game.cpp @@ -64,1131 +64,1131 @@ #include "get_pb_extension.h" ToggleButton::ToggleButton(QWidget *parent) - : QPushButton(parent), state(false) + : QPushButton(parent), state(false) { } void ToggleButton::paintEvent(QPaintEvent *event) { - QPushButton::paintEvent(event); - - QPainter painter(this); - if (state) - painter.setPen(QPen(Qt::green, 3)); - else - painter.setPen(QPen(Qt::red, 3)); - painter.drawRect(1, 1, width() - 3, height() - 3); + QPushButton::paintEvent(event); + + QPainter painter(this); + if (state) + painter.setPen(QPen(Qt::green, 3)); + else + painter.setPen(QPen(Qt::red, 3)); + painter.drawRect(1, 1, width() - 3, height() - 3); } void ToggleButton::setState(bool _state) { - state = _state; - emit stateChanged(); - update(); + state = _state; + emit stateChanged(); + update(); } DeckViewContainer::DeckViewContainer(int _playerId, TabGame *parent) - : QWidget(parent), playerId(_playerId) + : QWidget(parent), playerId(_playerId) { - loadLocalButton = new QPushButton; - loadRemoteButton = new QPushButton; - readyStartButton = new ToggleButton; - readyStartButton->setEnabled(false); - sideboardLockButton = new ToggleButton; - sideboardLockButton->setEnabled(false); - - connect(loadLocalButton, SIGNAL(clicked()), this, SLOT(loadLocalDeck())); - connect(loadRemoteButton, SIGNAL(clicked()), this, SLOT(loadRemoteDeck())); - connect(readyStartButton, SIGNAL(clicked()), this, SLOT(readyStart())); - connect(sideboardLockButton, SIGNAL(clicked()), this, SLOT(sideboardLockButtonClicked())); - connect(sideboardLockButton, SIGNAL(stateChanged()), this, SLOT(updateSideboardLockButtonText())); - - QHBoxLayout *buttonHBox = new QHBoxLayout; - buttonHBox->addWidget(loadLocalButton); - buttonHBox->addWidget(loadRemoteButton); - buttonHBox->addWidget(readyStartButton); - buttonHBox->addWidget(sideboardLockButton); - buttonHBox->addStretch(); - deckView = new DeckView; - connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); - connect(deckView, SIGNAL(sideboardPlanChanged()), this, SLOT(sideboardPlanChanged())); - - QVBoxLayout *deckViewLayout = new QVBoxLayout; - deckViewLayout->addLayout(buttonHBox); - deckViewLayout->addWidget(deckView); - setLayout(deckViewLayout); - - retranslateUi(); + loadLocalButton = new QPushButton; + loadRemoteButton = new QPushButton; + readyStartButton = new ToggleButton; + readyStartButton->setEnabled(false); + sideboardLockButton = new ToggleButton; + sideboardLockButton->setEnabled(false); + + connect(loadLocalButton, SIGNAL(clicked()), this, SLOT(loadLocalDeck())); + connect(loadRemoteButton, SIGNAL(clicked()), this, SLOT(loadRemoteDeck())); + connect(readyStartButton, SIGNAL(clicked()), this, SLOT(readyStart())); + connect(sideboardLockButton, SIGNAL(clicked()), this, SLOT(sideboardLockButtonClicked())); + connect(sideboardLockButton, SIGNAL(stateChanged()), this, SLOT(updateSideboardLockButtonText())); + + QHBoxLayout *buttonHBox = new QHBoxLayout; + buttonHBox->addWidget(loadLocalButton); + buttonHBox->addWidget(loadRemoteButton); + buttonHBox->addWidget(readyStartButton); + buttonHBox->addWidget(sideboardLockButton); + buttonHBox->addStretch(); + deckView = new DeckView; + connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SIGNAL(newCardAdded(AbstractCardItem *))); + connect(deckView, SIGNAL(sideboardPlanChanged()), this, SLOT(sideboardPlanChanged())); + + QVBoxLayout *deckViewLayout = new QVBoxLayout; + deckViewLayout->addLayout(buttonHBox); + deckViewLayout->addWidget(deckView); + setLayout(deckViewLayout); + + retranslateUi(); } void DeckViewContainer::retranslateUi() { - loadLocalButton->setText(tr("Load &local deck")); - loadRemoteButton->setText(tr("Load d&eck from server")); - readyStartButton->setText(tr("Ready to s&tart")); - updateSideboardLockButtonText(); + loadLocalButton->setText(tr("Load &local deck")); + loadRemoteButton->setText(tr("Load d&eck from server")); + readyStartButton->setText(tr("Ready to s&tart")); + updateSideboardLockButtonText(); } void DeckViewContainer::setButtonsVisible(bool _visible) { - loadLocalButton->setVisible(_visible); - loadRemoteButton->setVisible(_visible); - readyStartButton->setVisible(_visible); - sideboardLockButton->setVisible(_visible); + loadLocalButton->setVisible(_visible); + loadRemoteButton->setVisible(_visible); + readyStartButton->setVisible(_visible); + sideboardLockButton->setVisible(_visible); } void DeckViewContainer::updateSideboardLockButtonText() { - if (sideboardLockButton->getState()) - sideboardLockButton->setText(tr("S&ideboard unlocked")); - else - sideboardLockButton->setText(tr("S&ideboard locked")); + if (sideboardLockButton->getState()) + sideboardLockButton->setText(tr("S&ideboard unlocked")); + else + sideboardLockButton->setText(tr("S&ideboard locked")); } void DeckViewContainer::loadLocalDeck() { - QFileDialog dialog(this, tr("Load deck")); - dialog.setDirectory(settingsCache->getDeckPath()); - dialog.setNameFilters(DeckLoader::fileNameFilters); - if (!dialog.exec()) - return; + QFileDialog dialog(this, tr("Load deck")); + dialog.setDirectory(settingsCache->getDeckPath()); + dialog.setNameFilters(DeckLoader::fileNameFilters); + if (!dialog.exec()) + return; - QString fileName = dialog.selectedFiles().at(0); - DeckLoader::FileFormat fmt = DeckLoader::getFormatFromNameFilter(dialog.selectedNameFilter()); - DeckLoader deck; - if (!deck.loadFromFile(fileName, fmt)) { - QMessageBox::critical(this, tr("Error"), tr("The selected file could not be loaded.")); - return; - } - - Command_DeckSelect cmd; - cmd.set_deck(deck.writeToString_Native().toStdString()); - PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); - static_cast(parent())->sendGameCommand(pend, playerId); + QString fileName = dialog.selectedFiles().at(0); + DeckLoader::FileFormat fmt = DeckLoader::getFormatFromName(fileName); + DeckLoader deck; + if (!deck.loadFromFile(fileName, fmt)) { + QMessageBox::critical(this, tr("Error"), tr("The selected file could not be loaded.")); + return; + } + + Command_DeckSelect cmd; + cmd.set_deck(deck.writeToString_Native().toStdString()); + PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); + static_cast(parent())->sendGameCommand(pend, playerId); } void DeckViewContainer::loadRemoteDeck() { - DlgLoadRemoteDeck dlg(static_cast(parent())->getClientForPlayer(playerId)); - if (dlg.exec()) { - Command_DeckSelect cmd; - cmd.set_deck_id(dlg.getDeckId()); - PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); - static_cast(parent())->sendGameCommand(pend, playerId); - } + DlgLoadRemoteDeck dlg(static_cast(parent())->getClientForPlayer(playerId)); + if (dlg.exec()) { + Command_DeckSelect cmd; + cmd.set_deck_id(dlg.getDeckId()); + PendingCommand *pend = static_cast(parent())->prepareGameCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deckSelectFinished(const Response &))); + static_cast(parent())->sendGameCommand(pend, playerId); + } } void DeckViewContainer::deckSelectFinished(const Response &r) { - const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); - DeckLoader newDeck(QString::fromStdString(resp.deck())); - db->cacheCardPixmaps(newDeck.getCardList()); - setDeck(newDeck); + const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext); + DeckLoader newDeck(QString::fromStdString(resp.deck())); + db->cacheCardPixmaps(newDeck.getCardList()); + setDeck(newDeck); } void DeckViewContainer::readyStart() { - Command_ReadyStart cmd; - cmd.set_ready(!readyStartButton->getState()); - static_cast(parent())->sendGameCommand(cmd, playerId); + Command_ReadyStart cmd; + cmd.set_ready(!readyStartButton->getState()); + static_cast(parent())->sendGameCommand(cmd, playerId); } void DeckViewContainer::sideboardLockButtonClicked() { - Command_SetSideboardLock cmd; - cmd.set_locked(sideboardLockButton->getState()); - - static_cast(parent())->sendGameCommand(cmd, playerId); + Command_SetSideboardLock cmd; + cmd.set_locked(sideboardLockButton->getState()); + + static_cast(parent())->sendGameCommand(cmd, playerId); } void DeckViewContainer::sideboardPlanChanged() { - Command_SetSideboardPlan cmd; - const QList &newPlan = deckView->getSideboardPlan(); - for (int i = 0; i < newPlan.size(); ++i) - cmd.add_move_list()->CopyFrom(newPlan[i]); - static_cast(parent())->sendGameCommand(cmd, playerId); + Command_SetSideboardPlan cmd; + const QList &newPlan = deckView->getSideboardPlan(); + for (int i = 0; i < newPlan.size(); ++i) + cmd.add_move_list()->CopyFrom(newPlan[i]); + static_cast(parent())->sendGameCommand(cmd, playerId); } void DeckViewContainer::setReadyStart(bool ready) { - readyStartButton->setState(ready); - deckView->setLocked(ready || !sideboardLockButton->getState()); + readyStartButton->setState(ready); + deckView->setLocked(ready || !sideboardLockButton->getState()); } void DeckViewContainer::setSideboardLocked(bool locked) { - sideboardLockButton->setState(!locked); - deckView->setLocked(readyStartButton->getState() || !sideboardLockButton->getState()); - if (locked) - deckView->resetSideboardPlan(); + sideboardLockButton->setState(!locked); + deckView->setLocked(readyStartButton->getState() || !sideboardLockButton->getState()); + if (locked) + deckView->resetSideboardPlan(); } void DeckViewContainer::setDeck(const DeckLoader &deck) { - deckView->setDeck(deck); - readyStartButton->setEnabled(true); - sideboardLockButton->setState(false); - sideboardLockButton->setEnabled(true); + deckView->setDeck(deck); + readyStartButton->setEnabled(true); + sideboardLockButton->setState(false); + sideboardLockButton->setEnabled(true); } TabGame::TabGame(TabSupervisor *_tabSupervisor, GameReplay *_replay) - : Tab(_tabSupervisor), - hostId(-1), - localPlayerId(-1), - spectator(true), - gameStateKnown(false), - resuming(false), - currentPhase(-1), - activeCard(0), - gameClosed(false), - replay(_replay), - currentReplayStep(0) + : Tab(_tabSupervisor), + hostId(-1), + localPlayerId(-1), + spectator(true), + gameStateKnown(false), + resuming(false), + currentPhase(-1), + activeCard(0), + gameClosed(false), + replay(_replay), + currentReplayStep(0) { - setAttribute(Qt::WA_DeleteOnClose); - - gameInfo.CopyFrom(replay->game_info()); - gameInfo.set_spectators_omniscient(true); - - // Create list: event number -> time [ms] - // Distribute simultaneous events evenly across 1 second. - int lastEventTimestamp = -1; - const int eventCount = replay->event_list_size(); - for (int i = 0; i < eventCount; ++i) { - int j = i + 1; - while ((j < eventCount) && (replay->event_list(j).seconds_elapsed() == lastEventTimestamp)) - ++j; - - const int numberEventsThisSecond = j - i; - for (int k = 0; k < numberEventsThisSecond; ++k) - replayTimeline.append(replay->event_list(i + k).seconds_elapsed() * 1000 + (int) ((qreal) k / (qreal) numberEventsThisSecond * 1000)); - - if (j < eventCount) - lastEventTimestamp = replay->event_list(j).seconds_elapsed(); - i += numberEventsThisSecond - 1; - } - - phasesToolbar = new PhasesToolbar; - - scene = new GameScene(phasesToolbar, this); - gameView = new GameView(scene); - gameView->hide(); - - cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); - playerListWidget = new PlayerListWidget(0, 0, this); - playerListWidget->setFocusPolicy(Qt::NoFocus); - - timeElapsedLabel = new QLabel; - timeElapsedLabel->setAlignment(Qt::AlignCenter); - messageLog = new MessageLogWidget(tabSupervisor, this); - connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); - connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayLabel = 0; + setAttribute(Qt::WA_DeleteOnClose); + + gameInfo.CopyFrom(replay->game_info()); + gameInfo.set_spectators_omniscient(true); + + // Create list: event number -> time [ms] + // Distribute simultaneous events evenly across 1 second. + int lastEventTimestamp = -1; + const int eventCount = replay->event_list_size(); + for (int i = 0; i < eventCount; ++i) { + int j = i + 1; + while ((j < eventCount) && (replay->event_list(j).seconds_elapsed() == lastEventTimestamp)) + ++j; + + const int numberEventsThisSecond = j - i; + for (int k = 0; k < numberEventsThisSecond; ++k) + replayTimeline.append(replay->event_list(i + k).seconds_elapsed() * 1000 + (int) ((qreal) k / (qreal) numberEventsThisSecond * 1000)); + + if (j < eventCount) + lastEventTimestamp = replay->event_list(j).seconds_elapsed(); + i += numberEventsThisSecond - 1; + } + + phasesToolbar = new PhasesToolbar; + + scene = new GameScene(phasesToolbar, this); + gameView = new GameView(scene); + gameView->hide(); + + cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); + playerListWidget = new PlayerListWidget(0, 0, this); + playerListWidget->setFocusPolicy(Qt::NoFocus); + + timeElapsedLabel = new QLabel; + timeElapsedLabel->setAlignment(Qt::AlignCenter); + messageLog = new MessageLogWidget(tabSupervisor, this); + connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); + connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayLabel = 0; - deckViewContainerLayout = new QVBoxLayout; + deckViewContainerLayout = new QVBoxLayout; - QVBoxLayout *messageLogLayout = new QVBoxLayout; - messageLogLayout->addWidget(timeElapsedLabel); - messageLogLayout->addWidget(messageLog); - - QWidget *messageLogLayoutWidget = new QWidget; - messageLogLayoutWidget->setLayout(messageLogLayout); - - timelineWidget = new ReplayTimelineWidget; - timelineWidget->setTimeline(replayTimeline); - connect(timelineWidget, SIGNAL(processNextEvent()), this, SLOT(replayNextEvent())); - connect(timelineWidget, SIGNAL(replayFinished()), this, SLOT(replayFinished())); - - replayToStartButton = new QToolButton; - replayToStartButton->setIconSize(QSize(32, 32)); - replayToStartButton->setIcon(QIcon(":/resources/replay_tostart.svg")); - connect(replayToStartButton, SIGNAL(clicked()), this, SLOT(replayToStartButtonClicked())); - replayStartButton = new QToolButton; - replayStartButton->setIconSize(QSize(32, 32)); - replayStartButton->setIcon(QIcon(":/resources/replay_start.svg")); - connect(replayStartButton, SIGNAL(clicked()), this, SLOT(replayStartButtonClicked())); - replayPauseButton = new QToolButton; - replayPauseButton->setIconSize(QSize(32, 32)); - replayPauseButton->setEnabled(false); - replayPauseButton->setIcon(QIcon(":/resources/replay_pause.svg")); - connect(replayPauseButton, SIGNAL(clicked()), this, SLOT(replayPauseButtonClicked())); - replayStopButton = new QToolButton; - replayStopButton->setIconSize(QSize(32, 32)); - replayStopButton->setEnabled(false); - replayStopButton->setIcon(QIcon(":/resources/replay_stop.svg")); - connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayStopButtonClicked())); - replayFastForwardButton = new QToolButton; - replayFastForwardButton->setIconSize(QSize(32, 32)); - replayFastForwardButton->setEnabled(false); - replayFastForwardButton->setIcon(QIcon(":/resources/replay_fastforward.svg")); - replayFastForwardButton->setCheckable(true); - connect(replayFastForwardButton, SIGNAL(toggled(bool)), this, SLOT(replayFastForwardButtonToggled(bool))); - replayToEndButton = new QToolButton; - replayToEndButton->setIconSize(QSize(32, 32)); - replayToEndButton->setIcon(QIcon(":/resources/replay_toend.svg")); - connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayToEndButtonClicked())); - - splitter = new QSplitter(Qt::Vertical); - splitter->addWidget(cardInfo); - splitter->addWidget(playerListWidget); - splitter->addWidget(messageLogLayoutWidget); + QVBoxLayout *messageLogLayout = new QVBoxLayout; + messageLogLayout->addWidget(timeElapsedLabel); + messageLogLayout->addWidget(messageLog); + + QWidget *messageLogLayoutWidget = new QWidget; + messageLogLayoutWidget->setLayout(messageLogLayout); + + timelineWidget = new ReplayTimelineWidget; + timelineWidget->setTimeline(replayTimeline); + connect(timelineWidget, SIGNAL(processNextEvent()), this, SLOT(replayNextEvent())); + connect(timelineWidget, SIGNAL(replayFinished()), this, SLOT(replayFinished())); + + replayToStartButton = new QToolButton; + replayToStartButton->setIconSize(QSize(32, 32)); + replayToStartButton->setIcon(QIcon(":/resources/replay_tostart.svg")); + connect(replayToStartButton, SIGNAL(clicked()), this, SLOT(replayToStartButtonClicked())); + replayStartButton = new QToolButton; + replayStartButton->setIconSize(QSize(32, 32)); + replayStartButton->setIcon(QIcon(":/resources/replay_start.svg")); + connect(replayStartButton, SIGNAL(clicked()), this, SLOT(replayStartButtonClicked())); + replayPauseButton = new QToolButton; + replayPauseButton->setIconSize(QSize(32, 32)); + replayPauseButton->setEnabled(false); + replayPauseButton->setIcon(QIcon(":/resources/replay_pause.svg")); + connect(replayPauseButton, SIGNAL(clicked()), this, SLOT(replayPauseButtonClicked())); + replayStopButton = new QToolButton; + replayStopButton->setIconSize(QSize(32, 32)); + replayStopButton->setEnabled(false); + replayStopButton->setIcon(QIcon(":/resources/replay_stop.svg")); + connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayStopButtonClicked())); + replayFastForwardButton = new QToolButton; + replayFastForwardButton->setIconSize(QSize(32, 32)); + replayFastForwardButton->setEnabled(false); + replayFastForwardButton->setIcon(QIcon(":/resources/replay_fastforward.svg")); + replayFastForwardButton->setCheckable(true); + connect(replayFastForwardButton, SIGNAL(toggled(bool)), this, SLOT(replayFastForwardButtonToggled(bool))); + replayToEndButton = new QToolButton; + replayToEndButton->setIconSize(QSize(32, 32)); + replayToEndButton->setIcon(QIcon(":/resources/replay_toend.svg")); + connect(replayStopButton, SIGNAL(clicked()), this, SLOT(replayToEndButtonClicked())); + + splitter = new QSplitter(Qt::Vertical); + splitter->addWidget(cardInfo); + splitter->addWidget(playerListWidget); + splitter->addWidget(messageLogLayoutWidget); - mainLayout = new QHBoxLayout; - mainLayout->addWidget(gameView, 10); - mainLayout->addLayout(deckViewContainerLayout, 10); - mainLayout->addWidget(splitter); - - QHBoxLayout *replayControlLayout = new QHBoxLayout; - replayControlLayout->addWidget(timelineWidget, 10); - replayControlLayout->addWidget(replayToStartButton); - replayControlLayout->addWidget(replayStartButton); - replayControlLayout->addWidget(replayPauseButton); - replayControlLayout->addWidget(replayStopButton); - replayControlLayout->addWidget(replayFastForwardButton); - replayControlLayout->addWidget(replayToEndButton); - - QVBoxLayout *superMainLayout = new QVBoxLayout; - superMainLayout->addLayout(mainLayout); - superMainLayout->addLayout(replayControlLayout); - - aNextPhase = 0; - aNextTurn = 0; - aRemoveLocalArrows = 0; - aGameInfo = 0; - aConcede = 0; - aLeaveGame = 0; - aCloseReplay = new QAction(this); - connect(aCloseReplay, SIGNAL(triggered()), this, SLOT(actLeaveGame())); - - phasesMenu = 0; - gameMenu = new QMenu(this); - gameMenu->addAction(aCloseReplay); - addTabMenu(gameMenu); - - retranslateUi(); - setLayout(superMainLayout); + mainLayout = new QHBoxLayout; + mainLayout->addWidget(gameView, 10); + mainLayout->addLayout(deckViewContainerLayout, 10); + mainLayout->addWidget(splitter); + + QHBoxLayout *replayControlLayout = new QHBoxLayout; + replayControlLayout->addWidget(timelineWidget, 10); + replayControlLayout->addWidget(replayToStartButton); + replayControlLayout->addWidget(replayStartButton); + replayControlLayout->addWidget(replayPauseButton); + replayControlLayout->addWidget(replayStopButton); + replayControlLayout->addWidget(replayFastForwardButton); + replayControlLayout->addWidget(replayToEndButton); + + QVBoxLayout *superMainLayout = new QVBoxLayout; + superMainLayout->addLayout(mainLayout); + superMainLayout->addLayout(replayControlLayout); + + aNextPhase = 0; + aNextTurn = 0; + aRemoveLocalArrows = 0; + aGameInfo = 0; + aConcede = 0; + aLeaveGame = 0; + aCloseReplay = new QAction(this); + connect(aCloseReplay, SIGNAL(triggered()), this, SLOT(actLeaveGame())); + + phasesMenu = 0; + gameMenu = new QMenu(this); + gameMenu->addAction(aCloseReplay); + addTabMenu(gameMenu); + + retranslateUi(); + setLayout(superMainLayout); - splitter->restoreState(settingsCache->getTabGameSplitterSizes()); - - messageLog->logReplayStarted(gameInfo.game_id()); + splitter->restoreState(settingsCache->getTabGameSplitterSizes()); + + messageLog->logReplayStarted(gameInfo.game_id()); } TabGame::TabGame(TabSupervisor *_tabSupervisor, QList &_clients, const Event_GameJoined &event, const QMap &_roomGameTypes) - : Tab(_tabSupervisor), - clients(_clients), - gameInfo(event.game_info()), - roomGameTypes(_roomGameTypes), - hostId(event.host_id()), - localPlayerId(event.player_id()), - spectator(event.spectator()), - gameStateKnown(false), - resuming(event.resuming()), - currentPhase(-1), - activeCard(0), - gameClosed(false), - replay(0) + : Tab(_tabSupervisor), + clients(_clients), + gameInfo(event.game_info()), + roomGameTypes(_roomGameTypes), + hostId(event.host_id()), + localPlayerId(event.player_id()), + spectator(event.spectator()), + gameStateKnown(false), + resuming(event.resuming()), + currentPhase(-1), + activeCard(0), + gameClosed(false), + replay(0) { - gameInfo.set_started(false); - - gameTimer = new QTimer(this); - gameTimer->setInterval(1000); - connect(gameTimer, SIGNAL(timeout()), this, SLOT(incrementGameTime())); - gameTimer->start(); - - phasesToolbar = new PhasesToolbar; - connect(phasesToolbar, SIGNAL(sendGameCommand(const ::google::protobuf::Message &, int)), this, SLOT(sendGameCommand(const ::google::protobuf::Message &, int))); - - scene = new GameScene(phasesToolbar, this); - gameView = new GameView(scene); - gameView->hide(); - - cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); - playerListWidget = new PlayerListWidget(tabSupervisor, clients.first(), this); - playerListWidget->setFocusPolicy(Qt::NoFocus); - connect(playerListWidget, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - - timeElapsedLabel = new QLabel; - timeElapsedLabel->setAlignment(Qt::AlignCenter); - messageLog = new MessageLogWidget(tabSupervisor, this); - connect(messageLog, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); - connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayLabel = new QLabel; - sayEdit = new QLineEdit; - sayLabel->setBuddy(sayEdit); + gameInfo.set_started(false); + + gameTimer = new QTimer(this); + gameTimer->setInterval(1000); + connect(gameTimer, SIGNAL(timeout()), this, SLOT(incrementGameTime())); + gameTimer->start(); + + phasesToolbar = new PhasesToolbar; + connect(phasesToolbar, SIGNAL(sendGameCommand(const ::google::protobuf::Message &, int)), this, SLOT(sendGameCommand(const ::google::protobuf::Message &, int))); + + scene = new GameScene(phasesToolbar, this); + gameView = new GameView(scene); + gameView->hide(); + + cardInfo = new CardInfoWidget(CardInfoWidget::ModeGameTab); + playerListWidget = new PlayerListWidget(tabSupervisor, clients.first(), this); + playerListWidget->setFocusPolicy(Qt::NoFocus); + connect(playerListWidget, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + + timeElapsedLabel = new QLabel; + timeElapsedLabel->setAlignment(Qt::AlignCenter); + messageLog = new MessageLogWidget(tabSupervisor, this); + connect(messageLog, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + connect(messageLog, SIGNAL(cardNameHovered(QString)), cardInfo, SLOT(setCard(QString))); + connect(messageLog, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(messageLog, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayLabel = new QLabel; + sayEdit = new QLineEdit; + sayLabel->setBuddy(sayEdit); - QHBoxLayout *hLayout = new QHBoxLayout; - hLayout->addWidget(sayLabel); - hLayout->addWidget(sayEdit); - - deckViewContainerLayout = new QVBoxLayout; + QHBoxLayout *hLayout = new QHBoxLayout; + hLayout->addWidget(sayLabel); + hLayout->addWidget(sayEdit); + + deckViewContainerLayout = new QVBoxLayout; - QVBoxLayout *messageLogLayout = new QVBoxLayout; - messageLogLayout->addWidget(timeElapsedLabel); - messageLogLayout->addWidget(messageLog); - messageLogLayout->addLayout(hLayout); - - QWidget *messageLogLayoutWidget = new QWidget; - messageLogLayoutWidget->setLayout(messageLogLayout); - - splitter = new QSplitter(Qt::Vertical); - splitter->addWidget(cardInfo); - splitter->addWidget(playerListWidget); - splitter->addWidget(messageLogLayoutWidget); + QVBoxLayout *messageLogLayout = new QVBoxLayout; + messageLogLayout->addWidget(timeElapsedLabel); + messageLogLayout->addWidget(messageLog); + messageLogLayout->addLayout(hLayout); + + QWidget *messageLogLayoutWidget = new QWidget; + messageLogLayoutWidget->setLayout(messageLogLayout); + + splitter = new QSplitter(Qt::Vertical); + splitter->addWidget(cardInfo); + splitter->addWidget(playerListWidget); + splitter->addWidget(messageLogLayoutWidget); - mainLayout = new QHBoxLayout; - mainLayout->addWidget(gameView, 10); - mainLayout->addLayout(deckViewContainerLayout, 10); - mainLayout->addWidget(splitter); - - if (spectator && !gameInfo.spectators_can_chat() && tabSupervisor->getAdminLocked()) { - sayLabel->hide(); - sayEdit->hide(); - } - connect(tabSupervisor, SIGNAL(adminLockChanged(bool)), this, SLOT(adminLockChanged(bool))); - connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(actSay())); + mainLayout = new QHBoxLayout; + mainLayout->addWidget(gameView, 10); + mainLayout->addLayout(deckViewContainerLayout, 10); + mainLayout->addWidget(splitter); + + if (spectator && !gameInfo.spectators_can_chat() && tabSupervisor->getAdminLocked()) { + sayLabel->hide(); + sayEdit->hide(); + } + connect(tabSupervisor, SIGNAL(adminLockChanged(bool)), this, SLOT(adminLockChanged(bool))); + connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(actSay())); - // Menu actions - aNextPhase = new QAction(this); - connect(aNextPhase, SIGNAL(triggered()), this, SLOT(actNextPhase())); - aNextTurn = new QAction(this); - connect(aNextTurn, SIGNAL(triggered()), this, SLOT(actNextTurn())); - aRemoveLocalArrows = new QAction(this); - connect(aRemoveLocalArrows, SIGNAL(triggered()), this, SLOT(actRemoveLocalArrows())); - aGameInfo = new QAction(this); - connect(aGameInfo, SIGNAL(triggered()), this, SLOT(actGameInfo())); - aConcede = new QAction(this); - connect(aConcede, SIGNAL(triggered()), this, SLOT(actConcede())); - aLeaveGame = new QAction(this); - connect(aLeaveGame, SIGNAL(triggered()), this, SLOT(actLeaveGame())); - aCloseReplay = 0; - - phasesMenu = new QMenu(this); - for (int i = 0; i < phasesToolbar->phaseCount(); ++i) { - QAction *temp = new QAction(QString(), this); - connect(temp, SIGNAL(triggered()), this, SLOT(actPhaseAction())); - switch (i) { - case 0: temp->setShortcut(tr("F5")); break; - case 2: temp->setShortcut(tr("F6")); break; - case 3: temp->setShortcut(tr("F7")); break; - case 4: temp->setShortcut(tr("F8")); break; - case 9: temp->setShortcut(tr("F9")); break; - case 10: temp->setShortcut(tr("F10")); break; - default: ; - } - phasesMenu->addAction(temp); - phaseActions.append(temp); - } - phasesMenu->addSeparator(); - phasesMenu->addAction(aNextPhase); - - gameMenu = new QMenu(this); - playersSeparator = gameMenu->addSeparator(); - gameMenu->addMenu(phasesMenu); - gameMenu->addAction(aNextTurn); - gameMenu->addSeparator(); - gameMenu->addAction(aRemoveLocalArrows); - gameMenu->addSeparator(); - gameMenu->addAction(aGameInfo); - gameMenu->addAction(aConcede); - gameMenu->addAction(aLeaveGame); - addTabMenu(gameMenu); - - retranslateUi(); - setLayout(mainLayout); + // Menu actions + aNextPhase = new QAction(this); + connect(aNextPhase, SIGNAL(triggered()), this, SLOT(actNextPhase())); + aNextTurn = new QAction(this); + connect(aNextTurn, SIGNAL(triggered()), this, SLOT(actNextTurn())); + aRemoveLocalArrows = new QAction(this); + connect(aRemoveLocalArrows, SIGNAL(triggered()), this, SLOT(actRemoveLocalArrows())); + aGameInfo = new QAction(this); + connect(aGameInfo, SIGNAL(triggered()), this, SLOT(actGameInfo())); + aConcede = new QAction(this); + connect(aConcede, SIGNAL(triggered()), this, SLOT(actConcede())); + aLeaveGame = new QAction(this); + connect(aLeaveGame, SIGNAL(triggered()), this, SLOT(actLeaveGame())); + aCloseReplay = 0; + + phasesMenu = new QMenu(this); + for (int i = 0; i < phasesToolbar->phaseCount(); ++i) { + QAction *temp = new QAction(QString(), this); + connect(temp, SIGNAL(triggered()), this, SLOT(actPhaseAction())); + switch (i) { + case 0: temp->setShortcut(tr("F5")); break; + case 2: temp->setShortcut(tr("F6")); break; + case 3: temp->setShortcut(tr("F7")); break; + case 4: temp->setShortcut(tr("F8")); break; + case 9: temp->setShortcut(tr("F9")); break; + case 10: temp->setShortcut(tr("F10")); break; + default: ; + } + phasesMenu->addAction(temp); + phaseActions.append(temp); + } + phasesMenu->addSeparator(); + phasesMenu->addAction(aNextPhase); + + gameMenu = new QMenu(this); + playersSeparator = gameMenu->addSeparator(); + gameMenu->addMenu(phasesMenu); + gameMenu->addAction(aNextTurn); + gameMenu->addSeparator(); + gameMenu->addAction(aRemoveLocalArrows); + gameMenu->addSeparator(); + gameMenu->addAction(aGameInfo); + gameMenu->addAction(aConcede); + gameMenu->addAction(aLeaveGame); + addTabMenu(gameMenu); + + retranslateUi(); + setLayout(mainLayout); - splitter->restoreState(settingsCache->getTabGameSplitterSizes()); - - messageLog->logGameJoined(gameInfo.game_id()); + splitter->restoreState(settingsCache->getTabGameSplitterSizes()); + + messageLog->logGameJoined(gameInfo.game_id()); } TabGame::~TabGame() { - delete replay; - settingsCache->setTabGameSplitterSizes(splitter->saveState()); + delete replay; + settingsCache->setTabGameSplitterSizes(splitter->saveState()); - QMapIterator i(players); - while (i.hasNext()) - delete i.next().value(); - players.clear(); - - delete deckViewContainerLayout; - - emit gameClosing(this); + QMapIterator i(players); + while (i.hasNext()) + delete i.next().value(); + players.clear(); + + delete deckViewContainerLayout; + + emit gameClosing(this); } void TabGame::retranslateUi() { - if (phasesMenu) { - for (int i = 0; i < phaseActions.size(); ++i) - phaseActions[i]->setText(phasesToolbar->getLongPhaseName(i)); - phasesMenu->setTitle(tr("&Phases")); - } - - gameMenu->setTitle(tr("&Game")); - if (aNextPhase) { - aNextPhase->setText(tr("Next &phase")); - aNextPhase->setShortcut(tr("Ctrl+Space")); - } - if (aNextTurn) { - aNextTurn->setText(tr("Next &turn")); - aNextTurn->setShortcuts(QList() << QKeySequence(tr("Ctrl+Return")) << QKeySequence(tr("Ctrl+Enter"))); - } - if (aRemoveLocalArrows) { - aRemoveLocalArrows->setText(tr("&Remove all local arrows")); - aRemoveLocalArrows->setShortcut(tr("Ctrl+R")); - } - if (aGameInfo) - aGameInfo->setText(tr("Game &information")); - if (aConcede) { - aConcede->setText(tr("&Concede")); - aConcede->setShortcut(tr("F2")); - } - if (aLeaveGame) { - aLeaveGame->setText(tr("&Leave game")); - aLeaveGame->setShortcut(tr("Ctrl+Q")); - } - if (aCloseReplay) { - aCloseReplay->setText(tr("C&lose replay")); - aCloseReplay->setShortcut(tr("Ctrl+Q")); - } - - if (sayLabel) - sayLabel->setText(tr("&Say:")); - cardInfo->retranslateUi(); + if (phasesMenu) { + for (int i = 0; i < phaseActions.size(); ++i) + phaseActions[i]->setText(phasesToolbar->getLongPhaseName(i)); + phasesMenu->setTitle(tr("&Phases")); + } + + gameMenu->setTitle(tr("&Game")); + if (aNextPhase) { + aNextPhase->setText(tr("Next &phase")); + aNextPhase->setShortcut(tr("Ctrl+Space")); + } + if (aNextTurn) { + aNextTurn->setText(tr("Next &turn")); + aNextTurn->setShortcuts(QList() << QKeySequence(tr("Ctrl+Return")) << QKeySequence(tr("Ctrl+Enter"))); + } + if (aRemoveLocalArrows) { + aRemoveLocalArrows->setText(tr("&Remove all local arrows")); + aRemoveLocalArrows->setShortcut(tr("Ctrl+R")); + } + if (aGameInfo) + aGameInfo->setText(tr("Game &information")); + if (aConcede) { + aConcede->setText(tr("&Concede")); + aConcede->setShortcut(tr("F2")); + } + if (aLeaveGame) { + aLeaveGame->setText(tr("&Leave game")); + aLeaveGame->setShortcut(tr("Ctrl+Q")); + } + if (aCloseReplay) { + aCloseReplay->setText(tr("C&lose replay")); + aCloseReplay->setShortcut(tr("Ctrl+Q")); + } + + if (sayLabel) + sayLabel->setText(tr("&Say:")); + cardInfo->retranslateUi(); - QMapIterator i(players); - while (i.hasNext()) - i.next().value()->retranslateUi(); - QMapIterator j(deckViewContainers); - while (j.hasNext()) - j.next().value()->retranslateUi(); - - scene->retranslateUi(); + QMapIterator i(players); + while (i.hasNext()) + i.next().value()->retranslateUi(); + QMapIterator j(deckViewContainers); + while (j.hasNext()) + j.next().value()->retranslateUi(); + + scene->retranslateUi(); } void TabGame::closeRequest() { - actLeaveGame(); + actLeaveGame(); } void TabGame::replayNextEvent() { - processGameEventContainer(replay->event_list(timelineWidget->getCurrentEvent()), 0); + processGameEventContainer(replay->event_list(timelineWidget->getCurrentEvent()), 0); } void TabGame::replayFinished() { - replayStartButton->setEnabled(true); - replayPauseButton->setEnabled(false); - replayStopButton->setEnabled(false); - replayFastForwardButton->setEnabled(false); + replayStartButton->setEnabled(true); + replayPauseButton->setEnabled(false); + replayStopButton->setEnabled(false); + replayFastForwardButton->setEnabled(false); } void TabGame::replayToStartButtonClicked() { - // XXX + // XXX } void TabGame::replayStartButtonClicked() { - replayStartButton->setEnabled(false); - replayPauseButton->setEnabled(true); - replayStopButton->setEnabled(true); - replayFastForwardButton->setEnabled(true); - - timelineWidget->startReplay(); + replayStartButton->setEnabled(false); + replayPauseButton->setEnabled(true); + replayStopButton->setEnabled(true); + replayFastForwardButton->setEnabled(true); + + timelineWidget->startReplay(); } void TabGame::replayPauseButtonClicked() { - replayStartButton->setEnabled(true); - replayPauseButton->setEnabled(false); - replayFastForwardButton->setEnabled(false); - - timelineWidget->stopReplay(); + replayStartButton->setEnabled(true); + replayPauseButton->setEnabled(false); + replayFastForwardButton->setEnabled(false); + + timelineWidget->stopReplay(); } void TabGame::replayStopButtonClicked() { - replayStartButton->setEnabled(true); - replayPauseButton->setEnabled(false); - replayStopButton->setEnabled(false); - replayFastForwardButton->setEnabled(false); - - timelineWidget->stopReplay(); - // XXX to start + replayStartButton->setEnabled(true); + replayPauseButton->setEnabled(false); + replayStopButton->setEnabled(false); + replayFastForwardButton->setEnabled(false); + + timelineWidget->stopReplay(); + // XXX to start } void TabGame::replayFastForwardButtonToggled(bool checked) { - timelineWidget->setTimeScaleFactor(checked ? 10.0 : 1.0); + timelineWidget->setTimeScaleFactor(checked ? 10.0 : 1.0); } void TabGame::replayToEndButtonClicked() { - // XXX + // XXX } void TabGame::incrementGameTime() { - int seconds = ++secondsElapsed; - int minutes = seconds / 60; - seconds -= minutes * 60; - int hours = minutes / 60; - minutes -= hours * 60; - - timeElapsedLabel->setText(QString::number(hours).rightJustified(2, '0') + ":" + QString::number(minutes).rightJustified(2, '0') + ":" + QString::number(seconds).rightJustified(2, '0')); + int seconds = ++secondsElapsed; + int minutes = seconds / 60; + seconds -= minutes * 60; + int hours = minutes / 60; + minutes -= hours * 60; + + timeElapsedLabel->setText(QString::number(hours).rightJustified(2, '0') + ":" + QString::number(minutes).rightJustified(2, '0') + ":" + QString::number(seconds).rightJustified(2, '0')); } void TabGame::adminLockChanged(bool lock) { - bool v = !(spectator && !gameInfo.spectators_can_chat() && lock); - sayLabel->setVisible(v); - sayEdit->setVisible(v); + bool v = !(spectator && !gameInfo.spectators_can_chat() && lock); + sayLabel->setVisible(v); + sayEdit->setVisible(v); } void TabGame::actGameInfo() { - DlgCreateGame dlg(gameInfo, roomGameTypes); - dlg.exec(); + DlgCreateGame dlg(gameInfo, roomGameTypes); + dlg.exec(); } void TabGame::actConcede() { - if (QMessageBox::question(this, tr("Concede"), tr("Are you sure you want to concede this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) - return; + if (QMessageBox::question(this, tr("Concede"), tr("Are you sure you want to concede this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) + return; - sendGameCommand(Command_Concede()); + sendGameCommand(Command_Concede()); } void TabGame::actLeaveGame() { - if (!gameClosed) { - if (!spectator) - if (QMessageBox::question(this, tr("Leave game"), tr("Are you sure you want to leave this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) - return; - - if (!replay) - sendGameCommand(Command_LeaveGame()); - } - deleteLater(); + if (!gameClosed) { + if (!spectator) + if (QMessageBox::question(this, tr("Leave game"), tr("Are you sure you want to leave this game?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) + return; + + if (!replay) + sendGameCommand(Command_LeaveGame()); + } + deleteLater(); } void TabGame::actSay() { - if (!sayEdit->text().isEmpty()) { - Command_GameSay cmd; - cmd.set_message(sayEdit->text().toStdString()); - sendGameCommand(cmd); - sayEdit->clear(); - } + if (!sayEdit->text().isEmpty()) { + Command_GameSay cmd; + cmd.set_message(sayEdit->text().toStdString()); + sendGameCommand(cmd); + sayEdit->clear(); + } } void TabGame::actPhaseAction() { - int phase = phaseActions.indexOf(static_cast(sender())); - Command_SetActivePhase cmd; - cmd.set_phase(phase); - sendGameCommand(cmd); + int phase = phaseActions.indexOf(static_cast(sender())); + Command_SetActivePhase cmd; + cmd.set_phase(phase); + sendGameCommand(cmd); } void TabGame::actNextPhase() { - int phase = currentPhase; - if (++phase >= phasesToolbar->phaseCount()) - phase = 0; - Command_SetActivePhase cmd; - cmd.set_phase(phase); - sendGameCommand(cmd); + int phase = currentPhase; + if (++phase >= phasesToolbar->phaseCount()) + phase = 0; + Command_SetActivePhase cmd; + cmd.set_phase(phase); + sendGameCommand(cmd); } void TabGame::actNextTurn() { - sendGameCommand(Command_NextTurn()); + sendGameCommand(Command_NextTurn()); } void TabGame::actRemoveLocalArrows() { - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) { - Player *player = playerIterator.next().value(); - if (!player->getLocal()) - continue; - QMapIterator arrowIterator(player->getArrows()); - while (arrowIterator.hasNext()) { - ArrowItem *a = arrowIterator.next().value(); - Command_DeleteArrow cmd; - cmd.set_arrow_id(a->getId()); - sendGameCommand(cmd); - } - } + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) { + Player *player = playerIterator.next().value(); + if (!player->getLocal()) + continue; + QMapIterator arrowIterator(player->getArrows()); + while (arrowIterator.hasNext()) { + ArrowItem *a = arrowIterator.next().value(); + Command_DeleteArrow cmd; + cmd.set_arrow_id(a->getId()); + sendGameCommand(cmd); + } + } } Player *TabGame::addPlayer(int playerId, const ServerInfo_User &info) { - bool local = ((clients.size() > 1) || (playerId == localPlayerId)); - Player *newPlayer = new Player(info, playerId, local, this); - connect(newPlayer, SIGNAL(openDeckEditor(const DeckLoader *)), this, SIGNAL(openDeckEditor(const DeckLoader *))); - scene->addPlayer(newPlayer); + bool local = ((clients.size() > 1) || (playerId == localPlayerId)); + Player *newPlayer = new Player(info, playerId, local, this); + connect(newPlayer, SIGNAL(openDeckEditor(const DeckLoader *)), this, SIGNAL(openDeckEditor(const DeckLoader *))); + scene->addPlayer(newPlayer); - connect(newPlayer, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); - messageLog->connectToPlayer(newPlayer); - - if (local && !spectator) { - if (clients.size() == 1) - newPlayer->setShortcutsActive(); - - DeckViewContainer *deckView = new DeckViewContainer(playerId, this); - connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); - deckViewContainers.insert(playerId, deckView); - deckViewContainerLayout->addWidget(deckView); - } + connect(newPlayer, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); + messageLog->connectToPlayer(newPlayer); + + if (local && !spectator) { + if (clients.size() == 1) + newPlayer->setShortcutsActive(); + + DeckViewContainer *deckView = new DeckViewContainer(playerId, this); + connect(deckView, SIGNAL(newCardAdded(AbstractCardItem *)), this, SLOT(newCardAdded(AbstractCardItem *))); + deckViewContainers.insert(playerId, deckView); + deckViewContainerLayout->addWidget(deckView); + } - gameMenu->insertMenu(playersSeparator, newPlayer->getPlayerMenu()); - - players.insert(playerId, newPlayer); - emit playerAdded(newPlayer); + gameMenu->insertMenu(playersSeparator, newPlayer->getPlayerMenu()); + + players.insert(playerId, newPlayer); + emit playerAdded(newPlayer); - return newPlayer; + return newPlayer; } void TabGame::processGameEventContainer(const GameEventContainer &cont, AbstractClient *client) { - const GameEventContext &context = cont.context(); - messageLog->containerProcessingStarted(context); - const int eventListSize = cont.event_list_size(); - for (int i = 0; i < eventListSize; ++i) { - const GameEvent &event = cont.event_list(i); - const int playerId = event.player_id(); - const GameEvent::GameEventType eventType = static_cast(getPbExtension(event)); - if (spectators.contains(playerId)) { - switch (eventType) { - case GameEvent::GAME_SAY: eventSpectatorSay(event.GetExtension(Event_GameSay::ext), playerId, context); break; - case GameEvent::LEAVE: eventSpectatorLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; - default: { - qDebug() << "unhandled spectator game event"; - break; - } - } - } else { - if ((clients.size() > 1) && (playerId != -1)) - if (clients.at(playerId) != client) - continue; - - switch (eventType) { - case GameEvent::GAME_STATE_CHANGED: eventGameStateChanged(event.GetExtension(Event_GameStateChanged::ext), playerId, context); break; - case GameEvent::PLAYER_PROPERTIES_CHANGED: eventPlayerPropertiesChanged(event.GetExtension(Event_PlayerPropertiesChanged::ext), playerId, context); break; - case GameEvent::JOIN: eventJoin(event.GetExtension(Event_Join::ext), playerId, context); break; - case GameEvent::LEAVE: eventLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; - case GameEvent::KICKED: eventKicked(event.GetExtension(Event_Kicked::ext), playerId, context); break; - case GameEvent::GAME_HOST_CHANGED: eventGameHostChanged(event.GetExtension(Event_GameHostChanged::ext), playerId, context); break; - case GameEvent::GAME_CLOSED: eventGameClosed(event.GetExtension(Event_GameClosed::ext), playerId, context); break; - case GameEvent::SET_ACTIVE_PLAYER: eventSetActivePlayer(event.GetExtension(Event_SetActivePlayer::ext), playerId, context); break; - case GameEvent::SET_ACTIVE_PHASE: eventSetActivePhase(event.GetExtension(Event_SetActivePhase::ext), playerId, context); break; - - default: { - Player *player = players.value(playerId, 0); - if (!player) { - qDebug() << "unhandled game event: invalid player id"; - break; - } - player->processGameEvent(eventType, event, context); - emit userEvent(); - } - } - } - } - messageLog->containerProcessingDone(); + const GameEventContext &context = cont.context(); + messageLog->containerProcessingStarted(context); + const int eventListSize = cont.event_list_size(); + for (int i = 0; i < eventListSize; ++i) { + const GameEvent &event = cont.event_list(i); + const int playerId = event.player_id(); + const GameEvent::GameEventType eventType = static_cast(getPbExtension(event)); + if (spectators.contains(playerId)) { + switch (eventType) { + case GameEvent::GAME_SAY: eventSpectatorSay(event.GetExtension(Event_GameSay::ext), playerId, context); break; + case GameEvent::LEAVE: eventSpectatorLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; + default: { + qDebug() << "unhandled spectator game event"; + break; + } + } + } else { + if ((clients.size() > 1) && (playerId != -1)) + if (clients.at(playerId) != client) + continue; + + switch (eventType) { + case GameEvent::GAME_STATE_CHANGED: eventGameStateChanged(event.GetExtension(Event_GameStateChanged::ext), playerId, context); break; + case GameEvent::PLAYER_PROPERTIES_CHANGED: eventPlayerPropertiesChanged(event.GetExtension(Event_PlayerPropertiesChanged::ext), playerId, context); break; + case GameEvent::JOIN: eventJoin(event.GetExtension(Event_Join::ext), playerId, context); break; + case GameEvent::LEAVE: eventLeave(event.GetExtension(Event_Leave::ext), playerId, context); break; + case GameEvent::KICKED: eventKicked(event.GetExtension(Event_Kicked::ext), playerId, context); break; + case GameEvent::GAME_HOST_CHANGED: eventGameHostChanged(event.GetExtension(Event_GameHostChanged::ext), playerId, context); break; + case GameEvent::GAME_CLOSED: eventGameClosed(event.GetExtension(Event_GameClosed::ext), playerId, context); break; + case GameEvent::SET_ACTIVE_PLAYER: eventSetActivePlayer(event.GetExtension(Event_SetActivePlayer::ext), playerId, context); break; + case GameEvent::SET_ACTIVE_PHASE: eventSetActivePhase(event.GetExtension(Event_SetActivePhase::ext), playerId, context); break; + + default: { + Player *player = players.value(playerId, 0); + if (!player) { + qDebug() << "unhandled game event: invalid player id"; + break; + } + player->processGameEvent(eventType, event, context); + emit userEvent(); + } + } + } + } + messageLog->containerProcessingDone(); } AbstractClient *TabGame::getClientForPlayer(int playerId) const { - if (clients.size() > 1) { - if (playerId == -1) - playerId = getActiveLocalPlayer()->getId(); + if (clients.size() > 1) { + if (playerId == -1) + playerId = getActiveLocalPlayer()->getId(); - return clients.at(playerId); - } else if (clients.isEmpty()) - return 0; - else - return clients.first(); + return clients.at(playerId); + } else if (clients.isEmpty()) + return 0; + else + return clients.first(); } void TabGame::sendGameCommand(PendingCommand *pend, int playerId) { - AbstractClient *client = getClientForPlayer(playerId); - if (!client) - return; - client->sendCommand(pend); + AbstractClient *client = getClientForPlayer(playerId); + if (!client) + return; + client->sendCommand(pend); } void TabGame::sendGameCommand(const google::protobuf::Message &command, int playerId) { - AbstractClient *client = getClientForPlayer(playerId); - if (!client) - return; - client->sendCommand(prepareGameCommand(command)); + AbstractClient *client = getClientForPlayer(playerId); + if (!client) + return; + client->sendCommand(prepareGameCommand(command)); } PendingCommand *TabGame::prepareGameCommand(const ::google::protobuf::Message &cmd) { - CommandContainer cont; - cont.set_game_id(gameInfo.game_id()); - GameCommand *c = cont.add_game_command(); - c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); - return new PendingCommand(cont); + CommandContainer cont; + cont.set_game_id(gameInfo.game_id()); + GameCommand *c = cont.add_game_command(); + c->GetReflection()->MutableMessage(c, cmd.GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(cmd); + return new PendingCommand(cont); } PendingCommand *TabGame::prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList) { - CommandContainer cont; - cont.set_game_id(gameInfo.game_id()); - for (int i = 0; i < cmdList.size(); ++i) { - GameCommand *c = cont.add_game_command(); - c->GetReflection()->MutableMessage(c, cmdList[i]->GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(*cmdList[i]); - delete cmdList[i]; - } - return new PendingCommand(cont); + CommandContainer cont; + cont.set_game_id(gameInfo.game_id()); + for (int i = 0; i < cmdList.size(); ++i) { + GameCommand *c = cont.add_game_command(); + c->GetReflection()->MutableMessage(c, cmdList[i]->GetDescriptor()->FindExtensionByName("ext"))->CopyFrom(*cmdList[i]); + delete cmdList[i]; + } + return new PendingCommand(cont); } void TabGame::startGame(bool resuming) { - currentPhase = -1; + currentPhase = -1; - QMapIterator i(deckViewContainers); - while (i.hasNext()) { - i.next(); - i.value()->setReadyStart(false); - i.value()->hide(); - } - mainLayout->removeItem(deckViewContainerLayout); - - if (!resuming) { - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) - playerIterator.next().value()->setConceded(false); - } + QMapIterator i(deckViewContainers); + while (i.hasNext()) { + i.next(); + i.value()->setReadyStart(false); + i.value()->hide(); + } + mainLayout->removeItem(deckViewContainerLayout); + + if (!resuming) { + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) + playerIterator.next().value()->setConceded(false); + } - playerListWidget->setGameStarted(true, resuming); - gameInfo.set_started(true); - static_cast(gameView->scene())->rearrange(); - gameView->show(); + playerListWidget->setGameStarted(true, resuming); + gameInfo.set_started(true); + static_cast(gameView->scene())->rearrange(); + gameView->show(); } void TabGame::stopGame() { - currentPhase = -1; - activePlayer = -1; - - QMapIterator i(deckViewContainers); - while (i.hasNext()) { - i.next(); - i.value()->show(); - } - mainLayout->insertLayout(1, deckViewContainerLayout, 10); + currentPhase = -1; + activePlayer = -1; + + QMapIterator i(deckViewContainers); + while (i.hasNext()) { + i.next(); + i.value()->show(); + } + mainLayout->insertLayout(1, deckViewContainerLayout, 10); - playerListWidget->setActivePlayer(-1); - playerListWidget->setGameStarted(false, false); - gameInfo.set_started(false); - gameView->hide(); + playerListWidget->setActivePlayer(-1); + playerListWidget->setGameStarted(false, false); + gameInfo.set_started(false); + gameView->hide(); } void TabGame::closeGame() { - gameInfo.set_started(false); - gameClosed = true; - - gameMenu->clear(); - gameMenu->addAction(aLeaveGame); + gameInfo.set_started(false); + gameClosed = true; + + gameMenu->clear(); + gameMenu->addAction(aLeaveGame); } void TabGame::eventSpectatorSay(const Event_GameSay &event, int eventPlayerId, const GameEventContext & /*context*/) { - const ServerInfo_User &userInfo = spectators.value(eventPlayerId); - messageLog->logSpectatorSay(QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level()), QString::fromStdString(event.message())); + const ServerInfo_User &userInfo = spectators.value(eventPlayerId); + messageLog->logSpectatorSay(QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level()), QString::fromStdString(event.message())); } void TabGame::eventSpectatorLeave(const Event_Leave & /*event*/, int eventPlayerId, const GameEventContext & /*context*/) { - messageLog->logLeaveSpectator(QString::fromStdString(spectators.value(eventPlayerId).name())); - playerListWidget->removePlayer(eventPlayerId); - spectators.remove(eventPlayerId); - - emit userEvent(); + messageLog->logLeaveSpectator(QString::fromStdString(spectators.value(eventPlayerId).name())); + playerListWidget->removePlayer(eventPlayerId); + spectators.remove(eventPlayerId); + + emit userEvent(); } void TabGame::eventGameStateChanged(const Event_GameStateChanged &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - const int playerListSize = event.player_list_size(); - for (int i = 0; i < playerListSize; ++i) { - const ServerInfo_Player &playerInfo = event.player_list(i); - const ServerInfo_PlayerProperties &prop = playerInfo.properties(); - const int playerId = prop.player_id(); - if (prop.spectator()) { - if (!spectators.contains(playerId)) { - spectators.insert(playerId, prop.user_info()); - playerListWidget->addPlayer(prop); - } - } else { - Player *player = players.value(playerId, 0); - if (!player) { - player = addPlayer(playerId, prop.user_info()); - playerListWidget->addPlayer(prop); - } - player->processPlayerInfo(playerInfo); - if (player->getLocal()) { - DeckViewContainer *deckViewContainer = deckViewContainers.value(playerId); - if (playerInfo.has_deck_list()) { - DeckLoader newDeck(QString::fromStdString(playerInfo.deck_list())); - db->cacheCardPixmaps(newDeck.getCardList()); - deckViewContainer->setDeck(newDeck); - player->setDeck(newDeck); - } - deckViewContainer->setReadyStart(prop.ready_start()); - deckViewContainer->setSideboardLocked(prop.sideboard_locked()); - } - } - } - for (int i = 0; i < playerListSize; ++i) { - const ServerInfo_Player &playerInfo = event.player_list(i); - const ServerInfo_PlayerProperties &prop = playerInfo.properties(); - if (!prop.spectator()) { - Player *player = players.value(prop.player_id(), 0); - if (!player) - continue; - player->processCardAttachment(playerInfo); - } - } - - secondsElapsed = event.seconds_elapsed(); - - if (event.game_started() && !gameInfo.started()) { - startGame(!gameStateKnown); - if (gameStateKnown) - messageLog->logGameStart(); - setActivePlayer(event.active_player_id()); - setActivePhase(event.active_phase()); - } else if (!event.game_started() && gameInfo.started()) { - stopGame(); - scene->clearViews(); - } - gameStateKnown = true; - emit userEvent(); + const int playerListSize = event.player_list_size(); + for (int i = 0; i < playerListSize; ++i) { + const ServerInfo_Player &playerInfo = event.player_list(i); + const ServerInfo_PlayerProperties &prop = playerInfo.properties(); + const int playerId = prop.player_id(); + if (prop.spectator()) { + if (!spectators.contains(playerId)) { + spectators.insert(playerId, prop.user_info()); + playerListWidget->addPlayer(prop); + } + } else { + Player *player = players.value(playerId, 0); + if (!player) { + player = addPlayer(playerId, prop.user_info()); + playerListWidget->addPlayer(prop); + } + player->processPlayerInfo(playerInfo); + if (player->getLocal()) { + DeckViewContainer *deckViewContainer = deckViewContainers.value(playerId); + if (playerInfo.has_deck_list()) { + DeckLoader newDeck(QString::fromStdString(playerInfo.deck_list())); + db->cacheCardPixmaps(newDeck.getCardList()); + deckViewContainer->setDeck(newDeck); + player->setDeck(newDeck); + } + deckViewContainer->setReadyStart(prop.ready_start()); + deckViewContainer->setSideboardLocked(prop.sideboard_locked()); + } + } + } + for (int i = 0; i < playerListSize; ++i) { + const ServerInfo_Player &playerInfo = event.player_list(i); + const ServerInfo_PlayerProperties &prop = playerInfo.properties(); + if (!prop.spectator()) { + Player *player = players.value(prop.player_id(), 0); + if (!player) + continue; + player->processCardAttachment(playerInfo); + } + } + + secondsElapsed = event.seconds_elapsed(); + + if (event.game_started() && !gameInfo.started()) { + startGame(!gameStateKnown); + if (gameStateKnown) + messageLog->logGameStart(); + setActivePlayer(event.active_player_id()); + setActivePhase(event.active_phase()); + } else if (!event.game_started() && gameInfo.started()) { + stopGame(); + scene->clearViews(); + } + gameStateKnown = true; + emit userEvent(); } void TabGame::eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, int eventPlayerId, const GameEventContext &context) { - Player *player = players.value(eventPlayerId, 0); - if (!player) - return; - const ServerInfo_PlayerProperties &prop = event.player_properties(); - playerListWidget->updatePlayerProperties(prop, eventPlayerId); - - const GameEventContext::ContextType contextType = static_cast(getPbExtension(context)); - switch (contextType) { - case GameEventContext::READY_START: { - bool ready = prop.ready_start(); - if (player->getLocal()) - deckViewContainers.value(player->getId())->setReadyStart(ready); - if (ready) - messageLog->logReadyStart(player); - else - messageLog->logNotReadyStart(player); - break; - } - case GameEventContext::CONCEDE: { - messageLog->logConcede(player); - player->setConceded(true); - - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) - playerIterator.next().value()->updateZones(); - - break; - } - case GameEventContext::DECK_SELECT: { - messageLog->logDeckSelect(player, QString::fromStdString(context.GetExtension(Context_DeckSelect::ext).deck_hash())); - break; - } - case GameEventContext::SET_SIDEBOARD_LOCK: { - if (player->getLocal()) - deckViewContainers.value(player->getId())->setSideboardLocked(prop.sideboard_locked()); - messageLog->logSetSideboardLock(player, prop.sideboard_locked()); - break; - } - case GameEventContext::CONNECTION_STATE_CHANGED: { - messageLog->logConnectionStateChanged(player, prop.ping_seconds() != -1); - break; - } - default: ; - } + Player *player = players.value(eventPlayerId, 0); + if (!player) + return; + const ServerInfo_PlayerProperties &prop = event.player_properties(); + playerListWidget->updatePlayerProperties(prop, eventPlayerId); + + const GameEventContext::ContextType contextType = static_cast(getPbExtension(context)); + switch (contextType) { + case GameEventContext::READY_START: { + bool ready = prop.ready_start(); + if (player->getLocal()) + deckViewContainers.value(player->getId())->setReadyStart(ready); + if (ready) + messageLog->logReadyStart(player); + else + messageLog->logNotReadyStart(player); + break; + } + case GameEventContext::CONCEDE: { + messageLog->logConcede(player); + player->setConceded(true); + + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) + playerIterator.next().value()->updateZones(); + + break; + } + case GameEventContext::DECK_SELECT: { + messageLog->logDeckSelect(player, QString::fromStdString(context.GetExtension(Context_DeckSelect::ext).deck_hash())); + break; + } + case GameEventContext::SET_SIDEBOARD_LOCK: { + if (player->getLocal()) + deckViewContainers.value(player->getId())->setSideboardLocked(prop.sideboard_locked()); + messageLog->logSetSideboardLock(player, prop.sideboard_locked()); + break; + } + case GameEventContext::CONNECTION_STATE_CHANGED: { + messageLog->logConnectionStateChanged(player, prop.ping_seconds() != -1); + break; + } + default: ; + } } void TabGame::eventJoin(const Event_Join &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - const ServerInfo_PlayerProperties &playerInfo = event.player_properties(); - const int playerId = playerInfo.player_id(); - if (players.contains(playerId)) - return; - if (playerInfo.spectator()) { - spectators.insert(playerId, playerInfo.user_info()); - messageLog->logJoinSpectator(QString::fromStdString(playerInfo.user_info().name())); - } else { - Player *newPlayer = addPlayer(playerId, playerInfo.user_info()); - messageLog->logJoin(newPlayer); - } - playerListWidget->addPlayer(playerInfo); - emit userEvent(); + const ServerInfo_PlayerProperties &playerInfo = event.player_properties(); + const int playerId = playerInfo.player_id(); + if (players.contains(playerId)) + return; + if (playerInfo.spectator()) { + spectators.insert(playerId, playerInfo.user_info()); + messageLog->logJoinSpectator(QString::fromStdString(playerInfo.user_info().name())); + } else { + Player *newPlayer = addPlayer(playerId, playerInfo.user_info()); + messageLog->logJoin(newPlayer); + } + playerListWidget->addPlayer(playerInfo); + emit userEvent(); } void TabGame::eventLeave(const Event_Leave & /*event*/, int eventPlayerId, const GameEventContext & /*context*/) { - Player *player = players.value(eventPlayerId, 0); - if (!player) - return; - - messageLog->logLeave(player); - playerListWidget->removePlayer(eventPlayerId); - players.remove(eventPlayerId); - emit playerRemoved(player); - player->clear(); - player->deleteLater(); - - // Rearrange all remaining zones so that attachment relationship updates take place - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) - playerIterator.next().value()->updateZones(); - - emit userEvent(); + Player *player = players.value(eventPlayerId, 0); + if (!player) + return; + + messageLog->logLeave(player); + playerListWidget->removePlayer(eventPlayerId); + players.remove(eventPlayerId); + emit playerRemoved(player); + player->clear(); + player->deleteLater(); + + // Rearrange all remaining zones so that attachment relationship updates take place + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) + playerIterator.next().value()->updateZones(); + + emit userEvent(); } void TabGame::eventKicked(const Event_Kicked & /*event*/, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - closeGame(); - messageLog->logKicked(); - emit userEvent(); + closeGame(); + messageLog->logKicked(); + emit userEvent(); } void TabGame::eventGameHostChanged(const Event_GameHostChanged & /*event*/, int eventPlayerId, const GameEventContext & /*context*/) { - hostId = eventPlayerId; + hostId = eventPlayerId; } void TabGame::eventGameClosed(const Event_GameClosed & /*event*/, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - closeGame(); - messageLog->logGameClosed(); - emit userEvent(); + closeGame(); + messageLog->logGameClosed(); + emit userEvent(); } Player *TabGame::setActivePlayer(int id) { - Player *player = players.value(id, 0); - if (!player) - return 0; - activePlayer = id; - playerListWidget->setActivePlayer(id); - QMapIterator i(players); - while (i.hasNext()) { - i.next(); - if (i.value() == player) { - i.value()->setActive(true); - if (clients.size() > 1) - i.value()->setShortcutsActive(); - } else { - i.value()->setActive(false); - if (clients.size() > 1) - i.value()->setShortcutsInactive(); - } - } - currentPhase = -1; - emit userEvent(); - return player; + Player *player = players.value(id, 0); + if (!player) + return 0; + activePlayer = id; + playerListWidget->setActivePlayer(id); + QMapIterator i(players); + while (i.hasNext()) { + i.next(); + if (i.value() == player) { + i.value()->setActive(true); + if (clients.size() > 1) + i.value()->setShortcutsActive(); + } else { + i.value()->setActive(false); + if (clients.size() > 1) + i.value()->setShortcutsInactive(); + } + } + currentPhase = -1; + emit userEvent(); + return player; } void TabGame::eventSetActivePlayer(const Event_SetActivePlayer &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - Player *player = setActivePlayer(event.active_player_id()); - if (!player) - return; - messageLog->logSetActivePlayer(player); - emit userEvent(); + Player *player = setActivePlayer(event.active_player_id()); + if (!player) + return; + messageLog->logSetActivePlayer(player); + emit userEvent(); } void TabGame::setActivePhase(int phase) { - if (currentPhase != phase) { - currentPhase = phase; - phasesToolbar->setActivePhase(phase); - } + if (currentPhase != phase) { + currentPhase = phase; + phasesToolbar->setActivePhase(phase); + } } void TabGame::eventSetActivePhase(const Event_SetActivePhase &event, int /*eventPlayerId*/, const GameEventContext & /*context*/) { - const int phase = event.phase(); - if (currentPhase != phase) - messageLog->logSetActivePhase(phase); - setActivePhase(phase); - emit userEvent(); + const int phase = event.phase(); + if (currentPhase != phase) + messageLog->logSetActivePhase(phase); + setActivePhase(phase); + emit userEvent(); } void TabGame::newCardAdded(AbstractCardItem *card) { - connect(card, SIGNAL(hovered(AbstractCardItem *)), cardInfo, SLOT(setCard(AbstractCardItem *))); - connect(card, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(card, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - connect(card, SIGNAL(updateCardMenu(AbstractCardItem *)), this, SLOT(updateCardMenu(AbstractCardItem *))); + connect(card, SIGNAL(hovered(AbstractCardItem *)), cardInfo, SLOT(setCard(AbstractCardItem *))); + connect(card, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(card, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + connect(card, SIGNAL(updateCardMenu(AbstractCardItem *)), this, SLOT(updateCardMenu(AbstractCardItem *))); } CardItem *TabGame::getCard(int playerId, const QString &zoneName, int cardId) const { - Player *player = players.value(playerId, 0); - if (!player) - return 0; - - CardZone *zone = player->getZones().value(zoneName, 0); - if (!zone) - return 0; - - return zone->getCard(cardId, QString()); + Player *player = players.value(playerId, 0); + if (!player) + return 0; + + CardZone *zone = player->getZones().value(zoneName, 0); + if (!zone) + return 0; + + return zone->getCard(cardId, QString()); } QString TabGame::getTabText() const { - if (replay) - return tr("Replay %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); - else - return tr("Game %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); + if (replay) + return tr("Replay %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); + else + return tr("Game %1: %2").arg(gameInfo.game_id()).arg(QString::fromStdString(gameInfo.description())); } Player *TabGame::getActiveLocalPlayer() const { - Player *active = players.value(activePlayer, 0); - if (active) - if (active->getLocal()) - return active; - - QMapIterator playerIterator(players); - while (playerIterator.hasNext()) { - Player *temp = playerIterator.next().value(); - if (temp->getLocal()) - return temp; - } - - return 0; + Player *active = players.value(activePlayer, 0); + if (active) + if (active->getLocal()) + return active; + + QMapIterator playerIterator(players); + while (playerIterator.hasNext()) { + Player *temp = playerIterator.next().value(); + if (temp->getLocal()) + return temp; + } + + return 0; } void TabGame::updateCardMenu(AbstractCardItem *card) { - Player *p; - if ((clients.size() > 1) || !players.contains(localPlayerId)) - p = card->getOwner(); - else - p = players.value(localPlayerId); - p->updateCardMenu(static_cast(card)); + Player *p; + if ((clients.size() > 1) || !players.contains(localPlayerId)) + p = card->getOwner(); + else + p = players.value(localPlayerId); + p->updateCardMenu(static_cast(card)); } diff --git a/cockatrice/src/tab_game.h b/cockatrice/src/tab_game.h index f511ef69..50f77e1a 100644 --- a/cockatrice/src/tab_game.h +++ b/cockatrice/src/tab_game.h @@ -56,170 +56,170 @@ class ServerInfo_User; class PendingCommand; class ToggleButton : public QPushButton { - Q_OBJECT + Q_OBJECT private: - bool state; + bool state; signals: - void stateChanged(); + void stateChanged(); public: - ToggleButton(QWidget *parent = 0); - bool getState() const { return state; } - void setState(bool _state); + ToggleButton(QWidget *parent = 0); + bool getState() const { return state; } + void setState(bool _state); protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent *event); }; class DeckViewContainer : public QWidget { - Q_OBJECT + Q_OBJECT private: - QPushButton *loadLocalButton, *loadRemoteButton; - ToggleButton *readyStartButton, *sideboardLockButton; - DeckView *deckView; - int playerId; + QPushButton *loadLocalButton, *loadRemoteButton; + ToggleButton *readyStartButton, *sideboardLockButton; + DeckView *deckView; + int playerId; private slots: - void loadLocalDeck(); - void loadRemoteDeck(); - void readyStart(); - void deckSelectFinished(const Response &r); - void sideboardPlanChanged(); - void sideboardLockButtonClicked(); - void updateSideboardLockButtonText(); + void loadLocalDeck(); + void loadRemoteDeck(); + void readyStart(); + void deckSelectFinished(const Response &r); + void sideboardPlanChanged(); + void sideboardLockButtonClicked(); + void updateSideboardLockButtonText(); signals: - void newCardAdded(AbstractCardItem *card); + void newCardAdded(AbstractCardItem *card); public: - DeckViewContainer(int _playerId, TabGame *parent = 0); - void retranslateUi(); - void setButtonsVisible(bool _visible); - void setReadyStart(bool ready); - void setSideboardLocked(bool locked); - void setDeck(const DeckLoader &deck); + DeckViewContainer(int _playerId, TabGame *parent = 0); + void retranslateUi(); + void setButtonsVisible(bool _visible); + void setReadyStart(bool ready); + void setSideboardLocked(bool locked); + void setDeck(const DeckLoader &deck); }; class TabGame : public Tab { - Q_OBJECT + Q_OBJECT private: - QTimer *gameTimer; - int secondsElapsed; - QList clients; - ServerInfo_Game gameInfo; - QMap roomGameTypes; - int hostId; - int localPlayerId; - bool spectator; - QMap players; - QMap spectators; - bool gameStateKnown; - bool resuming; - QStringList phasesList; - int currentPhase; - int activePlayer; - CardItem *activeCard; - bool gameClosed; - - // Replay related members - GameReplay *replay; - int currentReplayStep; - QList replayTimeline; - ReplayTimelineWidget *timelineWidget; - QToolButton *replayToStartButton, *replayStartButton, *replayPauseButton, *replayStopButton, *replayFastForwardButton, *replayToEndButton; - - QSplitter *splitter; - CardInfoWidget *cardInfo; - PlayerListWidget *playerListWidget; - QLabel *timeElapsedLabel; - MessageLogWidget *messageLog; - QLabel *sayLabel; - QLineEdit *sayEdit; - PhasesToolbar *phasesToolbar; - GameScene *scene; - GameView *gameView; - QMap deckViewContainers; - QVBoxLayout *deckViewContainerLayout; - QHBoxLayout *mainLayout; - ZoneViewLayout *zoneLayout; - QAction *playersSeparator; - QMenu *gameMenu; - QMenu *phasesMenu; - QAction *aGameInfo, *aConcede, *aLeaveGame, *aCloseReplay, *aNextPhase, *aNextTurn, *aRemoveLocalArrows; - QList phaseActions; + QTimer *gameTimer; + int secondsElapsed; + QList clients; + ServerInfo_Game gameInfo; + QMap roomGameTypes; + int hostId; + int localPlayerId; + bool spectator; + QMap players; + QMap spectators; + bool gameStateKnown; + bool resuming; + QStringList phasesList; + int currentPhase; + int activePlayer; + CardItem *activeCard; + bool gameClosed; + + // Replay related members + GameReplay *replay; + int currentReplayStep; + QList replayTimeline; + ReplayTimelineWidget *timelineWidget; + QToolButton *replayToStartButton, *replayStartButton, *replayPauseButton, *replayStopButton, *replayFastForwardButton, *replayToEndButton; + + QSplitter *splitter; + CardInfoWidget *cardInfo; + PlayerListWidget *playerListWidget; + QLabel *timeElapsedLabel; + MessageLogWidget *messageLog; + QLabel *sayLabel; + QLineEdit *sayEdit; + PhasesToolbar *phasesToolbar; + GameScene *scene; + GameView *gameView; + QMap deckViewContainers; + QVBoxLayout *deckViewContainerLayout; + QHBoxLayout *mainLayout; + ZoneViewLayout *zoneLayout; + QAction *playersSeparator; + QMenu *gameMenu; + QMenu *phasesMenu; + QAction *aGameInfo, *aConcede, *aLeaveGame, *aCloseReplay, *aNextPhase, *aNextTurn, *aRemoveLocalArrows; + QList phaseActions; - Player *addPlayer(int playerId, const ServerInfo_User &info); + Player *addPlayer(int playerId, const ServerInfo_User &info); - void startGame(bool resuming); - void stopGame(); - void closeGame(); + void startGame(bool resuming); + void stopGame(); + void closeGame(); - void eventSpectatorSay(const Event_GameSay &event, int eventPlayerId, const GameEventContext &context); - void eventSpectatorLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); - - void eventGameStateChanged(const Event_GameStateChanged &event, int eventPlayerId, const GameEventContext &context); - void eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, int eventPlayerId, const GameEventContext &context); - void eventJoin(const Event_Join &event, int eventPlayerId, const GameEventContext &context); - void eventLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); - void eventKicked(const Event_Kicked &event, int eventPlayerId, const GameEventContext &context); - void eventGameHostChanged(const Event_GameHostChanged &event, int eventPlayerId, const GameEventContext &context); - void eventGameClosed(const Event_GameClosed &event, int eventPlayerId, const GameEventContext &context); - Player *setActivePlayer(int id); - void eventSetActivePlayer(const Event_SetActivePlayer &event, int eventPlayerId, const GameEventContext &context); - void setActivePhase(int phase); - void eventSetActivePhase(const Event_SetActivePhase &event, int eventPlayerId, const GameEventContext &context); - void eventPing(const Event_Ping &event, int eventPlayerId, const GameEventContext &context); + void eventSpectatorSay(const Event_GameSay &event, int eventPlayerId, const GameEventContext &context); + void eventSpectatorLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); + + void eventGameStateChanged(const Event_GameStateChanged &event, int eventPlayerId, const GameEventContext &context); + void eventPlayerPropertiesChanged(const Event_PlayerPropertiesChanged &event, int eventPlayerId, const GameEventContext &context); + void eventJoin(const Event_Join &event, int eventPlayerId, const GameEventContext &context); + void eventLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext &context); + void eventKicked(const Event_Kicked &event, int eventPlayerId, const GameEventContext &context); + void eventGameHostChanged(const Event_GameHostChanged &event, int eventPlayerId, const GameEventContext &context); + void eventGameClosed(const Event_GameClosed &event, int eventPlayerId, const GameEventContext &context); + Player *setActivePlayer(int id); + void eventSetActivePlayer(const Event_SetActivePlayer &event, int eventPlayerId, const GameEventContext &context); + void setActivePhase(int phase); + void eventSetActivePhase(const Event_SetActivePhase &event, int eventPlayerId, const GameEventContext &context); + void eventPing(const Event_Ping &event, int eventPlayerId, const GameEventContext &context); signals: - void gameClosing(TabGame *tab); - void playerAdded(Player *player); - void playerRemoved(Player *player); - void containerProcessingStarted(const GameEventContext &context); - void containerProcessingDone(); - void openMessageDialog(const QString &userName, bool focus); - void openDeckEditor(const DeckLoader *deck); + void gameClosing(TabGame *tab); + void playerAdded(Player *player); + void playerRemoved(Player *player); + void containerProcessingStarted(const GameEventContext &context); + void containerProcessingDone(); + void openMessageDialog(const QString &userName, bool focus); + void openDeckEditor(const DeckLoader *deck); private slots: - void replayNextEvent(); - void replayFinished(); - void replayToStartButtonClicked(); - void replayStartButtonClicked(); - void replayPauseButtonClicked(); - void replayStopButtonClicked(); - void replayFastForwardButtonToggled(bool checked); - void replayToEndButtonClicked(); - - void incrementGameTime(); - void adminLockChanged(bool lock); - void newCardAdded(AbstractCardItem *card); - void updateCardMenu(AbstractCardItem *card); - - void actGameInfo(); - void actConcede(); - void actLeaveGame(); - void actRemoveLocalArrows(); - void actSay(); - void actPhaseAction(); - void actNextPhase(); - void actNextTurn(); + void replayNextEvent(); + void replayFinished(); + void replayToStartButtonClicked(); + void replayStartButtonClicked(); + void replayPauseButtonClicked(); + void replayStopButtonClicked(); + void replayFastForwardButtonToggled(bool checked); + void replayToEndButtonClicked(); + + void incrementGameTime(); + void adminLockChanged(bool lock); + void newCardAdded(AbstractCardItem *card); + void updateCardMenu(AbstractCardItem *card); + + void actGameInfo(); + void actConcede(); + void actLeaveGame(); + void actRemoveLocalArrows(); + void actSay(); + void actPhaseAction(); + void actNextPhase(); + void actNextTurn(); public: - TabGame(TabSupervisor *_tabSupervisor, QList &_clients, const Event_GameJoined &event, const QMap &_roomGameTypes); - TabGame(TabSupervisor *_tabSupervisor, GameReplay *replay); - ~TabGame(); - void retranslateUi(); - void closeRequest(); - const QMap &getPlayers() const { return players; } - CardItem *getCard(int playerId, const QString &zoneName, int cardId) const; - bool isHost() const { return hostId == localPlayerId; } - int getGameId() const { return gameInfo.game_id(); } - QString getTabText() const; - bool getSpectator() const { return spectator; } - bool getSpectatorsSeeEverything() const { return gameInfo.spectators_omniscient(); } - Player *getActiveLocalPlayer() const; - AbstractClient *getClientForPlayer(int playerId) const; - - void setActiveCard(CardItem *_card) { activeCard = _card; } - CardItem *getActiveCard() const { return activeCard; } + TabGame(TabSupervisor *_tabSupervisor, QList &_clients, const Event_GameJoined &event, const QMap &_roomGameTypes); + TabGame(TabSupervisor *_tabSupervisor, GameReplay *replay); + ~TabGame(); + void retranslateUi(); + void closeRequest(); + const QMap &getPlayers() const { return players; } + CardItem *getCard(int playerId, const QString &zoneName, int cardId) const; + bool isHost() const { return hostId == localPlayerId; } + int getGameId() const { return gameInfo.game_id(); } + QString getTabText() const; + bool getSpectator() const { return spectator; } + bool getSpectatorsSeeEverything() const { return gameInfo.spectators_omniscient(); } + Player *getActiveLocalPlayer() const; + AbstractClient *getClientForPlayer(int playerId) const; + + void setActiveCard(CardItem *_card) { activeCard = _card; } + CardItem *getActiveCard() const { return activeCard; } - void processGameEventContainer(const GameEventContainer &cont, AbstractClient *client); - PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); - PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); + void processGameEventContainer(const GameEventContainer &cont, AbstractClient *client); + PendingCommand *prepareGameCommand(const ::google::protobuf::Message &cmd); + PendingCommand *prepareGameCommand(const QList< const ::google::protobuf::Message * > &cmdList); public slots: - void sendGameCommand(PendingCommand *pend, int playerId = -1); - void sendGameCommand(const ::google::protobuf::Message &command, int playerId = -1); + void sendGameCommand(PendingCommand *pend, int playerId = -1); + void sendGameCommand(const ::google::protobuf::Message &command, int playerId = -1); }; #endif diff --git a/cockatrice/src/tab_message.cpp b/cockatrice/src/tab_message.cpp index cfc5c050..80a56154 100644 --- a/cockatrice/src/tab_message.cpp +++ b/cockatrice/src/tab_message.cpp @@ -13,100 +13,100 @@ #include "pb/serverinfo_user.pb.h" TabMessage::TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &_ownUserInfo, const ServerInfo_User &_otherUserInfo) - : Tab(_tabSupervisor), client(_client), ownUserInfo(new ServerInfo_User(_ownUserInfo)), otherUserInfo(new ServerInfo_User(_otherUserInfo)), userOnline(true) + : Tab(_tabSupervisor), client(_client), ownUserInfo(new ServerInfo_User(_ownUserInfo)), otherUserInfo(new ServerInfo_User(_otherUserInfo)), userOnline(true) { - chatView = new ChatView(tabSupervisor, 0, true); - connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayEdit = new QLineEdit; - connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(chatView); - vbox->addWidget(sayEdit); - - aLeave = new QAction(this); - connect(aLeave, SIGNAL(triggered()), this, SLOT(actLeave())); + chatView = new ChatView(tabSupervisor, 0, true); + connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayEdit = new QLineEdit; + connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(chatView); + vbox->addWidget(sayEdit); + + aLeave = new QAction(this); + connect(aLeave, SIGNAL(triggered()), this, SLOT(actLeave())); - messageMenu = new QMenu(this); - messageMenu->addAction(aLeave); - addTabMenu(messageMenu); + messageMenu = new QMenu(this); + messageMenu->addAction(aLeave); + addTabMenu(messageMenu); - retranslateUi(); - setLayout(vbox); + retranslateUi(); + setLayout(vbox); } TabMessage::~TabMessage() { - emit talkClosing(this); - delete ownUserInfo; - delete otherUserInfo; + emit talkClosing(this); + delete ownUserInfo; + delete otherUserInfo; } void TabMessage::retranslateUi() { - messageMenu->setTitle(tr("Personal &talk")); - aLeave->setText(tr("&Leave")); + messageMenu->setTitle(tr("Personal &talk")); + aLeave->setText(tr("&Leave")); } QString TabMessage::getUserName() const { - return QString::fromStdString(otherUserInfo->name()); + return QString::fromStdString(otherUserInfo->name()); } QString TabMessage::getTabText() const { - return tr("Talking to %1").arg(QString::fromStdString(otherUserInfo->name())); + return tr("Talking to %1").arg(QString::fromStdString(otherUserInfo->name())); } void TabMessage::closeRequest() { - actLeave(); + actLeave(); } void TabMessage::sendMessage() { - if (sayEdit->text().isEmpty() || !userOnline) - return; - - Command_Message cmd; - cmd.set_user_name(otherUserInfo->name()); - cmd.set_message(sayEdit->text().toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(messageSent(const Response &))); - client->sendCommand(pend); - - sayEdit->clear(); + if (sayEdit->text().isEmpty() || !userOnline) + return; + + Command_Message cmd; + cmd.set_user_name(otherUserInfo->name()); + cmd.set_message(sayEdit->text().toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(messageSent(const Response &))); + client->sendCommand(pend); + + sayEdit->clear(); } void TabMessage::messageSent(const Response &response) { - if (response.response_code() == Response::RespInIgnoreList) - chatView->appendMessage(tr("This user is ignoring you.")); + if (response.response_code() == Response::RespInIgnoreList) + chatView->appendMessage(tr("This user is ignoring you.")); } void TabMessage::actLeave() { - deleteLater(); + deleteLater(); } void TabMessage::processUserMessageEvent(const Event_UserMessage &event) { - const UserLevelFlags userLevel(event.sender_name() == otherUserInfo->name() ? otherUserInfo->user_level() : ownUserInfo->user_level()); - chatView->appendMessage(QString::fromStdString(event.message()), QString::fromStdString(event.sender_name()), userLevel); - emit userEvent(); + const UserLevelFlags userLevel(event.sender_name() == otherUserInfo->name() ? otherUserInfo->user_level() : ownUserInfo->user_level()); + chatView->appendMessage(QString::fromStdString(event.message()), QString::fromStdString(event.sender_name()), userLevel); + emit userEvent(); } void TabMessage::processUserLeft() { - chatView->appendMessage(tr("%1 has left the server.").arg(QString::fromStdString(otherUserInfo->name()))); - userOnline = false; + chatView->appendMessage(tr("%1 has left the server.").arg(QString::fromStdString(otherUserInfo->name()))); + userOnline = false; } void TabMessage::processUserJoined(const ServerInfo_User &_userInfo) { - chatView->appendMessage(tr("%1 has joined the server.").arg(QString::fromStdString(otherUserInfo->name()))); - userOnline = true; - *otherUserInfo = _userInfo; + chatView->appendMessage(tr("%1 has joined the server.").arg(QString::fromStdString(otherUserInfo->name()))); + userOnline = true; + *otherUserInfo = _userInfo; } diff --git a/cockatrice/src/tab_message.h b/cockatrice/src/tab_message.h index 08307fff..b8f98959 100644 --- a/cockatrice/src/tab_message.h +++ b/cockatrice/src/tab_message.h @@ -11,35 +11,35 @@ class Response; class ServerInfo_User; class TabMessage : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - QMenu *messageMenu; - ServerInfo_User *ownUserInfo; - ServerInfo_User *otherUserInfo; - bool userOnline; - - ChatView *chatView; - QLineEdit *sayEdit; + AbstractClient *client; + QMenu *messageMenu; + ServerInfo_User *ownUserInfo; + ServerInfo_User *otherUserInfo; + bool userOnline; + + ChatView *chatView; + QLineEdit *sayEdit; - QAction *aLeave; + QAction *aLeave; signals: - void talkClosing(TabMessage *tab); + void talkClosing(TabMessage *tab); private slots: - void sendMessage(); - void actLeave(); - void messageSent(const Response &response); + void sendMessage(); + void actLeave(); + void messageSent(const Response &response); public: - TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &_ownUserInfo, const ServerInfo_User &_otherUserInfo); - ~TabMessage(); - void retranslateUi(); - void closeRequest(); - QString getUserName() const; - QString getTabText() const; + TabMessage(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &_ownUserInfo, const ServerInfo_User &_otherUserInfo); + ~TabMessage(); + void retranslateUi(); + void closeRequest(); + QString getUserName() const; + QString getTabText() const; - void processUserMessageEvent(const Event_UserMessage &event); - void processUserLeft(); - void processUserJoined(const ServerInfo_User &_userInfo); + void processUserMessageEvent(const Event_UserMessage &event); + void processUserLeft(); + void processUserJoined(const ServerInfo_User &_userInfo); }; #endif diff --git a/cockatrice/src/tab_replays.cpp b/cockatrice/src/tab_replays.cpp index 27fbce94..92b0be08 100644 --- a/cockatrice/src/tab_replays.cpp +++ b/cockatrice/src/tab_replays.cpp @@ -25,248 +25,248 @@ #include "pb/event_replay_added.pb.h" TabReplays::TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client) - : Tab(_tabSupervisor), client(_client) + : Tab(_tabSupervisor), client(_client) { - localDirModel = new QFileSystemModel(this); - localDirModel->setRootPath(settingsCache->getReplaysPath()); - localDirModel->sort(0, Qt::AscendingOrder); - - localDirView = new QTreeView; - localDirView->setModel(localDirModel); - localDirView->setColumnHidden(1, true); - localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); - localDirView->setSortingEnabled(true); - localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); - localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); - - leftToolBar = new QToolBar; - leftToolBar->setOrientation(Qt::Horizontal); - leftToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *leftToolBarLayout = new QHBoxLayout; - leftToolBarLayout->addStretch(); - leftToolBarLayout->addWidget(leftToolBar); - leftToolBarLayout->addStretch(); + localDirModel = new QFileSystemModel(this); + localDirModel->setRootPath(settingsCache->getReplaysPath()); + localDirModel->sort(0, Qt::AscendingOrder); + + localDirView = new QTreeView; + localDirView->setModel(localDirModel); + localDirView->setColumnHidden(1, true); + localDirView->setRootIndex(localDirModel->index(localDirModel->rootPath(), 0)); + localDirView->setSortingEnabled(true); + localDirView->header()->setResizeMode(QHeaderView::ResizeToContents); + localDirView->header()->setSortIndicator(0, Qt::AscendingOrder); + + leftToolBar = new QToolBar; + leftToolBar->setOrientation(Qt::Horizontal); + leftToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *leftToolBarLayout = new QHBoxLayout; + leftToolBarLayout->addStretch(); + leftToolBarLayout->addWidget(leftToolBar); + leftToolBarLayout->addStretch(); - QVBoxLayout *leftVbox = new QVBoxLayout; - leftVbox->addWidget(localDirView); - leftVbox->addLayout(leftToolBarLayout); - leftGroupBox = new QGroupBox; - leftGroupBox->setLayout(leftVbox); - - rightToolBar = new QToolBar; - rightToolBar->setOrientation(Qt::Horizontal); - rightToolBar->setIconSize(QSize(32, 32)); - QHBoxLayout *rightToolBarLayout = new QHBoxLayout; - rightToolBarLayout->addStretch(); - rightToolBarLayout->addWidget(rightToolBar); - rightToolBarLayout->addStretch(); + QVBoxLayout *leftVbox = new QVBoxLayout; + leftVbox->addWidget(localDirView); + leftVbox->addLayout(leftToolBarLayout); + leftGroupBox = new QGroupBox; + leftGroupBox->setLayout(leftVbox); + + rightToolBar = new QToolBar; + rightToolBar->setOrientation(Qt::Horizontal); + rightToolBar->setIconSize(QSize(32, 32)); + QHBoxLayout *rightToolBarLayout = new QHBoxLayout; + rightToolBarLayout->addStretch(); + rightToolBarLayout->addWidget(rightToolBar); + rightToolBarLayout->addStretch(); - serverDirView = new RemoteReplayList_TreeWidget(client); + serverDirView = new RemoteReplayList_TreeWidget(client); - QVBoxLayout *rightVbox = new QVBoxLayout; - rightVbox->addWidget(serverDirView); - rightVbox->addLayout(rightToolBarLayout); - rightGroupBox = new QGroupBox; - rightGroupBox->setLayout(rightVbox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addWidget(leftGroupBox); - hbox->addWidget(rightGroupBox); - - aOpenLocalReplay = new QAction(this); - aOpenLocalReplay->setIcon(QIcon(":/resources/icon_view.svg")); - connect(aOpenLocalReplay, SIGNAL(triggered()), this, SLOT(actOpenLocalReplay())); - aDeleteLocalReplay = new QAction(this); - aDeleteLocalReplay->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteLocalReplay, SIGNAL(triggered()), this, SLOT(actDeleteLocalReplay())); - aOpenRemoteReplay = new QAction(this); - aOpenRemoteReplay->setIcon(QIcon(":/resources/icon_view.svg")); - connect(aOpenRemoteReplay, SIGNAL(triggered()), this, SLOT(actOpenRemoteReplay())); - aDownload = new QAction(this); - aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); - connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); - aKeep = new QAction(this); - aKeep->setIcon(QIcon(":/resources/lock.svg")); - connect(aKeep, SIGNAL(triggered()), this, SLOT(actKeepRemoteReplay())); - aDeleteRemoteReplay = new QAction(this); - aDeleteRemoteReplay->setIcon(QIcon(":/resources/remove_row.svg")); - connect(aDeleteRemoteReplay, SIGNAL(triggered()), this, SLOT(actDeleteRemoteReplay())); - - leftToolBar->addAction(aOpenLocalReplay); - leftToolBar->addAction(aDeleteLocalReplay); - rightToolBar->addAction(aOpenRemoteReplay); - rightToolBar->addAction(aDownload); - rightToolBar->addAction(aKeep); - rightToolBar->addAction(aDeleteRemoteReplay); - - retranslateUi(); - setLayout(hbox); - - connect(client, SIGNAL(replayAddedEventReceived(const Event_ReplayAdded &)), this, SLOT(replayAddedEventReceived(const Event_ReplayAdded &))); + QVBoxLayout *rightVbox = new QVBoxLayout; + rightVbox->addWidget(serverDirView); + rightVbox->addLayout(rightToolBarLayout); + rightGroupBox = new QGroupBox; + rightGroupBox->setLayout(rightVbox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addWidget(leftGroupBox); + hbox->addWidget(rightGroupBox); + + aOpenLocalReplay = new QAction(this); + aOpenLocalReplay->setIcon(QIcon(":/resources/icon_view.svg")); + connect(aOpenLocalReplay, SIGNAL(triggered()), this, SLOT(actOpenLocalReplay())); + aDeleteLocalReplay = new QAction(this); + aDeleteLocalReplay->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteLocalReplay, SIGNAL(triggered()), this, SLOT(actDeleteLocalReplay())); + aOpenRemoteReplay = new QAction(this); + aOpenRemoteReplay->setIcon(QIcon(":/resources/icon_view.svg")); + connect(aOpenRemoteReplay, SIGNAL(triggered()), this, SLOT(actOpenRemoteReplay())); + aDownload = new QAction(this); + aDownload->setIcon(QIcon(":/resources/arrow_left_green.svg")); + connect(aDownload, SIGNAL(triggered()), this, SLOT(actDownload())); + aKeep = new QAction(this); + aKeep->setIcon(QIcon(":/resources/lock.svg")); + connect(aKeep, SIGNAL(triggered()), this, SLOT(actKeepRemoteReplay())); + aDeleteRemoteReplay = new QAction(this); + aDeleteRemoteReplay->setIcon(QIcon(":/resources/remove_row.svg")); + connect(aDeleteRemoteReplay, SIGNAL(triggered()), this, SLOT(actDeleteRemoteReplay())); + + leftToolBar->addAction(aOpenLocalReplay); + leftToolBar->addAction(aDeleteLocalReplay); + rightToolBar->addAction(aOpenRemoteReplay); + rightToolBar->addAction(aDownload); + rightToolBar->addAction(aKeep); + rightToolBar->addAction(aDeleteRemoteReplay); + + retranslateUi(); + setLayout(hbox); + + connect(client, SIGNAL(replayAddedEventReceived(const Event_ReplayAdded &)), this, SLOT(replayAddedEventReceived(const Event_ReplayAdded &))); } void TabReplays::retranslateUi() { - leftGroupBox->setTitle(tr("Local file system")); - rightGroupBox->setTitle(tr("Server replay storage")); - - aOpenLocalReplay->setText(tr("Watch replay")); - aDeleteLocalReplay->setText(tr("Delete")); - aOpenRemoteReplay->setText(tr("Watch replay")); - aDownload->setText(tr("Download replay")); - aKeep->setText(tr("Toggle expiration lock")); - aDeleteLocalReplay->setText(tr("Delete")); + leftGroupBox->setTitle(tr("Local file system")); + rightGroupBox->setTitle(tr("Server replay storage")); + + aOpenLocalReplay->setText(tr("Watch replay")); + aDeleteLocalReplay->setText(tr("Delete")); + aOpenRemoteReplay->setText(tr("Watch replay")); + aDownload->setText(tr("Download replay")); + aKeep->setText(tr("Toggle expiration lock")); + aDeleteLocalReplay->setText(tr("Delete")); } void TabReplays::actOpenLocalReplay() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (localDirModel->isDir(curLeft)) - return; - QString filePath = localDirModel->filePath(curLeft); - - QFile f(filePath); - if (!f.open(QIODevice::ReadOnly)) - return; - QByteArray data = f.readAll(); - f.close(); - - GameReplay *replay = new GameReplay; - replay->ParseFromArray(data.data(), data.size()); - - emit openReplay(replay); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (localDirModel->isDir(curLeft)) + return; + QString filePath = localDirModel->filePath(curLeft); + + QFile f(filePath); + if (!f.open(QIODevice::ReadOnly)) + return; + QByteArray data = f.readAll(); + f.close(); + + GameReplay *replay = new GameReplay; + replay->ParseFromArray(data.data(), data.size()); + + emit openReplay(replay); } void TabReplays::actDeleteLocalReplay() { - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - localDirModel->remove(curLeft); + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete \"%1\"?").arg(localDirModel->fileName(curLeft)), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + localDirModel->remove(curLeft); } void TabReplays::actOpenRemoteReplay() { - ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); - if (!curRight) - return; - - Command_ReplayDownload cmd; - cmd.set_replay_id(curRight->replay_id()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteReplayFinished(const Response &))); - client->sendCommand(pend); + ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); + if (!curRight) + return; + + Command_ReplayDownload cmd; + cmd.set_replay_id(curRight->replay_id()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(openRemoteReplayFinished(const Response &))); + client->sendCommand(pend); } void TabReplays::openRemoteReplayFinished(const Response &r) { - if (r.response_code() != Response::RespOk) - return; - - const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); - GameReplay *replay = new GameReplay; - replay->ParseFromString(resp.replay_data()); - - emit openReplay(replay); + if (r.response_code() != Response::RespOk) + return; + + const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); + GameReplay *replay = new GameReplay; + replay->ParseFromString(resp.replay_data()); + + emit openReplay(replay); } void TabReplays::actDownload() { - QString filePath; - QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); - if (!curLeft.isValid()) - filePath = localDirModel->rootPath(); - else { - while (!localDirModel->isDir(curLeft)) - curLeft = curLeft.parent(); - filePath = localDirModel->filePath(curLeft); - } + QString filePath; + QModelIndex curLeft = localDirView->selectionModel()->currentIndex(); + if (!curLeft.isValid()) + filePath = localDirModel->rootPath(); + else { + while (!localDirModel->isDir(curLeft)) + curLeft = curLeft.parent(); + filePath = localDirModel->filePath(curLeft); + } - ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); - if (!curRight) - return; - filePath += QString("/replay_%1.cor").arg(curRight->replay_id()); - - Command_ReplayDownload cmd; - cmd.set_replay_id(curRight->replay_id()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - pend->setExtraData(filePath); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); - client->sendCommand(pend); + ServerInfo_Replay const *curRight = serverDirView->getCurrentReplay(); + if (!curRight) + return; + filePath += QString("/replay_%1.cor").arg(curRight->replay_id()); + + Command_ReplayDownload cmd; + cmd.set_replay_id(curRight->replay_id()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + pend->setExtraData(filePath); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(downloadFinished(Response, CommandContainer, QVariant))); + client->sendCommand(pend); } void TabReplays::downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData) { - if (r.response_code() != Response::RespOk) - return; - - const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); - QString filePath = extraData.toString(); - - const std::string &data = resp.replay_data(); - QFile f(filePath); - f.open(QIODevice::WriteOnly); - f.write((const char *) data.data(), data.size()); - f.close(); + if (r.response_code() != Response::RespOk) + return; + + const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext); + QString filePath = extraData.toString(); + + const std::string &data = resp.replay_data(); + QFile f(filePath); + f.open(QIODevice::WriteOnly); + f.write((const char *) data.data(), data.size()); + f.close(); } void TabReplays::actKeepRemoteReplay() { - ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); - if (!curRight) - return; - - Command_ReplayModifyMatch cmd; - cmd.set_game_id(curRight->game_id()); - cmd.set_do_not_hide(!curRight->do_not_hide()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(keepRemoteReplayFinished(Response, CommandContainer))); - client->sendCommand(pend); + ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); + if (!curRight) + return; + + Command_ReplayModifyMatch cmd; + cmd.set_game_id(curRight->game_id()); + cmd.set_do_not_hide(!curRight->do_not_hide()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(keepRemoteReplayFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabReplays::keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Command_ReplayModifyMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayModifyMatch::ext); - - ServerInfo_ReplayMatch temp; - temp.set_do_not_hide(cmd.do_not_hide()); - - serverDirView->updateMatchInfo(cmd.game_id(), temp); + if (r.response_code() != Response::RespOk) + return; + + const Command_ReplayModifyMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayModifyMatch::ext); + + ServerInfo_ReplayMatch temp; + temp.set_do_not_hide(cmd.do_not_hide()); + + serverDirView->updateMatchInfo(cmd.game_id(), temp); } void TabReplays::actDeleteRemoteReplay() { - ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); - if (!curRight) - return; - if (QMessageBox::warning(this, tr("Delete remote replay"), tr("Are you sure you want to delete the replay of game %1?").arg(curRight->game_id()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - - Command_ReplayDeleteMatch cmd; - cmd.set_game_id(curRight->game_id()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteRemoteReplayFinished(Response, CommandContainer))); - client->sendCommand(pend); + ServerInfo_ReplayMatch const *curRight = serverDirView->getCurrentReplayMatch(); + if (!curRight) + return; + if (QMessageBox::warning(this, tr("Delete remote replay"), tr("Are you sure you want to delete the replay of game %1?").arg(curRight->game_id()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + + Command_ReplayDeleteMatch cmd; + cmd.set_game_id(curRight->game_id()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(deleteRemoteReplayFinished(Response, CommandContainer))); + client->sendCommand(pend); } void TabReplays::deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer) { - if (r.response_code() != Response::RespOk) - return; - - const Command_ReplayDeleteMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext); - serverDirView->removeMatchInfo(cmd.game_id()); + if (r.response_code() != Response::RespOk) + return; + + const Command_ReplayDeleteMatch &cmd = commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext); + serverDirView->removeMatchInfo(cmd.game_id()); } void TabReplays::replayAddedEventReceived(const Event_ReplayAdded &event) { - serverDirView->addMatchInfo(event.match_info()); + serverDirView->addMatchInfo(event.match_info()); } diff --git a/cockatrice/src/tab_replays.h b/cockatrice/src/tab_replays.h index dd3e3b0e..99f1c6f4 100644 --- a/cockatrice/src/tab_replays.h +++ b/cockatrice/src/tab_replays.h @@ -15,40 +15,40 @@ class Event_ReplayAdded; class CommandContainer; class TabReplays : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - QTreeView *localDirView; - QFileSystemModel *localDirModel; - QToolBar *leftToolBar, *rightToolBar; - RemoteReplayList_TreeWidget *serverDirView; - QGroupBox *leftGroupBox, *rightGroupBox; - - QAction *aOpenLocalReplay, *aDeleteLocalReplay, *aOpenRemoteReplay, *aDownload, *aKeep, *aDeleteRemoteReplay; + AbstractClient *client; + QTreeView *localDirView; + QFileSystemModel *localDirModel; + QToolBar *leftToolBar, *rightToolBar; + RemoteReplayList_TreeWidget *serverDirView; + QGroupBox *leftGroupBox, *rightGroupBox; + + QAction *aOpenLocalReplay, *aDeleteLocalReplay, *aOpenRemoteReplay, *aDownload, *aKeep, *aDeleteRemoteReplay; private slots: - void actOpenLocalReplay(); - - void actDeleteLocalReplay(); - - void actOpenRemoteReplay(); - void openRemoteReplayFinished(const Response &r); - - void actDownload(); - void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); - - void actKeepRemoteReplay(); - void keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); - - void actDeleteRemoteReplay(); - void deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); - - void replayAddedEventReceived(const Event_ReplayAdded &event); + void actOpenLocalReplay(); + + void actDeleteLocalReplay(); + + void actOpenRemoteReplay(); + void openRemoteReplayFinished(const Response &r); + + void actDownload(); + void downloadFinished(const Response &r, const CommandContainer &commandContainer, const QVariant &extraData); + + void actKeepRemoteReplay(); + void keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); + + void actDeleteRemoteReplay(); + void deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer); + + void replayAddedEventReceived(const Event_ReplayAdded &event); signals: - void openReplay(GameReplay *replay); + void openReplay(GameReplay *replay); public: - TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client); - void retranslateUi(); - QString getTabText() const { return tr("Game replays"); } + TabReplays(TabSupervisor *_tabSupervisor, AbstractClient *_client); + void retranslateUi(); + QString getTabText() const { return tr("Game replays"); } }; #endif diff --git a/cockatrice/src/tab_room.cpp b/cockatrice/src/tab_room.cpp index 04ceb338..79673e0f 100644 --- a/cockatrice/src/tab_room.cpp +++ b/cockatrice/src/tab_room.cpp @@ -28,195 +28,195 @@ #include "pending_command.h" TabRoom::TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info) - : Tab(_tabSupervisor), client(_client), roomId(info.room_id()), roomName(QString::fromStdString(info.name())), ownUser(_ownUser) + : Tab(_tabSupervisor), client(_client), roomId(info.room_id()), roomName(QString::fromStdString(info.name())), ownUser(_ownUser) { - const int gameTypeListSize = info.gametype_list_size(); - for (int i = 0; i < gameTypeListSize; ++i) - gameTypes.insert(info.gametype_list(i).game_type_id(), QString::fromStdString(info.gametype_list(i).description())); - - QMap tempMap; - tempMap.insert(info.room_id(), gameTypes); - gameSelector = new GameSelector(client, tabSupervisor, this, QMap(), tempMap); - userList = new UserList(tabSupervisor, client, UserList::RoomList); - connect(userList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - - chatView = new ChatView(tabSupervisor, 0, true); - connect(chatView, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); - connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); - sayLabel = new QLabel; - sayEdit = new QLineEdit; - sayLabel->setBuddy(sayEdit); - connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); - - QMenu *chatSettingsMenu = new QMenu(this); - aIgnoreUnregisteredUsers = chatSettingsMenu->addAction(QString()); - aIgnoreUnregisteredUsers->setCheckable(true); - connect(aIgnoreUnregisteredUsers, SIGNAL(triggered()), this, SLOT(actIgnoreUnregisteredUsers())); - connect(settingsCache, SIGNAL(ignoreUnregisteredUsersChanged()), this, SLOT(ignoreUnregisteredUsersChanged())); - QToolButton *chatSettingsButton = new QToolButton; - chatSettingsButton->setIcon(QIcon(":/resources/icon_settings.svg")); - chatSettingsButton->setMenu(chatSettingsMenu); - chatSettingsButton->setPopupMode(QToolButton::InstantPopup); - - QHBoxLayout *sayHbox = new QHBoxLayout; - sayHbox->addWidget(sayLabel); - sayHbox->addWidget(sayEdit); - sayHbox->addWidget(chatSettingsButton); - - QVBoxLayout *chatVbox = new QVBoxLayout; - chatVbox->addWidget(chatView); - chatVbox->addLayout(sayHbox); - - chatGroupBox = new QGroupBox; - chatGroupBox->setLayout(chatVbox); - - QSplitter *splitter = new QSplitter(Qt::Vertical); - splitter->addWidget(gameSelector); - splitter->addWidget(chatGroupBox); - - QHBoxLayout *hbox = new QHBoxLayout; - hbox->addWidget(splitter, 3); - hbox->addWidget(userList, 1); - - aLeaveRoom = new QAction(this); - connect(aLeaveRoom, SIGNAL(triggered()), this, SLOT(actLeaveRoom())); + const int gameTypeListSize = info.gametype_list_size(); + for (int i = 0; i < gameTypeListSize; ++i) + gameTypes.insert(info.gametype_list(i).game_type_id(), QString::fromStdString(info.gametype_list(i).description())); + + QMap tempMap; + tempMap.insert(info.room_id(), gameTypes); + gameSelector = new GameSelector(client, tabSupervisor, this, QMap(), tempMap); + userList = new UserList(tabSupervisor, client, UserList::RoomList); + connect(userList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + + chatView = new ChatView(tabSupervisor, 0, true); + connect(chatView, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString))); + connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString))); + sayLabel = new QLabel; + sayEdit = new QLineEdit; + sayLabel->setBuddy(sayEdit); + connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage())); + + QMenu *chatSettingsMenu = new QMenu(this); + aIgnoreUnregisteredUsers = chatSettingsMenu->addAction(QString()); + aIgnoreUnregisteredUsers->setCheckable(true); + connect(aIgnoreUnregisteredUsers, SIGNAL(triggered()), this, SLOT(actIgnoreUnregisteredUsers())); + connect(settingsCache, SIGNAL(ignoreUnregisteredUsersChanged()), this, SLOT(ignoreUnregisteredUsersChanged())); + QToolButton *chatSettingsButton = new QToolButton; + chatSettingsButton->setIcon(QIcon(":/resources/icon_settings.svg")); + chatSettingsButton->setMenu(chatSettingsMenu); + chatSettingsButton->setPopupMode(QToolButton::InstantPopup); + + QHBoxLayout *sayHbox = new QHBoxLayout; + sayHbox->addWidget(sayLabel); + sayHbox->addWidget(sayEdit); + sayHbox->addWidget(chatSettingsButton); + + QVBoxLayout *chatVbox = new QVBoxLayout; + chatVbox->addWidget(chatView); + chatVbox->addLayout(sayHbox); + + chatGroupBox = new QGroupBox; + chatGroupBox->setLayout(chatVbox); + + QSplitter *splitter = new QSplitter(Qt::Vertical); + splitter->addWidget(gameSelector); + splitter->addWidget(chatGroupBox); + + QHBoxLayout *hbox = new QHBoxLayout; + hbox->addWidget(splitter, 3); + hbox->addWidget(userList, 1); + + aLeaveRoom = new QAction(this); + connect(aLeaveRoom, SIGNAL(triggered()), this, SLOT(actLeaveRoom())); - roomMenu = new QMenu(this); - roomMenu->addAction(aLeaveRoom); - addTabMenu(roomMenu); + roomMenu = new QMenu(this); + roomMenu->addAction(aLeaveRoom); + addTabMenu(roomMenu); - retranslateUi(); - setLayout(hbox); - - const int userListSize = info.user_list_size(); - for (int i = 0; i < userListSize; ++i) - userList->processUserInfo(info.user_list(i), true); - userList->sortItems(); - - const int gameListSize = info.game_list_size(); - for (int i = 0; i < gameListSize; ++i) - gameSelector->processGameInfo(info.game_list(i)); + retranslateUi(); + setLayout(hbox); + + const int userListSize = info.user_list_size(); + for (int i = 0; i < userListSize; ++i) + userList->processUserInfo(info.user_list(i), true); + userList->sortItems(); + + const int gameListSize = info.game_list_size(); + for (int i = 0; i < gameListSize; ++i) + gameSelector->processGameInfo(info.game_list(i)); } TabRoom::~TabRoom() { - emit roomClosing(this); + emit roomClosing(this); } void TabRoom::retranslateUi() { gameSelector->retranslateUi(); - chatView->retranslateUi(); - userList->retranslateUi(); - sayLabel->setText(tr("&Say:")); - chatGroupBox->setTitle(tr("Chat")); - roomMenu->setTitle(tr("&Room")); - aLeaveRoom->setText(tr("&Leave room")); - aIgnoreUnregisteredUsers->setText(tr("&Ignore unregistered users in chat")); + chatView->retranslateUi(); + userList->retranslateUi(); + sayLabel->setText(tr("&Say:")); + chatGroupBox->setTitle(tr("Chat")); + roomMenu->setTitle(tr("&Room")); + aLeaveRoom->setText(tr("&Leave room")); + aIgnoreUnregisteredUsers->setText(tr("&Ignore unregistered users in chat")); } void TabRoom::closeRequest() { - actLeaveRoom(); + actLeaveRoom(); } QString TabRoom::sanitizeHtml(QString dirty) const { - return dirty - .replace("&", "&") - .replace("<", "<") - .replace(">", ">"); + return dirty + .replace("&", "&") + .replace("<", "<") + .replace(">", ">"); } void TabRoom::sendMessage() { - if (sayEdit->text().isEmpty()) - return; - - Command_RoomSay cmd; - cmd.set_message(sayEdit->text().toStdString()); - - PendingCommand *pend = prepareRoomCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(sayFinished(const Response &))); - sendRoomCommand(pend); - sayEdit->clear(); + if (sayEdit->text().isEmpty()) + return; + + Command_RoomSay cmd; + cmd.set_message(sayEdit->text().toStdString()); + + PendingCommand *pend = prepareRoomCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(sayFinished(const Response &))); + sendRoomCommand(pend); + sayEdit->clear(); } void TabRoom::sayFinished(const Response &response) { - if (response.response_code() == Response::RespChatFlood) - chatView->appendMessage(tr("You are flooding the chat. Please wait a couple of seconds.")); + if (response.response_code() == Response::RespChatFlood) + chatView->appendMessage(tr("You are flooding the chat. Please wait a couple of seconds.")); } void TabRoom::actLeaveRoom() { - sendRoomCommand(prepareRoomCommand(Command_LeaveRoom())); - deleteLater(); + sendRoomCommand(prepareRoomCommand(Command_LeaveRoom())); + deleteLater(); } void TabRoom::actIgnoreUnregisteredUsers() { - aIgnoreUnregisteredUsers->setChecked(!aIgnoreUnregisteredUsers->isChecked()); - settingsCache->setIgnoreUnregisteredUsers(!settingsCache->getIgnoreUnregisteredUsers()); + aIgnoreUnregisteredUsers->setChecked(!aIgnoreUnregisteredUsers->isChecked()); + settingsCache->setIgnoreUnregisteredUsers(!settingsCache->getIgnoreUnregisteredUsers()); } void TabRoom::ignoreUnregisteredUsersChanged() { - aIgnoreUnregisteredUsers->setChecked(settingsCache->getIgnoreUnregisteredUsers()); + aIgnoreUnregisteredUsers->setChecked(settingsCache->getIgnoreUnregisteredUsers()); } void TabRoom::processRoomEvent(const RoomEvent &event) { - switch (static_cast(getPbExtension(event))) { - case RoomEvent::LIST_GAMES: processListGamesEvent(event.GetExtension(Event_ListGames::ext)); break; - case RoomEvent::JOIN_ROOM: processJoinRoomEvent(event.GetExtension(Event_JoinRoom::ext)); break; - case RoomEvent::LEAVE_ROOM: processLeaveRoomEvent(event.GetExtension(Event_LeaveRoom::ext)); break; - case RoomEvent::ROOM_SAY: processRoomSayEvent(event.GetExtension(Event_RoomSay::ext)); break; - default: ; - } + switch (static_cast(getPbExtension(event))) { + case RoomEvent::LIST_GAMES: processListGamesEvent(event.GetExtension(Event_ListGames::ext)); break; + case RoomEvent::JOIN_ROOM: processJoinRoomEvent(event.GetExtension(Event_JoinRoom::ext)); break; + case RoomEvent::LEAVE_ROOM: processLeaveRoomEvent(event.GetExtension(Event_LeaveRoom::ext)); break; + case RoomEvent::ROOM_SAY: processRoomSayEvent(event.GetExtension(Event_RoomSay::ext)); break; + default: ; + } } void TabRoom::processListGamesEvent(const Event_ListGames &event) { - const int gameListSize = event.game_list_size(); - for (int i = 0; i < gameListSize; ++i) - gameSelector->processGameInfo(event.game_list(i)); + const int gameListSize = event.game_list_size(); + for (int i = 0; i < gameListSize; ++i) + gameSelector->processGameInfo(event.game_list(i)); } void TabRoom::processJoinRoomEvent(const Event_JoinRoom &event) { - userList->processUserInfo(event.user_info(), true); - userList->sortItems(); + userList->processUserInfo(event.user_info(), true); + userList->sortItems(); } void TabRoom::processLeaveRoomEvent(const Event_LeaveRoom &event) { - userList->deleteUser(QString::fromStdString(event.name())); + userList->deleteUser(QString::fromStdString(event.name())); } void TabRoom::processRoomSayEvent(const Event_RoomSay &event) { - QString senderName = QString::fromStdString(event.name()); - if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(senderName)) - return; - UserListTWI *twi = userList->getUsers().value(senderName); - UserLevelFlags userLevel; - if (twi) { - userLevel = UserLevelFlags(twi->getUserInfo().user_level()); - if (settingsCache->getIgnoreUnregisteredUsers() && !userLevel.testFlag(ServerInfo_User::IsRegistered)) - return; - } - chatView->appendMessage(QString::fromStdString(event.message()), senderName, userLevel); - emit userEvent(false); + QString senderName = QString::fromStdString(event.name()); + if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(senderName)) + return; + UserListTWI *twi = userList->getUsers().value(senderName); + UserLevelFlags userLevel; + if (twi) { + userLevel = UserLevelFlags(twi->getUserInfo().user_level()); + if (settingsCache->getIgnoreUnregisteredUsers() && !userLevel.testFlag(ServerInfo_User::IsRegistered)) + return; + } + chatView->appendMessage(QString::fromStdString(event.message()), senderName, userLevel); + emit userEvent(false); } PendingCommand *TabRoom::prepareRoomCommand(const ::google::protobuf::Message &cmd) { - return client->prepareRoomCommand(cmd, roomId); + return client->prepareRoomCommand(cmd, roomId); } void TabRoom::sendRoomCommand(PendingCommand *pend) { - client->sendCommand(pend); + client->sendCommand(pend); } diff --git a/cockatrice/src/tab_room.h b/cockatrice/src/tab_room.h index 752a4672..ada3aca8 100644 --- a/cockatrice/src/tab_room.h +++ b/cockatrice/src/tab_room.h @@ -26,53 +26,53 @@ class PendingCommand; class ServerInfo_User; class TabRoom : public Tab { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - int roomId; - QString roomName; - ServerInfo_User *ownUser; - QMap gameTypes; - - GameSelector *gameSelector; - UserList *userList; - ChatView *chatView; - QLabel *sayLabel; - QLineEdit *sayEdit; - QGroupBox *chatGroupBox; - - QMenu *roomMenu; - QAction *aLeaveRoom; - QAction *aIgnoreUnregisteredUsers; - QString sanitizeHtml(QString dirty) const; + AbstractClient *client; + int roomId; + QString roomName; + ServerInfo_User *ownUser; + QMap gameTypes; + + GameSelector *gameSelector; + UserList *userList; + ChatView *chatView; + QLabel *sayLabel; + QLineEdit *sayEdit; + QGroupBox *chatGroupBox; + + QMenu *roomMenu; + QAction *aLeaveRoom; + QAction *aIgnoreUnregisteredUsers; + QString sanitizeHtml(QString dirty) const; signals: - void roomClosing(TabRoom *tab); - void openMessageDialog(const QString &userName, bool focus); + void roomClosing(TabRoom *tab); + void openMessageDialog(const QString &userName, bool focus); private slots: - void sendMessage(); - void sayFinished(const Response &response); - void actLeaveRoom(); - void actIgnoreUnregisteredUsers(); - void ignoreUnregisteredUsersChanged(); - - void processListGamesEvent(const Event_ListGames &event); - void processJoinRoomEvent(const Event_JoinRoom &event); - void processLeaveRoomEvent(const Event_LeaveRoom &event); - void processRoomSayEvent(const Event_RoomSay &event); + void sendMessage(); + void sayFinished(const Response &response); + void actLeaveRoom(); + void actIgnoreUnregisteredUsers(); + void ignoreUnregisteredUsersChanged(); + + void processListGamesEvent(const Event_ListGames &event); + void processJoinRoomEvent(const Event_JoinRoom &event); + void processLeaveRoomEvent(const Event_LeaveRoom &event); + void processRoomSayEvent(const Event_RoomSay &event); public: - TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info); - ~TabRoom(); - void retranslateUi(); - void closeRequest(); - void processRoomEvent(const RoomEvent &event); - int getRoomId() const { return roomId; } - const QMap &getGameTypes() const { return gameTypes; } - QString getChannelName() const { return roomName; } - QString getTabText() const { return roomName; } - const ServerInfo_User *getUserInfo() const { return ownUser; } + TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info); + ~TabRoom(); + void retranslateUi(); + void closeRequest(); + void processRoomEvent(const RoomEvent &event); + int getRoomId() const { return roomId; } + const QMap &getGameTypes() const { return gameTypes; } + QString getChannelName() const { return roomName; } + QString getTabText() const { return roomName; } + const ServerInfo_User *getUserInfo() const { return ownUser; } - PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd); - void sendRoomCommand(PendingCommand *pend); + PendingCommand *prepareRoomCommand(const ::google::protobuf::Message &cmd); + void sendRoomCommand(PendingCommand *pend); }; #endif diff --git a/cockatrice/src/tab_server.cpp b/cockatrice/src/tab_server.cpp index 0ad57ccd..a8e89af5 100644 --- a/cockatrice/src/tab_server.cpp +++ b/cockatrice/src/tab_server.cpp @@ -22,140 +22,140 @@ #include "pb/response_join_room.pb.h" RoomSelector::RoomSelector(AbstractClient *_client, QWidget *parent) - : QGroupBox(parent), client(_client) + : QGroupBox(parent), client(_client) { - roomList = new QTreeWidget; - roomList->setRootIsDecorated(false); - roomList->setColumnCount(4); - roomList->header()->setStretchLastSection(false); - roomList->header()->setResizeMode(0, QHeaderView::ResizeToContents); - roomList->header()->setResizeMode(1, QHeaderView::Stretch); - roomList->header()->setResizeMode(2, QHeaderView::ResizeToContents); - roomList->header()->setResizeMode(3, QHeaderView::ResizeToContents); - - joinButton = new QPushButton; - connect(joinButton, SIGNAL(clicked()), this, SLOT(joinClicked())); - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addStretch(); - buttonLayout->addWidget(joinButton); - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(roomList); - vbox->addLayout(buttonLayout); - - retranslateUi(); - setLayout(vbox); - - connect(client, SIGNAL(listRoomsEventReceived(const Event_ListRooms &)), this, SLOT(processListRoomsEvent(const Event_ListRooms &))); - client->sendCommand(client->prepareSessionCommand(Command_ListRooms())); + roomList = new QTreeWidget; + roomList->setRootIsDecorated(false); + roomList->setColumnCount(4); + roomList->header()->setStretchLastSection(false); + roomList->header()->setResizeMode(0, QHeaderView::ResizeToContents); + roomList->header()->setResizeMode(1, QHeaderView::Stretch); + roomList->header()->setResizeMode(2, QHeaderView::ResizeToContents); + roomList->header()->setResizeMode(3, QHeaderView::ResizeToContents); + + joinButton = new QPushButton; + connect(joinButton, SIGNAL(clicked()), this, SLOT(joinClicked())); + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addStretch(); + buttonLayout->addWidget(joinButton); + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(roomList); + vbox->addLayout(buttonLayout); + + retranslateUi(); + setLayout(vbox); + + connect(client, SIGNAL(listRoomsEventReceived(const Event_ListRooms &)), this, SLOT(processListRoomsEvent(const Event_ListRooms &))); + client->sendCommand(client->prepareSessionCommand(Command_ListRooms())); } void RoomSelector::retranslateUi() { - setTitle(tr("Rooms")); - joinButton->setText(tr("Joi&n")); + setTitle(tr("Rooms")); + joinButton->setText(tr("Joi&n")); - QTreeWidgetItem *header = roomList->headerItem(); - header->setText(0, tr("Room")); - header->setText(1, tr("Description")); - header->setText(2, tr("Players")); - header->setText(3, tr("Games")); - header->setTextAlignment(2, Qt::AlignRight); - header->setTextAlignment(3, Qt::AlignRight); + QTreeWidgetItem *header = roomList->headerItem(); + header->setText(0, tr("Room")); + header->setText(1, tr("Description")); + header->setText(2, tr("Players")); + header->setText(3, tr("Games")); + header->setTextAlignment(2, Qt::AlignRight); + header->setTextAlignment(3, Qt::AlignRight); } void RoomSelector::processListRoomsEvent(const Event_ListRooms &event) { - const int roomListSize = event.room_list_size(); - for (int i = 0; i < roomListSize; ++i) { - const ServerInfo_Room &room = event.room_list(i); - - for (int j = 0; j < roomList->topLevelItemCount(); ++j) { - QTreeWidgetItem *twi = roomList->topLevelItem(j); - if (twi->data(0, Qt::UserRole).toInt() == room.room_id()) { - if (room.has_name()) - twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); - if (room.has_description()) - twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); - if (room.has_player_count()) - twi->setData(2, Qt::DisplayRole, room.player_count()); - if (room.has_game_count()) - twi->setData(3, Qt::DisplayRole, room.game_count()); - return; - } - } - QTreeWidgetItem *twi = new QTreeWidgetItem; - twi->setData(0, Qt::UserRole, room.room_id()); - if (room.has_name()) - twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); - if (room.has_description()) - twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); - twi->setData(2, Qt::DisplayRole, room.player_count()); - twi->setData(3, Qt::DisplayRole, room.game_count()); - twi->setTextAlignment(2, Qt::AlignRight); - twi->setTextAlignment(3, Qt::AlignRight); - - roomList->addTopLevelItem(twi); - if (room.has_auto_join()) - if (room.auto_join()) - joinRoom(room.room_id(), false); - } + const int roomListSize = event.room_list_size(); + for (int i = 0; i < roomListSize; ++i) { + const ServerInfo_Room &room = event.room_list(i); + + for (int j = 0; j < roomList->topLevelItemCount(); ++j) { + QTreeWidgetItem *twi = roomList->topLevelItem(j); + if (twi->data(0, Qt::UserRole).toInt() == room.room_id()) { + if (room.has_name()) + twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); + if (room.has_description()) + twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); + if (room.has_player_count()) + twi->setData(2, Qt::DisplayRole, room.player_count()); + if (room.has_game_count()) + twi->setData(3, Qt::DisplayRole, room.game_count()); + return; + } + } + QTreeWidgetItem *twi = new QTreeWidgetItem; + twi->setData(0, Qt::UserRole, room.room_id()); + if (room.has_name()) + twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name())); + if (room.has_description()) + twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description())); + twi->setData(2, Qt::DisplayRole, room.player_count()); + twi->setData(3, Qt::DisplayRole, room.game_count()); + twi->setTextAlignment(2, Qt::AlignRight); + twi->setTextAlignment(3, Qt::AlignRight); + + roomList->addTopLevelItem(twi); + if (room.has_auto_join()) + if (room.auto_join()) + joinRoom(room.room_id(), false); + } } void RoomSelector::joinRoom(int id, bool setCurrent) { - Command_JoinRoom cmd; - cmd.set_room_id(id); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - pend->setExtraData(setCurrent); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(joinFinished(Response, CommandContainer, QVariant))); - - client->sendCommand(pend); + Command_JoinRoom cmd; + cmd.set_room_id(id); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + pend->setExtraData(setCurrent); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(joinFinished(Response, CommandContainer, QVariant))); + + client->sendCommand(pend); } void RoomSelector::joinClicked() { - QTreeWidgetItem *twi = roomList->currentItem(); - if (!twi) - return; - - joinRoom(twi->data(0, Qt::UserRole).toInt(), true); + QTreeWidgetItem *twi = roomList->currentItem(); + if (!twi) + return; + + joinRoom(twi->data(0, Qt::UserRole).toInt(), true); } void RoomSelector::joinFinished(const Response &r, const CommandContainer & /*commandContainer*/, const QVariant &extraData) { - if (r.response_code() != Response::RespOk) - return; - const Response_JoinRoom &resp = r.GetExtension(Response_JoinRoom::ext); - - emit roomJoined(resp.room_info(), extraData.toBool()); + if (r.response_code() != Response::RespOk) + return; + const Response_JoinRoom &resp = r.GetExtension(Response_JoinRoom::ext); + + emit roomJoined(resp.room_info(), extraData.toBool()); } TabServer::TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent) - : Tab(_tabSupervisor, parent), client(_client) + : Tab(_tabSupervisor, parent), client(_client) { - roomSelector = new RoomSelector(client); - serverInfoBox = new QTextBrowser; - serverInfoBox->setOpenExternalLinks(true); - - connect(roomSelector, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SIGNAL(roomJoined(const ServerInfo_Room &, bool))); - - connect(client, SIGNAL(serverMessageEventReceived(const Event_ServerMessage &)), this, SLOT(processServerMessageEvent(const Event_ServerMessage &))); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(roomSelector); - vbox->addWidget(serverInfoBox); - - setLayout(vbox); + roomSelector = new RoomSelector(client); + serverInfoBox = new QTextBrowser; + serverInfoBox->setOpenExternalLinks(true); + + connect(roomSelector, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SIGNAL(roomJoined(const ServerInfo_Room &, bool))); + + connect(client, SIGNAL(serverMessageEventReceived(const Event_ServerMessage &)), this, SLOT(processServerMessageEvent(const Event_ServerMessage &))); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(roomSelector); + vbox->addWidget(serverInfoBox); + + setLayout(vbox); } void TabServer::retranslateUi() { - roomSelector->retranslateUi(); + roomSelector->retranslateUi(); } void TabServer::processServerMessageEvent(const Event_ServerMessage &event) { - serverInfoBox->setHtml(QString::fromStdString(event.message())); - emit userEvent(); + serverInfoBox->setHtml(QString::fromStdString(event.message())); + emit userEvent(); } diff --git a/cockatrice/src/tab_server.h b/cockatrice/src/tab_server.h index f64e4871..a057660b 100644 --- a/cockatrice/src/tab_server.h +++ b/cockatrice/src/tab_server.h @@ -19,38 +19,38 @@ class ServerInfo_Room; class CommandContainer; class RoomSelector : public QGroupBox { - Q_OBJECT + Q_OBJECT private: - QTreeWidget *roomList; - QPushButton *joinButton; - AbstractClient *client; - - void joinRoom(int id, bool setCurrent); + QTreeWidget *roomList; + QPushButton *joinButton; + AbstractClient *client; + + void joinRoom(int id, bool setCurrent); private slots: - void processListRoomsEvent(const Event_ListRooms &event); - void joinClicked(); - void joinFinished(const Response &resp, const CommandContainer &commandContainer, const QVariant &extraData); + void processListRoomsEvent(const Event_ListRooms &event); + void joinClicked(); + void joinFinished(const Response &resp, const CommandContainer &commandContainer, const QVariant &extraData); signals: - void roomJoined(const ServerInfo_Room &info, bool setCurrent); + void roomJoined(const ServerInfo_Room &info, bool setCurrent); public: - RoomSelector(AbstractClient *_client, QWidget *parent = 0); - void retranslateUi(); + RoomSelector(AbstractClient *_client, QWidget *parent = 0); + void retranslateUi(); }; class TabServer : public Tab { - Q_OBJECT + Q_OBJECT signals: - void roomJoined(const ServerInfo_Room &info, bool setCurrent); + void roomJoined(const ServerInfo_Room &info, bool setCurrent); private slots: - void processServerMessageEvent(const Event_ServerMessage &event); + void processServerMessageEvent(const Event_ServerMessage &event); private: - AbstractClient *client; - RoomSelector *roomSelector; - QTextBrowser *serverInfoBox; + AbstractClient *client; + RoomSelector *roomSelector; + QTextBrowser *serverInfoBox; public: - TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent = 0); - void retranslateUi(); - QString getTabText() const { return tr("Server"); } + TabServer(TabSupervisor *_tabSupervisor, AbstractClient *_client, QWidget *parent = 0); + void retranslateUi(); + QString getTabText() const { return tr("Server"); } }; #endif diff --git a/cockatrice/src/tab_supervisor.cpp b/cockatrice/src/tab_supervisor.cpp index fde4ff6e..e85efc6a 100644 --- a/cockatrice/src/tab_supervisor.cpp +++ b/cockatrice/src/tab_supervisor.cpp @@ -25,466 +25,467 @@ #include "pb/serverinfo_room.pb.h" CloseButton::CloseButton(QWidget *parent) - : QAbstractButton(parent) + : QAbstractButton(parent) { - setFocusPolicy(Qt::NoFocus); - setCursor(Qt::ArrowCursor); - resize(sizeHint()); + setFocusPolicy(Qt::NoFocus); + setCursor(Qt::ArrowCursor); + resize(sizeHint()); } QSize CloseButton::sizeHint() const { - ensurePolished(); - int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this); - int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this); - return QSize(width, height); + ensurePolished(); + int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this); + int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this); + return QSize(width, height); } void CloseButton::enterEvent(QEvent *event) { - update(); - QAbstractButton::enterEvent(event); + update(); + QAbstractButton::enterEvent(event); } void CloseButton::leaveEvent(QEvent *event) { - update(); - QAbstractButton::leaveEvent(event); + update(); + QAbstractButton::leaveEvent(event); } void CloseButton::paintEvent(QPaintEvent * /*event*/) { - QPainter p(this); - QStyleOption opt; - opt.init(this); - opt.state |= QStyle::State_AutoRaise; - if (isEnabled() && underMouse() && !isChecked() && !isDown()) - opt.state |= QStyle::State_Raised; - if (isChecked()) - opt.state |= QStyle::State_On; - if (isDown()) - opt.state |= QStyle::State_Sunken; - - if (const QTabBar *tb = qobject_cast(parent())) { - int index = tb->currentIndex(); - QTabBar::ButtonPosition position = (QTabBar::ButtonPosition) style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tb); - if (tb->tabButton(index, position) == this) - opt.state |= QStyle::State_Selected; - } - - style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this); + QPainter p(this); + QStyleOption opt; + opt.init(this); + opt.state |= QStyle::State_AutoRaise; + if (isEnabled() && underMouse() && !isChecked() && !isDown()) + opt.state |= QStyle::State_Raised; + if (isChecked()) + opt.state |= QStyle::State_On; + if (isDown()) + opt.state |= QStyle::State_Sunken; + + if (const QTabBar *tb = qobject_cast(parent())) { + int index = tb->currentIndex(); + QTabBar::ButtonPosition position = (QTabBar::ButtonPosition) style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tb); + if (tb->tabButton(index, position) == this) + opt.state |= QStyle::State_Selected; + } + + style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this); } TabSupervisor::TabSupervisor(AbstractClient *_client, QWidget *parent) - : QTabWidget(parent), userInfo(0), client(_client), tabUserLists(0), tabServer(0), tabDeckStorage(0), tabAdmin(0), tabReplays(0) + : QTabWidget(parent), userInfo(0), client(_client), tabUserLists(0), tabServer(0), tabDeckStorage(0), tabAdmin(0), tabReplays(0) { - tabChangedIcon = new QIcon(":/resources/icon_tab_changed.svg"); - setElideMode(Qt::ElideRight); - setIconSize(QSize(15, 15)); - connect(this, SIGNAL(currentChanged(int)), this, SLOT(updateCurrent(int))); + tabChangedIcon = new QIcon(":/resources/icon_tab_changed.svg"); + setElideMode(Qt::ElideRight); + setMovable(true); + setIconSize(QSize(15, 15)); + connect(this, SIGNAL(currentChanged(int)), this, SLOT(updateCurrent(int))); - connect(client, SIGNAL(roomEventReceived(const RoomEvent &)), this, SLOT(processRoomEvent(const RoomEvent &))); - connect(client, SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); - connect(client, SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(gameJoined(const Event_GameJoined &))); - connect(client, SIGNAL(userMessageEventReceived(const Event_UserMessage &)), this, SLOT(processUserMessageEvent(const Event_UserMessage &))); - connect(client, SIGNAL(maxPingTime(int, int)), this, SLOT(updatePingTime(int, int))); - - retranslateUi(); + connect(client, SIGNAL(roomEventReceived(const RoomEvent &)), this, SLOT(processRoomEvent(const RoomEvent &))); + connect(client, SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); + connect(client, SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(gameJoined(const Event_GameJoined &))); + connect(client, SIGNAL(userMessageEventReceived(const Event_UserMessage &)), this, SLOT(processUserMessageEvent(const Event_UserMessage &))); + connect(client, SIGNAL(maxPingTime(int, int)), this, SLOT(updatePingTime(int, int))); + + retranslateUi(); } TabSupervisor::~TabSupervisor() { - stop(); - delete tabChangedIcon; + stop(); + delete tabChangedIcon; } void TabSupervisor::retranslateUi() { - QList tabs; - tabs.append(tabServer); - tabs.append(tabReplays); - tabs.append(tabDeckStorage); - tabs.append(tabAdmin); - tabs.append(tabUserLists); - QMapIterator roomIterator(roomTabs); - while (roomIterator.hasNext()) - tabs.append(roomIterator.next().value()); - QMapIterator gameIterator(gameTabs); - while (gameIterator.hasNext()) - tabs.append(gameIterator.next().value()); - QListIterator replayIterator(replayTabs); - while (replayIterator.hasNext()) - tabs.append(replayIterator.next()); - QListIterator deckEditorIterator(deckEditorTabs); - while (deckEditorIterator.hasNext()) - tabs.append(deckEditorIterator.next()); - QMapIterator messageIterator(messageTabs); - while (messageIterator.hasNext()) - tabs.append(messageIterator.next().value()); - - for (int i = 0; i < tabs.size(); ++i) - if (tabs[i]) { - setTabText(indexOf(tabs[i]), tabs[i]->getTabText()); - tabs[i]->retranslateUi(); - } + QList tabs; + tabs.append(tabServer); + tabs.append(tabReplays); + tabs.append(tabDeckStorage); + tabs.append(tabAdmin); + tabs.append(tabUserLists); + QMapIterator roomIterator(roomTabs); + while (roomIterator.hasNext()) + tabs.append(roomIterator.next().value()); + QMapIterator gameIterator(gameTabs); + while (gameIterator.hasNext()) + tabs.append(gameIterator.next().value()); + QListIterator replayIterator(replayTabs); + while (replayIterator.hasNext()) + tabs.append(replayIterator.next()); + QListIterator deckEditorIterator(deckEditorTabs); + while (deckEditorIterator.hasNext()) + tabs.append(deckEditorIterator.next()); + QMapIterator messageIterator(messageTabs); + while (messageIterator.hasNext()) + tabs.append(messageIterator.next().value()); + + for (int i = 0; i < tabs.size(); ++i) + if (tabs[i]) { + setTabText(indexOf(tabs[i]), tabs[i]->getTabText()); + tabs[i]->retranslateUi(); + } } AbstractClient *TabSupervisor::getClient() const { - return localClients.isEmpty() ? client : localClients.first(); + return localClients.isEmpty() ? client : localClients.first(); } int TabSupervisor::myAddTab(Tab *tab) { - connect(tab, SIGNAL(userEvent(bool)), this, SLOT(tabUserEvent(bool))); - connect(tab, SIGNAL(tabTextChanged(Tab *, QString)), this, SLOT(updateTabText(Tab *, QString))); - return addTab(tab, tab->getTabText()); + connect(tab, SIGNAL(userEvent(bool)), this, SLOT(tabUserEvent(bool))); + connect(tab, SIGNAL(tabTextChanged(Tab *, QString)), this, SLOT(updateTabText(Tab *, QString))); + return addTab(tab, tab->getTabText()); } void TabSupervisor::start(const ServerInfo_User &_userInfo) { - userInfo = new ServerInfo_User(_userInfo); - - tabServer = new TabServer(this, client); - connect(tabServer, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SLOT(addRoomTab(const ServerInfo_Room &, bool))); - myAddTab(tabServer); - - tabUserLists = new TabUserLists(this, client, *userInfo); - connect(tabUserLists, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); - connect(tabUserLists, SIGNAL(userJoined(ServerInfo_User)), this, SLOT(processUserJoined(ServerInfo_User))); - connect(tabUserLists, SIGNAL(userLeft(const QString &)), this, SLOT(processUserLeft(const QString &))); - myAddTab(tabUserLists); - - updatePingTime(0, -1); - - if (userInfo->user_level() & ServerInfo_User::IsRegistered) { - tabDeckStorage = new TabDeckStorage(this, client); - connect(tabDeckStorage, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); - myAddTab(tabDeckStorage); - - tabReplays = new TabReplays(this, client); - connect(tabReplays, SIGNAL(openReplay(GameReplay *)), this, SLOT(openReplay(GameReplay *))); - myAddTab(tabReplays); - } else { - tabDeckStorage = 0; - tabReplays = 0; - } - - if (userInfo->user_level() & ServerInfo_User::IsModerator) { - tabAdmin = new TabAdmin(this, client, (userInfo->user_level() & ServerInfo_User::IsAdmin)); - connect(tabAdmin, SIGNAL(adminLockChanged(bool)), this, SIGNAL(adminLockChanged(bool))); - myAddTab(tabAdmin); - } else - tabAdmin = 0; + userInfo = new ServerInfo_User(_userInfo); + + tabServer = new TabServer(this, client); + connect(tabServer, SIGNAL(roomJoined(const ServerInfo_Room &, bool)), this, SLOT(addRoomTab(const ServerInfo_Room &, bool))); + myAddTab(tabServer); + + tabUserLists = new TabUserLists(this, client, *userInfo); + connect(tabUserLists, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); + connect(tabUserLists, SIGNAL(userJoined(ServerInfo_User)), this, SLOT(processUserJoined(ServerInfo_User))); + connect(tabUserLists, SIGNAL(userLeft(const QString &)), this, SLOT(processUserLeft(const QString &))); + myAddTab(tabUserLists); + + updatePingTime(0, -1); + + if (userInfo->user_level() & ServerInfo_User::IsRegistered) { + tabDeckStorage = new TabDeckStorage(this, client); + connect(tabDeckStorage, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); + myAddTab(tabDeckStorage); + + tabReplays = new TabReplays(this, client); + connect(tabReplays, SIGNAL(openReplay(GameReplay *)), this, SLOT(openReplay(GameReplay *))); + myAddTab(tabReplays); + } else { + tabDeckStorage = 0; + tabReplays = 0; + } + + if (userInfo->user_level() & ServerInfo_User::IsModerator) { + tabAdmin = new TabAdmin(this, client, (userInfo->user_level() & ServerInfo_User::IsAdmin)); + connect(tabAdmin, SIGNAL(adminLockChanged(bool)), this, SIGNAL(adminLockChanged(bool))); + myAddTab(tabAdmin); + } else + tabAdmin = 0; - retranslateUi(); + retranslateUi(); } void TabSupervisor::startLocal(const QList &_clients) { - tabUserLists = 0; - tabDeckStorage = 0; - tabReplays = 0; - tabAdmin = 0; - userInfo = new ServerInfo_User; - localClients = _clients; - for (int i = 0; i < localClients.size(); ++i) - connect(localClients[i], SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); - connect(localClients.first(), SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(localGameJoined(const Event_GameJoined &))); + tabUserLists = 0; + tabDeckStorage = 0; + tabReplays = 0; + tabAdmin = 0; + userInfo = new ServerInfo_User; + localClients = _clients; + for (int i = 0; i < localClients.size(); ++i) + connect(localClients[i], SIGNAL(gameEventContainerReceived(const GameEventContainer &)), this, SLOT(processGameEventContainer(const GameEventContainer &))); + connect(localClients.first(), SIGNAL(gameJoinedEventReceived(const Event_GameJoined &)), this, SLOT(localGameJoined(const Event_GameJoined &))); } void TabSupervisor::stop() { - if ((!client) && localClients.isEmpty()) - return; - - if (!localClients.isEmpty()) { - for (int i = 0; i < localClients.size(); ++i) - localClients[i]->deleteLater(); - localClients.clear(); - - emit localGameEnded(); - } else { - if (tabUserLists) - tabUserLists->deleteLater(); - if (tabServer) - tabServer->deleteLater(); - if (tabDeckStorage) - tabDeckStorage->deleteLater(); - if (tabReplays) - tabReplays->deleteLater(); - if (tabAdmin) - tabAdmin->deleteLater(); - } - tabUserLists = 0; - tabServer = 0; - tabDeckStorage = 0; - tabReplays = 0; - tabAdmin = 0; - - QMapIterator roomIterator(roomTabs); - while (roomIterator.hasNext()) - roomIterator.next().value()->deleteLater(); - roomTabs.clear(); + if ((!client) && localClients.isEmpty()) + return; + + if (!localClients.isEmpty()) { + for (int i = 0; i < localClients.size(); ++i) + localClients[i]->deleteLater(); + localClients.clear(); + + emit localGameEnded(); + } else { + if (tabUserLists) + tabUserLists->deleteLater(); + if (tabServer) + tabServer->deleteLater(); + if (tabDeckStorage) + tabDeckStorage->deleteLater(); + if (tabReplays) + tabReplays->deleteLater(); + if (tabAdmin) + tabAdmin->deleteLater(); + } + tabUserLists = 0; + tabServer = 0; + tabDeckStorage = 0; + tabReplays = 0; + tabAdmin = 0; + + QMapIterator roomIterator(roomTabs); + while (roomIterator.hasNext()) + roomIterator.next().value()->deleteLater(); + roomTabs.clear(); - QMapIterator gameIterator(gameTabs); - while (gameIterator.hasNext()) - gameIterator.next().value()->deleteLater(); - gameTabs.clear(); + QMapIterator gameIterator(gameTabs); + while (gameIterator.hasNext()) + gameIterator.next().value()->deleteLater(); + gameTabs.clear(); - QListIterator replayIterator(replayTabs); - while (replayIterator.hasNext()) - replayIterator.next()->deleteLater(); - replayTabs.clear(); + QListIterator replayIterator(replayTabs); + while (replayIterator.hasNext()) + replayIterator.next()->deleteLater(); + replayTabs.clear(); - QMapIterator messageIterator(messageTabs); - while (messageIterator.hasNext()) - messageIterator.next().value()->deleteLater(); - messageTabs.clear(); - - delete userInfo; - userInfo = 0; + QMapIterator messageIterator(messageTabs); + while (messageIterator.hasNext()) + messageIterator.next().value()->deleteLater(); + messageTabs.clear(); + + delete userInfo; + userInfo = 0; } void TabSupervisor::updatePingTime(int value, int max) { - if (!tabServer) - return; - if (tabServer->getContentsChanged()) - return; - - setTabIcon(indexOf(tabServer), QIcon(PingPixmapGenerator::generatePixmap(15, value, max))); + if (!tabServer) + return; + if (tabServer->getContentsChanged()) + return; + + setTabIcon(indexOf(tabServer), QIcon(PingPixmapGenerator::generatePixmap(15, value, max))); } void TabSupervisor::closeButtonPressed() { - Tab *tab = static_cast(static_cast(sender())->property("tab").value()); - tab->closeRequest(); + Tab *tab = static_cast(static_cast(sender())->property("tab").value()); + tab->closeRequest(); } void TabSupervisor::addCloseButtonToTab(Tab *tab, int tabIndex) { - QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition) tabBar()->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tabBar()); - CloseButton *closeButton = new CloseButton; - connect(closeButton, SIGNAL(clicked()), this, SLOT(closeButtonPressed())); - closeButton->setProperty("tab", qVariantFromValue((QObject *) tab)); - tabBar()->setTabButton(tabIndex, closeSide, closeButton); + QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition) tabBar()->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tabBar()); + CloseButton *closeButton = new CloseButton; + connect(closeButton, SIGNAL(clicked()), this, SLOT(closeButtonPressed())); + closeButton->setProperty("tab", qVariantFromValue((QObject *) tab)); + tabBar()->setTabButton(tabIndex, closeSide, closeButton); } void TabSupervisor::gameJoined(const Event_GameJoined &event) { - QMap roomGameTypes; - TabRoom *room = roomTabs.value(event.game_info().room_id()); - if (room) - roomGameTypes = room->getGameTypes(); - else - for (int i = 0; i < event.game_types_size(); ++i) - roomGameTypes.insert(event.game_types(i).game_type_id(), QString::fromStdString(event.game_types(i).description())); - - TabGame *tab = new TabGame(this, QList() << client, event, roomGameTypes); - connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); - connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); - connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - gameTabs.insert(event.game_info().game_id(), tab); - setCurrentWidget(tab); + QMap roomGameTypes; + TabRoom *room = roomTabs.value(event.game_info().room_id()); + if (room) + roomGameTypes = room->getGameTypes(); + else + for (int i = 0; i < event.game_types_size(); ++i) + roomGameTypes.insert(event.game_types(i).game_type_id(), QString::fromStdString(event.game_types(i).description())); + + TabGame *tab = new TabGame(this, QList() << client, event, roomGameTypes); + connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); + connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); + connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + gameTabs.insert(event.game_info().game_id(), tab); + setCurrentWidget(tab); } void TabSupervisor::localGameJoined(const Event_GameJoined &event) { - TabGame *tab = new TabGame(this, localClients, event, QMap()); - connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); - connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - gameTabs.insert(event.game_info().game_id(), tab); - setCurrentWidget(tab); - - for (int i = 1; i < localClients.size(); ++i) { - Command_JoinGame cmd; - cmd.set_game_id(event.game_info().game_id()); - localClients[i]->sendCommand(localClients[i]->prepareRoomCommand(cmd, 0)); - } + TabGame *tab = new TabGame(this, localClients, event, QMap()); + connect(tab, SIGNAL(gameClosing(TabGame *)), this, SLOT(gameLeft(TabGame *))); + connect(tab, SIGNAL(openDeckEditor(const DeckLoader *)), this, SLOT(addDeckEditorTab(const DeckLoader *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + gameTabs.insert(event.game_info().game_id(), tab); + setCurrentWidget(tab); + + for (int i = 1; i < localClients.size(); ++i) { + Command_JoinGame cmd; + cmd.set_game_id(event.game_info().game_id()); + localClients[i]->sendCommand(localClients[i]->prepareRoomCommand(cmd, 0)); + } } void TabSupervisor::gameLeft(TabGame *tab) { - if (tab == currentWidget()) - emit setMenu(); + if (tab == currentWidget()) + emit setMenu(); - gameTabs.remove(tab->getGameId()); - removeTab(indexOf(tab)); - - if (!localClients.isEmpty()) - stop(); + gameTabs.remove(tab->getGameId()); + removeTab(indexOf(tab)); + + if (!localClients.isEmpty()) + stop(); } void TabSupervisor::addRoomTab(const ServerInfo_Room &info, bool setCurrent) { - TabRoom *tab = new TabRoom(this, client, userInfo, info); - connect(tab, SIGNAL(roomClosing(TabRoom *)), this, SLOT(roomLeft(TabRoom *))); - connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - roomTabs.insert(info.room_id(), tab); - if (setCurrent) - setCurrentWidget(tab); + TabRoom *tab = new TabRoom(this, client, userInfo, info); + connect(tab, SIGNAL(roomClosing(TabRoom *)), this, SLOT(roomLeft(TabRoom *))); + connect(tab, SIGNAL(openMessageDialog(const QString &, bool)), this, SLOT(addMessageTab(const QString &, bool))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + roomTabs.insert(info.room_id(), tab); + if (setCurrent) + setCurrentWidget(tab); } void TabSupervisor::roomLeft(TabRoom *tab) { - if (tab == currentWidget()) - emit setMenu(); - - roomTabs.remove(tab->getRoomId()); - removeTab(indexOf(tab)); + if (tab == currentWidget()) + emit setMenu(); + + roomTabs.remove(tab->getRoomId()); + removeTab(indexOf(tab)); } void TabSupervisor::openReplay(GameReplay *replay) { - TabGame *replayTab = new TabGame(this, replay); - connect(replayTab, SIGNAL(gameClosing(TabGame *)), this, SLOT(replayLeft(TabGame *))); - int tabIndex = myAddTab(replayTab); - addCloseButtonToTab(replayTab, tabIndex); - replayTabs.append(replayTab); - setCurrentWidget(replayTab); + TabGame *replayTab = new TabGame(this, replay); + connect(replayTab, SIGNAL(gameClosing(TabGame *)), this, SLOT(replayLeft(TabGame *))); + int tabIndex = myAddTab(replayTab); + addCloseButtonToTab(replayTab, tabIndex); + replayTabs.append(replayTab); + setCurrentWidget(replayTab); } void TabSupervisor::replayLeft(TabGame *tab) { - if (tab == currentWidget()) - emit setMenu(); - - replayTabs.removeAt(replayTabs.indexOf(tab)); + if (tab == currentWidget()) + emit setMenu(); + + replayTabs.removeAt(replayTabs.indexOf(tab)); } TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus) { - if (receiverName == QString::fromStdString(userInfo->name())) - return 0; - - ServerInfo_User otherUser; - UserListTWI *twi = tabUserLists->getAllUsersList()->getUsers().value(receiverName); - if (twi) - otherUser = twi->getUserInfo(); - else - otherUser.set_name(receiverName.toStdString()); - TabMessage *tab = new TabMessage(this, client, *userInfo, otherUser); - connect(tab, SIGNAL(talkClosing(TabMessage *)), this, SLOT(talkLeft(TabMessage *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - messageTabs.insert(receiverName, tab); - if (focus) - setCurrentWidget(tab); - return tab; + if (receiverName == QString::fromStdString(userInfo->name())) + return 0; + + ServerInfo_User otherUser; + UserListTWI *twi = tabUserLists->getAllUsersList()->getUsers().value(receiverName); + if (twi) + otherUser = twi->getUserInfo(); + else + otherUser.set_name(receiverName.toStdString()); + TabMessage *tab = new TabMessage(this, client, *userInfo, otherUser); + connect(tab, SIGNAL(talkClosing(TabMessage *)), this, SLOT(talkLeft(TabMessage *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + messageTabs.insert(receiverName, tab); + if (focus) + setCurrentWidget(tab); + return tab; } void TabSupervisor::talkLeft(TabMessage *tab) { - if (tab == currentWidget()) - emit setMenu(); + if (tab == currentWidget()) + emit setMenu(); - messageTabs.remove(tab->getUserName()); - removeTab(indexOf(tab)); + messageTabs.remove(tab->getUserName()); + removeTab(indexOf(tab)); } TabDeckEditor *TabSupervisor::addDeckEditorTab(const DeckLoader *deckToOpen) { - TabDeckEditor *tab = new TabDeckEditor(this); - if (deckToOpen) - tab->setDeck(new DeckLoader(*deckToOpen)); - connect(tab, SIGNAL(deckEditorClosing(TabDeckEditor *)), this, SLOT(deckEditorClosed(TabDeckEditor *))); - int tabIndex = myAddTab(tab); - addCloseButtonToTab(tab, tabIndex); - deckEditorTabs.append(tab); - setCurrentWidget(tab); - return tab; + TabDeckEditor *tab = new TabDeckEditor(this); + if (deckToOpen) + tab->setDeck(new DeckLoader(*deckToOpen)); + connect(tab, SIGNAL(deckEditorClosing(TabDeckEditor *)), this, SLOT(deckEditorClosed(TabDeckEditor *))); + int tabIndex = myAddTab(tab); + addCloseButtonToTab(tab, tabIndex); + deckEditorTabs.append(tab); + setCurrentWidget(tab); + return tab; } void TabSupervisor::deckEditorClosed(TabDeckEditor *tab) { - if (tab == currentWidget()) - emit setMenu(); - - deckEditorTabs.removeAt(deckEditorTabs.indexOf(tab)); - removeTab(indexOf(tab)); + if (tab == currentWidget()) + emit setMenu(); + + deckEditorTabs.removeAt(deckEditorTabs.indexOf(tab)); + removeTab(indexOf(tab)); } void TabSupervisor::tabUserEvent(bool globalEvent) { - Tab *tab = static_cast(sender()); - if (tab != currentWidget()) { - tab->setContentsChanged(true); - setTabIcon(indexOf(tab), *tabChangedIcon); - } - if (globalEvent && settingsCache->getNotificationsEnabled()) - QApplication::alert(this); + Tab *tab = static_cast(sender()); + if (tab != currentWidget()) { + tab->setContentsChanged(true); + setTabIcon(indexOf(tab), *tabChangedIcon); + } + if (globalEvent && settingsCache->getNotificationsEnabled()) + QApplication::alert(this); } void TabSupervisor::updateTabText(Tab *tab, const QString &newTabText) { - setTabText(indexOf(tab), newTabText); + setTabText(indexOf(tab), newTabText); } void TabSupervisor::processRoomEvent(const RoomEvent &event) { - TabRoom *tab = roomTabs.value(event.room_id(), 0); - if (tab) - tab->processRoomEvent(event); + TabRoom *tab = roomTabs.value(event.room_id(), 0); + if (tab) + tab->processRoomEvent(event); } void TabSupervisor::processGameEventContainer(const GameEventContainer &cont) { - TabGame *tab = gameTabs.value(cont.game_id()); - if (tab) - tab->processGameEventContainer(cont, qobject_cast(sender())); - else - qDebug() << "gameEvent: invalid gameId"; + TabGame *tab = gameTabs.value(cont.game_id()); + if (tab) + tab->processGameEventContainer(cont, qobject_cast(sender())); + else + qDebug() << "gameEvent: invalid gameId"; } void TabSupervisor::processUserMessageEvent(const Event_UserMessage &event) { - TabMessage *tab = messageTabs.value(QString::fromStdString(event.sender_name())); - if (!tab) - tab = messageTabs.value(QString::fromStdString(event.receiver_name())); - if (!tab) - tab = addMessageTab(QString::fromStdString(event.sender_name()), false); - if (!tab) - return; - tab->processUserMessageEvent(event); + TabMessage *tab = messageTabs.value(QString::fromStdString(event.sender_name())); + if (!tab) + tab = messageTabs.value(QString::fromStdString(event.receiver_name())); + if (!tab) + tab = addMessageTab(QString::fromStdString(event.sender_name()), false); + if (!tab) + return; + tab->processUserMessageEvent(event); } void TabSupervisor::processUserLeft(const QString &userName) { - TabMessage *tab = messageTabs.value(userName); - if (tab) - tab->processUserLeft(); + TabMessage *tab = messageTabs.value(userName); + if (tab) + tab->processUserLeft(); } void TabSupervisor::processUserJoined(const ServerInfo_User &userInfo) { - TabMessage *tab = messageTabs.value(QString::fromStdString(userInfo.name())); - if (tab) - tab->processUserJoined(userInfo); + TabMessage *tab = messageTabs.value(QString::fromStdString(userInfo.name())); + if (tab) + tab->processUserJoined(userInfo); } void TabSupervisor::updateCurrent(int index) { - if (index != -1) { - Tab *tab = static_cast(widget(index)); - if (tab->getContentsChanged()) { - setTabIcon(index, QIcon()); - tab->setContentsChanged(false); - } - emit setMenu(static_cast(widget(index))->getTabMenus()); - } else - emit setMenu(); + if (index != -1) { + Tab *tab = static_cast(widget(index)); + if (tab->getContentsChanged()) { + setTabIcon(index, QIcon()); + tab->setContentsChanged(false); + } + emit setMenu(static_cast(widget(index))->getTabMenus()); + } else + emit setMenu(); } bool TabSupervisor::getAdminLocked() const { - if (!tabAdmin) - return true; - return tabAdmin->getLocked(); + if (!tabAdmin) + return true; + return tabAdmin->getLocked(); } diff --git a/cockatrice/src/tab_supervisor.h b/cockatrice/src/tab_supervisor.h index 70941e12..48af3c8a 100644 --- a/cockatrice/src/tab_supervisor.h +++ b/cockatrice/src/tab_supervisor.h @@ -28,76 +28,76 @@ class GameReplay; class DeckList; class CloseButton : public QAbstractButton { - Q_OBJECT + Q_OBJECT public: - CloseButton(QWidget *parent = 0); - QSize sizeHint() const; - inline QSize minimumSizeHint() const { return sizeHint(); } + CloseButton(QWidget *parent = 0); + QSize sizeHint() const; + inline QSize minimumSizeHint() const { return sizeHint(); } protected: - void enterEvent(QEvent *event); - void leaveEvent(QEvent *event); - void paintEvent(QPaintEvent *event); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + void paintEvent(QPaintEvent *event); }; class TabSupervisor : public QTabWidget { - Q_OBJECT + Q_OBJECT private: - ServerInfo_User *userInfo; - QIcon *tabChangedIcon; - AbstractClient *client; - QList localClients; - TabServer *tabServer; - TabUserLists *tabUserLists; - TabDeckStorage *tabDeckStorage; - TabReplays *tabReplays; - TabAdmin *tabAdmin; - QMap roomTabs; - QMap gameTabs; - QList replayTabs; - QMap messageTabs; - QList deckEditorTabs; - int myAddTab(Tab *tab); - void addCloseButtonToTab(Tab *tab, int tabIndex); + ServerInfo_User *userInfo; + QIcon *tabChangedIcon; + AbstractClient *client; + QList localClients; + TabServer *tabServer; + TabUserLists *tabUserLists; + TabDeckStorage *tabDeckStorage; + TabReplays *tabReplays; + TabAdmin *tabAdmin; + QMap roomTabs; + QMap gameTabs; + QList replayTabs; + QMap messageTabs; + QList deckEditorTabs; + int myAddTab(Tab *tab); + void addCloseButtonToTab(Tab *tab, int tabIndex); public: - TabSupervisor(AbstractClient *_client, QWidget *parent = 0); - ~TabSupervisor(); - void retranslateUi(); - void start(const ServerInfo_User &userInfo); - void startLocal(const QList &_clients); - void stop(); - int getGameCount() const { return gameTabs.size(); } - TabUserLists *getUserListsTab() const { return tabUserLists; } - ServerInfo_User *getUserInfo() const { return userInfo; } - AbstractClient *getClient() const; - const QMap &getRoomTabs() const { return roomTabs; } - bool getAdminLocked() const; + TabSupervisor(AbstractClient *_client, QWidget *parent = 0); + ~TabSupervisor(); + void retranslateUi(); + void start(const ServerInfo_User &userInfo); + void startLocal(const QList &_clients); + void stop(); + int getGameCount() const { return gameTabs.size(); } + TabUserLists *getUserListsTab() const { return tabUserLists; } + ServerInfo_User *getUserInfo() const { return userInfo; } + AbstractClient *getClient() const; + const QMap &getRoomTabs() const { return roomTabs; } + bool getAdminLocked() const; signals: - void setMenu(const QList &newMenuList = QList()); - void localGameEnded(); - void adminLockChanged(bool lock); + void setMenu(const QList &newMenuList = QList()); + void localGameEnded(); + void adminLockChanged(bool lock); public slots: - TabDeckEditor *addDeckEditorTab(const DeckLoader *deckToOpen); - void openReplay(GameReplay *replay); + TabDeckEditor *addDeckEditorTab(const DeckLoader *deckToOpen); + void openReplay(GameReplay *replay); private slots: - void closeButtonPressed(); - void updateCurrent(int index); - void updatePingTime(int value, int max); - void gameJoined(const Event_GameJoined &event); - void localGameJoined(const Event_GameJoined &event); - void gameLeft(TabGame *tab); - void addRoomTab(const ServerInfo_Room &info, bool setCurrent); - void roomLeft(TabRoom *tab); - TabMessage *addMessageTab(const QString &userName, bool focus); - void replayLeft(TabGame *tab); - void processUserLeft(const QString &userName); - void processUserJoined(const ServerInfo_User &userInfo); - void talkLeft(TabMessage *tab); - void deckEditorClosed(TabDeckEditor *tab); - void tabUserEvent(bool globalEvent); - void updateTabText(Tab *tab, const QString &newTabText); - void processRoomEvent(const RoomEvent &event); - void processGameEventContainer(const GameEventContainer &cont); - void processUserMessageEvent(const Event_UserMessage &event); + void closeButtonPressed(); + void updateCurrent(int index); + void updatePingTime(int value, int max); + void gameJoined(const Event_GameJoined &event); + void localGameJoined(const Event_GameJoined &event); + void gameLeft(TabGame *tab); + void addRoomTab(const ServerInfo_Room &info, bool setCurrent); + void roomLeft(TabRoom *tab); + TabMessage *addMessageTab(const QString &userName, bool focus); + void replayLeft(TabGame *tab); + void processUserLeft(const QString &userName); + void processUserJoined(const ServerInfo_User &userInfo); + void talkLeft(TabMessage *tab); + void deckEditorClosed(TabDeckEditor *tab); + void tabUserEvent(bool globalEvent); + void updateTabText(Tab *tab, const QString &newTabText); + void processRoomEvent(const RoomEvent &event); + void processGameEventContainer(const GameEventContainer &cont); + void processUserMessageEvent(const Event_UserMessage &event); }; #endif diff --git a/cockatrice/src/tab_userlists.cpp b/cockatrice/src/tab_userlists.cpp index 4059a3e7..3ad1d96a 100644 --- a/cockatrice/src/tab_userlists.cpp +++ b/cockatrice/src/tab_userlists.cpp @@ -14,137 +14,137 @@ #include "pb/event_remove_from_list.pb.h" TabUserLists::TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent) - : Tab(_tabSupervisor, parent), client(_client) + : Tab(_tabSupervisor, parent), client(_client) { - allUsersList = new UserList(_tabSupervisor, client, UserList::AllUsersList); - buddyList = new UserList(_tabSupervisor, client, UserList::BuddyList); - ignoreList = new UserList(_tabSupervisor, client, UserList::IgnoreList); - userInfoBox = new UserInfoBox(client, false); - userInfoBox->updateInfo(userInfo); - - connect(allUsersList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - connect(buddyList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - connect(ignoreList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); - - connect(client, SIGNAL(userJoinedEventReceived(const Event_UserJoined &)), this, SLOT(processUserJoinedEvent(const Event_UserJoined &))); - connect(client, SIGNAL(userLeftEventReceived(const Event_UserLeft &)), this, SLOT(processUserLeftEvent(const Event_UserLeft &))); - connect(client, SIGNAL(buddyListReceived(const QList &)), this, SLOT(buddyListReceived(const QList &))); - connect(client, SIGNAL(ignoreListReceived(const QList &)), this, SLOT(ignoreListReceived(const QList &))); - connect(client, SIGNAL(addToListEventReceived(const Event_AddToList &)), this, SLOT(processAddToListEvent(const Event_AddToList &))); - connect(client, SIGNAL(removeFromListEventReceived(const Event_RemoveFromList &)), this, SLOT(processRemoveFromListEvent(const Event_RemoveFromList &))); - - PendingCommand *pend = client->prepareSessionCommand(Command_ListUsers()); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processListUsersResponse(const Response &))); - client->sendCommand(pend); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(userInfoBox); - vbox->addWidget(allUsersList); - - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addWidget(buddyList); - mainLayout->addWidget(ignoreList); - mainLayout->addLayout(vbox); - - setLayout(mainLayout); + allUsersList = new UserList(_tabSupervisor, client, UserList::AllUsersList); + buddyList = new UserList(_tabSupervisor, client, UserList::BuddyList); + ignoreList = new UserList(_tabSupervisor, client, UserList::IgnoreList); + userInfoBox = new UserInfoBox(client, false); + userInfoBox->updateInfo(userInfo); + + connect(allUsersList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + connect(buddyList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + connect(ignoreList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool))); + + connect(client, SIGNAL(userJoinedEventReceived(const Event_UserJoined &)), this, SLOT(processUserJoinedEvent(const Event_UserJoined &))); + connect(client, SIGNAL(userLeftEventReceived(const Event_UserLeft &)), this, SLOT(processUserLeftEvent(const Event_UserLeft &))); + connect(client, SIGNAL(buddyListReceived(const QList &)), this, SLOT(buddyListReceived(const QList &))); + connect(client, SIGNAL(ignoreListReceived(const QList &)), this, SLOT(ignoreListReceived(const QList &))); + connect(client, SIGNAL(addToListEventReceived(const Event_AddToList &)), this, SLOT(processAddToListEvent(const Event_AddToList &))); + connect(client, SIGNAL(removeFromListEventReceived(const Event_RemoveFromList &)), this, SLOT(processRemoveFromListEvent(const Event_RemoveFromList &))); + + PendingCommand *pend = client->prepareSessionCommand(Command_ListUsers()); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processListUsersResponse(const Response &))); + client->sendCommand(pend); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(userInfoBox); + vbox->addWidget(allUsersList); + + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addWidget(buddyList); + mainLayout->addWidget(ignoreList); + mainLayout->addLayout(vbox); + + setLayout(mainLayout); } void TabUserLists::retranslateUi() { - allUsersList->retranslateUi(); - buddyList->retranslateUi(); - ignoreList->retranslateUi(); - userInfoBox->retranslateUi(); + allUsersList->retranslateUi(); + buddyList->retranslateUi(); + ignoreList->retranslateUi(); + userInfoBox->retranslateUi(); } void TabUserLists::processListUsersResponse(const Response &response) { - const Response_ListUsers &resp = response.GetExtension(Response_ListUsers::ext); - - const int userListSize = resp.user_list_size(); - for (int i = 0; i < userListSize; ++i) { - const ServerInfo_User &info = resp.user_list(i); - const QString userName = QString::fromStdString(info.name()); - allUsersList->processUserInfo(info, true); - ignoreList->setUserOnline(userName, true); - buddyList->setUserOnline(userName, true); - } - - allUsersList->sortItems(); - ignoreList->sortItems(); - buddyList->sortItems(); + const Response_ListUsers &resp = response.GetExtension(Response_ListUsers::ext); + + const int userListSize = resp.user_list_size(); + for (int i = 0; i < userListSize; ++i) { + const ServerInfo_User &info = resp.user_list(i); + const QString userName = QString::fromStdString(info.name()); + allUsersList->processUserInfo(info, true); + ignoreList->setUserOnline(userName, true); + buddyList->setUserOnline(userName, true); + } + + allUsersList->sortItems(); + ignoreList->sortItems(); + buddyList->sortItems(); } void TabUserLists::processUserJoinedEvent(const Event_UserJoined &event) { - const ServerInfo_User &info = event.user_info(); - const QString userName = QString::fromStdString(info.name()); - - allUsersList->processUserInfo(info, true); - ignoreList->setUserOnline(userName, true); - buddyList->setUserOnline(userName, true); - - allUsersList->sortItems(); - ignoreList->sortItems(); - buddyList->sortItems(); - - emit userJoined(info); + const ServerInfo_User &info = event.user_info(); + const QString userName = QString::fromStdString(info.name()); + + allUsersList->processUserInfo(info, true); + ignoreList->setUserOnline(userName, true); + buddyList->setUserOnline(userName, true); + + allUsersList->sortItems(); + ignoreList->sortItems(); + buddyList->sortItems(); + + emit userJoined(info); } void TabUserLists::processUserLeftEvent(const Event_UserLeft &event) { - QString userName = QString::fromStdString(event.name()); - if (allUsersList->deleteUser(userName)) { - ignoreList->setUserOnline(userName, false); - buddyList->setUserOnline(userName, false); - ignoreList->sortItems(); - buddyList->sortItems(); - - emit userLeft(userName); - } + QString userName = QString::fromStdString(event.name()); + if (allUsersList->deleteUser(userName)) { + ignoreList->setUserOnline(userName, false); + buddyList->setUserOnline(userName, false); + ignoreList->sortItems(); + buddyList->sortItems(); + + emit userLeft(userName); + } } void TabUserLists::buddyListReceived(const QList &_buddyList) { - for (int i = 0; i < _buddyList.size(); ++i) - buddyList->processUserInfo(_buddyList[i], false); - buddyList->sortItems(); + for (int i = 0; i < _buddyList.size(); ++i) + buddyList->processUserInfo(_buddyList[i], false); + buddyList->sortItems(); } void TabUserLists::ignoreListReceived(const QList &_ignoreList) { - for (int i = 0; i < _ignoreList.size(); ++i) - ignoreList->processUserInfo(_ignoreList[i], false); - ignoreList->sortItems(); + for (int i = 0; i < _ignoreList.size(); ++i) + ignoreList->processUserInfo(_ignoreList[i], false); + ignoreList->sortItems(); } void TabUserLists::processAddToListEvent(const Event_AddToList &event) { - const ServerInfo_User &info = event.user_info(); - bool online = allUsersList->getUsers().contains(QString::fromStdString(info.name())); - QString list = QString::fromStdString(event.list_name()); - UserList *userList = 0; - if (list == "buddy") - userList = buddyList; - else if (list == "ignore") - userList = ignoreList; - if (!userList) - return; - - userList->processUserInfo(info, online); - userList->sortItems(); + const ServerInfo_User &info = event.user_info(); + bool online = allUsersList->getUsers().contains(QString::fromStdString(info.name())); + QString list = QString::fromStdString(event.list_name()); + UserList *userList = 0; + if (list == "buddy") + userList = buddyList; + else if (list == "ignore") + userList = ignoreList; + if (!userList) + return; + + userList->processUserInfo(info, online); + userList->sortItems(); } void TabUserLists::processRemoveFromListEvent(const Event_RemoveFromList &event) { - QString list = QString::fromStdString(event.list_name()); - QString user = QString::fromStdString(event.user_name()); - UserList *userList = 0; - if (list == "buddy") - userList = buddyList; - else if (list == "ignore") - userList = ignoreList; - if (!userList) - return; - userList->deleteUser(user); + QString list = QString::fromStdString(event.list_name()); + QString user = QString::fromStdString(event.user_name()); + UserList *userList = 0; + if (list == "buddy") + userList = buddyList; + else if (list == "ignore") + userList = ignoreList; + if (!userList) + return; + userList->deleteUser(user); } diff --git a/cockatrice/src/tab_userlists.h b/cockatrice/src/tab_userlists.h index 866ae579..90e25604 100644 --- a/cockatrice/src/tab_userlists.h +++ b/cockatrice/src/tab_userlists.h @@ -17,32 +17,32 @@ class Event_AddToList; class Event_RemoveFromList; class TabUserLists : public Tab { - Q_OBJECT + Q_OBJECT signals: - void openMessageDialog(const QString &userName, bool focus); - void userLeft(const QString &userName); - void userJoined(const ServerInfo_User &userInfo); + void openMessageDialog(const QString &userName, bool focus); + void userLeft(const QString &userName); + void userJoined(const ServerInfo_User &userInfo); private slots: - void processListUsersResponse(const Response &response); - void processUserJoinedEvent(const Event_UserJoined &event); - void processUserLeftEvent(const Event_UserLeft &event); - void buddyListReceived(const QList &_buddyList); - void ignoreListReceived(const QList &_ignoreList); - void processAddToListEvent(const Event_AddToList &event); - void processRemoveFromListEvent(const Event_RemoveFromList &event); + void processListUsersResponse(const Response &response); + void processUserJoinedEvent(const Event_UserJoined &event); + void processUserLeftEvent(const Event_UserLeft &event); + void buddyListReceived(const QList &_buddyList); + void ignoreListReceived(const QList &_ignoreList); + void processAddToListEvent(const Event_AddToList &event); + void processRemoveFromListEvent(const Event_RemoveFromList &event); private: - AbstractClient *client; - UserList *allUsersList; - UserList *buddyList; - UserList *ignoreList; - UserInfoBox *userInfoBox; + AbstractClient *client; + UserList *allUsersList; + UserList *buddyList; + UserList *ignoreList; + UserInfoBox *userInfoBox; public: - TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent = 0); - void retranslateUi(); - QString getTabText() const { return tr("User lists"); } - const UserList *getAllUsersList() const { return allUsersList; } - const UserList *getBuddyList() const { return buddyList; } - const UserList *getIgnoreList() const { return ignoreList; } + TabUserLists(TabSupervisor *_tabSupervisor, AbstractClient *_client, const ServerInfo_User &userInfo, QWidget *parent = 0); + void retranslateUi(); + QString getTabText() const { return tr("User lists"); } + const UserList *getAllUsersList() const { return allUsersList; } + const UserList *getBuddyList() const { return buddyList; } + const UserList *getIgnoreList() const { return ignoreList; } }; #endif diff --git a/cockatrice/src/tablezone.cpp b/cockatrice/src/tablezone.cpp index 63c17a5f..49965929 100644 --- a/cockatrice/src/tablezone.cpp +++ b/cockatrice/src/tablezone.cpp @@ -14,306 +14,306 @@ #include "pb/command_set_card_attr.pb.h" TableZone::TableZone(Player *_p, QGraphicsItem *parent) - : SelectZone(_p, "table", true, false, true, parent), active(false) + : SelectZone(_p, "table", true, false, true, parent), active(false) { - connect(settingsCache, SIGNAL(tableBgPathChanged()), this, SLOT(updateBgPixmap())); - connect(settingsCache, SIGNAL(invertVerticalCoordinateChanged()), this, SLOT(reorganizeCards())); - updateBgPixmap(); + connect(settingsCache, SIGNAL(tableBgPathChanged()), this, SLOT(updateBgPixmap())); + connect(settingsCache, SIGNAL(invertVerticalCoordinateChanged()), this, SLOT(reorganizeCards())); + updateBgPixmap(); - height = 2 * boxLineWidth + 3 * (CARD_HEIGHT + 20) + 2 * paddingY; - width = minWidth + 2 * marginX + 2 * boxLineWidth; - currentMinimumWidth = minWidth; + height = 2 * boxLineWidth + 3 * (CARD_HEIGHT + 20) + 2 * paddingY; + width = minWidth + 2 * marginX + 2 * boxLineWidth; + currentMinimumWidth = minWidth; - setCacheMode(DeviceCoordinateCache); - setAcceptsHoverEvents(true); + setCacheMode(DeviceCoordinateCache); + setAcceptsHoverEvents(true); } void TableZone::updateBgPixmap() { - QString bgPath = settingsCache->getTableBgPath(); - if (!bgPath.isEmpty()) - bgPixmap.load(bgPath); - update(); + QString bgPath = settingsCache->getTableBgPath(); + if (!bgPath.isEmpty()) + bgPixmap.load(bgPath); + update(); } QRectF TableZone::boundingRect() const { - return QRectF(0, 0, width, height); + return QRectF(0, 0, width, height); } bool TableZone::isInverted() const { - return ((player->getMirrored() && !settingsCache->getInvertVerticalCoordinate()) || (!player->getMirrored() && settingsCache->getInvertVerticalCoordinate())); + return ((player->getMirrored() && !settingsCache->getInvertVerticalCoordinate()) || (!player->getMirrored() && settingsCache->getInvertVerticalCoordinate())); } void TableZone::paint(QPainter *painter, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) { - if (bgPixmap.isNull()) - painter->fillRect(boundingRect(), QColor(0, 0, 100)); - else - painter->fillRect(boundingRect(), QBrush(bgPixmap)); - painter->setPen(QColor(255, 255, 255, 40)); - qreal separatorY = 2 * (CARD_HEIGHT + 20 + paddingY) + boxLineWidth - paddingY / 2; - if (isInverted()) - separatorY = height - separatorY; - painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); - - if (active) { - QColor color1(255, 255, 255, 150); - QColor color2(255, 255, 255, 0); - QLinearGradient grad1(0, 0, 0, 1); - grad1.setCoordinateMode(QGradient::ObjectBoundingMode); - grad1.setColorAt(0, color1); - grad1.setColorAt(1, color2); - painter->fillRect(QRectF(0, 0, width, boxLineWidth), QBrush(grad1)); - - grad1.setFinalStop(1, 0); - painter->fillRect(QRectF(0, 0, boxLineWidth, height), QBrush(grad1)); - - grad1.setStart(0, 1); - grad1.setFinalStop(0, 0); - painter->fillRect(QRectF(0, height - boxLineWidth, width, boxLineWidth), QBrush(grad1)); - - grad1.setStart(1, 0); - painter->fillRect(QRectF(width - boxLineWidth, 0, boxLineWidth, height), QBrush(grad1)); - } + if (bgPixmap.isNull()) + painter->fillRect(boundingRect(), QColor(0, 0, 100)); + else + painter->fillRect(boundingRect(), QBrush(bgPixmap)); + painter->setPen(QColor(255, 255, 255, 40)); + qreal separatorY = 2 * (CARD_HEIGHT + 20 + paddingY) + boxLineWidth - paddingY / 2; + if (isInverted()) + separatorY = height - separatorY; + painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); + + if (active) { + QColor color1(255, 255, 255, 150); + QColor color2(255, 255, 255, 0); + QLinearGradient grad1(0, 0, 0, 1); + grad1.setCoordinateMode(QGradient::ObjectBoundingMode); + grad1.setColorAt(0, color1); + grad1.setColorAt(1, color2); + painter->fillRect(QRectF(0, 0, width, boxLineWidth), QBrush(grad1)); + + grad1.setFinalStop(1, 0); + painter->fillRect(QRectF(0, 0, boxLineWidth, height), QBrush(grad1)); + + grad1.setStart(0, 1); + grad1.setFinalStop(0, 0); + painter->fillRect(QRectF(0, height - boxLineWidth, width, boxLineWidth), QBrush(grad1)); + + grad1.setStart(1, 0); + painter->fillRect(QRectF(width - boxLineWidth, 0, boxLineWidth, height), QBrush(grad1)); + } } void TableZone::addCardImpl(CardItem *card, int _x, int _y) { - cards.append(card); - card->setGridPoint(QPoint(_x, _y)); + cards.append(card); + card->setGridPoint(QPoint(_x, _y)); - card->setParentItem(this); - card->setVisible(true); - card->update(); + card->setParentItem(this); + card->setVisible(true); + card->update(); } void TableZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint) { - handleDropEventByGrid(dragItems, startZone, mapToGrid(dropPoint)); + handleDropEventByGrid(dragItems, startZone, mapToGrid(dropPoint)); } void TableZone::handleDropEventByGrid(const QList &dragItems, CardZone *startZone, const QPoint &gridPoint) { - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(gridPoint.x()); - cmd.set_y(gridPoint.y()); - - for (int i = 0; i < dragItems.size(); ++i) { - CardToMove *ctm = cmd.mutable_cards_to_move()->add_card(); - ctm->set_card_id(dragItems[i]->getId()); - ctm->set_face_down(dragItems[i]->getFaceDown()); - ctm->set_pt(startZone->getName() == name ? std::string() : dragItems[i]->getItem()->getInfo()->getPowTough().toStdString()); - } - - startZone->getPlayer()->sendGameCommand(cmd); + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(gridPoint.x()); + cmd.set_y(gridPoint.y()); + + for (int i = 0; i < dragItems.size(); ++i) { + CardToMove *ctm = cmd.mutable_cards_to_move()->add_card(); + ctm->set_card_id(dragItems[i]->getId()); + ctm->set_face_down(dragItems[i]->getFaceDown()); + ctm->set_pt(startZone->getName() == name ? std::string() : dragItems[i]->getItem()->getInfo()->getPowTough().toStdString()); + } + + startZone->getPlayer()->sendGameCommand(cmd); } void TableZone::reorganizeCards() { - QList arrowsToUpdate; - - // Calculate table grid distortion so that the mapping functions work properly - QMap gridPointStackCount; - for (int i = 0; i < cards.size(); ++i) { - const QPoint &gridPoint = cards[i]->getGridPos(); - if (gridPoint.x() == -1) - continue; - - const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; - gridPointStackCount.insert(key, gridPointStackCount.value(key, 0) + 1); - } - gridPointWidth.clear(); - for (int i = 0; i < cards.size(); ++i) { - const QPoint &gridPoint = cards[i]->getGridPos(); - if (gridPoint.x() == -1) - continue; - - const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; - const int stackCount = gridPointStackCount.value(key, 0); - if (stackCount == 1) - gridPointWidth.insert(key, CARD_WIDTH * (1 + cards[i]->getAttachedCards().size() / 3.0)); - else - gridPointWidth.insert(key, CARD_WIDTH * (1 + (stackCount - 1) / 3.0)); - } - - for (int i = 0; i < cards.size(); ++i) { - QPoint gridPoint = cards[i]->getGridPos(); - if (gridPoint.x() == -1) - continue; - - QPointF mapPoint = mapFromGrid(gridPoint); - qreal x = mapPoint.x(); - qreal y = mapPoint.y(); - - int numberAttachedCards = cards[i]->getAttachedCards().size(); - qreal actualX = x + numberAttachedCards * CARD_WIDTH / 3.0; - qreal actualY = y; - if (numberAttachedCards) - actualY += 15; - - cards[i]->setPos(actualX, actualY); - cards[i]->setRealZValue((actualY + CARD_HEIGHT) * 100000 + (actualX + 1) * 100); - - QListIterator attachedCardIterator(cards[i]->getAttachedCards()); - int j = 0; - while (attachedCardIterator.hasNext()) { - ++j; - CardItem *attachedCard = attachedCardIterator.next(); - qreal childX = actualX - j * CARD_WIDTH / 3.0; - qreal childY = y + 5; - attachedCard->setPos(childX, childY); - attachedCard->setRealZValue((childY + CARD_HEIGHT) * 100000 + (childX + 1) * 100); + QList arrowsToUpdate; + + // Calculate table grid distortion so that the mapping functions work properly + QMap gridPointStackCount; + for (int i = 0; i < cards.size(); ++i) { + const QPoint &gridPoint = cards[i]->getGridPos(); + if (gridPoint.x() == -1) + continue; + + const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; + gridPointStackCount.insert(key, gridPointStackCount.value(key, 0) + 1); + } + gridPointWidth.clear(); + for (int i = 0; i < cards.size(); ++i) { + const QPoint &gridPoint = cards[i]->getGridPos(); + if (gridPoint.x() == -1) + continue; + + const int key = gridPoint.x() / 3 + gridPoint.y() * 1000; + const int stackCount = gridPointStackCount.value(key, 0); + if (stackCount == 1) + gridPointWidth.insert(key, CARD_WIDTH * (1 + cards[i]->getAttachedCards().size() / 3.0)); + else + gridPointWidth.insert(key, CARD_WIDTH * (1 + (stackCount - 1) / 3.0)); + } + + for (int i = 0; i < cards.size(); ++i) { + QPoint gridPoint = cards[i]->getGridPos(); + if (gridPoint.x() == -1) + continue; + + QPointF mapPoint = mapFromGrid(gridPoint); + qreal x = mapPoint.x(); + qreal y = mapPoint.y(); + + int numberAttachedCards = cards[i]->getAttachedCards().size(); + qreal actualX = x + numberAttachedCards * CARD_WIDTH / 3.0; + qreal actualY = y; + if (numberAttachedCards) + actualY += 15; + + cards[i]->setPos(actualX, actualY); + cards[i]->setRealZValue((actualY + CARD_HEIGHT) * 100000 + (actualX + 1) * 100); + + QListIterator attachedCardIterator(cards[i]->getAttachedCards()); + int j = 0; + while (attachedCardIterator.hasNext()) { + ++j; + CardItem *attachedCard = attachedCardIterator.next(); + qreal childX = actualX - j * CARD_WIDTH / 3.0; + qreal childY = y + 5; + attachedCard->setPos(childX, childY); + attachedCard->setRealZValue((childY + CARD_HEIGHT) * 100000 + (childX + 1) * 100); - arrowsToUpdate.append(attachedCard->getArrowsFrom()); - arrowsToUpdate.append(attachedCard->getArrowsTo()); - } - - arrowsToUpdate.append(cards[i]->getArrowsFrom()); - arrowsToUpdate.append(cards[i]->getArrowsTo()); - } + arrowsToUpdate.append(attachedCard->getArrowsFrom()); + arrowsToUpdate.append(attachedCard->getArrowsTo()); + } + + arrowsToUpdate.append(cards[i]->getArrowsFrom()); + arrowsToUpdate.append(cards[i]->getArrowsTo()); + } - QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); - while (arrowIterator.hasNext()) - arrowIterator.next()->updatePath(); - - resizeToContents(); - update(); + QSetIterator arrowIterator(QSet::fromList(arrowsToUpdate)); + while (arrowIterator.hasNext()) + arrowIterator.next()->updatePath(); + + resizeToContents(); + update(); } void TableZone::toggleTapped() { - QList selectedItems = scene()->selectedItems(); - bool tapAll = false; - for (int i = 0; i < selectedItems.size(); i++) - if (!qgraphicsitem_cast(selectedItems[i])->getTapped()) { - tapAll = true; - break; - } - QList< const ::google::protobuf::Message * > cmdList; - for (int i = 0; i < selectedItems.size(); i++) { - CardItem *temp = qgraphicsitem_cast(selectedItems[i]); - if (temp->getTapped() != tapAll) { - Command_SetCardAttr *cmd = new Command_SetCardAttr; - cmd->set_zone(name.toStdString()); - cmd->set_card_id(temp->getId()); - cmd->set_attribute(AttrTapped); - cmd->set_attr_value(tapAll ? "1" : "0"); - cmdList.append(cmd); - } - } - player->sendGameCommand(player->prepareGameCommand(cmdList)); + QList selectedItems = scene()->selectedItems(); + bool tapAll = false; + for (int i = 0; i < selectedItems.size(); i++) + if (!qgraphicsitem_cast(selectedItems[i])->getTapped()) { + tapAll = true; + break; + } + QList< const ::google::protobuf::Message * > cmdList; + for (int i = 0; i < selectedItems.size(); i++) { + CardItem *temp = qgraphicsitem_cast(selectedItems[i]); + if (temp->getTapped() != tapAll) { + Command_SetCardAttr *cmd = new Command_SetCardAttr; + cmd->set_zone(name.toStdString()); + cmd->set_card_id(temp->getId()); + cmd->set_attribute(AttrTapped); + cmd->set_attr_value(tapAll ? "1" : "0"); + cmdList.append(cmd); + } + } + player->sendGameCommand(player->prepareGameCommand(cmdList)); } CardItem *TableZone::takeCard(int position, int cardId, bool canResize) { - CardItem *result = CardZone::takeCard(position, cardId); - if (canResize) - resizeToContents(); - return result; + CardItem *result = CardZone::takeCard(position, cardId); + if (canResize) + resizeToContents(); + return result; } void TableZone::resizeToContents() { - int xMax = 0; - for (int i = 0; i < cards.size(); ++i) - if (cards[i]->pos().x() > xMax) - xMax = (int) cards[i]->pos().x(); - xMax += 2 * CARD_WIDTH; - if (xMax < minWidth) - xMax = minWidth; - currentMinimumWidth = xMax + 2 * marginX + 2 * boxLineWidth; - if (currentMinimumWidth != width) { - prepareGeometryChange(); - width = currentMinimumWidth; - emit sizeChanged(); - } + int xMax = 0; + for (int i = 0; i < cards.size(); ++i) + if (cards[i]->pos().x() > xMax) + xMax = (int) cards[i]->pos().x(); + xMax += 2 * CARD_WIDTH; + if (xMax < minWidth) + xMax = minWidth; + currentMinimumWidth = xMax + 2 * marginX + 2 * boxLineWidth; + if (currentMinimumWidth != width) { + prepareGeometryChange(); + width = currentMinimumWidth; + emit sizeChanged(); + } } CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const { - for (int i = 0; i < cards.size(); i++) - if (cards.at(i)->getGridPoint() == gridPoint) - return cards.at(i); - return 0; + for (int i = 0; i < cards.size(); i++) + if (cards.at(i)->getGridPoint() == gridPoint) + return cards.at(i); + return 0; } CardItem *TableZone::getCardFromCoords(const QPointF &point) const { - QPoint gridPoint = mapToGrid(point); - return getCardFromGrid(gridPoint); + QPoint gridPoint = mapToGrid(point); + return getCardFromGrid(gridPoint); } QPointF TableZone::mapFromGrid(QPoint gridPoint) const { - qreal x, y; - x = marginX + (gridPoint.x() % 3) * CARD_WIDTH / 3.0; - for (int i = 0; i < gridPoint.x() / 3; ++i) - x += gridPointWidth.value(gridPoint.y() * 1000 + i, CARD_WIDTH) + paddingX; - - if (isInverted()) - gridPoint.setY(2 - gridPoint.y()); - - y = boxLineWidth + gridPoint.y() * (CARD_HEIGHT + paddingY + 20) + (gridPoint.x() % 3) * 10; -/* - if (isInverted()) - y = height - CARD_HEIGHT - y; -*/ - return QPointF(x, y); + qreal x, y; + x = marginX + (gridPoint.x() % 3) * CARD_WIDTH / 3.0; + for (int i = 0; i < gridPoint.x() / 3; ++i) + x += gridPointWidth.value(gridPoint.y() * 1000 + i, CARD_WIDTH) + paddingX; + + if (isInverted()) + gridPoint.setY(2 - gridPoint.y()); + + y = boxLineWidth + gridPoint.y() * (CARD_HEIGHT + paddingY + 20) + (gridPoint.x() % 3) * 10; +/* + if (isInverted()) + y = height - CARD_HEIGHT - y; +*/ + return QPointF(x, y); } QPoint TableZone::mapToGrid(const QPointF &mapPoint) const { - qreal x = mapPoint.x() - marginX; - qreal y = mapPoint.y(); -/* if (isInverted()) - y = height - y; -*/ y -= boxLineWidth; - - if (x < 0) - x = 0; - else if (x > width - CARD_WIDTH - marginX) - x = width - CARD_WIDTH - marginX; - if (y < 0) - y = 0; - else if (y > height - CARD_HEIGHT) - y = height - CARD_HEIGHT; - - int resultY = round(y / (CARD_HEIGHT + paddingY + 20)); - if (isInverted()) - resultY = 2 - resultY; + qreal x = mapPoint.x() - marginX; + qreal y = mapPoint.y(); +/* if (isInverted()) + y = height - y; +*/ y -= boxLineWidth; + + if (x < 0) + x = 0; + else if (x > width - CARD_WIDTH - marginX) + x = width - CARD_WIDTH - marginX; + if (y < 0) + y = 0; + else if (y > height - CARD_HEIGHT) + y = height - CARD_HEIGHT; + + int resultY = round(y / (CARD_HEIGHT + paddingY + 20)); + if (isInverted()) + resultY = 2 - resultY; - int baseX = -1; - qreal oldTempX = 0, tempX = 0; - do { - ++baseX; - oldTempX = tempX; - tempX += gridPointWidth.value(resultY * 1000 + baseX, CARD_WIDTH) + paddingX; - } while (tempX < x + 1); - - qreal xdiff = x - oldTempX; - int resultX = baseX * 3 + qMin((int) floor(xdiff * 3 / CARD_WIDTH), 2); - return QPoint(resultX, resultY); + int baseX = -1; + qreal oldTempX = 0, tempX = 0; + do { + ++baseX; + oldTempX = tempX; + tempX += gridPointWidth.value(resultY * 1000 + baseX, CARD_WIDTH) + paddingX; + } while (tempX < x + 1); + + qreal xdiff = x - oldTempX; + int resultX = baseX * 3 + qMin((int) floor(xdiff * 3 / CARD_WIDTH), 2); + return QPoint(resultX, resultY); } QPointF TableZone::closestGridPoint(const QPointF &point) { - QPoint gridPoint = mapToGrid(point + QPoint(1, 1)); - gridPoint.setX((gridPoint.x() / 3) * 3); - if (getCardFromGrid(gridPoint)) - gridPoint.setX(gridPoint.x() + 1); - if (getCardFromGrid(gridPoint)) - gridPoint.setX(gridPoint.x() + 1); - return mapFromGrid(gridPoint); + QPoint gridPoint = mapToGrid(point + QPoint(1, 1)); + gridPoint.setX((gridPoint.x() / 3) * 3); + if (getCardFromGrid(gridPoint)) + gridPoint.setX(gridPoint.x() + 1); + if (getCardFromGrid(gridPoint)) + gridPoint.setX(gridPoint.x() + 1); + return mapFromGrid(gridPoint); } void TableZone::setWidth(qreal _width) { - prepareGeometryChange(); - width = _width; + prepareGeometryChange(); + width = _width; } diff --git a/cockatrice/src/tablezone.h b/cockatrice/src/tablezone.h index 44cca399..297f097f 100644 --- a/cockatrice/src/tablezone.h +++ b/cockatrice/src/tablezone.h @@ -5,46 +5,46 @@ #include "abstractcarditem.h" class TableZone : public SelectZone { - Q_OBJECT + Q_OBJECT signals: - void sizeChanged(); + void sizeChanged(); private: - static const int boxLineWidth = 10; - static const int paddingX = 35; - static const int paddingY = 10; - static const int marginX = 20; - static const int minWidth = 15 * CARD_WIDTH / 2; + static const int boxLineWidth = 10; + static const int paddingX = 35; + static const int paddingY = 10; + static const int marginX = 20; + static const int minWidth = 15 * CARD_WIDTH / 2; - QMap gridPointWidth; - int width, height; - int currentMinimumWidth; - QPixmap bgPixmap; - bool active; - bool isInverted() const; -private slots: - void updateBgPixmap(); + QMap gridPointWidth; + int width, height; + int currentMinimumWidth; + QPixmap bgPixmap; + bool active; + bool isInverted() const; +private slots: + void updateBgPixmap(); public slots: - void reorganizeCards(); + void reorganizeCards(); public: - TableZone(Player *_p, QGraphicsItem *parent = 0); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void toggleTapped(); - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - void handleDropEventByGrid(const QList &dragItems, CardZone *startZone, const QPoint &gridPoint); - CardItem *getCardFromGrid(const QPoint &gridPoint) const; - CardItem *getCardFromCoords(const QPointF &point) const; - QPointF mapFromGrid(QPoint gridPoint) const; - QPoint mapToGrid(const QPointF &mapPoint) const; - QPointF closestGridPoint(const QPointF &point); - CardItem *takeCard(int position, int cardId, bool canResize = true); - void resizeToContents(); - int getMinimumWidth() const { return currentMinimumWidth; } - void setWidth(qreal _width); - qreal getWidth() const { return width; } - void setActive(bool _active) { active = _active; update(); } + TableZone(Player *_p, QGraphicsItem *parent = 0); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void toggleTapped(); + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + void handleDropEventByGrid(const QList &dragItems, CardZone *startZone, const QPoint &gridPoint); + CardItem *getCardFromGrid(const QPoint &gridPoint) const; + CardItem *getCardFromCoords(const QPointF &point) const; + QPointF mapFromGrid(QPoint gridPoint) const; + QPoint mapToGrid(const QPointF &mapPoint) const; + QPointF closestGridPoint(const QPointF &point); + CardItem *takeCard(int position, int cardId, bool canResize = true); + void resizeToContents(); + int getMinimumWidth() const { return currentMinimumWidth; } + void setWidth(qreal _width); + qreal getWidth() const { return width; } + void setActive(bool _active) { active = _active; update(); } protected: - void addCardImpl(CardItem *card, int x, int y); + void addCardImpl(CardItem *card, int x, int y); }; #endif diff --git a/cockatrice/src/user_context_menu.cpp b/cockatrice/src/user_context_menu.cpp index 657dc40b..eab48f47 100644 --- a/cockatrice/src/user_context_menu.cpp +++ b/cockatrice/src/user_context_menu.cpp @@ -18,181 +18,181 @@ #include "pb/response_get_user_info.pb.h" UserContextMenu::UserContextMenu(const TabSupervisor *_tabSupervisor, QWidget *parent, TabGame *_game) - : QObject(parent), client(_tabSupervisor->getClient()), tabSupervisor(_tabSupervisor), game(_game) + : QObject(parent), client(_tabSupervisor->getClient()), tabSupervisor(_tabSupervisor), game(_game) { - aUserName = new QAction(QString(), this); - aUserName->setEnabled(false); - aDetails = new QAction(QString(), this); - aChat = new QAction(QString(), this); - aShowGames = new QAction(QString(), this); - aAddToBuddyList = new QAction(QString(), this); - aRemoveFromBuddyList = new QAction(QString(), this); - aAddToIgnoreList = new QAction(QString(), this); - aRemoveFromIgnoreList = new QAction(QString(), this); - aKick = new QAction(QString(), this); - aBan = new QAction(QString(), this); - - retranslateUi(); + aUserName = new QAction(QString(), this); + aUserName->setEnabled(false); + aDetails = new QAction(QString(), this); + aChat = new QAction(QString(), this); + aShowGames = new QAction(QString(), this); + aAddToBuddyList = new QAction(QString(), this); + aRemoveFromBuddyList = new QAction(QString(), this); + aAddToIgnoreList = new QAction(QString(), this); + aRemoveFromIgnoreList = new QAction(QString(), this); + aKick = new QAction(QString(), this); + aBan = new QAction(QString(), this); + + retranslateUi(); } void UserContextMenu::retranslateUi() { - aDetails->setText(tr("User &details")); - aChat->setText(tr("Direct &chat")); - aShowGames->setText(tr("Show this user's &games")); - aAddToBuddyList->setText(tr("Add to &buddy list")); - aRemoveFromBuddyList->setText(tr("Remove from &buddy list")); - aAddToIgnoreList->setText(tr("Add to &ignore list")); - aRemoveFromIgnoreList->setText(tr("Remove from &ignore list")); - aKick->setText(tr("Kick from &game")); - aBan->setText(tr("Ban from &server")); + aDetails->setText(tr("User &details")); + aChat->setText(tr("Direct &chat")); + aShowGames->setText(tr("Show this user's &games")); + aAddToBuddyList->setText(tr("Add to &buddy list")); + aRemoveFromBuddyList->setText(tr("Remove from &buddy list")); + aAddToIgnoreList->setText(tr("Add to &ignore list")); + aRemoveFromIgnoreList->setText(tr("Remove from &ignore list")); + aKick->setText(tr("Kick from &game")); + aBan->setText(tr("Ban from &server")); } void UserContextMenu::gamesOfUserReceived(const Response &resp, const CommandContainer &commandContainer) { - const Response_GetGamesOfUser &response = resp.GetExtension(Response_GetGamesOfUser::ext); - const Command_GetGamesOfUser &cmd = commandContainer.session_command(0).GetExtension(Command_GetGamesOfUser::ext); - - QMap gameTypeMap; - QMap roomMap; - const int roomListSize = response.room_list_size(); - for (int i = 0; i < roomListSize; ++i) { - const ServerInfo_Room &roomInfo = response.room_list(i); - roomMap.insert(roomInfo.room_id(), QString::fromStdString(roomInfo.name())); - GameTypeMap tempMap; - const int gameTypeListSize = roomInfo.gametype_list_size(); - for (int j = 0; j < gameTypeListSize; ++j) { - const ServerInfo_GameType &gameTypeInfo = roomInfo.gametype_list(j); - tempMap.insert(gameTypeInfo.game_type_id(), QString::fromStdString(gameTypeInfo.description())); - } - gameTypeMap.insert(roomInfo.room_id(), tempMap); - } - - GameSelector *selector = new GameSelector(client, tabSupervisor, 0, roomMap, gameTypeMap); - const int gameListSize = response.game_list_size(); - for (int i = 0; i < gameListSize; ++i) - selector->processGameInfo(response.game_list(i)); - - selector->setWindowTitle(tr("%1's games").arg(QString::fromStdString(cmd.user_name()))); - selector->setAttribute(Qt::WA_DeleteOnClose); - selector->show(); + const Response_GetGamesOfUser &response = resp.GetExtension(Response_GetGamesOfUser::ext); + const Command_GetGamesOfUser &cmd = commandContainer.session_command(0).GetExtension(Command_GetGamesOfUser::ext); + + QMap gameTypeMap; + QMap roomMap; + const int roomListSize = response.room_list_size(); + for (int i = 0; i < roomListSize; ++i) { + const ServerInfo_Room &roomInfo = response.room_list(i); + roomMap.insert(roomInfo.room_id(), QString::fromStdString(roomInfo.name())); + GameTypeMap tempMap; + const int gameTypeListSize = roomInfo.gametype_list_size(); + for (int j = 0; j < gameTypeListSize; ++j) { + const ServerInfo_GameType &gameTypeInfo = roomInfo.gametype_list(j); + tempMap.insert(gameTypeInfo.game_type_id(), QString::fromStdString(gameTypeInfo.description())); + } + gameTypeMap.insert(roomInfo.room_id(), tempMap); + } + + GameSelector *selector = new GameSelector(client, tabSupervisor, 0, roomMap, gameTypeMap); + const int gameListSize = response.game_list_size(); + for (int i = 0; i < gameListSize; ++i) + selector->processGameInfo(response.game_list(i)); + + selector->setWindowTitle(tr("%1's games").arg(QString::fromStdString(cmd.user_name()))); + selector->setAttribute(Qt::WA_DeleteOnClose); + selector->show(); } void UserContextMenu::banUser_processUserInfoResponse(const Response &r) { - const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); - - // The dialog needs to be non-modal in order to not block the event queue of the client. - BanDialog *dlg = new BanDialog(response.user_info(), static_cast(parent())); - connect(dlg, SIGNAL(accepted()), this, SLOT(banUser_dialogFinished())); - dlg->show(); + const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); + + // The dialog needs to be non-modal in order to not block the event queue of the client. + BanDialog *dlg = new BanDialog(response.user_info(), static_cast(parent())); + connect(dlg, SIGNAL(accepted()), this, SLOT(banUser_dialogFinished())); + dlg->show(); } void UserContextMenu::banUser_dialogFinished() { - BanDialog *dlg = static_cast(sender()); - - Command_BanFromServer cmd; - cmd.set_user_name(dlg->getBanName().toStdString()); - cmd.set_address(dlg->getBanIP().toStdString()); - cmd.set_minutes(dlg->getMinutes()); - cmd.set_reason(dlg->getReason().toStdString()); - cmd.set_visible_reason(dlg->getVisibleReason().toStdString()); - - client->sendCommand(client->prepareModeratorCommand(cmd)); + BanDialog *dlg = static_cast(sender()); + + Command_BanFromServer cmd; + cmd.set_user_name(dlg->getBanName().toStdString()); + cmd.set_address(dlg->getBanIP().toStdString()); + cmd.set_minutes(dlg->getMinutes()); + cmd.set_reason(dlg->getReason().toStdString()); + cmd.set_visible_reason(dlg->getVisibleReason().toStdString()); + + client->sendCommand(client->prepareModeratorCommand(cmd)); } void UserContextMenu::showContextMenu(const QPoint &pos, const QString &userName, UserLevelFlags userLevel, int playerId) { - aUserName->setText(userName); - - QMenu *menu = new QMenu(static_cast(parent())); - menu->addAction(aUserName); - menu->addSeparator(); - menu->addAction(aDetails); - menu->addAction(aShowGames); - menu->addAction(aChat); - if (userLevel.testFlag(ServerInfo_User::IsRegistered) && (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsRegistered)) { - menu->addSeparator(); - if (tabSupervisor->getUserListsTab()->getBuddyList()->getUsers().contains(userName)) - menu->addAction(aRemoveFromBuddyList); - else - menu->addAction(aAddToBuddyList); - if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(userName)) - menu->addAction(aRemoveFromIgnoreList); - else - menu->addAction(aAddToIgnoreList); - } - if (game && (game->isHost() || !tabSupervisor->getAdminLocked())) { - menu->addSeparator(); - menu->addAction(aKick); - } - if (!tabSupervisor->getAdminLocked()) { - menu->addSeparator(); - menu->addAction(aBan); - } - bool anotherUser = userName != QString::fromStdString(tabSupervisor->getUserInfo()->name()); - aChat->setEnabled(anotherUser); - aShowGames->setEnabled(anotherUser); - aAddToBuddyList->setEnabled(anotherUser); - aRemoveFromBuddyList->setEnabled(anotherUser); - aAddToIgnoreList->setEnabled(anotherUser); - aRemoveFromIgnoreList->setEnabled(anotherUser); - aKick->setEnabled(anotherUser); - aBan->setEnabled(anotherUser); - - QAction *actionClicked = menu->exec(pos); - if (actionClicked == aDetails) { - UserInfoBox *infoWidget = new UserInfoBox(client, true, static_cast(parent()), Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); - infoWidget->setAttribute(Qt::WA_DeleteOnClose); - infoWidget->updateInfo(userName); - } else if (actionClicked == aChat) - emit openMessageDialog(userName, true); - else if (actionClicked == aShowGames) { - Command_GetGamesOfUser cmd; - cmd.set_user_name(userName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(gamesOfUserReceived(Response, CommandContainer))); - - client->sendCommand(pend); - } else if (actionClicked == aAddToBuddyList) { - Command_AddToList cmd; - cmd.set_list("buddy"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aRemoveFromBuddyList) { - Command_RemoveFromList cmd; - cmd.set_list("buddy"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aAddToIgnoreList) { - Command_AddToList cmd; - cmd.set_list("ignore"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aRemoveFromIgnoreList) { - Command_RemoveFromList cmd; - cmd.set_list("ignore"); - cmd.set_user_name(userName.toStdString()); - - client->sendCommand(client->prepareSessionCommand(cmd)); - } else if (actionClicked == aKick) { - Command_KickFromGame cmd; - cmd.set_player_id(playerId); - game->sendGameCommand(cmd); - } else if (actionClicked == aBan) { - Command_GetUserInfo cmd; - cmd.set_user_name(userName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(banUser_processUserInfoResponse(Response))); - - client->sendCommand(pend); - } - - delete menu; + aUserName->setText(userName); + + QMenu *menu = new QMenu(static_cast(parent())); + menu->addAction(aUserName); + menu->addSeparator(); + menu->addAction(aDetails); + menu->addAction(aShowGames); + menu->addAction(aChat); + if (userLevel.testFlag(ServerInfo_User::IsRegistered) && (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsRegistered)) { + menu->addSeparator(); + if (tabSupervisor->getUserListsTab()->getBuddyList()->getUsers().contains(userName)) + menu->addAction(aRemoveFromBuddyList); + else + menu->addAction(aAddToBuddyList); + if (tabSupervisor->getUserListsTab()->getIgnoreList()->getUsers().contains(userName)) + menu->addAction(aRemoveFromIgnoreList); + else + menu->addAction(aAddToIgnoreList); + } + if (game && (game->isHost() || !tabSupervisor->getAdminLocked())) { + menu->addSeparator(); + menu->addAction(aKick); + } + if (!tabSupervisor->getAdminLocked()) { + menu->addSeparator(); + menu->addAction(aBan); + } + bool anotherUser = userName != QString::fromStdString(tabSupervisor->getUserInfo()->name()); + aChat->setEnabled(anotherUser); + aShowGames->setEnabled(anotherUser); + aAddToBuddyList->setEnabled(anotherUser); + aRemoveFromBuddyList->setEnabled(anotherUser); + aAddToIgnoreList->setEnabled(anotherUser); + aRemoveFromIgnoreList->setEnabled(anotherUser); + aKick->setEnabled(anotherUser); + aBan->setEnabled(anotherUser); + + QAction *actionClicked = menu->exec(pos); + if (actionClicked == aDetails) { + UserInfoBox *infoWidget = new UserInfoBox(client, true, static_cast(parent()), Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); + infoWidget->setAttribute(Qt::WA_DeleteOnClose); + infoWidget->updateInfo(userName); + } else if (actionClicked == aChat) + emit openMessageDialog(userName, true); + else if (actionClicked == aShowGames) { + Command_GetGamesOfUser cmd; + cmd.set_user_name(userName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(gamesOfUserReceived(Response, CommandContainer))); + + client->sendCommand(pend); + } else if (actionClicked == aAddToBuddyList) { + Command_AddToList cmd; + cmd.set_list("buddy"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aRemoveFromBuddyList) { + Command_RemoveFromList cmd; + cmd.set_list("buddy"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aAddToIgnoreList) { + Command_AddToList cmd; + cmd.set_list("ignore"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aRemoveFromIgnoreList) { + Command_RemoveFromList cmd; + cmd.set_list("ignore"); + cmd.set_user_name(userName.toStdString()); + + client->sendCommand(client->prepareSessionCommand(cmd)); + } else if (actionClicked == aKick) { + Command_KickFromGame cmd; + cmd.set_player_id(playerId); + game->sendGameCommand(cmd); + } else if (actionClicked == aBan) { + Command_GetUserInfo cmd; + cmd.set_user_name(userName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(banUser_processUserInfoResponse(Response))); + + client->sendCommand(pend); + } + + delete menu; } diff --git a/cockatrice/src/user_context_menu.h b/cockatrice/src/user_context_menu.h index 7634b962..8e6708b0 100644 --- a/cockatrice/src/user_context_menu.h +++ b/cockatrice/src/user_context_menu.h @@ -13,30 +13,30 @@ class Response; class AbstractClient; class UserContextMenu : public QObject { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - const TabSupervisor *tabSupervisor; - TabGame *game; - - QAction *aUserName; - QAction *aDetails; - QAction *aShowGames; - QAction *aChat; - QAction *aAddToBuddyList, *aRemoveFromBuddyList; - QAction *aAddToIgnoreList, *aRemoveFromIgnoreList; - QAction *aKick; - QAction *aBan; + AbstractClient *client; + const TabSupervisor *tabSupervisor; + TabGame *game; + + QAction *aUserName; + QAction *aDetails; + QAction *aShowGames; + QAction *aChat; + QAction *aAddToBuddyList, *aRemoveFromBuddyList; + QAction *aAddToIgnoreList, *aRemoveFromIgnoreList; + QAction *aKick; + QAction *aBan; signals: - void openMessageDialog(const QString &userName, bool focus); + void openMessageDialog(const QString &userName, bool focus); private slots: - void banUser_processUserInfoResponse(const Response &resp); - void banUser_dialogFinished(); - void gamesOfUserReceived(const Response &resp, const CommandContainer &commandContainer); + void banUser_processUserInfoResponse(const Response &resp); + void banUser_dialogFinished(); + void gamesOfUserReceived(const Response &resp, const CommandContainer &commandContainer); public: - UserContextMenu(const TabSupervisor *_tabSupervisor, QWidget *_parent, TabGame *_game = 0); - void retranslateUi(); - void showContextMenu(const QPoint &pos, const QString &userName, UserLevelFlags userLevel, int playerId = -1); + UserContextMenu(const TabSupervisor *_tabSupervisor, QWidget *_parent, TabGame *_game = 0); + void retranslateUi(); + void showContextMenu(const QPoint &pos, const QString &userName, UserLevelFlags userLevel, int playerId = -1); }; #endif diff --git a/cockatrice/src/userinfobox.cpp b/cockatrice/src/userinfobox.cpp index 79d64afa..855cd748 100644 --- a/cockatrice/src/userinfobox.cpp +++ b/cockatrice/src/userinfobox.cpp @@ -9,93 +9,93 @@ #include "pb/response_get_user_info.pb.h" UserInfoBox::UserInfoBox(AbstractClient *_client, bool _fullInfo, QWidget *parent, Qt::WindowFlags flags) - : QWidget(parent, flags), client(_client), fullInfo(_fullInfo) + : QWidget(parent, flags), client(_client), fullInfo(_fullInfo) { - avatarLabel = new QLabel; - nameLabel = new QLabel; - QFont nameFont = nameLabel->font(); - nameFont.setBold(true); - nameFont.setPointSize(nameFont.pointSize() * 1.5); - nameLabel->setFont(nameFont); - realNameLabel1 = new QLabel; - realNameLabel2 = new QLabel; - genderLabel1 = new QLabel; - genderLabel2 = new QLabel; - countryLabel1 = new QLabel; - countryLabel2 = new QLabel; - userLevelLabel1 = new QLabel; - userLevelLabel2 = new QLabel; - userLevelLabel3 = new QLabel; - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(avatarLabel, 0, 0, 1, 3, Qt::AlignCenter); - mainLayout->addWidget(nameLabel, 1, 0, 1, 3); - mainLayout->addWidget(realNameLabel1, 2, 0, 1, 1); - mainLayout->addWidget(realNameLabel2, 2, 1, 1, 2); - mainLayout->addWidget(genderLabel1, 3, 0, 1, 1); - mainLayout->addWidget(genderLabel2, 3, 1, 1, 2); - mainLayout->addWidget(countryLabel1, 4, 0, 1, 1); - mainLayout->addWidget(countryLabel2, 4, 1, 1, 2); - mainLayout->addWidget(userLevelLabel1, 5, 0, 1, 1); - mainLayout->addWidget(userLevelLabel2, 5, 1, 1, 1); - mainLayout->addWidget(userLevelLabel3, 5, 2, 1, 1); - mainLayout->setColumnStretch(2, 10); - - setWindowTitle(tr("User information")); - setLayout(mainLayout); - retranslateUi(); + avatarLabel = new QLabel; + nameLabel = new QLabel; + QFont nameFont = nameLabel->font(); + nameFont.setBold(true); + nameFont.setPointSize(nameFont.pointSize() * 1.5); + nameLabel->setFont(nameFont); + realNameLabel1 = new QLabel; + realNameLabel2 = new QLabel; + genderLabel1 = new QLabel; + genderLabel2 = new QLabel; + countryLabel1 = new QLabel; + countryLabel2 = new QLabel; + userLevelLabel1 = new QLabel; + userLevelLabel2 = new QLabel; + userLevelLabel3 = new QLabel; + + QGridLayout *mainLayout = new QGridLayout; + mainLayout->addWidget(avatarLabel, 0, 0, 1, 3, Qt::AlignCenter); + mainLayout->addWidget(nameLabel, 1, 0, 1, 3); + mainLayout->addWidget(realNameLabel1, 2, 0, 1, 1); + mainLayout->addWidget(realNameLabel2, 2, 1, 1, 2); + mainLayout->addWidget(genderLabel1, 3, 0, 1, 1); + mainLayout->addWidget(genderLabel2, 3, 1, 1, 2); + mainLayout->addWidget(countryLabel1, 4, 0, 1, 1); + mainLayout->addWidget(countryLabel2, 4, 1, 1, 2); + mainLayout->addWidget(userLevelLabel1, 5, 0, 1, 1); + mainLayout->addWidget(userLevelLabel2, 5, 1, 1, 1); + mainLayout->addWidget(userLevelLabel3, 5, 2, 1, 1); + mainLayout->setColumnStretch(2, 10); + + setWindowTitle(tr("User information")); + setLayout(mainLayout); + retranslateUi(); } void UserInfoBox::retranslateUi() { - realNameLabel1->setText(tr("Real name:")); - genderLabel1->setText(tr("Gender:")); - countryLabel1->setText(tr("Location:")); - userLevelLabel1->setText(tr("User level:")); + realNameLabel1->setText(tr("Real name:")); + genderLabel1->setText(tr("Gender:")); + countryLabel1->setText(tr("Location:")); + userLevelLabel1->setText(tr("User level:")); } void UserInfoBox::updateInfo(const ServerInfo_User &user) { - const UserLevelFlags userLevel(user.user_level()); - - QPixmap avatarPixmap; - const std::string bmp = user.avatar_bmp(); - if (!avatarPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) - avatarPixmap = UserLevelPixmapGenerator::generatePixmap(64, userLevel); - avatarLabel->setPixmap(avatarPixmap); - - nameLabel->setText(QString::fromStdString(user.name())); - realNameLabel2->setText(QString::fromStdString(user.real_name())); - genderLabel2->setPixmap(GenderPixmapGenerator::generatePixmap(15, user.gender())); - countryLabel2->setPixmap(CountryPixmapGenerator::generatePixmap(15, QString::fromStdString(user.country()))); - userLevelLabel2->setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel)); - QString userLevelText; - if (userLevel.testFlag(ServerInfo_User::IsAdmin)) - userLevelText = tr("Administrator"); - else if (userLevel.testFlag(ServerInfo_User::IsModerator)) - userLevelText = tr("Moderator"); - else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) - userLevelText = tr("Registered user"); - else - userLevelText = tr("Unregistered user"); - userLevelLabel3->setText(userLevelText); + const UserLevelFlags userLevel(user.user_level()); + + QPixmap avatarPixmap; + const std::string bmp = user.avatar_bmp(); + if (!avatarPixmap.loadFromData((const uchar *) bmp.data(), bmp.size())) + avatarPixmap = UserLevelPixmapGenerator::generatePixmap(64, userLevel); + avatarLabel->setPixmap(avatarPixmap); + + nameLabel->setText(QString::fromStdString(user.name())); + realNameLabel2->setText(QString::fromStdString(user.real_name())); + genderLabel2->setPixmap(GenderPixmapGenerator::generatePixmap(15, user.gender())); + countryLabel2->setPixmap(CountryPixmapGenerator::generatePixmap(15, QString::fromStdString(user.country()))); + userLevelLabel2->setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel)); + QString userLevelText; + if (userLevel.testFlag(ServerInfo_User::IsAdmin)) + userLevelText = tr("Administrator"); + else if (userLevel.testFlag(ServerInfo_User::IsModerator)) + userLevelText = tr("Moderator"); + else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) + userLevelText = tr("Registered user"); + else + userLevelText = tr("Unregistered user"); + userLevelLabel3->setText(userLevelText); } void UserInfoBox::updateInfo(const QString &userName) { - Command_GetUserInfo cmd; - cmd.set_user_name(userName.toStdString()); - - PendingCommand *pend = client->prepareSessionCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processResponse(const Response &))); - - client->sendCommand(pend); + Command_GetUserInfo cmd; + cmd.set_user_name(userName.toStdString()); + + PendingCommand *pend = client->prepareSessionCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(processResponse(const Response &))); + + client->sendCommand(pend); } void UserInfoBox::processResponse(const Response &r) { - const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); - updateInfo(response.user_info()); - setFixedSize(sizeHint()); - show(); + const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); + updateInfo(response.user_info()); + setFixedSize(sizeHint()); + show(); } diff --git a/cockatrice/src/userinfobox.h b/cockatrice/src/userinfobox.h index 186ca8ff..5c47c4a2 100644 --- a/cockatrice/src/userinfobox.h +++ b/cockatrice/src/userinfobox.h @@ -9,19 +9,19 @@ class AbstractClient; class Response; class UserInfoBox : public QWidget { - Q_OBJECT + Q_OBJECT private: - AbstractClient *client; - bool fullInfo; - QLabel *avatarLabel, *nameLabel, *realNameLabel1, *realNameLabel2, *genderLabel1, *genderLabel2, *countryLabel1, *countryLabel2, *userLevelLabel1, *userLevelLabel2, *userLevelLabel3; + AbstractClient *client; + bool fullInfo; + QLabel *avatarLabel, *nameLabel, *realNameLabel1, *realNameLabel2, *genderLabel1, *genderLabel2, *countryLabel1, *countryLabel2, *userLevelLabel1, *userLevelLabel2, *userLevelLabel3; public: - UserInfoBox(AbstractClient *_client, bool fullInfo, QWidget *parent = 0, Qt::WindowFlags flags = 0); - void retranslateUi(); + UserInfoBox(AbstractClient *_client, bool fullInfo, QWidget *parent = 0, Qt::WindowFlags flags = 0); + void retranslateUi(); private slots: - void processResponse(const Response &r); + void processResponse(const Response &r); public slots: - void updateInfo(const ServerInfo_User &user); - void updateInfo(const QString &userName); + void updateInfo(const ServerInfo_User &user); + void updateInfo(const QString &userName); }; #endif diff --git a/cockatrice/src/userlist.cpp b/cockatrice/src/userlist.cpp index 205418f0..562d395b 100644 --- a/cockatrice/src/userlist.cpp +++ b/cockatrice/src/userlist.cpp @@ -27,291 +27,291 @@ #include "pb/response_get_user_info.pb.h" BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) - : QDialog(parent) + : QDialog(parent) { - setAttribute(Qt::WA_DeleteOnClose); - - nameBanCheckBox = new QCheckBox(tr("ban &user name")); - nameBanCheckBox->setChecked(true); - nameBanEdit = new QLineEdit(QString::fromStdString(info.name())); - ipBanCheckBox = new QCheckBox(tr("ban &IP address")); - ipBanCheckBox->setChecked(true); - ipBanEdit = new QLineEdit(QString::fromStdString(info.address())); - QGridLayout *banTypeGrid = new QGridLayout; - banTypeGrid->addWidget(nameBanCheckBox, 0, 0); - banTypeGrid->addWidget(nameBanEdit, 0, 1); - banTypeGrid->addWidget(ipBanCheckBox, 1, 0); - banTypeGrid->addWidget(ipBanEdit, 1, 1); - QGroupBox *banTypeGroupBox = new QGroupBox(tr("Ban type")); - banTypeGroupBox->setLayout(banTypeGrid); - - permanentRadio = new QRadioButton(tr("&permanent ban")); - temporaryRadio = new QRadioButton(tr("&temporary ban")); - temporaryRadio->setChecked(true); - connect(temporaryRadio, SIGNAL(toggled(bool)), this, SLOT(enableTemporaryEdits(bool))); - daysLabel = new QLabel(tr("&Days:")); - daysEdit = new QSpinBox; - daysEdit->setMinimum(0); - daysEdit->setValue(0); - daysEdit->setMaximum(10000); - daysLabel->setBuddy(daysEdit); - hoursLabel = new QLabel(tr("&Hours:")); - hoursEdit = new QSpinBox; - hoursEdit->setMinimum(0); - hoursEdit->setValue(0); - hoursEdit->setMaximum(24); - hoursLabel->setBuddy(hoursEdit); - minutesLabel = new QLabel(tr("&Minutes:")); - minutesEdit = new QSpinBox; - minutesEdit->setMinimum(0); - minutesEdit->setValue(5); - minutesEdit->setMaximum(60); - minutesLabel->setBuddy(minutesEdit); - QGridLayout *durationLayout = new QGridLayout; - durationLayout->addWidget(permanentRadio, 0, 0, 1, 6); - durationLayout->addWidget(temporaryRadio, 1, 0, 1, 6); - durationLayout->addWidget(daysLabel, 2, 0); - durationLayout->addWidget(daysEdit, 2, 1); - durationLayout->addWidget(hoursLabel, 2, 2); - durationLayout->addWidget(hoursEdit, 2, 3); - durationLayout->addWidget(minutesLabel, 2, 4); - durationLayout->addWidget(minutesEdit, 2, 5); - QGroupBox *durationGroupBox = new QGroupBox(tr("Duration of the ban")); - durationGroupBox->setLayout(durationLayout); - - QLabel *reasonLabel = new QLabel(tr("Please enter the reason for the ban.\nThis is only saved for moderators and cannot be seen by the banned person.")); - reasonEdit = new QPlainTextEdit; - - QLabel *visibleReasonLabel = new QLabel(tr("Please enter the reason for the ban that will be visible to the banned person.")); - visibleReasonEdit = new QPlainTextEdit; - - QPushButton *okButton = new QPushButton(tr("&OK")); - okButton->setAutoDefault(true); - connect(okButton, SIGNAL(clicked()), this, SLOT(okClicked())); - QPushButton *cancelButton = new QPushButton(tr("&Cancel")); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); - - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addStretch(); - buttonLayout->addWidget(okButton); - buttonLayout->addWidget(cancelButton); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(banTypeGroupBox); - vbox->addWidget(durationGroupBox); - vbox->addWidget(reasonLabel); - vbox->addWidget(reasonEdit); - vbox->addWidget(visibleReasonLabel); - vbox->addWidget(visibleReasonEdit); - vbox->addLayout(buttonLayout); - - setLayout(vbox); - setWindowTitle(tr("Ban user from server")); + setAttribute(Qt::WA_DeleteOnClose); + + nameBanCheckBox = new QCheckBox(tr("ban &user name")); + nameBanCheckBox->setChecked(true); + nameBanEdit = new QLineEdit(QString::fromStdString(info.name())); + ipBanCheckBox = new QCheckBox(tr("ban &IP address")); + ipBanCheckBox->setChecked(true); + ipBanEdit = new QLineEdit(QString::fromStdString(info.address())); + QGridLayout *banTypeGrid = new QGridLayout; + banTypeGrid->addWidget(nameBanCheckBox, 0, 0); + banTypeGrid->addWidget(nameBanEdit, 0, 1); + banTypeGrid->addWidget(ipBanCheckBox, 1, 0); + banTypeGrid->addWidget(ipBanEdit, 1, 1); + QGroupBox *banTypeGroupBox = new QGroupBox(tr("Ban type")); + banTypeGroupBox->setLayout(banTypeGrid); + + permanentRadio = new QRadioButton(tr("&permanent ban")); + temporaryRadio = new QRadioButton(tr("&temporary ban")); + temporaryRadio->setChecked(true); + connect(temporaryRadio, SIGNAL(toggled(bool)), this, SLOT(enableTemporaryEdits(bool))); + daysLabel = new QLabel(tr("&Days:")); + daysEdit = new QSpinBox; + daysEdit->setMinimum(0); + daysEdit->setValue(0); + daysEdit->setMaximum(10000); + daysLabel->setBuddy(daysEdit); + hoursLabel = new QLabel(tr("&Hours:")); + hoursEdit = new QSpinBox; + hoursEdit->setMinimum(0); + hoursEdit->setValue(0); + hoursEdit->setMaximum(24); + hoursLabel->setBuddy(hoursEdit); + minutesLabel = new QLabel(tr("&Minutes:")); + minutesEdit = new QSpinBox; + minutesEdit->setMinimum(0); + minutesEdit->setValue(5); + minutesEdit->setMaximum(60); + minutesLabel->setBuddy(minutesEdit); + QGridLayout *durationLayout = new QGridLayout; + durationLayout->addWidget(permanentRadio, 0, 0, 1, 6); + durationLayout->addWidget(temporaryRadio, 1, 0, 1, 6); + durationLayout->addWidget(daysLabel, 2, 0); + durationLayout->addWidget(daysEdit, 2, 1); + durationLayout->addWidget(hoursLabel, 2, 2); + durationLayout->addWidget(hoursEdit, 2, 3); + durationLayout->addWidget(minutesLabel, 2, 4); + durationLayout->addWidget(minutesEdit, 2, 5); + QGroupBox *durationGroupBox = new QGroupBox(tr("Duration of the ban")); + durationGroupBox->setLayout(durationLayout); + + QLabel *reasonLabel = new QLabel(tr("Please enter the reason for the ban.\nThis is only saved for moderators and cannot be seen by the banned person.")); + reasonEdit = new QPlainTextEdit; + + QLabel *visibleReasonLabel = new QLabel(tr("Please enter the reason for the ban that will be visible to the banned person.")); + visibleReasonEdit = new QPlainTextEdit; + + QPushButton *okButton = new QPushButton(tr("&OK")); + okButton->setAutoDefault(true); + connect(okButton, SIGNAL(clicked()), this, SLOT(okClicked())); + QPushButton *cancelButton = new QPushButton(tr("&Cancel")); + connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addStretch(); + buttonLayout->addWidget(okButton); + buttonLayout->addWidget(cancelButton); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(banTypeGroupBox); + vbox->addWidget(durationGroupBox); + vbox->addWidget(reasonLabel); + vbox->addWidget(reasonEdit); + vbox->addWidget(visibleReasonLabel); + vbox->addWidget(visibleReasonEdit); + vbox->addLayout(buttonLayout); + + setLayout(vbox); + setWindowTitle(tr("Ban user from server")); } void BanDialog::okClicked() { - if (!nameBanCheckBox->isChecked() && !ipBanCheckBox->isChecked()) { - QMessageBox::critical(this, tr("Error"), tr("You have to select a name-based or IP-based ban, or both.")); - return; - } - accept(); + if (!nameBanCheckBox->isChecked() && !ipBanCheckBox->isChecked()) { + QMessageBox::critical(this, tr("Error"), tr("You have to select a name-based or IP-based ban, or both.")); + return; + } + accept(); } void BanDialog::enableTemporaryEdits(bool enabled) { - daysLabel->setEnabled(enabled); - daysEdit->setEnabled(enabled); - hoursLabel->setEnabled(enabled); - hoursEdit->setEnabled(enabled); - minutesLabel->setEnabled(enabled); - minutesEdit->setEnabled(enabled); + daysLabel->setEnabled(enabled); + daysEdit->setEnabled(enabled); + hoursLabel->setEnabled(enabled); + hoursEdit->setEnabled(enabled); + minutesLabel->setEnabled(enabled); + minutesEdit->setEnabled(enabled); } QString BanDialog::getBanName() const { - return nameBanCheckBox->isChecked() ? nameBanEdit->text() : QString(); + return nameBanCheckBox->isChecked() ? nameBanEdit->text() : QString(); } QString BanDialog::getBanIP() const { - return ipBanCheckBox->isChecked() ? ipBanEdit->text() : QString(); + return ipBanCheckBox->isChecked() ? ipBanEdit->text() : QString(); } int BanDialog::getMinutes() const { - return permanentRadio->isChecked() ? 0 : (daysEdit->value() * 24 * 60 + hoursEdit->value() * 60 + minutesEdit->value()); + return permanentRadio->isChecked() ? 0 : (daysEdit->value() * 24 * 60 + hoursEdit->value() * 60 + minutesEdit->value()); } QString BanDialog::getReason() const { - return reasonEdit->toPlainText(); + return reasonEdit->toPlainText(); } QString BanDialog::getVisibleReason() const { - return visibleReasonEdit->toPlainText(); + return visibleReasonEdit->toPlainText(); } UserListItemDelegate::UserListItemDelegate(QObject *const parent) - : QStyledItemDelegate(parent) + : QStyledItemDelegate(parent) { } bool UserListItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { - if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { - QMouseEvent *const mouseEvent = static_cast(event); - if (mouseEvent->button() == Qt::RightButton) { - static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); - return true; - } - } - return QStyledItemDelegate::editorEvent(event, model, option, index); + if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { + QMouseEvent *const mouseEvent = static_cast(event); + if (mouseEvent->button() == Qt::RightButton) { + static_cast(parent())->showContextMenu(mouseEvent->globalPos(), index); + return true; + } + } + return QStyledItemDelegate::editorEvent(event, model, option, index); } UserListTWI::UserListTWI(const ServerInfo_User &_userInfo) - : QTreeWidgetItem(Type) + : QTreeWidgetItem(Type) { - setUserInfo(_userInfo); + setUserInfo(_userInfo); } void UserListTWI::setUserInfo(const ServerInfo_User &_userInfo) { - userInfo = _userInfo; + userInfo = _userInfo; - setData(0, Qt::UserRole, userInfo.user_level()); - setIcon(0, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(userInfo.user_level())))); - setIcon(1, QIcon(CountryPixmapGenerator::generatePixmap(12, QString::fromStdString(userInfo.country())))); - setData(2, Qt::UserRole, QString::fromStdString(userInfo.name())); - setData(2, Qt::DisplayRole, QString::fromStdString(userInfo.name())); + setData(0, Qt::UserRole, userInfo.user_level()); + setIcon(0, QIcon(UserLevelPixmapGenerator::generatePixmap(12, UserLevelFlags(userInfo.user_level())))); + setIcon(1, QIcon(CountryPixmapGenerator::generatePixmap(12, QString::fromStdString(userInfo.country())))); + setData(2, Qt::UserRole, QString::fromStdString(userInfo.name())); + setData(2, Qt::DisplayRole, QString::fromStdString(userInfo.name())); } void UserListTWI::setOnline(bool online) { - setData(0, Qt::UserRole + 1, online); - setData(2, Qt::ForegroundRole, online ? QBrush() : QBrush(Qt::gray)); + setData(0, Qt::UserRole + 1, online); + setData(2, Qt::ForegroundRole, online ? QBrush() : QBrush(Qt::gray)); } bool UserListTWI::operator<(const QTreeWidgetItem &other) const { - // Sort by online/offline - if (data(0, Qt::UserRole + 1) != other.data(0, Qt::UserRole + 1)) - return data(0, Qt::UserRole + 1).toBool(); - - // Sort by user level - if (data(0, Qt::UserRole) != other.data(0, Qt::UserRole)) - return data(0, Qt::UserRole).toInt() > other.data(0, Qt::UserRole).toInt(); - - // Sort by name - return QString::localeAwareCompare(data(2, Qt::UserRole).toString(), other.data(2, Qt::UserRole).toString()) < 0; + // Sort by online/offline + if (data(0, Qt::UserRole + 1) != other.data(0, Qt::UserRole + 1)) + return data(0, Qt::UserRole + 1).toBool(); + + // Sort by user level + if (data(0, Qt::UserRole) != other.data(0, Qt::UserRole)) + return data(0, Qt::UserRole).toInt() > other.data(0, Qt::UserRole).toInt(); + + // Sort by name + return QString::localeAwareCompare(data(2, Qt::UserRole).toString(), other.data(2, Qt::UserRole).toString()) < 0; } UserList::UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserListType _type, QWidget *parent) - : QGroupBox(parent), tabSupervisor(_tabSupervisor), client(_client), type(_type), onlineCount(0) + : QGroupBox(parent), tabSupervisor(_tabSupervisor), client(_client), type(_type), onlineCount(0) { - itemDelegate = new UserListItemDelegate(this); - userContextMenu = new UserContextMenu(tabSupervisor, this); - connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); - - userTree = new QTreeWidget; - userTree->setColumnCount(3); - userTree->header()->setResizeMode(QHeaderView::ResizeToContents); - userTree->setHeaderHidden(true); - userTree->setRootIsDecorated(false); - userTree->setIconSize(QSize(20, 12)); - userTree->setItemDelegate(itemDelegate); - userTree->setAlternatingRowColors(true); - connect(userTree, SIGNAL(itemActivated(QTreeWidgetItem *, int)), this, SLOT(userClicked(QTreeWidgetItem *, int))); - - QVBoxLayout *vbox = new QVBoxLayout; - vbox->addWidget(userTree); - - setLayout(vbox); - - retranslateUi(); + itemDelegate = new UserListItemDelegate(this); + userContextMenu = new UserContextMenu(tabSupervisor, this); + connect(userContextMenu, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool))); + + userTree = new QTreeWidget; + userTree->setColumnCount(3); + userTree->header()->setResizeMode(QHeaderView::ResizeToContents); + userTree->setHeaderHidden(true); + userTree->setRootIsDecorated(false); + userTree->setIconSize(QSize(20, 12)); + userTree->setItemDelegate(itemDelegate); + userTree->setAlternatingRowColors(true); + connect(userTree, SIGNAL(itemActivated(QTreeWidgetItem *, int)), this, SLOT(userClicked(QTreeWidgetItem *, int))); + + QVBoxLayout *vbox = new QVBoxLayout; + vbox->addWidget(userTree); + + setLayout(vbox); + + retranslateUi(); } void UserList::retranslateUi() { - userContextMenu->retranslateUi(); - switch (type) { - case AllUsersList: titleStr = tr("Users online: %1"); break; - case RoomList: titleStr = tr("Users in this room: %1"); break; - case BuddyList: titleStr = tr("Buddies online: %1 / %2"); break; - case IgnoreList: titleStr = tr("Ignored users online: %1 / %2"); break; - } - updateCount(); + userContextMenu->retranslateUi(); + switch (type) { + case AllUsersList: titleStr = tr("Users online: %1"); break; + case RoomList: titleStr = tr("Users in this room: %1"); break; + case BuddyList: titleStr = tr("Buddies online: %1 / %2"); break; + case IgnoreList: titleStr = tr("Ignored users online: %1 / %2"); break; + } + updateCount(); } void UserList::processUserInfo(const ServerInfo_User &user, bool online) { - const QString userName = QString::fromStdString(user.name()); - UserListTWI *item = users.value(userName); - if (item) - item->setUserInfo(user); - else { - item = new UserListTWI(user); - users.insert(userName, item); - userTree->addTopLevelItem(item); - if (online) - ++onlineCount; - updateCount(); - } - item->setOnline(online); + const QString userName = QString::fromStdString(user.name()); + UserListTWI *item = users.value(userName); + if (item) + item->setUserInfo(user); + else { + item = new UserListTWI(user); + users.insert(userName, item); + userTree->addTopLevelItem(item); + if (online) + ++onlineCount; + updateCount(); + } + item->setOnline(online); } bool UserList::deleteUser(const QString &userName) { - UserListTWI *twi = users.value(userName); - if (twi) { - users.remove(userName); - userTree->takeTopLevelItem(userTree->indexOfTopLevelItem(twi)); - if (twi->data(0, Qt::UserRole + 1).toBool()) - --onlineCount; - delete twi; - updateCount(); - return true; - } - - return false; + UserListTWI *twi = users.value(userName); + if (twi) { + users.remove(userName); + userTree->takeTopLevelItem(userTree->indexOfTopLevelItem(twi)); + if (twi->data(0, Qt::UserRole + 1).toBool()) + --onlineCount; + delete twi; + updateCount(); + return true; + } + + return false; } void UserList::setUserOnline(const QString &userName, bool online) { - UserListTWI *twi = users.value(userName); - if (!twi) - return; - - twi->setOnline(online); - if (online) - ++onlineCount; - else - --onlineCount; - updateCount(); + UserListTWI *twi = users.value(userName); + if (!twi) + return; + + twi->setOnline(online); + if (online) + ++onlineCount; + else + --onlineCount; + updateCount(); } void UserList::updateCount() { - QString str = titleStr; - if ((type == BuddyList) || (type == IgnoreList)) - str = str.arg(onlineCount); - setTitle(str.arg(userTree->topLevelItemCount())); + QString str = titleStr; + if ((type == BuddyList) || (type == IgnoreList)) + str = str.arg(onlineCount); + setTitle(str.arg(userTree->topLevelItemCount())); } void UserList::userClicked(QTreeWidgetItem *item, int /*column*/) { - emit openMessageDialog(item->data(2, Qt::UserRole).toString(), true); + emit openMessageDialog(item->data(2, Qt::UserRole).toString(), true); } void UserList::showContextMenu(const QPoint &pos, const QModelIndex &index) { - const ServerInfo_User &userInfo = static_cast(userTree->topLevelItem(index.row()))->getUserInfo(); - - userContextMenu->showContextMenu(pos, QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level())); + const ServerInfo_User &userInfo = static_cast(userTree->topLevelItem(index.row()))->getUserInfo(); + + userContextMenu->showContextMenu(pos, QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level())); } void UserList::sortItems() { - userTree->sortItems(1, Qt::AscendingOrder); + userTree->sortItems(1, Qt::AscendingOrder); } diff --git a/cockatrice/src/userlist.h b/cockatrice/src/userlist.h index 001db621..fc043b1d 100644 --- a/cockatrice/src/userlist.h +++ b/cockatrice/src/userlist.h @@ -21,75 +21,75 @@ class CommandContainer; class UserContextMenu; class BanDialog : public QDialog { - Q_OBJECT + Q_OBJECT private: - QLabel *daysLabel, *hoursLabel, *minutesLabel; - QCheckBox *nameBanCheckBox, *ipBanCheckBox; - QLineEdit *nameBanEdit, *ipBanEdit; - QSpinBox *daysEdit, *hoursEdit, *minutesEdit; - QRadioButton *permanentRadio, *temporaryRadio; - QPlainTextEdit *reasonEdit, *visibleReasonEdit; + QLabel *daysLabel, *hoursLabel, *minutesLabel; + QCheckBox *nameBanCheckBox, *ipBanCheckBox; + QLineEdit *nameBanEdit, *ipBanEdit; + QSpinBox *daysEdit, *hoursEdit, *minutesEdit; + QRadioButton *permanentRadio, *temporaryRadio; + QPlainTextEdit *reasonEdit, *visibleReasonEdit; private slots: - void okClicked(); - void enableTemporaryEdits(bool enabled); + void okClicked(); + void enableTemporaryEdits(bool enabled); public: - BanDialog(const ServerInfo_User &info, QWidget *parent = 0); - QString getBanName() const; - QString getBanIP() const; - int getMinutes() const; - QString getReason() const; - QString getVisibleReason() const; + BanDialog(const ServerInfo_User &info, QWidget *parent = 0); + QString getBanName() const; + QString getBanIP() const; + int getMinutes() const; + QString getReason() const; + QString getVisibleReason() const; }; class UserListItemDelegate : public QStyledItemDelegate { public: - UserListItemDelegate(QObject *const parent); - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); + UserListItemDelegate(QObject *const parent); + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); }; class UserListTWI : public QTreeWidgetItem { private: - ServerInfo_User userInfo; + ServerInfo_User userInfo; public: - UserListTWI(const ServerInfo_User &_userInfo); - const ServerInfo_User &getUserInfo() const { return userInfo; } - void setUserInfo(const ServerInfo_User &_userInfo); - void setOnline(bool online); - bool operator<(const QTreeWidgetItem &other) const; + UserListTWI(const ServerInfo_User &_userInfo); + const ServerInfo_User &getUserInfo() const { return userInfo; } + void setUserInfo(const ServerInfo_User &_userInfo); + void setOnline(bool online); + bool operator<(const QTreeWidgetItem &other) const; }; class UserList : public QGroupBox { - Q_OBJECT + Q_OBJECT public: - enum UserListType { AllUsersList, RoomList, BuddyList, IgnoreList }; + enum UserListType { AllUsersList, RoomList, BuddyList, IgnoreList }; private: - QMap users; - TabSupervisor *tabSupervisor; - AbstractClient *client; - UserListType type; - QTreeWidget *userTree; - UserListItemDelegate *itemDelegate; - UserContextMenu *userContextMenu; - int onlineCount; - QString titleStr; - void updateCount(); + QMap users; + TabSupervisor *tabSupervisor; + AbstractClient *client; + UserListType type; + QTreeWidget *userTree; + UserListItemDelegate *itemDelegate; + UserContextMenu *userContextMenu; + int onlineCount; + QString titleStr; + void updateCount(); private slots: - void userClicked(QTreeWidgetItem *item, int column); + void userClicked(QTreeWidgetItem *item, int column); signals: - void openMessageDialog(const QString &userName, bool focus); - void addBuddy(const QString &userName); - void removeBuddy(const QString &userName); - void addIgnore(const QString &userName); - void removeIgnore(const QString &userName); + void openMessageDialog(const QString &userName, bool focus); + void addBuddy(const QString &userName); + void removeBuddy(const QString &userName); + void addIgnore(const QString &userName); + void removeIgnore(const QString &userName); public: - UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserListType _type, QWidget *parent = 0); - void retranslateUi(); - void processUserInfo(const ServerInfo_User &user, bool online); - bool deleteUser(const QString &userName); - void setUserOnline(const QString &userName, bool online); - const QMap &getUsers() const { return users; } - void showContextMenu(const QPoint &pos, const QModelIndex &index); - void sortItems(); + UserList(TabSupervisor *_tabSupervisor, AbstractClient *_client, UserListType _type, QWidget *parent = 0); + void retranslateUi(); + void processUserInfo(const ServerInfo_User &user, bool online); + bool deleteUser(const QString &userName); + void setUserOnline(const QString &userName, bool online); + const QMap &getUsers() const { return users; } + void showContextMenu(const QPoint &pos, const QModelIndex &index); + void sortItems(); }; #endif diff --git a/cockatrice/src/window_main.cpp b/cockatrice/src/window_main.cpp index f3d20e19..f5dc2684 100644 --- a/cockatrice/src/window_main.cpp +++ b/cockatrice/src/window_main.cpp @@ -52,369 +52,369 @@ const QString MainWindow::appName = "Cockatrice"; void MainWindow::updateTabMenu(const QList &newMenuList) { - for (int i = 0; i < tabMenus.size(); ++i) - menuBar()->removeAction(tabMenus[i]->menuAction()); - tabMenus = newMenuList; - for (int i = 0; i < tabMenus.size(); ++i) - menuBar()->insertMenu(helpMenu->menuAction(), tabMenus[i]); + for (int i = 0; i < tabMenus.size(); ++i) + menuBar()->removeAction(tabMenus[i]->menuAction()); + tabMenus = newMenuList; + for (int i = 0; i < tabMenus.size(); ++i) + menuBar()->insertMenu(helpMenu->menuAction(), tabMenus[i]); } void MainWindow::processConnectionClosedEvent(const Event_ConnectionClosed &event) { - client->disconnectFromServer(); - QString reasonStr; - switch (event.reason()) { - case Event_ConnectionClosed::TOO_MANY_CONNECTIONS: reasonStr = tr("There are too many concurrent connections from your address."); break; - case Event_ConnectionClosed::BANNED: { - reasonStr = tr("Banned by moderator"); - if (event.has_end_time()) - reasonStr.append("\n" + tr("Expected end time: %1").arg(QDateTime::fromTime_t(event.end_time()).toString())); - else - reasonStr.append("\n" + tr("This ban lasts indefinitely.")); - if (event.has_reason_str()) - reasonStr.append("\n\n" + QString::fromStdString(event.reason_str())); - break; - } - case Event_ConnectionClosed::SERVER_SHUTDOWN: reasonStr = tr("Scheduled server shutdown."); break; - case Event_ConnectionClosed::USERNAMEINVALID: reasonStr = tr("Invalid username."); break; - default: reasonStr = QString::fromStdString(event.reason_str()); - } - QMessageBox::critical(this, tr("Connection closed"), tr("The server has terminated your connection.\nReason: %1").arg(reasonStr)); + client->disconnectFromServer(); + QString reasonStr; + switch (event.reason()) { + case Event_ConnectionClosed::TOO_MANY_CONNECTIONS: reasonStr = tr("There are too many concurrent connections from your address."); break; + case Event_ConnectionClosed::BANNED: { + reasonStr = tr("Banned by moderator"); + if (event.has_end_time()) + reasonStr.append("\n" + tr("Expected end time: %1").arg(QDateTime::fromTime_t(event.end_time()).toString())); + else + reasonStr.append("\n" + tr("This ban lasts indefinitely.")); + if (event.has_reason_str()) + reasonStr.append("\n\n" + QString::fromStdString(event.reason_str())); + break; + } + case Event_ConnectionClosed::SERVER_SHUTDOWN: reasonStr = tr("Scheduled server shutdown."); break; + case Event_ConnectionClosed::USERNAMEINVALID: reasonStr = tr("Invalid username."); break; + default: reasonStr = QString::fromStdString(event.reason_str()); + } + QMessageBox::critical(this, tr("Connection closed"), tr("The server has terminated your connection.\nReason: %1").arg(reasonStr)); } void MainWindow::processServerShutdownEvent(const Event_ServerShutdown &event) { - QMessageBox::information(this, tr("Scheduled server shutdown"), tr("The server is going to be restarted in %n minute(s).\nAll running games will be lost.\nReason for shutdown: %1", "", event.minutes()).arg(QString::fromStdString(event.reason()))); + QMessageBox::information(this, tr("Scheduled server shutdown"), tr("The server is going to be restarted in %n minute(s).\nAll running games will be lost.\nReason for shutdown: %1", "", event.minutes()).arg(QString::fromStdString(event.reason()))); } void MainWindow::statusChanged(ClientStatus _status) { - setClientStatusTitle(); - switch (_status) { - case StatusConnecting: - break; - case StatusDisconnected: - tabSupervisor->stop(); - aSinglePlayer->setEnabled(true); - aConnect->setEnabled(true); - aDisconnect->setEnabled(false); - break; - case StatusLoggingIn: - aSinglePlayer->setEnabled(false); - aConnect->setEnabled(false); - aDisconnect->setEnabled(true); - break; - case StatusLoggedIn: - break; - default: - break; - } + setClientStatusTitle(); + switch (_status) { + case StatusConnecting: + break; + case StatusDisconnected: + tabSupervisor->stop(); + aSinglePlayer->setEnabled(true); + aConnect->setEnabled(true); + aDisconnect->setEnabled(false); + break; + case StatusLoggingIn: + aSinglePlayer->setEnabled(false); + aConnect->setEnabled(false); + aDisconnect->setEnabled(true); + break; + case StatusLoggedIn: + break; + default: + break; + } } void MainWindow::userInfoReceived(const ServerInfo_User &info) { - tabSupervisor->start(info); + tabSupervisor->start(info); } // Actions void MainWindow::actConnect() { - DlgConnect dlg(this); - if (dlg.exec()) - client->connectToServer(dlg.getHost(), dlg.getPort(), dlg.getPlayerName(), dlg.getPassword()); + DlgConnect dlg(this); + if (dlg.exec()) + client->connectToServer(dlg.getHost(), dlg.getPort(), dlg.getPlayerName(), dlg.getPassword()); } void MainWindow::actDisconnect() { - client->disconnectFromServer(); + client->disconnectFromServer(); } void MainWindow::actSinglePlayer() { - bool ok; - int numberPlayers = QInputDialog::getInt(this, tr("Number of players"), tr("Please enter the number of players."), 2, 1, 8, 1, &ok); - if (!ok) - return; - - aConnect->setEnabled(false); - aSinglePlayer->setEnabled(false); - - localServer = new LocalServer(this); - LocalServerInterface *mainLsi = localServer->newConnection(); - LocalClient *mainClient = new LocalClient(mainLsi, tr("Player %1").arg(1), this); - QList localClients; - localClients.append(mainClient); - - for (int i = 0; i < numberPlayers - 1; ++i) { - LocalServerInterface *slaveLsi = localServer->newConnection(); - LocalClient *slaveClient = new LocalClient(slaveLsi, tr("Player %1").arg(i + 2), this); - localClients.append(slaveClient); - } - tabSupervisor->startLocal(localClients); - - Command_CreateGame createCommand; - createCommand.set_max_players(numberPlayers); - mainClient->sendCommand(mainClient->prepareRoomCommand(createCommand, 0)); + bool ok; + int numberPlayers = QInputDialog::getInt(this, tr("Number of players"), tr("Please enter the number of players."), 2, 1, 8, 1, &ok); + if (!ok) + return; + + aConnect->setEnabled(false); + aSinglePlayer->setEnabled(false); + + localServer = new LocalServer(this); + LocalServerInterface *mainLsi = localServer->newConnection(); + LocalClient *mainClient = new LocalClient(mainLsi, tr("Player %1").arg(1), this); + QList localClients; + localClients.append(mainClient); + + for (int i = 0; i < numberPlayers - 1; ++i) { + LocalServerInterface *slaveLsi = localServer->newConnection(); + LocalClient *slaveClient = new LocalClient(slaveLsi, tr("Player %1").arg(i + 2), this); + localClients.append(slaveClient); + } + tabSupervisor->startLocal(localClients); + + Command_CreateGame createCommand; + createCommand.set_max_players(numberPlayers); + mainClient->sendCommand(mainClient->prepareRoomCommand(createCommand, 0)); } void MainWindow::actWatchReplay() { - QFileDialog dlg(this, tr("Load replay")); - dlg.setDirectory(settingsCache->getReplaysPath()); - dlg.setNameFilters(QStringList() << QObject::tr("Cockatrice replays (*.cor)")); - if (!dlg.exec()) - return; - - QString fileName = dlg.selectedFiles().at(0); - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly)) - return; - QByteArray buf = file.readAll(); - file.close(); - - GameReplay *replay = new GameReplay; - replay->ParseFromArray(buf.data(), buf.size()); - - tabSupervisor->openReplay(replay); + QFileDialog dlg(this, tr("Load replay")); + dlg.setDirectory(settingsCache->getReplaysPath()); + dlg.setNameFilters(QStringList() << QObject::tr("Cockatrice replays (*.cor)")); + if (!dlg.exec()) + return; + + QString fileName = dlg.selectedFiles().at(0); + QFile file(fileName); + if (!file.open(QIODevice::ReadOnly)) + return; + QByteArray buf = file.readAll(); + file.close(); + + GameReplay *replay = new GameReplay; + replay->ParseFromArray(buf.data(), buf.size()); + + tabSupervisor->openReplay(replay); } void MainWindow::localGameEnded() { - delete localServer; - localServer = 0; - - aConnect->setEnabled(true); - aSinglePlayer->setEnabled(true); + delete localServer; + localServer = 0; + + aConnect->setEnabled(true); + aSinglePlayer->setEnabled(true); } void MainWindow::actDeckEditor() { - tabSupervisor->addDeckEditorTab(0); + tabSupervisor->addDeckEditorTab(0); } void MainWindow::actFullScreen(bool checked) { - if (checked) - setWindowState(windowState() | Qt::WindowFullScreen); - else - setWindowState(windowState() & ~Qt::WindowFullScreen); + if (checked) + setWindowState(windowState() | Qt::WindowFullScreen); + else + setWindowState(windowState() & ~Qt::WindowFullScreen); } void MainWindow::actSettings() { - DlgSettings dlg(this); - dlg.exec(); + DlgSettings dlg(this); + dlg.exec(); } void MainWindow::actExit() { - close(); + close(); } void MainWindow::actAbout() { - QMessageBox::about(this, tr("About Cockatrice"), QString( - "Cockatrice
" - + tr("Version %1").arg(VERSION_STRING) - + "


" + tr("Authors:") + "
Max-Wilhelm Bruker
Marcus Schütz

" - + "" + tr("Translators:") + "
" - + tr("Spanish:") + " Víctor Martínez
" - + tr("Portugese (Portugal):") + " Milton Gonçalves
" - + tr("Portugese (Brazil):") + " Thiago Queiroz
" - + tr("French:") + " Yannick Hammer, Arnaud Faes
" - + tr("Japanese:") + " Nagase Task
" - + tr("Russian:") + " Alexander Davidov
" -// + tr("Czech:") + " Ondřej Trhoň
" -// + tr("Slovak:") + " Ganjalf Rendy
" - + tr("Italian:") + " Luigi Sciolla
" - + tr("Swedish:") + " Jessica Dahl
" - )); + QMessageBox::about(this, tr("About Cockatrice"), QString( + "Cockatrice
" + + tr("Version %1").arg(VERSION_STRING) + + "


" + tr("Authors:") + "
Max-Wilhelm Bruker
Marcus Schütz

" + + "" + tr("Translators:") + "
" + + tr("Spanish:") + " Víctor Martínez
" + + tr("Portugese (Portugal):") + " Milton Gonçalves
" + + tr("Portugese (Brazil):") + " Thiago Queiroz
" + + tr("French:") + " Yannick Hammer, Arnaud Faes
" + + tr("Japanese:") + " Nagase Task
" + + tr("Russian:") + " Alexander Davidov
" +// + tr("Czech:") + " Ondřej Trhoň
" +// + tr("Slovak:") + " Ganjalf Rendy
" + + tr("Italian:") + " Luigi Sciolla
" + + tr("Swedish:") + " Jessica Dahl
" + )); } void MainWindow::serverTimeout() { - QMessageBox::critical(this, tr("Error"), tr("Server timeout")); + QMessageBox::critical(this, tr("Error"), tr("Server timeout")); } void MainWindow::loginError(Response::ResponseCode r, QString reasonStr, quint32 endTime) { - switch (r) { - case Response::RespWrongPassword: - QMessageBox::critical(this, tr("Error"), tr("Invalid login data.")); - break; - case Response::RespWouldOverwriteOldSession: - QMessageBox::critical(this, tr("Error"), tr("There is already an active session using this user name.\nPlease close that session first and re-login.")); - break; - case Response::RespUserIsBanned: { - QString bannedStr; - if (endTime) - bannedStr = tr("You are banned until %1.").arg(QDateTime::fromTime_t(endTime).toString()); - else - bannedStr = tr("You are banned indefinitely."); - if (!reasonStr.isEmpty()) - bannedStr.append("\n\n" + reasonStr); - - QMessageBox::critical(this, tr("Error"), bannedStr); - break; - } - case Response::RespUsernameInvalid: - QMessageBox::critical(this, tr("Error"), tr("Invalid username.")); - break; - default: - QMessageBox::critical(this, tr("Error"), tr("Unknown login error: %1").arg(static_cast(r))); - } + switch (r) { + case Response::RespWrongPassword: + QMessageBox::critical(this, tr("Error"), tr("Invalid login data.")); + break; + case Response::RespWouldOverwriteOldSession: + QMessageBox::critical(this, tr("Error"), tr("There is already an active session using this user name.\nPlease close that session first and re-login.")); + break; + case Response::RespUserIsBanned: { + QString bannedStr; + if (endTime) + bannedStr = tr("You are banned until %1.").arg(QDateTime::fromTime_t(endTime).toString()); + else + bannedStr = tr("You are banned indefinitely."); + if (!reasonStr.isEmpty()) + bannedStr.append("\n\n" + reasonStr); + + QMessageBox::critical(this, tr("Error"), bannedStr); + break; + } + case Response::RespUsernameInvalid: + QMessageBox::critical(this, tr("Error"), tr("Invalid username.")); + break; + default: + QMessageBox::critical(this, tr("Error"), tr("Unknown login error: %1").arg(static_cast(r))); + } } void MainWindow::socketError(const QString &errorStr) { - QMessageBox::critical(this, tr("Error"), tr("Socket error: %1").arg(errorStr)); + QMessageBox::critical(this, tr("Error"), tr("Socket error: %1").arg(errorStr)); } void MainWindow::protocolVersionMismatch(int localVersion, int remoteVersion) { - if (localVersion > remoteVersion) - QMessageBox::critical(this, tr("Error"), tr("You are trying to connect to an obsolete server. Please downgrade your Cockatrice version or connect to a suitable server.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); - else - QMessageBox::critical(this, tr("Error"), tr("Your Cockatrice client is obsolete. Please update your Cockatrice version.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); + if (localVersion > remoteVersion) + QMessageBox::critical(this, tr("Error"), tr("You are trying to connect to an obsolete server. Please downgrade your Cockatrice version or connect to a suitable server.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); + else + QMessageBox::critical(this, tr("Error"), tr("Your Cockatrice client is obsolete. Please update your Cockatrice version.\nLocal version is %1, remote version is %2.").arg(localVersion).arg(remoteVersion)); } void MainWindow::setClientStatusTitle() { - switch (client->getStatus()) { - case StatusConnecting: setWindowTitle(appName + " - " + tr("Connecting to %1...").arg(client->peerName())); break; - case StatusDisconnected: setWindowTitle(appName + " - " + tr("Disconnected")); break; - case StatusLoggingIn: setWindowTitle(appName + " - " + tr("Connected, logging in at %1").arg(client->peerName())); break; - case StatusLoggedIn: setWindowTitle(appName + " - " + tr("Logged in at %1").arg(client->peerName())); break; - default: setWindowTitle(appName); - } + switch (client->getStatus()) { + case StatusConnecting: setWindowTitle(appName + " - " + tr("Connecting to %1...").arg(client->peerName())); break; + case StatusDisconnected: setWindowTitle(appName + " - " + tr("Disconnected")); break; + case StatusLoggingIn: setWindowTitle(appName + " - " + tr("Connected, logging in at %1").arg(client->peerName())); break; + case StatusLoggedIn: setWindowTitle(appName + " - " + tr("Logged in at %1").arg(client->peerName())); break; + default: setWindowTitle(appName); + } } void MainWindow::retranslateUi() { - setClientStatusTitle(); - - aConnect->setText(tr("&Connect...")); - aDisconnect->setText(tr("&Disconnect")); - aSinglePlayer->setText(tr("Start &local game...")); - aWatchReplay->setText(tr("&Watch replay...")); - aDeckEditor->setText(tr("&Deck editor")); - aFullScreen->setText(tr("&Full screen")); - aFullScreen->setShortcut(tr("Ctrl+F")); - aSettings->setText(tr("&Settings...")); - aExit->setText(tr("&Exit")); - - cockatriceMenu->setTitle(tr("&Cockatrice")); - - aAbout->setText(tr("&About Cockatrice")); - helpMenu->setTitle(tr("&Help")); - - tabSupervisor->retranslateUi(); + setClientStatusTitle(); + + aConnect->setText(tr("&Connect...")); + aDisconnect->setText(tr("&Disconnect")); + aSinglePlayer->setText(tr("Start &local game...")); + aWatchReplay->setText(tr("&Watch replay...")); + aDeckEditor->setText(tr("&Deck editor")); + aFullScreen->setText(tr("&Full screen")); + aFullScreen->setShortcut(tr("Ctrl+F")); + aSettings->setText(tr("&Settings...")); + aExit->setText(tr("&Exit")); + + cockatriceMenu->setTitle(tr("&Cockatrice")); + + aAbout->setText(tr("&About Cockatrice")); + helpMenu->setTitle(tr("&Help")); + + tabSupervisor->retranslateUi(); } void MainWindow::createActions() { - aConnect = new QAction(this); - connect(aConnect, SIGNAL(triggered()), this, SLOT(actConnect())); - aDisconnect = new QAction(this); - aDisconnect->setEnabled(false); - connect(aDisconnect, SIGNAL(triggered()), this, SLOT(actDisconnect())); - aSinglePlayer = new QAction(this); - connect(aSinglePlayer, SIGNAL(triggered()), this, SLOT(actSinglePlayer())); - aWatchReplay = new QAction(this); - connect(aWatchReplay, SIGNAL(triggered()), this, SLOT(actWatchReplay())); - aDeckEditor = new QAction(this); - connect(aDeckEditor, SIGNAL(triggered()), this, SLOT(actDeckEditor())); - aFullScreen = new QAction(this); - aFullScreen->setCheckable(true); - connect(aFullScreen, SIGNAL(toggled(bool)), this, SLOT(actFullScreen(bool))); - aSettings = new QAction(this); - connect(aSettings, SIGNAL(triggered()), this, SLOT(actSettings())); - aExit = new QAction(this); - connect(aExit, SIGNAL(triggered()), this, SLOT(actExit())); - - aAbout = new QAction(this); - connect(aAbout, SIGNAL(triggered()), this, SLOT(actAbout())); + aConnect = new QAction(this); + connect(aConnect, SIGNAL(triggered()), this, SLOT(actConnect())); + aDisconnect = new QAction(this); + aDisconnect->setEnabled(false); + connect(aDisconnect, SIGNAL(triggered()), this, SLOT(actDisconnect())); + aSinglePlayer = new QAction(this); + connect(aSinglePlayer, SIGNAL(triggered()), this, SLOT(actSinglePlayer())); + aWatchReplay = new QAction(this); + connect(aWatchReplay, SIGNAL(triggered()), this, SLOT(actWatchReplay())); + aDeckEditor = new QAction(this); + connect(aDeckEditor, SIGNAL(triggered()), this, SLOT(actDeckEditor())); + aFullScreen = new QAction(this); + aFullScreen->setCheckable(true); + connect(aFullScreen, SIGNAL(toggled(bool)), this, SLOT(actFullScreen(bool))); + aSettings = new QAction(this); + connect(aSettings, SIGNAL(triggered()), this, SLOT(actSettings())); + aExit = new QAction(this); + connect(aExit, SIGNAL(triggered()), this, SLOT(actExit())); + + aAbout = new QAction(this); + connect(aAbout, SIGNAL(triggered()), this, SLOT(actAbout())); } void MainWindow::createMenus() { - cockatriceMenu = menuBar()->addMenu(QString()); - cockatriceMenu->addAction(aConnect); - cockatriceMenu->addAction(aDisconnect); - cockatriceMenu->addAction(aSinglePlayer); - cockatriceMenu->addAction(aWatchReplay); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aDeckEditor); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aFullScreen); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aSettings); - cockatriceMenu->addSeparator(); - cockatriceMenu->addAction(aExit); - - helpMenu = menuBar()->addMenu(QString()); - helpMenu->addAction(aAbout); + cockatriceMenu = menuBar()->addMenu(QString()); + cockatriceMenu->addAction(aConnect); + cockatriceMenu->addAction(aDisconnect); + cockatriceMenu->addAction(aSinglePlayer); + cockatriceMenu->addAction(aWatchReplay); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aDeckEditor); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aFullScreen); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aSettings); + cockatriceMenu->addSeparator(); + cockatriceMenu->addAction(aExit); + + helpMenu = menuBar()->addMenu(QString()); + helpMenu->addAction(aAbout); } MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), localServer(0) + : QMainWindow(parent), localServer(0) { - QPixmapCache::setCacheLimit(200000); + QPixmapCache::setCacheLimit(200000); - client = new RemoteClient; - connect(client, SIGNAL(connectionClosedEventReceived(const Event_ConnectionClosed &)), this, SLOT(processConnectionClosedEvent(const Event_ConnectionClosed &))); - connect(client, SIGNAL(serverShutdownEventReceived(const Event_ServerShutdown &)), this, SLOT(processServerShutdownEvent(const Event_ServerShutdown &))); - connect(client, SIGNAL(loginError(Response::ResponseCode, QString, quint32)), this, SLOT(loginError(Response::ResponseCode, QString, quint32))); - connect(client, SIGNAL(socketError(const QString &)), this, SLOT(socketError(const QString &))); - connect(client, SIGNAL(serverTimeout()), this, SLOT(serverTimeout())); - connect(client, SIGNAL(statusChanged(ClientStatus)), this, SLOT(statusChanged(ClientStatus))); - connect(client, SIGNAL(protocolVersionMismatch(int, int)), this, SLOT(protocolVersionMismatch(int, int))); - connect(client, SIGNAL(userInfoChanged(const ServerInfo_User &)), this, SLOT(userInfoReceived(const ServerInfo_User &)), Qt::BlockingQueuedConnection); - - clientThread = new QThread(this); - client->moveToThread(clientThread); - clientThread->start(); + client = new RemoteClient; + connect(client, SIGNAL(connectionClosedEventReceived(const Event_ConnectionClosed &)), this, SLOT(processConnectionClosedEvent(const Event_ConnectionClosed &))); + connect(client, SIGNAL(serverShutdownEventReceived(const Event_ServerShutdown &)), this, SLOT(processServerShutdownEvent(const Event_ServerShutdown &))); + connect(client, SIGNAL(loginError(Response::ResponseCode, QString, quint32)), this, SLOT(loginError(Response::ResponseCode, QString, quint32))); + connect(client, SIGNAL(socketError(const QString &)), this, SLOT(socketError(const QString &))); + connect(client, SIGNAL(serverTimeout()), this, SLOT(serverTimeout())); + connect(client, SIGNAL(statusChanged(ClientStatus)), this, SLOT(statusChanged(ClientStatus))); + connect(client, SIGNAL(protocolVersionMismatch(int, int)), this, SLOT(protocolVersionMismatch(int, int))); + connect(client, SIGNAL(userInfoChanged(const ServerInfo_User &)), this, SLOT(userInfoReceived(const ServerInfo_User &)), Qt::BlockingQueuedConnection); + + clientThread = new QThread(this); + client->moveToThread(clientThread); + clientThread->start(); - createActions(); - createMenus(); - - tabSupervisor = new TabSupervisor(client); - connect(tabSupervisor, SIGNAL(setMenu(QList)), this, SLOT(updateTabMenu(QList))); - connect(tabSupervisor, SIGNAL(localGameEnded()), this, SLOT(localGameEnded())); - tabSupervisor->addDeckEditorTab(0); - - setCentralWidget(tabSupervisor); + createActions(); + createMenus(); + + tabSupervisor = new TabSupervisor(client); + connect(tabSupervisor, SIGNAL(setMenu(QList)), this, SLOT(updateTabMenu(QList))); + connect(tabSupervisor, SIGNAL(localGameEnded()), this, SLOT(localGameEnded())); + tabSupervisor->addDeckEditorTab(0); + + setCentralWidget(tabSupervisor); - retranslateUi(); - - resize(900, 700); - restoreGeometry(settingsCache->getMainWindowGeometry()); - aFullScreen->setChecked(windowState() & Qt::WindowFullScreen); + retranslateUi(); + + resize(900, 700); + restoreGeometry(settingsCache->getMainWindowGeometry()); + aFullScreen->setChecked(windowState() & Qt::WindowFullScreen); } MainWindow::~MainWindow() { - client->deleteLater(); - clientThread->wait(); + client->deleteLater(); + clientThread->wait(); } void MainWindow::closeEvent(QCloseEvent *event) { - if (tabSupervisor->getGameCount()) { - if (QMessageBox::question(this, tr("Are you sure?"), tr("There are still open games. Are you sure you want to quit?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) { - event->ignore(); - return; - } - } - event->accept(); - settingsCache->setMainWindowGeometry(saveGeometry()); - delete tabSupervisor; + if (tabSupervisor->getGameCount()) { + if (QMessageBox::question(this, tr("Are you sure?"), tr("There are still open games. Are you sure you want to quit?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) { + event->ignore(); + return; + } + } + event->accept(); + settingsCache->setMainWindowGeometry(saveGeometry()); + delete tabSupervisor; } void MainWindow::changeEvent(QEvent *event) { - if (event->type() == QEvent::LanguageChange) - retranslateUi(); - QMainWindow::changeEvent(event); + if (event->type() == QEvent::LanguageChange) + retranslateUi(); + QMainWindow::changeEvent(event); } diff --git a/cockatrice/src/window_main.h b/cockatrice/src/window_main.h index e8b42a6a..07ad1d71 100644 --- a/cockatrice/src/window_main.h +++ b/cockatrice/src/window_main.h @@ -32,51 +32,51 @@ class ServerInfo_User; class QThread; class MainWindow : public QMainWindow { - Q_OBJECT + Q_OBJECT private slots: - void updateTabMenu(const QList &newMenuList); - void statusChanged(ClientStatus _status); - void processConnectionClosedEvent(const Event_ConnectionClosed &event); - void processServerShutdownEvent(const Event_ServerShutdown &event); - void serverTimeout(); - void loginError(Response::ResponseCode r, QString reasonStr, quint32 endTime); - void socketError(const QString &errorStr); - void protocolVersionMismatch(int localVersion, int remoteVersion); - void userInfoReceived(const ServerInfo_User &userInfo); - void localGameEnded(); + void updateTabMenu(const QList &newMenuList); + void statusChanged(ClientStatus _status); + void processConnectionClosedEvent(const Event_ConnectionClosed &event); + void processServerShutdownEvent(const Event_ServerShutdown &event); + void serverTimeout(); + void loginError(Response::ResponseCode r, QString reasonStr, quint32 endTime); + void socketError(const QString &errorStr); + void protocolVersionMismatch(int localVersion, int remoteVersion); + void userInfoReceived(const ServerInfo_User &userInfo); + void localGameEnded(); - void actConnect(); - void actDisconnect(); - void actSinglePlayer(); - void actWatchReplay(); - void actDeckEditor(); - void actFullScreen(bool checked); - void actSettings(); - void actExit(); - - void actAbout(); + void actConnect(); + void actDisconnect(); + void actSinglePlayer(); + void actWatchReplay(); + void actDeckEditor(); + void actFullScreen(bool checked); + void actSettings(); + void actExit(); + + void actAbout(); private: - static const QString appName; - void setClientStatusTitle(); - void retranslateUi(); - void createActions(); - void createMenus(); - QList tabMenus; - QMenu *cockatriceMenu, *helpMenu; - QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit, - *aAbout; - TabSupervisor *tabSupervisor; + static const QString appName; + void setClientStatusTitle(); + void retranslateUi(); + void createActions(); + void createMenus(); + QList tabMenus; + QMenu *cockatriceMenu, *helpMenu; + QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit, + *aAbout; + TabSupervisor *tabSupervisor; - RemoteClient *client; - QThread *clientThread; - - LocalServer *localServer; + RemoteClient *client; + QThread *clientThread; + + LocalServer *localServer; public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); + MainWindow(QWidget *parent = 0); + ~MainWindow(); protected: - void closeEvent(QCloseEvent *event); - void changeEvent(QEvent *event); + void closeEvent(QCloseEvent *event); + void changeEvent(QEvent *event); }; #endif diff --git a/cockatrice/src/window_sets.cpp b/cockatrice/src/window_sets.cpp index dd6bcd8a..668b36e0 100644 --- a/cockatrice/src/window_sets.cpp +++ b/cockatrice/src/window_sets.cpp @@ -5,29 +5,29 @@ #include WndSets::WndSets(QWidget *parent) - : QMainWindow(parent) + : QMainWindow(parent) { - model = new SetsModel(db, this); - view = new QTreeView; - view->setModel(model); - view->setAlternatingRowColors(true); - view->setUniformRowHeights(true); - view->setAllColumnsShowFocus(true); + model = new SetsModel(db, this); + view = new QTreeView; + view->setModel(model); + view->setAlternatingRowColors(true); + view->setUniformRowHeights(true); + view->setAllColumnsShowFocus(true); - view->setDragEnabled(true); - view->setAcceptDrops(true); - view->setDropIndicatorShown(true); - view->setDragDropMode(QAbstractItemView::InternalMove); + view->setDragEnabled(true); + view->setAcceptDrops(true); + view->setDropIndicatorShown(true); + view->setDragDropMode(QAbstractItemView::InternalMove); - QHBoxLayout *mainLayout = new QHBoxLayout; - mainLayout->addWidget(view); + QHBoxLayout *mainLayout = new QHBoxLayout; + mainLayout->addWidget(view); - QWidget *centralWidget = new QWidget; - centralWidget->setLayout(mainLayout); - setCentralWidget(centralWidget); + QWidget *centralWidget = new QWidget; + centralWidget->setLayout(mainLayout); + setCentralWidget(centralWidget); - setWindowTitle(tr("Edit sets")); - resize(400, 400); + setWindowTitle(tr("Edit sets")); + resize(400, 400); } WndSets::~WndSets() diff --git a/cockatrice/src/window_sets.h b/cockatrice/src/window_sets.h index 4c10d249..ce7cb622 100644 --- a/cockatrice/src/window_sets.h +++ b/cockatrice/src/window_sets.h @@ -8,13 +8,13 @@ class QTreeView; class CardDatabase; class WndSets : public QMainWindow { - Q_OBJECT + Q_OBJECT private: - SetsModel *model; - QTreeView *view; + SetsModel *model; + QTreeView *view; public: - WndSets(QWidget *parent = 0); - ~WndSets(); + WndSets(QWidget *parent = 0); + ~WndSets(); }; #endif diff --git a/cockatrice/src/zoneviewwidget.cpp b/cockatrice/src/zoneviewwidget.cpp index 580624e7..9fd13272 100644 --- a/cockatrice/src/zoneviewwidget.cpp +++ b/cockatrice/src/zoneviewwidget.cpp @@ -19,197 +19,197 @@ #include "pb/command_shuffle.pb.h" TitleLabel::TitleLabel() - : QGraphicsWidget(), text(" ") + : QGraphicsWidget(), text(" ") { - setAcceptHoverEvents(true); + setAcceptHoverEvents(true); } void TitleLabel::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QBrush windowBrush = palette().window(); - windowBrush.setColor(windowBrush.color().darker(150)); - painter->fillRect(boundingRect(), windowBrush); - painter->drawText(boundingRect(), Qt::AlignLeft | Qt::AlignVCenter, text); + QBrush windowBrush = palette().window(); + windowBrush.setColor(windowBrush.color().darker(150)); + painter->fillRect(boundingRect(), windowBrush); + painter->drawText(boundingRect(), Qt::AlignLeft | Qt::AlignVCenter, text); } QSizeF TitleLabel::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { - QFont f; - QFontMetrics fm(f); - if (which == Qt::MaximumSize) - return QSizeF(constraint.width(), fm.size(Qt::TextSingleLine, text).height() + 10); - else - return fm.size(Qt::TextSingleLine, text) + QSizeF(10, 10); + QFont f; + QFontMetrics fm(f); + if (which == Qt::MaximumSize) + return QSizeF(constraint.width(), fm.size(Qt::TextSingleLine, text).height() + 10); + else + return fm.size(Qt::TextSingleLine, text) + QSizeF(10, 10); } void TitleLabel::mousePressEvent(QGraphicsSceneMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - buttonDownPos = static_cast(scene())->getViewTransform().inverted().map(event->pos()); - event->accept(); - } else - event->ignore(); + if (event->button() == Qt::LeftButton) { + buttonDownPos = static_cast(scene())->getViewTransform().inverted().map(event->pos()); + event->accept(); + } else + event->ignore(); } void TitleLabel::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - emit mouseMoved(event->scenePos() - buttonDownPos); + emit mouseMoved(event->scenePos() - buttonDownPos); } ZoneViewWidget::ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards, bool _revealZone, bool _writeableRevealZone, const QList &cardList) - : QGraphicsWidget(0, Qt::Tool | Qt::FramelessWindowHint), player(_player) + : QGraphicsWidget(0, Qt::Tool | Qt::FramelessWindowHint), player(_player) { - setAcceptHoverEvents(true); - setAttribute(Qt::WA_DeleteOnClose); - setZValue(2000000006); - setFlag(ItemIgnoresTransformations); - - QGraphicsLinearLayout *hbox = new QGraphicsLinearLayout(Qt::Horizontal); - titleLabel = new TitleLabel; - connect(titleLabel, SIGNAL(mouseMoved(QPointF)), this, SLOT(moveWidget(QPointF))); - closeButton = new QPushButton("X"); - connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); - closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - QGraphicsProxyWidget *closeButtonProxy = new QGraphicsProxyWidget; - closeButtonProxy->setWidget(closeButton); - - hbox->addItem(titleLabel); - hbox->addItem(closeButtonProxy); - QGraphicsLinearLayout *vbox = new QGraphicsLinearLayout(Qt::Vertical); - - vbox->addItem(hbox); - - if (numberCards < 0) { - sortByNameCheckBox = new QCheckBox; - QGraphicsProxyWidget *sortByNameProxy = new QGraphicsProxyWidget; - sortByNameProxy->setWidget(sortByNameCheckBox); - vbox->addItem(sortByNameProxy); + setAcceptHoverEvents(true); + setAttribute(Qt::WA_DeleteOnClose); + setZValue(2000000006); + setFlag(ItemIgnoresTransformations); + + QGraphicsLinearLayout *hbox = new QGraphicsLinearLayout(Qt::Horizontal); + titleLabel = new TitleLabel; + connect(titleLabel, SIGNAL(mouseMoved(QPointF)), this, SLOT(moveWidget(QPointF))); + closeButton = new QPushButton("X"); + connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); + closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + QGraphicsProxyWidget *closeButtonProxy = new QGraphicsProxyWidget; + closeButtonProxy->setWidget(closeButton); + + hbox->addItem(titleLabel); + hbox->addItem(closeButtonProxy); + QGraphicsLinearLayout *vbox = new QGraphicsLinearLayout(Qt::Vertical); + + vbox->addItem(hbox); + + if (numberCards < 0) { + sortByNameCheckBox = new QCheckBox; + QGraphicsProxyWidget *sortByNameProxy = new QGraphicsProxyWidget; + sortByNameProxy->setWidget(sortByNameCheckBox); + vbox->addItem(sortByNameProxy); - sortByTypeCheckBox = new QCheckBox; - QGraphicsProxyWidget *sortByTypeProxy = new QGraphicsProxyWidget; - sortByTypeProxy->setWidget(sortByTypeCheckBox); - vbox->addItem(sortByTypeProxy); - } else { - sortByNameCheckBox = 0; - sortByTypeCheckBox = 0; - } - - if (_origZone->getIsShufflable() && (numberCards == -1)) { - shuffleCheckBox = new QCheckBox; - shuffleCheckBox->setChecked(true); - QGraphicsProxyWidget *shuffleProxy = new QGraphicsProxyWidget; - shuffleProxy->setWidget(shuffleCheckBox); - vbox->addItem(shuffleProxy); - } else - shuffleCheckBox = 0; - - extraHeight = vbox->sizeHint(Qt::PreferredSize).height(); - resize(150, 150); - - QGraphicsLinearLayout *zoneHBox = new QGraphicsLinearLayout(Qt::Horizontal); - - zoneContainer = new QGraphicsWidget(this); - zoneContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - zoneContainer->setFlag(QGraphicsItem::ItemClipsChildrenToShape); - zoneHBox->addItem(zoneContainer); - - scrollBar = new QScrollBar(Qt::Vertical); - scrollBar->setMinimum(0); - scrollBar->setSingleStep(50); - connect(scrollBar, SIGNAL(valueChanged(int)), this, SLOT(handleScrollBarChange(int))); - QGraphicsProxyWidget *scrollBarProxy = new QGraphicsProxyWidget; - scrollBarProxy->setWidget(scrollBar); - zoneHBox->addItem(scrollBarProxy); - - vbox->addItem(zoneHBox); - - zone = new ZoneViewZone(player, _origZone, numberCards, _revealZone, _writeableRevealZone, zoneContainer); - connect(zone, SIGNAL(wheelEventReceived(QGraphicsSceneWheelEvent *)), this, SLOT(handleWheelEvent(QGraphicsSceneWheelEvent *))); - - if (sortByNameCheckBox) { - connect(sortByNameCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByName(int))); - connect(sortByTypeCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByType(int))); - sortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); - sortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); - } + sortByTypeCheckBox = new QCheckBox; + QGraphicsProxyWidget *sortByTypeProxy = new QGraphicsProxyWidget; + sortByTypeProxy->setWidget(sortByTypeCheckBox); + vbox->addItem(sortByTypeProxy); + } else { + sortByNameCheckBox = 0; + sortByTypeCheckBox = 0; + } + + if (_origZone->getIsShufflable() && (numberCards == -1)) { + shuffleCheckBox = new QCheckBox; + shuffleCheckBox->setChecked(true); + QGraphicsProxyWidget *shuffleProxy = new QGraphicsProxyWidget; + shuffleProxy->setWidget(shuffleCheckBox); + vbox->addItem(shuffleProxy); + } else + shuffleCheckBox = 0; + + extraHeight = vbox->sizeHint(Qt::PreferredSize).height(); + resize(150, 150); + + QGraphicsLinearLayout *zoneHBox = new QGraphicsLinearLayout(Qt::Horizontal); + + zoneContainer = new QGraphicsWidget(this); + zoneContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + zoneContainer->setFlag(QGraphicsItem::ItemClipsChildrenToShape); + zoneHBox->addItem(zoneContainer); + + scrollBar = new QScrollBar(Qt::Vertical); + scrollBar->setMinimum(0); + scrollBar->setSingleStep(50); + connect(scrollBar, SIGNAL(valueChanged(int)), this, SLOT(handleScrollBarChange(int))); + QGraphicsProxyWidget *scrollBarProxy = new QGraphicsProxyWidget; + scrollBarProxy->setWidget(scrollBar); + zoneHBox->addItem(scrollBarProxy); + + vbox->addItem(zoneHBox); + + zone = new ZoneViewZone(player, _origZone, numberCards, _revealZone, _writeableRevealZone, zoneContainer); + connect(zone, SIGNAL(wheelEventReceived(QGraphicsSceneWheelEvent *)), this, SLOT(handleWheelEvent(QGraphicsSceneWheelEvent *))); + + if (sortByNameCheckBox) { + connect(sortByNameCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByName(int))); + connect(sortByTypeCheckBox, SIGNAL(stateChanged(int)), zone, SLOT(setSortByType(int))); + sortByNameCheckBox->setChecked(settingsCache->getZoneViewSortByName()); + sortByTypeCheckBox->setChecked(settingsCache->getZoneViewSortByType()); + } - retranslateUi(); - setLayout(vbox); - - connect(zone, SIGNAL(optimumRectChanged()), this, SLOT(resizeToZoneContents())); - connect(zone, SIGNAL(beingDeleted()), this, SLOT(zoneDeleted())); - zone->initializeCards(cardList); + retranslateUi(); + setLayout(vbox); + + connect(zone, SIGNAL(optimumRectChanged()), this, SLOT(resizeToZoneContents())); + connect(zone, SIGNAL(beingDeleted()), this, SLOT(zoneDeleted())); + zone->initializeCards(cardList); } void ZoneViewWidget::retranslateUi() { - titleLabel->setText(zone->getTranslatedName(false, CaseNominative)); - if (sortByNameCheckBox) - sortByNameCheckBox->setText(tr("sort by name")); - if (sortByTypeCheckBox) - sortByTypeCheckBox->setText(tr("sort by type")); - if (shuffleCheckBox) - shuffleCheckBox->setText(tr("shuffle when closing")); + titleLabel->setText(zone->getTranslatedName(false, CaseNominative)); + if (sortByNameCheckBox) + sortByNameCheckBox->setText(tr("sort by name")); + if (sortByTypeCheckBox) + sortByTypeCheckBox->setText(tr("sort by type")); + if (shuffleCheckBox) + shuffleCheckBox->setText(tr("shuffle when closing")); } void ZoneViewWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - painter->fillRect(boundingRect(), palette().color(QPalette::Window)); - QGraphicsWidget::paint(painter, option, widget); + painter->fillRect(boundingRect(), palette().color(QPalette::Window)); + QGraphicsWidget::paint(painter, option, widget); } void ZoneViewWidget::moveWidget(QPointF scenePos) { - setPos(scenePos); + setPos(scenePos); } void ZoneViewWidget::resizeToZoneContents() { - QRectF zoneRect = zone->getOptimumRect(); - qreal totalZoneHeight = zoneRect.height(); - if (zoneRect.height() > 500) - zoneRect.setHeight(500); - QSizeF newSize(qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), zoneRect.width() + scrollBar->width() + 10), zoneRect.height() + extraHeight + 10); - setMaximumSize(newSize); - resize(newSize); - - zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight)); - scrollBar->setMaximum(totalZoneHeight - zoneRect.height()); - - if (layout()) - layout()->invalidate(); + QRectF zoneRect = zone->getOptimumRect(); + qreal totalZoneHeight = zoneRect.height(); + if (zoneRect.height() > 500) + zoneRect.setHeight(500); + QSizeF newSize(qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), zoneRect.width() + scrollBar->width() + 10), zoneRect.height() + extraHeight + 10); + setMaximumSize(newSize); + resize(newSize); + + zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight)); + scrollBar->setMaximum(totalZoneHeight - zoneRect.height()); + + if (layout()) + layout()->invalidate(); } void ZoneViewWidget::handleWheelEvent(QGraphicsSceneWheelEvent *event) { - QWheelEvent wheelEvent(QPoint(), event->delta(), event->buttons(), event->modifiers(), event->orientation()); - scrollBar->event(&wheelEvent); + QWheelEvent wheelEvent(QPoint(), event->delta(), event->buttons(), event->modifiers(), event->orientation()); + scrollBar->event(&wheelEvent); } void ZoneViewWidget::handleScrollBarChange(int value) { - zone->setY(-value); + zone->setY(-value); } void ZoneViewWidget::closeEvent(QCloseEvent *event) { - disconnect(zone, SIGNAL(beingDeleted()), this, 0); - if (zone->getNumberCards() != -2) { - Command_StopDumpZone cmd; - cmd.set_player_id(player->getId()); - cmd.set_zone_name(zone->getName().toStdString()); - player->sendGameCommand(cmd); - } - if (shuffleCheckBox) - if (shuffleCheckBox->isChecked()) - player->sendGameCommand(Command_Shuffle()); - emit closePressed(this); - deleteLater(); - event->accept(); + disconnect(zone, SIGNAL(beingDeleted()), this, 0); + if (zone->getNumberCards() != -2) { + Command_StopDumpZone cmd; + cmd.set_player_id(player->getId()); + cmd.set_zone_name(zone->getName().toStdString()); + player->sendGameCommand(cmd); + } + if (shuffleCheckBox) + if (shuffleCheckBox->isChecked()) + player->sendGameCommand(Command_Shuffle()); + emit closePressed(this); + deleteLater(); + event->accept(); } void ZoneViewWidget::zoneDeleted() { - emit closePressed(this); - deleteLater(); + emit closePressed(this); + deleteLater(); } diff --git a/cockatrice/src/zoneviewwidget.h b/cockatrice/src/zoneviewwidget.h index 5148ba74..2c89a571 100644 --- a/cockatrice/src/zoneviewwidget.h +++ b/cockatrice/src/zoneviewwidget.h @@ -17,50 +17,50 @@ class QGraphicsSceneMouseEvent; class QGraphicsSceneWheelEvent; class TitleLabel : public QGraphicsWidget { - Q_OBJECT + Q_OBJECT private: - QString text; - QPointF buttonDownPos; + QString text; + QPointF buttonDownPos; public: - TitleLabel(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); - void setText(const QString &_text) { text = _text; update(); } + TitleLabel(); + void paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/); + void setText(const QString &_text) { text = _text; update(); } signals: - void mouseMoved(QPointF scenePos); + void mouseMoved(QPointF scenePos); protected: - QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint) const; - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); - void mousePressEvent(QGraphicsSceneMouseEvent *event); + QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint) const; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); }; class ZoneViewWidget : public QGraphicsWidget { - Q_OBJECT + Q_OBJECT private: - ZoneViewZone *zone; - QGraphicsWidget *zoneContainer; - - TitleLabel *titleLabel; - QPushButton *closeButton; - QScrollBar *scrollBar; - QCheckBox *sortByNameCheckBox, *sortByTypeCheckBox, *shuffleCheckBox; - - int extraHeight; - Player *player; + ZoneViewZone *zone; + QGraphicsWidget *zoneContainer; + + TitleLabel *titleLabel; + QPushButton *closeButton; + QScrollBar *scrollBar; + QCheckBox *sortByNameCheckBox, *sortByTypeCheckBox, *shuffleCheckBox; + + int extraHeight; + Player *player; signals: - void closePressed(ZoneViewWidget *zv); + void closePressed(ZoneViewWidget *zv); private slots: - void resizeToZoneContents(); - void handleWheelEvent(QGraphicsSceneWheelEvent *event); - void handleScrollBarChange(int value); - void zoneDeleted(); - void moveWidget(QPointF scenePos); + void resizeToZoneContents(); + void handleWheelEvent(QGraphicsSceneWheelEvent *event); + void handleScrollBarChange(int value); + void zoneDeleted(); + void moveWidget(QPointF scenePos); public: - ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards = 0, bool _revealZone = false, bool _writeableRevealZone = false, const QList &cardList = QList()); - ZoneViewZone *getZone() const { return zone; } - void retranslateUi(); + ZoneViewWidget(Player *_player, CardZone *_origZone, int numberCards = 0, bool _revealZone = false, bool _writeableRevealZone = false, const QList &cardList = QList()); + ZoneViewZone *getZone() const { return zone; } + void retranslateUi(); protected: - void closeEvent(QCloseEvent *event); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void closeEvent(QCloseEvent *event); + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; #endif diff --git a/cockatrice/src/zoneviewzone.cpp b/cockatrice/src/zoneviewzone.cpp index cfa1dda2..c42dfd0e 100644 --- a/cockatrice/src/zoneviewzone.cpp +++ b/cockatrice/src/zoneviewzone.cpp @@ -12,23 +12,23 @@ #include "pending_command.h" ZoneViewZone::ZoneViewZone(Player *_p, CardZone *_origZone, int _numberCards, bool _revealZone, bool _writeableRevealZone, QGraphicsItem *parent) - : SelectZone(_p, _origZone->getName(), false, false, true, parent, true), bRect(QRectF()), minRows(0), numberCards(_numberCards), origZone(_origZone), revealZone(_revealZone), writeableRevealZone(_writeableRevealZone), sortByName(false), sortByType(false) + : SelectZone(_p, _origZone->getName(), false, false, true, parent, true), bRect(QRectF()), minRows(0), numberCards(_numberCards), origZone(_origZone), revealZone(_revealZone), writeableRevealZone(_writeableRevealZone), sortByName(false), sortByType(false) { - if (!(revealZone && !writeableRevealZone)) - origZone->setView(this); + if (!(revealZone && !writeableRevealZone)) + origZone->setView(this); } ZoneViewZone::~ZoneViewZone() { - emit beingDeleted(); - qDebug("ZoneViewZone destructor"); - if (!(revealZone && !writeableRevealZone)) - origZone->setView(NULL); + emit beingDeleted(); + qDebug("ZoneViewZone destructor"); + if (!(revealZone && !writeableRevealZone)) + origZone->setView(NULL); } QRectF ZoneViewZone::boundingRect() const { - return bRect; + return bRect; } void ZoneViewZone::paint(QPainter */*painter*/, const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/) @@ -37,154 +37,154 @@ void ZoneViewZone::paint(QPainter */*painter*/, const QStyleOptionGraphicsItem * void ZoneViewZone::initializeCards(const QList &cardList) { - if (!cardList.isEmpty()) { - for (int i = 0; i < cardList.size(); ++i) - addCard(new CardItem(player, QString::fromStdString(cardList[i]->name()), cardList[i]->id(), revealZone, this), false, i); - reorganizeCards(); - } else if (!origZone->contentsKnown()) { - Command_DumpZone cmd; - cmd.set_player_id(player->getId()); - cmd.set_zone_name(name.toStdString()); - cmd.set_number_cards(numberCards); - - PendingCommand *pend = player->prepareGameCommand(cmd); - connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(zoneDumpReceived(const Response &))); - player->sendGameCommand(pend); - } else { - const CardList &c = origZone->getCards(); - int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size()); - for (int i = 0; i < number; i++) { - CardItem *card = c.at(i); - addCard(new CardItem(player, card->getName(), card->getId(), revealZone, this), false, i); - } - reorganizeCards(); - } + if (!cardList.isEmpty()) { + for (int i = 0; i < cardList.size(); ++i) + addCard(new CardItem(player, QString::fromStdString(cardList[i]->name()), cardList[i]->id(), revealZone, this), false, i); + reorganizeCards(); + } else if (!origZone->contentsKnown()) { + Command_DumpZone cmd; + cmd.set_player_id(player->getId()); + cmd.set_zone_name(name.toStdString()); + cmd.set_number_cards(numberCards); + + PendingCommand *pend = player->prepareGameCommand(cmd); + connect(pend, SIGNAL(finished(Response, CommandContainer, QVariant)), this, SLOT(zoneDumpReceived(const Response &))); + player->sendGameCommand(pend); + } else { + const CardList &c = origZone->getCards(); + int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size()); + for (int i = 0; i < number; i++) { + CardItem *card = c.at(i); + addCard(new CardItem(player, card->getName(), card->getId(), revealZone, this), false, i); + } + reorganizeCards(); + } } void ZoneViewZone::zoneDumpReceived(const Response &r) { - const Response_DumpZone &resp = r.GetExtension(Response_DumpZone::ext); - const int respCardListSize = resp.zone_info().card_list_size(); - for (int i = 0; i < respCardListSize; ++i) { - const ServerInfo_Card &cardInfo = resp.zone_info().card_list(i); - CardItem *card = new CardItem(player, QString::fromStdString(cardInfo.name()), cardInfo.id(), revealZone, this); - addCard(card, false, i); - } - - reorganizeCards(); + const Response_DumpZone &resp = r.GetExtension(Response_DumpZone::ext); + const int respCardListSize = resp.zone_info().card_list_size(); + for (int i = 0; i < respCardListSize; ++i) { + const ServerInfo_Card &cardInfo = resp.zone_info().card_list(i); + CardItem *card = new CardItem(player, QString::fromStdString(cardInfo.name()), cardInfo.id(), revealZone, this); + addCard(card, false, i); + } + + reorganizeCards(); } // Because of boundingRect(), this function must not be called before the zone was added to a scene. void ZoneViewZone::reorganizeCards() { - int cardCount = cards.size(); - if (!origZone->contentsKnown()) - for (int i = 0; i < cardCount; ++i) - cards[i]->setId(i); + int cardCount = cards.size(); + if (!origZone->contentsKnown()) + for (int i = 0; i < cardCount; ++i) + cards[i]->setId(i); - int cols = floor(sqrt((double) cardCount / 2)); - if (cols > 7) - cols = 7; - int rows = ceil((double) cardCount / cols); - if (rows < 1) - rows = 1; - if (minRows == 0) - minRows = rows; - else if (rows < minRows) { - rows = minRows; - cols = ceil((double) cardCount / minRows); - } - if (cols < 2) - cols = 2; - - qDebug() << "reorganizeCards: rows=" << rows << "cols=" << cols; + int cols = floor(sqrt((double) cardCount / 2)); + if (cols > 7) + cols = 7; + int rows = ceil((double) cardCount / cols); + if (rows < 1) + rows = 1; + if (minRows == 0) + minRows = rows; + else if (rows < minRows) { + rows = minRows; + cols = ceil((double) cardCount / minRows); + } + if (cols < 2) + cols = 2; + + qDebug() << "reorganizeCards: rows=" << rows << "cols=" << cols; - CardList cardsToDisplay(cards); - if (sortByName || sortByType) - cardsToDisplay.sort((sortByName ? CardList::SortByName : 0) | (sortByType ? CardList::SortByType : 0)); - - for (int i = 0; i < cardCount; i++) { - CardItem *c = cardsToDisplay.at(i); - qreal x = (i / rows) * CARD_WIDTH; - qreal y = (i % rows) * CARD_HEIGHT / 3; - c->setPos(x + 5, y + 5); - c->setRealZValue(i); - } + CardList cardsToDisplay(cards); + if (sortByName || sortByType) + cardsToDisplay.sort((sortByName ? CardList::SortByName : 0) | (sortByType ? CardList::SortByType : 0)); + + for (int i = 0; i < cardCount; i++) { + CardItem *c = cardsToDisplay.at(i); + qreal x = (i / rows) * CARD_WIDTH; + qreal y = (i % rows) * CARD_HEIGHT / 3; + c->setPos(x + 5, y + 5); + c->setRealZValue(i); + } - optimumRect = QRectF(0, 0, qMax(cols, 3) * CARD_WIDTH + 10, ((rows - 1) * CARD_HEIGHT) / 3 + CARD_HEIGHT + 10); - updateGeometry(); - emit optimumRectChanged(); + optimumRect = QRectF(0, 0, qMax(cols, 3) * CARD_WIDTH + 10, ((rows - 1) * CARD_HEIGHT) / 3 + CARD_HEIGHT + 10); + updateGeometry(); + emit optimumRectChanged(); } void ZoneViewZone::setSortByName(int _sortByName) { - sortByName = _sortByName; - reorganizeCards(); + sortByName = _sortByName; + reorganizeCards(); } void ZoneViewZone::setSortByType(int _sortByType) { - sortByType = _sortByType; - reorganizeCards(); + sortByType = _sortByType; + reorganizeCards(); } void ZoneViewZone::addCardImpl(CardItem *card, int x, int /*y*/) { - cards.insert(x, card); - card->setParentItem(this); - card->update(); + cards.insert(x, card); + card->setParentItem(this); + card->update(); } void ZoneViewZone::handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &/*dropPoint*/) { - Command_MoveCard cmd; - cmd.set_start_player_id(startZone->getPlayer()->getId()); - cmd.set_start_zone(startZone->getName().toStdString()); - cmd.set_target_player_id(player->getId()); - cmd.set_target_zone(getName().toStdString()); - cmd.set_x(0); - cmd.set_y(0); - - for (int i = 0; i < dragItems.size(); ++i) - cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); + Command_MoveCard cmd; + cmd.set_start_player_id(startZone->getPlayer()->getId()); + cmd.set_start_zone(startZone->getName().toStdString()); + cmd.set_target_player_id(player->getId()); + cmd.set_target_zone(getName().toStdString()); + cmd.set_x(0); + cmd.set_y(0); + + for (int i = 0; i < dragItems.size(); ++i) + cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId()); - player->sendGameCommand(cmd); + player->sendGameCommand(cmd); } void ZoneViewZone::removeCard(int position) { - if (position >= cards.size()) - return; + if (position >= cards.size()) + return; - CardItem *card = cards.takeAt(position); - card->deleteLater(); - reorganizeCards(); + CardItem *card = cards.takeAt(position); + card->deleteLater(); + reorganizeCards(); } void ZoneViewZone::setGeometry(const QRectF &rect) { - prepareGeometryChange(); - setPos(rect.x(), rect.y()); - bRect = QRectF(0, 0, rect.width(), rect.height()); + prepareGeometryChange(); + setPos(rect.x(), rect.y()); + bRect = QRectF(0, 0, rect.width(), rect.height()); } QSizeF ZoneViewZone::sizeHint(Qt::SizeHint /*which*/, const QSizeF & /*constraint*/) const { - return optimumRect.size(); + return optimumRect.size(); } void ZoneViewZone::setWriteableRevealZone(bool _writeableRevealZone) { - if (writeableRevealZone && !_writeableRevealZone) - origZone->setView(this); - else if (!writeableRevealZone && _writeableRevealZone) - origZone->setView(NULL); - - writeableRevealZone = _writeableRevealZone; - + if (writeableRevealZone && !_writeableRevealZone) + origZone->setView(this); + else if (!writeableRevealZone && _writeableRevealZone) + origZone->setView(NULL); + + writeableRevealZone = _writeableRevealZone; + } void ZoneViewZone::wheelEvent(QGraphicsSceneWheelEvent *event) { - emit wheelEventReceived(event); + emit wheelEventReceived(event); } diff --git a/cockatrice/src/zoneviewzone.h b/cockatrice/src/zoneviewzone.h index 25850e38..727148a8 100644 --- a/cockatrice/src/zoneviewzone.h +++ b/cockatrice/src/zoneviewzone.h @@ -10,41 +10,41 @@ class ServerInfo_Card; class QGraphicsSceneWheelEvent; class ZoneViewZone : public SelectZone, public QGraphicsLayoutItem { - Q_OBJECT + Q_OBJECT private: - QRectF bRect, optimumRect; - int minRows, numberCards; - void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); - CardZone *origZone; - bool revealZone, writeableRevealZone; - bool sortByName, sortByType; + QRectF bRect, optimumRect; + int minRows, numberCards; + void handleDropEvent(const QList &dragItems, CardZone *startZone, const QPoint &dropPoint); + CardZone *origZone; + bool revealZone, writeableRevealZone; + bool sortByName, sortByType; public: - ZoneViewZone(Player *_p, CardZone *_origZone, int _numberCards = -1, bool _revealZone = false, bool _writeableRevealZone = false, QGraphicsItem *parent = 0); - ~ZoneViewZone(); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void reorganizeCards(); - void initializeCards(const QList &cardList = QList()); - void removeCard(int position); - int getNumberCards() const { return numberCards; } - void setGeometry(const QRectF &rect); - QRectF getOptimumRect() const { return optimumRect; } - bool getRevealZone() const { return revealZone; } - bool getWriteableRevealZone() const { return writeableRevealZone; } - void setWriteableRevealZone(bool _writeableRevealZone); + ZoneViewZone(Player *_p, CardZone *_origZone, int _numberCards = -1, bool _revealZone = false, bool _writeableRevealZone = false, QGraphicsItem *parent = 0); + ~ZoneViewZone(); + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void reorganizeCards(); + void initializeCards(const QList &cardList = QList()); + void removeCard(int position); + int getNumberCards() const { return numberCards; } + void setGeometry(const QRectF &rect); + QRectF getOptimumRect() const { return optimumRect; } + bool getRevealZone() const { return revealZone; } + bool getWriteableRevealZone() const { return writeableRevealZone; } + void setWriteableRevealZone(bool _writeableRevealZone); public slots: - void setSortByName(int _sortByName); - void setSortByType(int _sortByType); + void setSortByName(int _sortByName); + void setSortByType(int _sortByType); private slots: - void zoneDumpReceived(const Response &r); + void zoneDumpReceived(const Response &r); signals: - void beingDeleted(); - void optimumRectChanged(); - void wheelEventReceived(QGraphicsSceneWheelEvent *event); + void beingDeleted(); + void optimumRectChanged(); + void wheelEventReceived(QGraphicsSceneWheelEvent *event); protected: - void addCardImpl(CardItem *card, int x, int y); - QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; - void wheelEvent(QGraphicsSceneWheelEvent *event); + void addCardImpl(CardItem *card, int x, int y); + QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; + void wheelEvent(QGraphicsSceneWheelEvent *event); }; #endif diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 51ce1650..3a8031b1 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -48,5 +48,9 @@ INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) add_library(cockatrice_common ${common_SOURCES} ${common_HEADERS_MOC}) -target_link_libraries(cockatrice_common cockatrice_protocol) - +# Without this check, Linux will put -pthread out of order in link.txt and build will fail +if (UNIX) + target_link_libraries(cockatrice_common cockatrice_protocol pthread) +else (UNIX) + target_link_libraries(cockatrice_common cockatrice_protocol) +endif (UNIX) diff --git a/common/decklist.cpp b/common/decklist.cpp index 7c1430a6..d9a3d7f3 100644 --- a/common/decklist.cpp +++ b/common/decklist.cpp @@ -449,8 +449,12 @@ bool DeckList::loadFromStream_Plain(QTextStream &in) line.remove(rx); rx.setPattern("\\(.*\\)"); line.remove(rx); + //Filter out post card name editions + rx.setPattern("\\|.*$"); + line.remove(rx); line = line.simplified(); + int i = line.indexOf(' '); bool ok; int number = line.left(i).toInt(&ok); diff --git a/doc/usermanual/Usermanual.pdf b/doc/usermanual/Usermanual.pdf index 59638227..361bf157 100644 Binary files a/doc/usermanual/Usermanual.pdf and b/doc/usermanual/Usermanual.pdf differ diff --git a/doc/usermanual/Usermanual.tex b/doc/usermanual/Usermanual.tex index a0821d61..61643701 100644 --- a/doc/usermanual/Usermanual.tex +++ b/doc/usermanual/Usermanual.tex @@ -195,7 +195,7 @@ Start the oracle.exe (the installer does this automatically) and let it generate Congratulations, you may now use Cockatrice! \subsubsection{Linux and BSD} -The following procedures have been tested with Debian Wheezy, Fedora 18 and FreeBSD 9.1. +The following procedures have been tested with Debian Wheezy, Fedora 18, XUbuntu 13.10, FreeBSD 9.1 and 10.0. If you use Gentoo with KDE you have the needed prerequisites and may continue with downloading the source. If you use Bodhi or Arch Linux (AUR) or another distribution that includes Cockatrice, you might install Cockatrice from the default packages -- though the package might be old, so you probably should continue with this howto. @@ -204,10 +204,11 @@ Before you install new software, you should update your system. The following in \begin{enumerate} \item You need to install the build tools and dependencies. This varies between the Linux distributions. \begin{description} - \item[Debian, Ubuntu and spin-offs] \shellcmd{sudo apt-get install build-essential git libqt4-dev qtmobility-dev libprotobuf-dev protobuf-compiler cmake} + \item[Debian, Ubuntu and spin-offs] \shellcmd{sudo apt-get install build-essential git libqt4-dev qtmobility-dev libprotobuf-dev protobuf-compiler cmake} (see note below regarding pthread) \item[Fedora] \shellcmd{sudo yum groupinstall "Development Tools"\\ yum install qt-devel qt-mobility-devel protobuf-devel protobuf-compiler cmake} - \item[FreeBSD] \shellcmd{pkg\_add -r qt4 qt4-linguist qt4-moc qt4-qmake qt4-rcc qt4-uic git cmake protobuf} + \item[FreeBSD 9] \shellcmd{pkg\_add -r qt4 qt4-linguist qt4-moc qt4-qmake qt4-rcc qt4-uic git cmake protobuf} + \item[FreeBSD 10] \shellcmd{pkg install qt4 qt4-linguist qt4-moc qt4-qmake qt4-rcc qt4-uic git cmake protobuf} \end{description} \item Download the sources from github via \\ \shellcmd{cd\\ git clone https://github.com/Daenyth/Cockatrice.git} \item To compile the sources, change into the newly created directory, create a build directory and invoke cmake:\\ @@ -216,10 +217,12 @@ mkdir build \\ cd build \\ cmake ..\\ make}\\ -If you have some issues with pthread\_* add 'pthread' to the ``target\_link\_libraries'' entry in the \shellcmd{CMakeFiles.txt} in \shellcmd{Cockatrice/common}. +\begin{framed} +If you have linking errors with pthread\_* add 'pthread' to the ``target\_link\_libraries'' entry in the \shellcmd{CMakeFiles.txt} in \shellcmd{Cockatrice/common}, e.g. for Xubuntu, then continue the make process. +\end{framed} \item You may install the program into the directory \shellcmd{/usr/local} by typing \shellcmd{sudo make install} but you should also be able to start cockatrice and the oracle from the build directory. - \item Before you start Cockatrice for the first time, run \shellcmd{oracle -dlsets} and download available cards, denn run \shellcmd{cockatrice}. + \item Before you start Cockatrice for the first time, run \shellcmd{oracle -dlsets} and download available cards, then run \shellcmd{cockatrice}. The default paths for decks, pics, cards and tokens are located in \\ \shellcmd{/home//.local/share/data/Cockatrice/Cockatrice}. \end{enumerate} @@ -233,6 +236,10 @@ The compilation works like already written above, but instead of invoking \shell \item If you want to build the server, use:\\ \shellcmd{cmake -DWITH\_SERVER=1 ..} \item If you want to build the server, but not the client, use:\\ \shellcmd{cmake -DWITH\_SERVER=1 -DWITHOUT\_CLIENT=1 ..} \end{itemize} +Further, the server has a dependency on libgcrypt, so you need to install it as well: +\begin{description} + \item[FreeBSD 10] \shellcmd{pkg install libgcrypt} +\end{description} There is more information on compiling and running Servatrice on CentOS 6 in chapter \ref{servatrice} on page \pageref{servatrice}. \section{Downloading Card Database Using the Oracle}